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