Skip to main content

gate4agent_runtime_native/
launch_profiles.rs

1use gate4agent_adapters::OneShotSessionPersistence;
2use gate4agent_catalog::{EnvMutation, McpServerSpec, McpServerSpecError};
3use gate4agent_types::{AgentId, AgentInstanceId, TransportKind};
4use std::collections::{BTreeMap, BTreeSet};
5use std::ffi::{OsStr, OsString};
6use std::fmt;
7use std::sync::{Arc, Mutex, MutexGuard};
8use thiserror::Error;
9
10const NATIVE_LAUNCH_PROFILE_ID_MAX_BYTES: usize = 64;
11const NATIVE_LAUNCH_PROFILES_MAX: usize = 512;
12const NATIVE_LAUNCH_PROFILE_SELECTIONS_MAX: usize = 512;
13const NATIVE_LAUNCH_PROFILE_ENV_MUTATIONS_MAX: usize = 128;
14const NATIVE_LAUNCH_PROFILE_ENV_KEY_MAX_BYTES: usize = 1_024;
15const NATIVE_LAUNCH_PROFILE_ENV_VALUE_MAX_BYTES: usize = 65_536;
16const NATIVE_LAUNCH_PROFILE_ENV_TOTAL_MAX_BYTES: usize = 1_048_576;
17const NATIVE_INSTANCE_LAUNCH_ARGS_MAX: usize = 128;
18const NATIVE_INSTANCE_LAUNCH_ARG_MAX_BYTES: usize = 65_536;
19const NATIVE_INSTANCE_LAUNCH_ARGS_TOTAL_MAX_BYTES: usize = 262_144;
20const RESERVED_HOOK_ENV_PREFIX: &str = "GATE4AGENT_HOOK_";
21const CONTEXT_ROOT_ENVIRONMENT_KEY: &str = "GATE4AGENT_CONTEXT_ROOT";
22
23/// The only keys of a host-assigned session identity (the messaging account the host gives
24/// one session: nick = key = role). They are host-owned like the context root, so they need no
25/// native launch profile and can ride on top of any other overlay.
26/// Besides nick/key/handle, the account's own non-secret client settings ride along: its store
27/// root, the display name the nick came from, and where its messenger is.
28pub const SESSION_IDENTITY_ENVIRONMENT_KEYS: &[&str] = &[
29    "M4A_NICK",
30    "M4A_SESSION_CAP",
31    "M4A_SESSION_ID",
32    "M4A_SESSION_HANDLE",
33    "M4A_SIGNER_SOCK",
34    "M4A_STORE_ROOT",
35    "M4A_BOT_NAME",
36    "M4A_PRODUCT_URL",
37    "M4A_HOMESERVER_URL",
38    "M4A_TIER",
39];
40
41fn is_session_identity(environment: &[EnvMutation]) -> bool {
42    !environment.is_empty()
43        && environment.iter().all(|m| {
44            SESSION_IDENTITY_ENVIRONMENT_KEYS.iter().any(|k| m.key == OsStr::new(k)) && m.value.as_ref().is_some_and(|v| !v.is_empty())
45        })
46}
47const RESERVED_CLAUDE_LAUNCH_FLAGS: &[&str] = &[
48    "--continue",
49    "--print",
50    "--prompt",
51    "--prompt-interactive",
52    "--resume",
53    "--session-id",
54    "-c",
55    "-p",
56    "-r",
57];
58
59pub const ZAI_GLM_CLAUDE_PROFILE_ID: &str = "zai-glm";
60pub const ZAI_GLM_CLAUDE_PROFILE_REVISION: &str = "zai-claude-env-2026-07-21";
61pub const ZAI_GLM_ANTHROPIC_BASE_URL: &str = "https://api.z.ai/api/anthropic";
62pub const ZAI_GLM_CLAUDE_REQUIRED_ENV_KEYS: &[&str] =
63    &["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL"];
64pub const ZAI_GLM_CLAUDE_OPTIONAL_ENV_KEYS: &[&str] = &[
65    "API_TIMEOUT_MS",
66    "ANTHROPIC_DEFAULT_HAIKU_MODEL",
67    "ANTHROPIC_DEFAULT_SONNET_MODEL",
68    "ANTHROPIC_DEFAULT_OPUS_MODEL",
69    "CLAUDE_CODE_AUTO_COMPACT_WINDOW",
70    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
71];
72pub const ZAI_GLM_CLAUDE_OWNED_ENV_KEYS: &[&str] = &[
73    "ANTHROPIC_AUTH_TOKEN",
74    "ANTHROPIC_BASE_URL",
75    "API_TIMEOUT_MS",
76    "ANTHROPIC_DEFAULT_HAIKU_MODEL",
77    "ANTHROPIC_DEFAULT_SONNET_MODEL",
78    "ANTHROPIC_DEFAULT_OPUS_MODEL",
79    "CLAUDE_CODE_AUTO_COMPACT_WINDOW",
80    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
81];
82
83/// Revisioned non-secret descriptor for a built-in native launch profile.
84#[derive(Clone, Copy, Debug, Eq, PartialEq)]
85pub struct NativeLaunchProfileDescriptor {
86    id: &'static str,
87    revision: &'static str,
88    agent_id: &'static str,
89    transport: TransportKind,
90    required_env_keys: &'static [&'static str],
91    optional_env_keys: &'static [&'static str],
92    owned_env_keys: &'static [&'static str],
93    contract: NativeLaunchProfileContract,
94}
95
96impl NativeLaunchProfileDescriptor {
97    pub const fn id(&self) -> &'static str {
98        self.id
99    }
100
101    pub const fn revision(&self) -> &'static str {
102        self.revision
103    }
104
105    pub const fn agent_id(&self) -> &'static str {
106        self.agent_id
107    }
108
109    pub const fn transport(&self) -> TransportKind {
110        self.transport
111    }
112
113    pub const fn required_env_keys(&self) -> &'static [&'static str] {
114        self.required_env_keys
115    }
116
117    pub const fn optional_env_keys(&self) -> &'static [&'static str] {
118        self.optional_env_keys
119    }
120
121    pub const fn owned_env_keys(&self) -> &'static [&'static str] {
122        self.owned_env_keys
123    }
124
125    pub fn instantiate(
126        &self,
127        resolver: Arc<dyn NativeChildEnvironmentResolver>,
128    ) -> Result<NativeLaunchProfile, NativeLaunchProfileError> {
129        let id = NativeLaunchProfileId::new(self.id)
130            .expect("built-in native launch profile ID must be valid");
131        let agent_id = AgentId::new(self.agent_id)
132            .expect("built-in native launch profile agent ID must be valid");
133        NativeLaunchProfile::new_with_contract(
134            id,
135            agent_id,
136            self.transport,
137            self.owned_env_keys.iter().map(OsString::from).collect(),
138            resolver,
139            self.contract,
140        )
141    }
142}
143
144#[derive(Clone, Copy, Debug, Eq, PartialEq)]
145enum NativeLaunchProfileContract {
146    ExactOwnership,
147    ZaiGlmClaude,
148}
149
150impl NativeLaunchProfileContract {
151    fn validate(self, environment: &[EnvMutation]) -> Result<(), NativeLaunchProfileError> {
152        match self {
153            Self::ExactOwnership => Ok(()),
154            Self::ZaiGlmClaude => validate_zai_glm_claude_environment(environment),
155        }
156    }
157}
158
159/// Z.AI GLM Coding Plan over the installed Claude Code CLI.
160///
161/// The key inventory follows the official Z.AI Claude Code environment example
162/// reviewed on 2026-07-21. Only the token and base URL are required; a resolver
163/// must still return every owned key and use `None` for optional values it does
164/// not set. No model value is embedded because the current upstream example is
165/// internally inconsistent and model selection remains host configuration.
166pub const ZAI_GLM_CLAUDE_PROFILE: NativeLaunchProfileDescriptor =
167    NativeLaunchProfileDescriptor {
168        id: ZAI_GLM_CLAUDE_PROFILE_ID,
169        revision: ZAI_GLM_CLAUDE_PROFILE_REVISION,
170        agent_id: "claude",
171        transport: TransportKind::Pty,
172        required_env_keys: ZAI_GLM_CLAUDE_REQUIRED_ENV_KEYS,
173        optional_env_keys: ZAI_GLM_CLAUDE_OPTIONAL_ENV_KEYS,
174        owned_env_keys: ZAI_GLM_CLAUDE_OWNED_ENV_KEYS,
175        contract: NativeLaunchProfileContract::ZaiGlmClaude,
176    };
177
178/// Host-local identifier for a non-wire native launch profile.
179#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
180pub struct NativeLaunchProfileId(String);
181
182impl NativeLaunchProfileId {
183    pub fn new(value: impl Into<String>) -> Result<Self, NativeLaunchProfileError> {
184        let value = value.into();
185        if value.is_empty() {
186            return Err(NativeLaunchProfileError::EmptyId);
187        }
188        if value.len() > NATIVE_LAUNCH_PROFILE_ID_MAX_BYTES {
189            return Err(NativeLaunchProfileError::IdTooLong {
190                len: value.len(),
191                max: NATIVE_LAUNCH_PROFILE_ID_MAX_BYTES,
192            });
193        }
194        if !value.bytes().all(|byte| {
195            byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'_')
196        }) || matches!(value.as_bytes().first(), Some(b'-' | b'_'))
197            || matches!(value.as_bytes().last(), Some(b'-' | b'_'))
198        {
199            return Err(NativeLaunchProfileError::InvalidId);
200        }
201        Ok(Self(value))
202    }
203
204    pub fn as_str(&self) -> &str {
205        &self.0
206    }
207}
208
209impl fmt::Display for NativeLaunchProfileId {
210    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
211        formatter.write_str(self.as_str())
212    }
213}
214
215/// Host-owned child-process environment policy, absent from the wire protocol.
216///
217/// The profile retains an opaque resolver rather than resolved values and does
218/// not implement `Debug`, preventing routine diagnostics from exposing child
219/// environment material.
220#[derive(Clone)]
221pub struct NativeLaunchProfile {
222    id: NativeLaunchProfileId,
223    agent_id: AgentId,
224    transport: TransportKind,
225    owned_env_keys: Vec<OsString>,
226    resolver: Arc<dyn NativeChildEnvironmentResolver>,
227    contract: NativeLaunchProfileContract,
228    one_shot_session_persistence: OneShotSessionPersistence,
229}
230
231/// Host-only launch mutations applied to one exact native PTY instance.
232///
233/// The overlay does not implement `Debug` because environment values and argv
234/// may contain secret material. It is validated and retained without crossing
235/// the wire or durable state boundaries.
236pub struct NativeInstanceLaunchOverlay {
237    agent_id: AgentId,
238    transport: TransportKind,
239    environment: Vec<EnvMutation>,
240    extra_args: Vec<OsString>,
241    profile_selection_required: bool,
242}
243
244/// Host-only MCP-server launch overlay for one exact instance, PTY or ACP.
245///
246/// Built from a caller-supplied [`McpServerSpec`] plus whatever the caller
247/// wants installed into, or scrubbed from, a PTY child's own OS environment.
248/// The two never disagree on the server's own environment entries: `env`
249/// below both becomes the PTY child's environment (as `Some` mutations,
250/// alongside `env_removals` as `None` mutations) and travels unchanged as
251/// [`McpServerSpec::env`] for an ACP-transport agent's own stdio server
252/// entry -- `NativeSpawnOverlay::resolve_environment`, below, does not gate
253/// this overlay by transport, and `gate4agent-shell-native`'s ACP branch
254/// receives the resolved spec as a typed value from
255/// `gate4agent-runtime-native`, in-process
256/// (`NativeSpawnOverlay`/`NativeEffectRequest`), never a wire type or a
257/// well-known environment key it has to re-read.
258///
259/// This crate never interprets `name`, `program`, `args`, or any entry in
260/// `env`/`env_removals` -- they, and any trace opt-in a caller wants, are
261/// entirely the caller's concern.
262pub struct NativeMcpServerLaunchOverlay {
263    agent_id: AgentId,
264    environment: Vec<EnvMutation>,
265    mcp_server: McpServerSpec,
266    /// Further stdio servers registered alongside `mcp_server` on an ACP
267    /// `session/new` only (a PTY child gets no extra environment from
268    /// them). Names are unique across `mcp_server` and this list.
269    additional_acp_servers: Vec<McpServerSpec>,
270}
271
272impl NativeMcpServerLaunchOverlay {
273    /// `env_entries` are installed into a PTY child's OS environment and
274    /// carried unchanged as the ACP stdio entry's own `env`. `env_removals`
275    /// applies to the PTY child's OS environment only -- an ACP
276    /// `mcpServers` entry is additive, so there is nothing there to remove.
277    pub fn new(
278        agent_id: AgentId,
279        name: impl Into<String>,
280        program: OsString,
281        args: Vec<OsString>,
282        env_entries: Vec<(OsString, OsString)>,
283        env_removals: Vec<OsString>,
284    ) -> Result<Self, NativeLaunchProfileError> {
285        let mcp_server = McpServerSpec::new(name, program, args, env_entries.clone())?;
286        let mut environment: Vec<EnvMutation> = env_entries
287            .into_iter()
288            .map(|(key, value)| EnvMutation {
289                key,
290                value: Some(value),
291            })
292            .collect();
293        environment.extend(
294            env_removals
295                .into_iter()
296                .map(|key| EnvMutation { key, value: None }),
297        );
298        validate_environment_mutations(&environment)?;
299        Ok(Self {
300            agent_id,
301            environment,
302            mcp_server,
303            additional_acp_servers: Vec::new(),
304        })
305    }
306
307    /// Adds one more stdio MCP server to the ACP `session/new`
308    /// `mcpServers` list, after the primary server given to [`Self::new`].
309    ///
310    /// The spec's `env` travels only as that ACP entry's own `env`; it is
311    /// never installed into a PTY child's OS environment (a PTY provider
312    /// learns about extra servers through its own configuration, not
313    /// through this overlay). A spec whose name equals the primary
314    /// server's name is ignored -- the primary always wins; a spec whose
315    /// name equals an earlier additional server replaces it in place.
316    pub fn with_additional_acp_server(mut self, spec: McpServerSpec) -> Self {
317        if spec.name() == self.mcp_server.name() {
318            return self;
319        }
320        if let Some(existing) = self
321            .additional_acp_servers
322            .iter_mut()
323            .find(|existing| existing.name() == spec.name())
324        {
325            *existing = spec;
326        } else {
327            self.additional_acp_servers.push(spec);
328        }
329        self
330    }
331
332    /// Names of every server this overlay registers on an ACP spawn, the
333    /// primary first.
334    pub fn acp_server_names(&self) -> Vec<&str> {
335        std::iter::once(self.mcp_server.name())
336            .chain(self.additional_acp_servers.iter().map(McpServerSpec::name))
337            .collect()
338    }
339
340    /// Every server for an ACP spawn, primary first.
341    pub(crate) fn acp_servers(&self) -> Vec<McpServerSpec> {
342        std::iter::once(self.mcp_server.clone())
343            .chain(self.additional_acp_servers.iter().cloned())
344            .collect()
345    }
346}
347
348impl NativeInstanceLaunchOverlay {
349    pub fn new(
350        agent_id: AgentId,
351        transport: TransportKind,
352        environment: Vec<EnvMutation>,
353        extra_args: Vec<OsString>,
354    ) -> Result<Self, NativeLaunchProfileError> {
355        match transport {
356            TransportKind::Pty => {}
357            // Codex first-slice network_access: argv-only `-c` overlays may
358            // ride ACP the same channel as catalog `windows_wsl_setup_*`.
359            // Environment mutations on ACP stay refused.
360            TransportKind::Acp
361                if environment.is_empty()
362                    && is_codex_config_c_overlay_args(&agent_id, &extra_args) => {}
363            _ => return Err(NativeLaunchProfileError::InstanceOverlayUnsupportedTransport),
364        }
365        validate_environment_mutations(&environment)?;
366        validate_launch_arguments(&agent_id, &extra_args)?;
367        let profile_selection_required = !environment.is_empty();
368        Ok(Self {
369            agent_id,
370            transport,
371            environment,
372            extra_args,
373            profile_selection_required,
374        })
375    }
376}
377
378/// Backward-compatible environment-only overlay used by existing node flows.
379///
380/// This type also intentionally omits `Debug`. New PTY feature bundles should
381/// use [`NativeInstanceLaunchOverlay`] when they need child argv.
382pub struct NativeLaunchEnvironmentOverlay {
383    agent_id: AgentId,
384    transport: TransportKind,
385    environment: Vec<EnvMutation>,
386    profile_selection_required: bool,
387}
388
389impl NativeLaunchEnvironmentOverlay {
390    pub fn new(
391        agent_id: AgentId,
392        transport: TransportKind,
393        environment: Vec<EnvMutation>,
394    ) -> Result<Self, NativeLaunchProfileError> {
395        if !matches!(transport, TransportKind::Pty | TransportKind::Pipe) {
396            return Err(NativeLaunchProfileError::UnsupportedTransport);
397        }
398        validate_environment_mutations(&environment)?;
399        // Every generic environment overlay -- an empty one included -- is bound
400        // to an explicitly selected native launch profile and is refused with
401        // `EnvironmentOverlaySelectionMissing` without one. The requirement used
402        // to follow from the mutation list being non-empty, which let an empty
403        // overlay install unprofiled; only `new_context_root` is exempt.
404        Ok(Self {
405            agent_id,
406            transport,
407            environment,
408            profile_selection_required: true,
409        })
410    }
411
412    /// Creates the one unprofiled environment overlay authorized by Node-owned
413    /// ContextPack materialization. All generic environment overlays remain
414    /// bound to an explicitly selected native launch profile.
415    pub fn new_context_root(
416        agent_id: AgentId,
417        transport: TransportKind,
418        environment: Vec<EnvMutation>,
419    ) -> Result<Self, NativeLaunchProfileError> {
420        let exact_context_root = match environment.as_slice() {
421            [mutation]
422                if mutation.key == OsStr::new(CONTEXT_ROOT_ENVIRONMENT_KEY)
423                    && mutation.value.as_ref().is_some_and(|value| !value.is_empty()) => true,
424            _ => false,
425        };
426        if !exact_context_root {
427            return Err(NativeLaunchProfileError::EnvironmentOverlaySelectionMissing);
428        }
429        let mut overlay = Self::new(agent_id, transport, environment)?;
430        overlay.profile_selection_required = false;
431        Ok(overlay)
432    }
433
434    /// See [`NativeInstanceLaunchOverlay::append_session_identity`].
435    pub fn append_session_identity(
436        &mut self,
437        environment: Vec<EnvMutation>,
438    ) -> Result<(), NativeLaunchProfileError> {
439        if self.transport != TransportKind::Pty {
440            return Err(NativeLaunchProfileError::UnsupportedTransport);
441        }
442        if !is_session_identity(&environment) {
443            return Err(NativeLaunchProfileError::EnvironmentOverlaySelectionMissing);
444        }
445        let mut merged = self.environment.clone();
446        merged.extend(environment);
447        validate_environment_mutations(&merged)?;
448        self.environment = merged;
449        Ok(())
450    }
451
452    fn into_instance_overlay(self) -> NativeInstanceLaunchOverlay {
453        NativeInstanceLaunchOverlay {
454            agent_id: self.agent_id,
455            transport: self.transport,
456            environment: self.environment,
457            extra_args: Vec::new(),
458            profile_selection_required: self.profile_selection_required,
459        }
460    }
461
462    /// Promote an environment overlay into an instance overlay that also
463    /// carries argv (Codex `-c` network_access first slice merge).
464    pub fn into_instance_with_extra_args(
465        self,
466        extra_args: Vec<OsString>,
467    ) -> Result<NativeInstanceLaunchOverlay, NativeLaunchProfileError> {
468        validate_launch_arguments(&self.agent_id, &extra_args)?;
469        if self.transport != TransportKind::Pty && !extra_args.is_empty() {
470            return Err(NativeLaunchProfileError::InstanceOverlayUnsupportedTransport);
471        }
472        Ok(NativeInstanceLaunchOverlay {
473            agent_id: self.agent_id,
474            transport: self.transport,
475            environment: self.environment,
476            extra_args,
477            profile_selection_required: self.profile_selection_required,
478        })
479    }
480}
481
482impl NativeInstanceLaunchOverlay {
483    /// A PTY overlay carrying only a host-assigned session identity
484    /// ([`SESSION_IDENTITY_ENVIRONMENT_KEYS`]); no native launch profile is required.
485    pub fn new_session_identity(
486        agent_id: AgentId,
487        environment: Vec<EnvMutation>,
488    ) -> Result<Self, NativeLaunchProfileError> {
489        if !is_session_identity(&environment) {
490            return Err(NativeLaunchProfileError::EnvironmentOverlaySelectionMissing);
491        }
492        let mut overlay = Self::new(agent_id, TransportKind::Pty, environment, Vec::new())?;
493        overlay.profile_selection_required = false;
494        Ok(overlay)
495    }
496
497    /// Adds a host-assigned session identity to this overlay without changing whether it needs
498    /// a profile. Refused for other keys, for a key the overlay already sets, and off PTY.
499    pub fn append_session_identity(
500        &mut self,
501        environment: Vec<EnvMutation>,
502    ) -> Result<(), NativeLaunchProfileError> {
503        if self.transport != TransportKind::Pty {
504            return Err(NativeLaunchProfileError::InstanceOverlayUnsupportedTransport);
505        }
506        if !is_session_identity(&environment) {
507            return Err(NativeLaunchProfileError::EnvironmentOverlaySelectionMissing);
508        }
509        let mut merged = self.environment.clone();
510        merged.extend(environment);
511        validate_environment_mutations(&merged)?;
512        self.environment = merged;
513        Ok(())
514    }
515
516    /// Append validated argv (Codex `-c` network_access merge onto an
517    /// existing instance overlay).
518    pub fn append_extra_args(
519        &mut self,
520        extra_args: Vec<OsString>,
521    ) -> Result<(), NativeLaunchProfileError> {
522        if extra_args.is_empty() {
523            return Ok(());
524        }
525        if self.transport != TransportKind::Pty
526            && !is_codex_config_c_overlay_args(&self.agent_id, &extra_args)
527        {
528            return Err(NativeLaunchProfileError::InstanceOverlayUnsupportedTransport);
529        }
530        validate_launch_arguments(&self.agent_id, &extra_args)?;
531        self.extra_args.extend(extra_args);
532        validate_launch_arguments(&self.agent_id, &self.extra_args)?;
533        Ok(())
534    }
535}
536
537impl NativeLaunchProfile {
538    pub fn new(
539        id: NativeLaunchProfileId,
540        agent_id: AgentId,
541        transport: TransportKind,
542        owned_env_keys: Vec<OsString>,
543        resolver: Arc<dyn NativeChildEnvironmentResolver>,
544    ) -> Result<Self, NativeLaunchProfileError> {
545        Self::new_with_contract(
546            id,
547            agent_id,
548            transport,
549            owned_env_keys,
550            resolver,
551            NativeLaunchProfileContract::ExactOwnership,
552        )
553    }
554
555    fn new_with_contract(
556        id: NativeLaunchProfileId,
557        agent_id: AgentId,
558        transport: TransportKind,
559        owned_env_keys: Vec<OsString>,
560        resolver: Arc<dyn NativeChildEnvironmentResolver>,
561        contract: NativeLaunchProfileContract,
562    ) -> Result<Self, NativeLaunchProfileError> {
563        if !matches!(transport, TransportKind::Pty | TransportKind::Pipe) {
564            return Err(NativeLaunchProfileError::UnsupportedTransport);
565        }
566        validate_owned_environment_keys(&owned_env_keys)?;
567        Ok(Self {
568            id,
569            agent_id,
570            transport,
571            owned_env_keys,
572            resolver,
573            contract,
574            one_shot_session_persistence: OneShotSessionPersistence::Ephemeral,
575        })
576    }
577
578    /// Selects whether an exact Codex OneShotText Pipe launch may retain its
579    /// vendor session for later resume.
580    pub fn with_one_shot_session_persistence(
581        mut self,
582        policy: OneShotSessionPersistence,
583    ) -> Result<Self, NativeLaunchProfileError> {
584        if policy == OneShotSessionPersistence::Persist
585            && (self.agent_id.as_str() != "codex" || self.transport != TransportKind::Pipe)
586        {
587            return Err(NativeLaunchProfileError::OneShotSessionPersistenceBindingMismatch);
588        }
589        self.one_shot_session_persistence = policy;
590        Ok(self)
591    }
592
593    pub fn id(&self) -> &NativeLaunchProfileId {
594        &self.id
595    }
596
597    pub fn agent_id(&self) -> &AgentId {
598        &self.agent_id
599    }
600
601    pub fn transport(&self) -> TransportKind {
602        self.transport
603    }
604
605    fn resolve_environment(
606        &self,
607        agent_id: &AgentId,
608        transport: TransportKind,
609    ) -> Result<Vec<EnvMutation>, NativeLaunchProfileError> {
610        if &self.agent_id != agent_id || self.transport != transport {
611            return Err(NativeLaunchProfileError::BindingMismatch);
612        }
613        let environment = self
614            .resolver
615            .resolve_child_environment()
616            .map_err(NativeLaunchProfileError::Resolve)?;
617        validate_resolved_environment(&self.owned_env_keys, &environment)?;
618        self.contract.validate(&environment)?;
619        Ok(environment)
620    }
621}
622
623/// Resolves an exact, declared environment overlay at native spawn dispatch.
624///
625/// Implementations should retain references to secret storage and resolve
626/// values only when called; resolver implementations must not expose them via
627/// `Debug` or error text.
628pub trait NativeChildEnvironmentResolver: Send + Sync + 'static {
629    fn resolve_child_environment(
630        &self,
631    ) -> Result<Vec<EnvMutation>, NativeChildEnvironmentResolveError>;
632}
633
634#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
635pub enum NativeChildEnvironmentResolveError {
636    #[error("native child environment is temporarily unavailable")]
637    TemporarilyUnavailable,
638    #[error("native child environment resolution was denied")]
639    Denied,
640}
641
642#[derive(Debug, Error, Eq, PartialEq)]
643pub enum NativeLaunchProfileError {
644    #[error("native launch profile ID must not be empty")]
645    EmptyId,
646    #[error("native launch profile ID is {len} bytes; maximum is {max}")]
647    IdTooLong { len: usize, max: usize },
648    #[error("native launch profile ID must be a lowercase ASCII slug")]
649    InvalidId,
650    #[error("native launch profiles support PTY and exact OneShotText Pipe transports only")]
651    UnsupportedTransport,
652    #[error("native launch profile must own at least one environment key")]
653    EmptyEnvironmentOwnership,
654    #[error("native launch profile has {count} environment mutations; maximum is {max}")]
655    TooManyEnvironmentMutations { count: usize, max: usize },
656    #[error("native launch profile environment mutation {index} has an invalid key")]
657    InvalidEnvironmentKey { index: usize },
658    #[error("native launch profile environment mutation {index} uses a reserved hook key")]
659    ReservedHookEnvironmentKey { index: usize },
660    #[error("native launch profile environment mutation {index} duplicates an earlier key")]
661    DuplicateEnvironmentKey { index: usize },
662    #[error("native launch profile environment mutation {index} value exceeds {max} bytes")]
663    EnvironmentValueTooLong { index: usize, max: usize },
664    #[error("native launch profile environment mutation {index} has an invalid value")]
665    InvalidEnvironmentValue { index: usize },
666    #[error("native launch profile environment payload exceeds {max} bytes")]
667    EnvironmentPayloadTooLarge { max: usize },
668    #[error("native launch profile resolver returned a key outside its exact ownership set")]
669    EnvironmentOwnershipMismatch,
670    #[error("native launch profile resolver omitted a required environment value")]
671    RequiredEnvironmentValueMissing,
672    #[error("native launch profile resolver returned an invalid fixed environment value")]
673    FixedEnvironmentValueMismatch,
674    #[error("native launch profile capacity is {max}")]
675    ProfileCapacityExceeded { max: usize },
676    #[error("native launch profile '{profile_id}' is not installed")]
677    UnknownProfile { profile_id: NativeLaunchProfileId },
678    #[error("native launch profile does not match the exact agent and transport binding")]
679    BindingMismatch,
680    #[error("persistent one-shot sessions require exact agent 'codex' and Pipe transport")]
681    OneShotSessionPersistenceBindingMismatch,
682    #[error("native instance launch overlay supports PTY, or argv-only Codex -c overlays on ACP")]
683    InstanceOverlayUnsupportedTransport,
684    #[error("native MCP server launch overlay requires PTY or ACP transport and the exact provider binding; saw transport {transport:?}, overlay provider '{overlay_provider}', spawn provider '{spawn_provider}'")]
685    McpServerOverlayBindingMismatch {
686        transport: TransportKind,
687        overlay_provider: AgentId,
688        spawn_provider: AgentId,
689    },
690    #[error("native launch profile selection capacity is {max}")]
691    SelectionCapacityExceeded { max: usize },
692    #[error("native launch environment overlay requires an existing profile selection")]
693    EnvironmentOverlaySelectionMissing,
694    #[error("native launch environment overlay does not match the selected profile binding")]
695    EnvironmentOverlayBindingMismatch,
696    #[error("native launch environment overlay conflicts with a selected profile-owned key")]
697    EnvironmentOverlayKeyConflict,
698    #[error("native launch environment overlay capacity is {max}")]
699    EnvironmentOverlayCapacityExceeded { max: usize },
700    #[error("native instance launch overlay has {count} arguments; maximum is {max}")]
701    TooManyLaunchArguments { count: usize, max: usize },
702    #[error("native instance launch overlay argument {index} is invalid")]
703    InvalidLaunchArgument { index: usize },
704    #[error("native instance launch overlay argument {index} exceeds {max} bytes")]
705    LaunchArgumentTooLong { index: usize, max: usize },
706    #[error("native instance launch overlay argument payload exceeds {max} bytes")]
707    LaunchArgumentsPayloadTooLarge { max: usize },
708    #[error("native instance launch overlay argument {index} conflicts with Claude session, resume, or prompt authority")]
709    ReservedClaudeLaunchArgument { index: usize },
710    #[error("native launch profile is selected by an instance; clear the selection first")]
711    ProfileInUse,
712    #[error(transparent)]
713    Resolve(#[from] NativeChildEnvironmentResolveError),
714    #[error(transparent)]
715    McpServerSpec(#[from] McpServerSpecError),
716}
717
718pub(crate) struct NativeLaunchProfiles {
719    profiles: BTreeMap<NativeLaunchProfileId, NativeLaunchProfile>,
720    selections: BTreeMap<AgentInstanceId, NativeLaunchProfileId>,
721    instance_overlays: BTreeMap<AgentInstanceId, Arc<NativeInstanceLaunchOverlay>>,
722    mcp_server_overlays: BTreeMap<AgentInstanceId, Arc<NativeMcpServerLaunchOverlay>>,
723}
724
725impl NativeLaunchProfiles {
726    pub(crate) fn new() -> Self {
727        Self {
728            profiles: BTreeMap::new(),
729            selections: BTreeMap::new(),
730            instance_overlays: BTreeMap::new(),
731            mcp_server_overlays: BTreeMap::new(),
732        }
733    }
734
735    pub(crate) fn upsert(
736        &mut self,
737        profile: NativeLaunchProfile,
738    ) -> Result<(), NativeLaunchProfileError> {
739        if !self.profiles.contains_key(profile.id())
740            && self.profiles.len() >= NATIVE_LAUNCH_PROFILES_MAX
741        {
742            return Err(NativeLaunchProfileError::ProfileCapacityExceeded {
743                max: NATIVE_LAUNCH_PROFILES_MAX,
744            });
745        }
746        for (instance_id, selected_profile_id) in &self.selections {
747            if selected_profile_id == profile.id() {
748                if let Some(overlay) = self.instance_overlays.get(instance_id) {
749                    validate_instance_overlay_binding(&profile, overlay)?;
750                }
751            }
752        }
753        self.profiles.insert(profile.id.clone(), profile);
754        Ok(())
755    }
756
757    pub(crate) fn remove(
758        &mut self,
759        profile_id: &NativeLaunchProfileId,
760    ) -> Result<bool, NativeLaunchProfileError> {
761        if self
762            .selections
763            .values()
764            .any(|selected_id| selected_id == profile_id)
765        {
766            return Err(NativeLaunchProfileError::ProfileInUse);
767        }
768        Ok(self.profiles.remove(profile_id).is_some())
769    }
770
771    pub(crate) fn select(
772        &mut self,
773        instance_id: AgentInstanceId,
774        profile_id: NativeLaunchProfileId,
775    ) -> Result<(), NativeLaunchProfileError> {
776        let profile = self.profiles.get(&profile_id).ok_or_else(|| {
777            NativeLaunchProfileError::UnknownProfile {
778                profile_id: profile_id.clone(),
779            }
780        })?;
781        if let Some(overlay) = self.instance_overlays.get(&instance_id) {
782            validate_instance_overlay_binding(profile, overlay)?;
783        }
784        if !self.selections.contains_key(&instance_id)
785            && self.selections.len() >= NATIVE_LAUNCH_PROFILE_SELECTIONS_MAX
786        {
787            return Err(NativeLaunchProfileError::SelectionCapacityExceeded {
788                max: NATIVE_LAUNCH_PROFILE_SELECTIONS_MAX,
789            });
790        }
791        self.selections.insert(instance_id, profile_id);
792        Ok(())
793    }
794
795    pub(crate) fn clear_selection(&mut self, instance_id: AgentInstanceId) -> bool {
796        let selection_removed = self.selections.remove(&instance_id).is_some();
797        let overlay_removed = self.instance_overlays.remove(&instance_id).is_some();
798        selection_removed || overlay_removed
799    }
800
801    pub(crate) fn install_environment_overlay(
802        &mut self,
803        instance_id: AgentInstanceId,
804        overlay: NativeLaunchEnvironmentOverlay,
805    ) -> Result<(), NativeLaunchProfileError> {
806        if overlay.profile_selection_required && !self.selections.contains_key(&instance_id) {
807            return Err(NativeLaunchProfileError::EnvironmentOverlaySelectionMissing);
808        }
809        self.install_instance_overlay(instance_id, overlay.into_instance_overlay())
810    }
811
812    pub(crate) fn install_instance_overlay(
813        &mut self,
814        instance_id: AgentInstanceId,
815        overlay: NativeInstanceLaunchOverlay,
816    ) -> Result<(), NativeLaunchProfileError> {
817        if let Some(profile_id) = self.selections.get(&instance_id) {
818            let profile = self.profiles.get(profile_id).ok_or_else(|| {
819                NativeLaunchProfileError::UnknownProfile {
820                    profile_id: profile_id.clone(),
821                }
822            })?;
823            validate_instance_overlay_binding(profile, &overlay)?;
824        } else if overlay.profile_selection_required {
825            return Err(NativeLaunchProfileError::EnvironmentOverlaySelectionMissing);
826        }
827        if !self.instance_overlays.contains_key(&instance_id)
828            && self.instance_overlays.len() >= NATIVE_LAUNCH_PROFILE_SELECTIONS_MAX
829        {
830            return Err(
831                NativeLaunchProfileError::EnvironmentOverlayCapacityExceeded {
832                    max: NATIVE_LAUNCH_PROFILE_SELECTIONS_MAX,
833                },
834            );
835        }
836        self.instance_overlays
837            .insert(instance_id, Arc::new(overlay));
838        Ok(())
839    }
840
841    pub(crate) fn clear_instance_overlay(&mut self, instance_id: AgentInstanceId) -> bool {
842        self.instance_overlays.remove(&instance_id).is_some()
843    }
844
845    pub(crate) fn install_mcp_server_overlay(
846        &mut self,
847        instance_id: AgentInstanceId,
848        overlay: NativeMcpServerLaunchOverlay,
849    ) -> Result<(), NativeLaunchProfileError> {
850        if !self.mcp_server_overlays.contains_key(&instance_id)
851            && self.mcp_server_overlays.len() >= NATIVE_LAUNCH_PROFILE_SELECTIONS_MAX
852        {
853            return Err(NativeLaunchProfileError::EnvironmentOverlayCapacityExceeded {
854                max: NATIVE_LAUNCH_PROFILE_SELECTIONS_MAX,
855            });
856        }
857        self.mcp_server_overlays
858            .insert(instance_id, Arc::new(overlay));
859        Ok(())
860    }
861
862    pub(crate) fn clear_mcp_server_overlay(&mut self, instance_id: AgentInstanceId) -> bool {
863        self.mcp_server_overlays.remove(&instance_id).is_some()
864    }
865
866    fn profile_for_spawn(
867        &self,
868        instance_id: AgentInstanceId,
869        agent_id: &AgentId,
870        transport: TransportKind,
871        pipe_binding_is_exact_one_shot: bool,
872    ) -> Result<Option<NativeLaunchSpawnEnvironment>, NativeLaunchProfileError> {
873        let overlay = self.instance_overlays.get(&instance_id).cloned();
874        let mcp_server_overlay = self.mcp_server_overlays.get(&instance_id).cloned();
875        let profile = if let Some(profile_id) = self.selections.get(&instance_id) {
876            let profile = self
877                .profiles
878                .get(profile_id)
879                .ok_or_else(|| NativeLaunchProfileError::UnknownProfile {
880                    profile_id: profile_id.clone(),
881                })?;
882            if profile.agent_id() != agent_id || profile.transport() != transport {
883                return Err(NativeLaunchProfileError::BindingMismatch);
884            }
885            if transport == TransportKind::Pipe && !pipe_binding_is_exact_one_shot {
886                return Err(NativeLaunchProfileError::UnsupportedTransport);
887            }
888            if let Some(overlay) = &overlay {
889                validate_instance_overlay_binding(profile, overlay)?;
890            }
891            Some(profile.clone())
892        } else {
893            None
894        };
895        if let Some(overlay) = &overlay {
896            validate_instance_overlay_spawn_binding(agent_id, transport, overlay)?;
897            if profile.is_none() && overlay.profile_selection_required {
898                return Err(NativeLaunchProfileError::EnvironmentOverlaySelectionMissing);
899            }
900        }
901        if let Some(mcp_server_overlay) = &mcp_server_overlay {
902            if !matches!(transport, TransportKind::Pty | TransportKind::Acp)
903                || mcp_server_overlay.agent_id != *agent_id
904            {
905                return Err(NativeLaunchProfileError::McpServerOverlayBindingMismatch {
906                    transport,
907                    overlay_provider: mcp_server_overlay.agent_id.clone(),
908                    spawn_provider: agent_id.clone(),
909                });
910            }
911        }
912        if profile.is_none() && overlay.is_none() && mcp_server_overlay.is_none() {
913            return Ok(None);
914        }
915        Ok(Some(NativeLaunchSpawnEnvironment {
916            profile,
917            overlay,
918            mcp_server_overlay,
919        }))
920    }
921}
922
923struct NativeLaunchSpawnEnvironment {
924    profile: Option<NativeLaunchProfile>,
925    overlay: Option<Arc<NativeInstanceLaunchOverlay>>,
926    mcp_server_overlay: Option<Arc<NativeMcpServerLaunchOverlay>>,
927}
928
929pub(crate) struct ResolvedNativeLaunchOverlay {
930    pub(crate) environment: Vec<EnvMutation>,
931    pub(crate) extra_args: Vec<OsString>,
932    pub(crate) one_shot_session_persistence: OneShotSessionPersistence,
933    /// Primary server first; empty when no MCP overlay was prepared.
934    pub(crate) mcp_servers: Vec<McpServerSpec>,
935}
936
937/// Clonable host-local control for selecting profiles without mutable runtime access.
938///
939/// The handle intentionally does not implement `Debug`: its shared registry retains
940/// opaque environment resolvers that may own secret material.
941#[derive(Clone)]
942pub struct NativeLaunchProfileControl {
943    launch_profiles: Arc<Mutex<NativeLaunchProfiles>>,
944}
945
946impl NativeLaunchProfileControl {
947    pub(crate) fn new() -> Self {
948        Self {
949            launch_profiles: Arc::new(Mutex::new(NativeLaunchProfiles::new())),
950        }
951    }
952
953    pub(crate) fn upsert(
954        &self,
955        profile: NativeLaunchProfile,
956    ) -> Result<(), NativeLaunchProfileError> {
957        self.lock().upsert(profile)
958    }
959
960    pub(crate) fn remove(
961        &self,
962        profile_id: &NativeLaunchProfileId,
963    ) -> Result<bool, NativeLaunchProfileError> {
964        self.lock().remove(profile_id)
965    }
966
967    /// Selects a profile for future spawns of one exact instance.
968    ///
969    /// Spawn dispatch snapshots the selection under the same registry lock, so
970    /// a selection change does not alter a child that was already dispatched.
971    pub fn select_native_launch_profile(
972        &self,
973        instance_id: AgentInstanceId,
974        profile_id: NativeLaunchProfileId,
975    ) -> Result<(), NativeLaunchProfileError> {
976        self.lock().select(instance_id, profile_id)
977    }
978
979    /// Clears one instance selection for future spawns only.
980    pub fn clear_native_launch_profile_selection(&self, instance_id: AgentInstanceId) -> bool {
981        self.lock().clear_selection(instance_id)
982    }
983
984    /// Installs or replaces one host-only environment overlay for an exact selection.
985    pub fn install_native_launch_environment_overlay(
986        &self,
987        instance_id: AgentInstanceId,
988        overlay: NativeLaunchEnvironmentOverlay,
989    ) -> Result<(), NativeLaunchProfileError> {
990        self.lock().install_environment_overlay(instance_id, overlay)
991    }
992
993    /// Installs or replaces one host-only PTY launch overlay for an exact instance.
994    ///
995    /// An argv-only overlay does not require an environment profile selection.
996    /// Environment mutations retain the existing exact-selection requirement.
997    pub fn install_native_instance_launch_overlay(
998        &self,
999        instance_id: AgentInstanceId,
1000        overlay: NativeInstanceLaunchOverlay,
1001    ) -> Result<(), NativeLaunchProfileError> {
1002        self.lock().install_instance_overlay(instance_id, overlay)
1003    }
1004
1005    /// Clears one host-only instance launch overlay for future spawns only.
1006    pub fn clear_native_instance_launch_overlay(&self, instance_id: AgentInstanceId) -> bool {
1007        self.lock().clear_instance_overlay(instance_id)
1008    }
1009
1010    /// Installs the dedicated MCP-server launch overlay for one exact future
1011    /// PTY or ACP spawn.
1012    pub fn install_native_mcp_server_launch_overlay(
1013        &self,
1014        instance_id: AgentInstanceId,
1015        overlay: NativeMcpServerLaunchOverlay,
1016    ) -> Result<(), NativeLaunchProfileError> {
1017        self.lock().install_mcp_server_overlay(instance_id, overlay)
1018    }
1019
1020    /// Clears one dedicated MCP-server launch overlay before or after the
1021    /// child lifetime.
1022    pub fn clear_native_mcp_server_launch_overlay(&self, instance_id: AgentInstanceId) -> bool {
1023        self.lock().clear_mcp_server_overlay(instance_id)
1024    }
1025
1026    pub(crate) fn resolve_launch_overlay(
1027        &self,
1028        instance_id: AgentInstanceId,
1029        agent_id: &AgentId,
1030        transport: TransportKind,
1031        pipe_binding_is_exact_one_shot: bool,
1032    ) -> Result<ResolvedNativeLaunchOverlay, NativeLaunchProfileError> {
1033        let spawn_environment = {
1034            self.lock().profile_for_spawn(
1035                instance_id,
1036                agent_id,
1037                transport,
1038                pipe_binding_is_exact_one_shot,
1039            )?
1040        };
1041        let Some(spawn_environment) = spawn_environment else {
1042            return Ok(ResolvedNativeLaunchOverlay {
1043                environment: Vec::new(),
1044                extra_args: Vec::new(),
1045                one_shot_session_persistence: OneShotSessionPersistence::Ephemeral,
1046                mcp_servers: Vec::new(),
1047            });
1048        };
1049        let one_shot_session_persistence = spawn_environment
1050            .profile
1051            .as_ref()
1052            .map_or(OneShotSessionPersistence::Ephemeral, |profile| {
1053                profile.one_shot_session_persistence
1054            });
1055        let mcp_servers = spawn_environment
1056            .mcp_server_overlay
1057            .as_ref()
1058            .map(|overlay| overlay.acp_servers())
1059            .unwrap_or_default();
1060        let mut environment = if let Some(profile) = spawn_environment.profile {
1061            profile.resolve_environment(agent_id, transport)?
1062        } else {
1063            Vec::new()
1064        };
1065        let mut extra_args = Vec::new();
1066        if let Some(overlay) = spawn_environment.overlay {
1067            environment.extend(overlay.environment.iter().cloned());
1068            extra_args.extend(overlay.extra_args.iter().cloned());
1069        }
1070        if let Some(overlay) = spawn_environment.mcp_server_overlay {
1071            environment.extend(overlay.environment.iter().cloned());
1072        }
1073        validate_environment_mutations(&environment)?;
1074        validate_launch_arguments(agent_id, &extra_args)?;
1075        Ok(ResolvedNativeLaunchOverlay {
1076            environment,
1077            extra_args,
1078            one_shot_session_persistence,
1079            mcp_servers,
1080        })
1081    }
1082
1083    fn lock(&self) -> MutexGuard<'_, NativeLaunchProfiles> {
1084        self.launch_profiles
1085            .lock()
1086            .unwrap_or_else(|poisoned| poisoned.into_inner())
1087    }
1088}
1089
1090fn validate_owned_environment_keys(keys: &[OsString]) -> Result<(), NativeLaunchProfileError> {
1091    if keys.is_empty() {
1092        return Err(NativeLaunchProfileError::EmptyEnvironmentOwnership);
1093    }
1094    if keys.len() > NATIVE_LAUNCH_PROFILE_ENV_MUTATIONS_MAX {
1095        return Err(NativeLaunchProfileError::TooManyEnvironmentMutations {
1096            count: keys.len(),
1097            max: NATIVE_LAUNCH_PROFILE_ENV_MUTATIONS_MAX,
1098        });
1099    }
1100    let mut normalized_keys = BTreeSet::new();
1101    for (index, key) in keys.iter().enumerate() {
1102        let Some(key) = key.to_str() else {
1103            return Err(NativeLaunchProfileError::InvalidEnvironmentKey { index });
1104        };
1105        if key.is_empty()
1106            || key.len() > NATIVE_LAUNCH_PROFILE_ENV_KEY_MAX_BYTES
1107            || key.contains(['\0', '='])
1108        {
1109            return Err(NativeLaunchProfileError::InvalidEnvironmentKey { index });
1110        }
1111        let normalized_key = key.to_ascii_uppercase();
1112        if normalized_key.starts_with(RESERVED_HOOK_ENV_PREFIX) {
1113            return Err(NativeLaunchProfileError::ReservedHookEnvironmentKey { index });
1114        }
1115        if !normalized_keys.insert(normalized_key) {
1116            return Err(NativeLaunchProfileError::DuplicateEnvironmentKey { index });
1117        }
1118    }
1119    Ok(())
1120}
1121
1122fn validate_resolved_environment(
1123    owned_keys: &[OsString],
1124    environment: &[EnvMutation],
1125) -> Result<(), NativeLaunchProfileError> {
1126    if owned_keys.len() != environment.len() {
1127        return Err(NativeLaunchProfileError::EnvironmentOwnershipMismatch);
1128    }
1129    validate_owned_environment_keys(
1130        &environment
1131            .iter()
1132            .map(|mutation| mutation.key.clone())
1133            .collect::<Vec<_>>(),
1134    )?;
1135    let owned_keys = owned_keys.iter().cloned().collect::<BTreeSet<_>>();
1136    let resolved_keys = environment
1137        .iter()
1138        .map(|mutation| mutation.key.clone())
1139        .collect::<BTreeSet<_>>();
1140    if owned_keys != resolved_keys {
1141        return Err(NativeLaunchProfileError::EnvironmentOwnershipMismatch);
1142    }
1143    validate_environment_mutations(environment)
1144}
1145
1146fn validate_environment_mutations(
1147    environment: &[EnvMutation],
1148) -> Result<(), NativeLaunchProfileError> {
1149    if environment.len() > NATIVE_LAUNCH_PROFILE_ENV_MUTATIONS_MAX {
1150        return Err(NativeLaunchProfileError::TooManyEnvironmentMutations {
1151            count: environment.len(),
1152            max: NATIVE_LAUNCH_PROFILE_ENV_MUTATIONS_MAX,
1153        });
1154    }
1155    let mut normalized_keys = BTreeSet::new();
1156    let mut total_bytes = 0usize;
1157    for (index, mutation) in environment.iter().enumerate() {
1158        let Some(key) = mutation.key.to_str() else {
1159            return Err(NativeLaunchProfileError::InvalidEnvironmentKey { index });
1160        };
1161        if key.is_empty()
1162            || key.len() > NATIVE_LAUNCH_PROFILE_ENV_KEY_MAX_BYTES
1163            || key.contains(['\0', '='])
1164        {
1165            return Err(NativeLaunchProfileError::InvalidEnvironmentKey { index });
1166        }
1167        let normalized_key = key.to_ascii_uppercase();
1168        if normalized_key.starts_with(RESERVED_HOOK_ENV_PREFIX) {
1169            return Err(NativeLaunchProfileError::ReservedHookEnvironmentKey { index });
1170        }
1171        if !normalized_keys.insert(normalized_key) {
1172            return Err(NativeLaunchProfileError::DuplicateEnvironmentKey { index });
1173        }
1174        total_bytes = total_bytes.saturating_add(os_string_bytes(&mutation.key));
1175        if let Some(value) = &mutation.value {
1176            let value_bytes = os_string_bytes(value);
1177            if contains_nul(value) {
1178                return Err(NativeLaunchProfileError::InvalidEnvironmentValue { index });
1179            }
1180            if value_bytes > NATIVE_LAUNCH_PROFILE_ENV_VALUE_MAX_BYTES {
1181                return Err(NativeLaunchProfileError::EnvironmentValueTooLong {
1182                    index,
1183                    max: NATIVE_LAUNCH_PROFILE_ENV_VALUE_MAX_BYTES,
1184                });
1185            }
1186            total_bytes = total_bytes.saturating_add(value_bytes);
1187        }
1188        if total_bytes > NATIVE_LAUNCH_PROFILE_ENV_TOTAL_MAX_BYTES {
1189            return Err(NativeLaunchProfileError::EnvironmentPayloadTooLarge {
1190                max: NATIVE_LAUNCH_PROFILE_ENV_TOTAL_MAX_BYTES,
1191            });
1192        }
1193    }
1194    Ok(())
1195}
1196
1197fn validate_instance_overlay_binding(
1198    profile: &NativeLaunchProfile,
1199    overlay: &NativeInstanceLaunchOverlay,
1200) -> Result<(), NativeLaunchProfileError> {
1201    validate_instance_overlay_spawn_binding(profile.agent_id(), profile.transport(), overlay)?;
1202    let profile_keys = profile
1203        .owned_env_keys
1204        .iter()
1205        .filter_map(|key| key.to_str())
1206        .map(str::to_ascii_uppercase)
1207        .collect::<BTreeSet<_>>();
1208    if overlay.environment.iter().any(|mutation| {
1209        mutation
1210            .key
1211            .to_str()
1212            .is_some_and(|key| profile_keys.contains(&key.to_ascii_uppercase()))
1213    }) {
1214        return Err(NativeLaunchProfileError::EnvironmentOverlayKeyConflict);
1215    }
1216    Ok(())
1217}
1218
1219fn validate_instance_overlay_spawn_binding(
1220    agent_id: &AgentId,
1221    transport: TransportKind,
1222    overlay: &NativeInstanceLaunchOverlay,
1223) -> Result<(), NativeLaunchProfileError> {
1224    if agent_id != &overlay.agent_id || transport != overlay.transport {
1225        return Err(NativeLaunchProfileError::EnvironmentOverlayBindingMismatch);
1226    }
1227    Ok(())
1228}
1229
1230
1231/// Codex config overlays are `-c` / `key=value` pairs (same channel as
1232/// catalog `windows_wsl_setup_acknowledged=true` and station
1233/// `sandbox_workspace_write.network_access`).
1234fn is_codex_config_c_overlay_args(agent_id: &AgentId, arguments: &[OsString]) -> bool {
1235    if agent_id.as_str() != "codex" || arguments.is_empty() || arguments.len() % 2 != 0 {
1236        return false;
1237    }
1238    arguments.chunks_exact(2).all(|pair| {
1239        pair[0].as_os_str() == "-c"
1240            && pair[1]
1241                .to_str()
1242                .is_some_and(|value| !value.is_empty() && value.contains('=') && !value.contains('\0'))
1243    })
1244}
1245
1246fn validate_launch_arguments(
1247    agent_id: &AgentId,
1248    arguments: &[OsString],
1249) -> Result<(), NativeLaunchProfileError> {
1250    if arguments.len() > NATIVE_INSTANCE_LAUNCH_ARGS_MAX {
1251        return Err(NativeLaunchProfileError::TooManyLaunchArguments {
1252            count: arguments.len(),
1253            max: NATIVE_INSTANCE_LAUNCH_ARGS_MAX,
1254        });
1255    }
1256    let mut total_bytes = 0usize;
1257    for (index, argument) in arguments.iter().enumerate() {
1258        if contains_nul(argument) {
1259            return Err(NativeLaunchProfileError::InvalidLaunchArgument { index });
1260        }
1261        let argument_bytes = os_string_bytes(argument);
1262        if argument_bytes > NATIVE_INSTANCE_LAUNCH_ARG_MAX_BYTES {
1263            return Err(NativeLaunchProfileError::LaunchArgumentTooLong {
1264                index,
1265                max: NATIVE_INSTANCE_LAUNCH_ARG_MAX_BYTES,
1266            });
1267        }
1268        total_bytes = total_bytes.saturating_add(argument_bytes);
1269        if total_bytes > NATIVE_INSTANCE_LAUNCH_ARGS_TOTAL_MAX_BYTES {
1270            return Err(NativeLaunchProfileError::LaunchArgumentsPayloadTooLarge {
1271                max: NATIVE_INSTANCE_LAUNCH_ARGS_TOTAL_MAX_BYTES,
1272            });
1273        }
1274        if agent_id.as_str() == "claude" && is_reserved_claude_launch_argument(argument) {
1275            return Err(NativeLaunchProfileError::ReservedClaudeLaunchArgument { index });
1276        }
1277    }
1278    Ok(())
1279}
1280
1281fn is_reserved_claude_launch_argument(argument: &OsStr) -> bool {
1282    let Some(argument) = argument.to_str() else {
1283        return false;
1284    };
1285    RESERVED_CLAUDE_LAUNCH_FLAGS.iter().any(|reserved| {
1286        argument == *reserved
1287            || (reserved.starts_with("--")
1288                && argument
1289                    .strip_prefix(reserved)
1290                    .is_some_and(|suffix| suffix.starts_with('=')))
1291            || (reserved.len() == 2
1292                && argument
1293                    .strip_prefix(reserved)
1294                    .is_some_and(|suffix| !suffix.is_empty() && !suffix.starts_with('-')))
1295    })
1296}
1297
1298fn validate_zai_glm_claude_environment(
1299    environment: &[EnvMutation],
1300) -> Result<(), NativeLaunchProfileError> {
1301    let token = environment
1302        .iter()
1303        .find(|mutation| mutation.key == OsStr::new("ANTHROPIC_AUTH_TOKEN"))
1304        .and_then(|mutation| mutation.value.as_deref())
1305        .and_then(OsStr::to_str)
1306        .filter(|value| !value.trim().is_empty());
1307    if token.is_none() {
1308        return Err(NativeLaunchProfileError::RequiredEnvironmentValueMissing);
1309    }
1310
1311    let endpoint = environment
1312        .iter()
1313        .find(|mutation| mutation.key == OsStr::new("ANTHROPIC_BASE_URL"))
1314        .and_then(|mutation| mutation.value.as_deref());
1315    if endpoint != Some(OsStr::new(ZAI_GLM_ANTHROPIC_BASE_URL)) {
1316        return Err(NativeLaunchProfileError::FixedEnvironmentValueMismatch);
1317    }
1318    Ok(())
1319}
1320
1321#[cfg(test)]
1322mod session_identity_tests {
1323    use super::*;
1324
1325    fn set(k: &str, v: &str) -> EnvMutation {
1326        EnvMutation { key: k.into(), value: Some(v.into()) }
1327    }
1328    fn codex() -> AgentId {
1329        AgentId::new("codex").unwrap()
1330    }
1331
1332    #[test]
1333    fn identity_overlay_needs_no_profile_and_only_takes_identity_keys() {
1334        let o = NativeInstanceLaunchOverlay::new_session_identity(codex(), vec![set("M4A_NICK", "codex-1"), set("M4A_SESSION_CAP", "ab")]).unwrap();
1335        assert!(!o.profile_selection_required);
1336        assert!(NativeInstanceLaunchOverlay::new_session_identity(codex(), vec![set("PATH", "/x")]).is_err());
1337        assert!(NativeInstanceLaunchOverlay::new_session_identity(codex(), vec![]).is_err());
1338        assert!(NativeInstanceLaunchOverlay::new_session_identity(codex(), vec![set("M4A_NICK", "")]).is_err());
1339    }
1340
1341    #[test]
1342    fn identity_appends_to_an_existing_overlay_without_relaxing_it() {
1343        let mut o = NativeInstanceLaunchOverlay::new(codex(), TransportKind::Pty, vec![set("FOO", "1")], Vec::new()).unwrap();
1344        assert!(o.profile_selection_required);
1345        o.append_session_identity(vec![set("M4A_NICK", "codex-2"), set("M4A_SESSION_CAP", "cd")]).unwrap();
1346        assert!(o.profile_selection_required);
1347        assert_eq!(o.environment.len(), 3);
1348        assert!(o.append_session_identity(vec![set("M4A_NICK", "again")]).is_err(), "duplicate key refused");
1349        assert!(o.append_session_identity(vec![set("HOME", "/h")]).is_err());
1350        let mut e = NativeLaunchEnvironmentOverlay::new(codex(), TransportKind::Pty, vec![set("BAR", "2")]).unwrap();
1351        e.append_session_identity(vec![set("M4A_SESSION_CAP", "ef")]).unwrap();
1352        assert_eq!(e.environment.len(), 2);
1353    }
1354}
1355
1356#[cfg(test)]
1357mod tests {
1358    use super::*;
1359
1360    struct CodexEnvironment;
1361
1362    impl NativeChildEnvironmentResolver for CodexEnvironment {
1363        fn resolve_child_environment(
1364            &self,
1365        ) -> Result<Vec<EnvMutation>, NativeChildEnvironmentResolveError> {
1366            Ok(vec![EnvMutation {
1367                key: OsString::from("GATE4AGENT_TEST_CODEX_PROFILE"),
1368                value: Some(OsString::from("selected")),
1369            }])
1370        }
1371    }
1372
1373    fn persistent_codex_profile() -> NativeLaunchProfile {
1374        NativeLaunchProfile::new(
1375            NativeLaunchProfileId::new("persistent-codex").unwrap(),
1376            AgentId::new("codex").unwrap(),
1377            TransportKind::Pipe,
1378            vec![OsString::from("GATE4AGENT_TEST_CODEX_PROFILE")],
1379            Arc::new(CodexEnvironment),
1380        )
1381        .unwrap()
1382        .with_one_shot_session_persistence(OneShotSessionPersistence::Persist)
1383        .unwrap()
1384    }
1385
1386    #[test]
1387    fn selected_persistence_is_snapshotted_and_clear_restores_ephemeral_default() {
1388        let control = NativeLaunchProfileControl::new();
1389        let profile = persistent_codex_profile();
1390        let profile_id = profile.id().clone();
1391        control.upsert(profile).unwrap();
1392        let selected = AgentInstanceId(1);
1393        control
1394            .select_native_launch_profile(selected, profile_id)
1395            .unwrap();
1396
1397        let resolved = control
1398            .resolve_launch_overlay(
1399                selected,
1400                &AgentId::new("codex").unwrap(),
1401                TransportKind::Pipe,
1402                true,
1403            )
1404            .unwrap();
1405        assert_eq!(
1406            resolved.one_shot_session_persistence,
1407            OneShotSessionPersistence::Persist
1408        );
1409
1410        assert!(control.clear_native_launch_profile_selection(selected));
1411        let cleared = control
1412            .resolve_launch_overlay(
1413                selected,
1414                &AgentId::new("codex").unwrap(),
1415                TransportKind::Pipe,
1416                true,
1417            )
1418            .unwrap();
1419        assert_eq!(
1420            cleared.one_shot_session_persistence,
1421            OneShotSessionPersistence::Ephemeral
1422        );
1423
1424        let unselected = control
1425            .resolve_launch_overlay(
1426                AgentInstanceId(2),
1427                &AgentId::new("codex").unwrap(),
1428                TransportKind::Pipe,
1429                true,
1430            )
1431            .unwrap();
1432        assert_eq!(
1433            unselected.one_shot_session_persistence,
1434            OneShotSessionPersistence::Ephemeral
1435        );
1436    }
1437
1438    /// A caller-supplied MCP-server overlay spec, generic on `agent_id` --
1439    /// mirrors what `hatchery-node` builds today (name `"hatchery"`,
1440    /// `--session-proxy`, endpoint/token/trace env entries, and the two
1441    /// legacy `GATE4AGENT_HARNESS_READ_*` names as removals), but under a
1442    /// caller-chosen name and env keys this crate never interprets.
1443    fn sample_mcp_server_overlay(agent_id: &str) -> NativeMcpServerLaunchOverlay {
1444        NativeMcpServerLaunchOverlay::new(
1445            AgentId::new(agent_id).unwrap(),
1446            "test-mcp-server",
1447            OsString::from("reviewed-program"),
1448            vec![OsString::from("--session-proxy")],
1449            vec![
1450                (
1451                    OsString::from("TEST_MCP_SESSION_ENDPOINT"),
1452                    OsString::from("private-endpoint"),
1453                ),
1454                (
1455                    OsString::from("TEST_MCP_SESSION_TOKEN"),
1456                    OsString::from("private-token"),
1457                ),
1458            ],
1459            vec![
1460                OsString::from("TEST_MCP_LEGACY_ENDPOINT"),
1461                OsString::from("TEST_MCP_LEGACY_CREDENTIAL"),
1462            ],
1463        )
1464        .unwrap()
1465    }
1466
1467    #[test]
1468    fn mcp_server_overlay_sets_given_environment_and_scrubs_given_removals() {
1469        let control = NativeLaunchProfileControl::new();
1470        let instance_id = AgentInstanceId(41);
1471        control
1472            .install_native_mcp_server_launch_overlay(instance_id, sample_mcp_server_overlay("codex"))
1473            .unwrap();
1474        let resolved = control
1475            .resolve_launch_overlay(
1476                instance_id,
1477                &AgentId::new("codex").unwrap(),
1478                TransportKind::Pty,
1479                true,
1480            )
1481            .unwrap();
1482        assert_eq!(resolved.environment.len(), 4);
1483        for key in ["TEST_MCP_LEGACY_ENDPOINT", "TEST_MCP_LEGACY_CREDENTIAL"] {
1484            assert!(resolved.environment.iter().any(|mutation| {
1485                mutation.key == OsString::from(key) && mutation.value.is_none()
1486            }));
1487        }
1488        for key in ["TEST_MCP_SESSION_ENDPOINT", "TEST_MCP_SESSION_TOKEN"] {
1489            assert!(resolved.environment.iter().any(|mutation| {
1490                mutation.key == OsString::from(key) && mutation.value.is_some()
1491            }));
1492        }
1493        assert_eq!(resolved.mcp_servers.len(), 1);
1494        let mcp_server = resolved
1495            .mcp_servers
1496            .into_iter()
1497            .next()
1498            .expect("mcp server spec resolved for this spawn");
1499        assert_eq!(mcp_server.name(), "test-mcp-server");
1500        assert_eq!(mcp_server.program(), OsStr::new("reviewed-program"));
1501        assert_eq!(mcp_server.args(), &[OsString::from("--session-proxy")]);
1502        assert_eq!(mcp_server.env().len(), 2, "exactly the two entries given, never the removals");
1503    }
1504
1505    #[test]
1506    fn mcp_server_overlay_admits_acp_transport_for_the_same_provider() {
1507        let control = NativeLaunchProfileControl::new();
1508        let instance_id = AgentInstanceId(42);
1509        control
1510            .install_native_mcp_server_launch_overlay(instance_id, sample_mcp_server_overlay("claude"))
1511            .unwrap();
1512        let resolved = control
1513            .resolve_launch_overlay(
1514                instance_id,
1515                &AgentId::new("claude").unwrap(),
1516                TransportKind::Acp,
1517                true,
1518            )
1519            .unwrap();
1520        assert_eq!(resolved.environment.len(), 4);
1521        assert_eq!(resolved.mcp_servers.len(), 1);
1522    }
1523
1524    fn extra_spec(name: &str, program: &str) -> McpServerSpec {
1525        McpServerSpec::new(
1526            name,
1527            OsString::from(program),
1528            vec![OsString::from("serve")],
1529            vec![(OsString::from("EXTRA_ONLY_KEY"), OsString::from("extra-value"))],
1530        )
1531        .unwrap()
1532    }
1533
1534    #[test]
1535    fn mcp_server_overlay_carries_additional_acp_servers_in_order() {
1536        let control = NativeLaunchProfileControl::new();
1537        let instance_id = AgentInstanceId(45);
1538        let overlay = sample_mcp_server_overlay("claude")
1539            .with_additional_acp_server(extra_spec("mind", "mind4agent"))
1540            .with_additional_acp_server(extra_spec("d2b", "d2b-mcp"))
1541            // same name as the primary: ignored
1542            .with_additional_acp_server(extra_spec("test-mcp-server", "impostor"))
1543            // same name as an earlier extra: replaces it in place
1544            .with_additional_acp_server(extra_spec("mind", "mind4agent-v2"));
1545        assert_eq!(overlay.acp_server_names(), vec!["test-mcp-server", "mind", "d2b"]);
1546        control
1547            .install_native_mcp_server_launch_overlay(instance_id, overlay)
1548            .unwrap();
1549        let resolved = control
1550            .resolve_launch_overlay(
1551                instance_id,
1552                &AgentId::new("claude").unwrap(),
1553                TransportKind::Acp,
1554                true,
1555            )
1556            .unwrap();
1557        let names: Vec<&str> = resolved.mcp_servers.iter().map(McpServerSpec::name).collect();
1558        assert_eq!(names, vec!["test-mcp-server", "mind", "d2b"]);
1559        assert_eq!(resolved.mcp_servers[0].program(), OsStr::new("reviewed-program"));
1560        assert_eq!(resolved.mcp_servers[1].program(), OsStr::new("mind4agent-v2"));
1561        // extras never leak into the child's OS environment
1562        assert_eq!(resolved.environment.len(), 4);
1563        assert!(!resolved
1564            .environment
1565            .iter()
1566            .any(|mutation| mutation.key == OsString::from("EXTRA_ONLY_KEY")));
1567    }
1568
1569    #[test]
1570    fn mcp_server_overlay_refuses_acp_transport_for_a_different_provider() {
1571        let control = NativeLaunchProfileControl::new();
1572        let instance_id = AgentInstanceId(43);
1573        control
1574            .install_native_mcp_server_launch_overlay(instance_id, sample_mcp_server_overlay("codex"))
1575            .unwrap();
1576        let result = control.resolve_launch_overlay(
1577            instance_id,
1578            &AgentId::new("claude").unwrap(),
1579            TransportKind::Acp,
1580            true,
1581        );
1582        match result {
1583            Ok(_) => panic!("expected the MCP server overlay gate to refuse a mismatched provider"),
1584            Err(error) => assert_eq!(
1585                error,
1586                NativeLaunchProfileError::McpServerOverlayBindingMismatch {
1587                    transport: TransportKind::Acp,
1588                    overlay_provider: AgentId::new("codex").unwrap(),
1589                    spawn_provider: AgentId::new("claude").unwrap(),
1590                }
1591            ),
1592        }
1593    }
1594
1595    #[test]
1596    fn mcp_server_overlay_refuses_pipe_transport_by_name() {
1597        let control = NativeLaunchProfileControl::new();
1598        let instance_id = AgentInstanceId(44);
1599        control
1600            .install_native_mcp_server_launch_overlay(instance_id, sample_mcp_server_overlay("codex"))
1601            .unwrap();
1602        let result = control.resolve_launch_overlay(
1603            instance_id,
1604            &AgentId::new("codex").unwrap(),
1605            TransportKind::Pipe,
1606            true,
1607        );
1608        match result {
1609            Ok(_) => panic!("expected the MCP server overlay gate to refuse Pipe transport"),
1610            Err(error) => assert_eq!(
1611                error,
1612                NativeLaunchProfileError::McpServerOverlayBindingMismatch {
1613                    transport: TransportKind::Pipe,
1614                    overlay_provider: AgentId::new("codex").unwrap(),
1615                    spawn_provider: AgentId::new("codex").unwrap(),
1616                }
1617            ),
1618        }
1619    }
1620}
1621
1622fn os_string_bytes(value: &OsStr) -> usize {
1623    value.to_string_lossy().len()
1624}
1625
1626fn contains_nul(value: &OsStr) -> bool {
1627    value.to_string_lossy().contains('\0')
1628}
1629
1630#[cfg(test)]
1631mod session_identity_keys_tests {
1632    use super::*;
1633
1634    fn m(k: &str) -> EnvMutation {
1635        EnvMutation { key: k.into(), value: Some("v".into()) }
1636    }
1637
1638    #[test]
1639    fn account_client_settings_ride_with_the_identity_but_nothing_else_does() {
1640        let agent = AgentId::new("codex").unwrap();
1641        assert!(NativeInstanceLaunchOverlay::new_session_identity(
1642            agent.clone(),
1643            vec![m("M4A_NICK"), m("M4A_SESSION_CAP"), m("M4A_STORE_ROOT"), m("M4A_BOT_NAME"), m("M4A_PRODUCT_URL")],
1644        )
1645        .is_ok());
1646        assert!(NativeInstanceLaunchOverlay::new_session_identity(agent, vec![m("M4A_NICK"), m("OPENAI_API_KEY")]).is_err());
1647    }
1648}