Skip to main content

gate4agent_shell_native/
lib.rs

1//! Native effect execution for gate4agent control-plane sessions.
2
3mod efficiency;
4mod provider_supervisor;
5
6pub use efficiency::ShellEfficiencyFacts;
7// Re-exported so a caller of `ShellEfficiencyFacts::record_foreground_probe`
8// (e.g. `gate4agent-runtime-native`, which does not itself depend on the
9// `gate4agent` crate) can name the type of the value it is handing in
10// without picking up a new dependency edge for it.
11pub use gate4agent::pty::ForegroundProbeTiming;
12pub use provider_supervisor::{
13    NativeProviderExecutor, NativeProviderExit, NativeProviderOperation,
14    NativeProviderOperationError, NativeProviderResultPoll, PhysicalExitAck,
15    ProviderOperationKey, ProviderOperationSnapshot, ProviderSupervisor,
16    ProviderSupervisorBuildError, ProviderSupervisorFault, ProviderSupervisorFaultKind,
17    ProviderStopCause, ProviderSupervisorSnapshot, ProviderSupervisorState,
18    ProviderSupervisorTick, DEFAULT_PROVIDER_STOP_GRACE,
19    MAX_PROVIDER_FORCE_STOP_ATTEMPTS, MAX_PROVIDER_STOP_SIGNAL_ATTEMPTS,
20    MAX_PROVIDER_SUPERVISOR_EVENTS, MAX_PROVIDER_SUPERVISOR_OPERATIONS,
21    MAX_PROVIDER_SUPERVISOR_OUTCOMES_PER_TICK, MAX_PROVIDER_SUPERVISOR_TOMBSTONES,
22    MAX_PROVIDER_SUPERVISOR_WORK_PER_TICK,
23};
24
25use gate4agent::acp::protocol::{McpServerConfig, SessionMode};
26use gate4agent::agent::{is_agent_foreground_wrapper, is_expected_agent_process, ReadinessStatus};
27use gate4agent::pty::cli::codex::strip_ansi_codes;
28use gate4agent::pty::cli::{create_pipeline, ClassificationPipeline, MessageClass, ParsedMessage};
29use gate4agent::pty::event::PtyMouseProtocolEncoding;
30use gate4agent::pty::{
31    PtyAttachment, PtyEvent, PtyEventEnvelope, PtyEventReceiver, PtyForegroundObservation,
32    PtyReplayCursor, PtySession, PtyTerminalSnapshot, RateLimitDetector, VteParser,
33};
34use gate4agent::{
35    AcpSession, AcpSessionOptions, AgentEvent, CliTool, HostDecisionAuthority, HostPolicy,
36    HostRequestDecision, HostRequestOutcome, LaunchRequest, OperatorPermissionChoice,
37    PipeProcessOptions, PipeSession, PromptFraming,
38    ReadinessIntent, ReadinessPermit, ReadinessTracker, RpcId, RuntimePlatform, SessionConfig,
39    StopReason,
40};
41use gate4agent_adapters::{
42    build_resume_plan_for_identity, builtin_adapter_registry, AdapterRuntimeRegistry,
43    CodexPtySessionIdentityExtractor, KimiPtySessionIdentityExtractor, OneShotSessionPersistence,
44};
45use gate4agent_catalog::{
46    acp_full_auto_is_host_policy, approval_level_resolution, ApprovalLevelResolution,
47    AgentRegistry, AgentSpec, EnvMutation,
48    McpServerSpec, ModeId,
49};
50use gate4agent_shell_one_shot::NativeOneShotSession;
51use gate4agent_types::{
52    AdapterFamily, AgentCommand, AgentId, AgentInstanceId, ApprovalLevel, CapabilityProbeFailure,
53    ContextWindowUsage as ProviderContextWindowUsage, ControlEffect,
54    ControlObservation, EffectEnvelope, ForegroundProcess, ForegroundProcessKind,
55    ForegroundRequirement, HostDecisionAuthority as ProviderHostDecisionAuthority,
56    HostRequestDecision as ProviderHostRequestDecision,
57    HostRequestOutcome as ProviderHostRequestOutcome, InputAction, ObservationEnvelope,
58    OperationId, OperatorGateInput,
59    OperatorGateKind, OperatorGateOption, OperatorGateOptionSemantics, OperatorGateState,
60    OperatorGateSubject, PipeProtocol,
61    PreparedInputKind, PromptPayload, ProviderAvailableCommand, ProviderConfigChoice,
62    ProviderConfigOption, ProviderConfigOptionKind, ProviderEvent, ProviderInteractionKind,
63    ProviderInteractionOption, ProviderInteractionResponse, ProviderInteractionTarget,
64    ProviderModeInfo, ProviderPlanPriority,
65    ProviderPlanStatus, ProviderPlanStep,
66    ProviderRateLimitKind, ProviderRuntimeCapability, ProviderRuntimePolicy,
67    ProviderSessionIdentity, ProviderSessionKey, ProviderStopReason,
68    ProviderSource, PtyScreenState, ResumeLaunchRequest, SessionGeneration, StartRequest,
69    TerminalFrame, TerminalMouseProtocolEncoding, TerminalSize, TokenUsage, TransportKind,
70    OPERATOR_GATE_OPTIONS_MAX, WORKING_DIRECTORY_MAX_BYTES,
71};
72use std::collections::{BTreeMap, VecDeque};
73use std::ffi::{OsStr, OsString};
74use std::path::PathBuf;
75use std::sync::Mutex;
76use std::time::{Duration, Instant};
77use tokio::sync::broadcast;
78use uuid::Uuid;
79
80const INSTANCE_LAUNCH_ARGS_MAX: usize = 128;
81const INSTANCE_LAUNCH_ARG_MAX_BYTES: usize = 65_536;
82const INSTANCE_LAUNCH_ARGS_TOTAL_MAX_BYTES: usize = 262_144;
83const RESERVED_CLAUDE_LAUNCH_FLAGS: &[&str] = &[
84    "--continue",
85    "--print",
86    "--prompt",
87    "--prompt-interactive",
88    "--resume",
89    "--session-id",
90    "-c",
91    "-p",
92    "-r",
93];
94
95/// Translates a resolved [`McpServerSpec`] into the one ACP `session/new`
96/// stdio entry the agent should register
97/// (`gate4agent::acp::protocol::McpServerConfig`). This is the ACP half of
98/// the same door a PTY child gets by installing the identical spec's `env`
99/// pairs into its own OS environment instead
100/// (`gate4agent-runtime-native::launch_profiles::NativeMcpServerLaunchOverlay`):
101/// the spec is resolved once, in-process, by `gate4agent-runtime-native` and
102/// handed down here as a typed value through `NativeSpawnOverlay`/
103/// `NativeEffectRequest` -- never a wire type, and never re-read out of a
104/// well-known environment key. This crate cannot depend on
105/// `gate4agent-runtime-native` (the dependency runs the other way), which is
106/// why the spec type itself lives one level below both, in
107/// `gate4agent-catalog`.
108///
109/// Server naming, program path, args, and every environment entry are
110/// entirely the caller's concern; this function does not interpret them.
111fn mcp_server_acp_entry(spec: &McpServerSpec) -> McpServerConfig {
112    McpServerConfig::stdio(
113        spec.name().to_owned(),
114        spec.program().to_string_lossy().into_owned(),
115        spec.args()
116            .iter()
117            .map(|arg| arg.to_string_lossy().into_owned())
118            .collect::<Vec<_>>(),
119        spec.env()
120            .iter()
121            .map(|(key, value)| (key.to_string_lossy().into_owned(), value.to_string_lossy().into_owned()))
122            .collect::<Vec<_>>(),
123    )
124}
125
126#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
127pub struct NativeSessionKey {
128    pub instance_id: AgentInstanceId,
129    pub generation: SessionGeneration,
130}
131
132struct NativeSpawnRequest {
133    agent_id: AgentId,
134    transport: TransportKind,
135    request: StartRequest,
136    runtime_policy: ProviderRuntimePolicy,
137    launch_extra_args: Vec<OsString>,
138    instance_extra_args: Vec<OsString>,
139    resumed_provider_session: Option<gate4agent_types::ProviderSessionIdentity>,
140    one_shot_session_persistence: OneShotSessionPersistence,
141}
142
143struct OwnedPtySession {
144    session: PtySession,
145    spawn_operation_id: OperationId,
146    last_terminal_sequence: u64,
147    terminal_stale_published: bool,
148    runtime_policy: ProviderRuntimePolicy,
149    provider: Option<OwnedPtyProvider>,
150    /// Set once at the spawn site and never mutated -- this is what lets
151    /// `reclassify_foreground` resolve the session's `AgentSpec` from
152    /// `NativeEffectShell::catalog` without holding a borrow of `session`
153    /// across the same loop iteration it awaits `observe_foreground` on.
154    agent_id: AgentId,
155    last_screen_gate: Option<OperatorGateState>,
156    last_screen_failure: Option<&'static str>,
157    last_foreground_verdict: Option<ForegroundVerdict>,
158    last_screen_state: PtyScreenState,
159    /// Whether this generation's merged state has ever been `Ready` WITH
160    /// something on screen. Text crash/missing-command markers are only
161    /// trustworthy before this flips -- see the gate in
162    /// `collect_terminal_frames`. The screen-content half is load-bearing:
163    /// `Ready` is proved by foreground process identity and so arrives
164    /// within a frame or two of spawn, while the terminal is still blank,
165    /// and arming on a blank frame retires the failure detector before any
166    /// failure text can exist. Never reset in place; a new generation gets
167    /// a fresh `OwnedPtySession`, so `false` is simply this field's initial
168    /// value at the spawn site.
169    ever_reached_ready: bool,
170    /// Whether any frame of this generation has carried non-blank screen
171    /// text yet. Read by the process-only path in `reclassify_foreground`,
172    /// which has no snapshot of its own to test and would otherwise arm
173    /// `ever_reached_ready` on a blank screen.
174    screen_had_content: bool,
175    /// `None` means disarmed -- the session reached `Ready` and stays
176    /// unprobed until its text disagrees again. See
177    /// `NativeEffectShell::reclassify_foreground` for the cadence this
178    /// drives.
179    next_foreground_probe: Option<Instant>,
180}
181
182struct OwnedPtyProvider {
183    source: ProviderSource,
184    receiver: PtyEventReceiver,
185    replay: VecDeque<PtyEventEnvelope>,
186    pending_events: VecDeque<ProviderEvent>,
187    utf8: Utf8ChunkDecoder,
188    pipeline: Mutex<ClassificationPipeline>,
189    rate_limits: RateLimitFeed,
190    kimi_identity: Option<KimiPtySessionIdentityExtractor>,
191    semantic_events: bool,
192    provider_session_started: bool,
193    next_provider_sequence: u64,
194}
195
196/// Buffers ANSI-stripped PTY output across output chunks before running
197/// rate-limit detection over it.
198///
199/// PTY reads are chunked arbitrarily -- neither the OS nor this crate's
200/// own reader loop promises "one call per terminal row" or even "one call
201/// per escape sequence". Two separate problems follow from that, and this
202/// type exists to solve both rather than hoping a caller's chunk
203/// boundaries are ever polite:
204///
205/// - An ANSI escape sequence split across two chunks must still be
206///   recognized as one escape, not leak its tail bytes into the visible
207///   text as a false line-break in the middle of `\x1b[m`. `VteParser`
208///   already solves this -- its own `vte::Parser` state machine persists
209///   across calls, so an escape completes correctly regardless of where
210///   a chunk boundary falls -- this type just keeps ONE `VteParser` alive
211///   for the provider's whole lifetime instead of a fresh, stateless one
212///   per chunk (which would forget an escape's first half).
213/// - A LOGICAL LINE (e.g. codex's `/status` quota-state row) can itself
214///   be split across chunks at a point that is not inside any escape.
215///   `VteParser::parse` only returns the printable text produced by the
216///   bytes handed to THAT call, so two separate calls can each return one
217///   half of the same row, and neither half alone matches the quota-state
218///   pattern. This type accumulates cleaned text across calls and runs
219///   detection over everything seen so far, keeping whatever has not yet
220///   been confirmed complete (the tail after the last newline) instead of
221///   discarding a still-forming row.
222struct RateLimitFeed {
223    detector: RateLimitDetector,
224    vte: VteParser,
225    buffer: String,
226}
227
228impl RateLimitFeed {
229    fn new_for_tool(tool: CliTool) -> Self {
230        Self {
231            detector: RateLimitDetector::new_for_tool(tool),
232            vte: VteParser::new(),
233            buffer: String::new(),
234        }
235    }
236
237    /// Strip ANSI from one more raw PTY chunk, fold it into the pending
238    /// line buffer, and run detection over everything accumulated so far
239    /// -- not just the newest chunk, since a match can straddle a chunk
240    /// boundary. Lines already terminated by `\n` are then dropped from
241    /// the buffer regardless of whether they matched: a later chunk
242    /// cannot retroactively extend a row that has already ended. The
243    /// unterminated tail (a row still in progress) is always kept -- but
244    /// see `RATE_LIMIT_FEED_BUFFER_MAX_BYTES` for what happens when that
245    /// tail itself grows unreasonably large.
246    fn detect(&mut self, raw: &str) -> Option<gate4agent::core::types::RateLimitInfo> {
247        let cleaned = self.vte.parse(raw);
248        self.buffer.push_str(&cleaned);
249        let info = self.detector.detect(&self.buffer);
250        if let Some(last_newline) = self.buffer.rfind('\n') {
251            self.buffer.drain(..=last_newline);
252        } else if self.buffer.len() > RATE_LIMIT_FEED_BUFFER_MAX_BYTES {
253            // A full-screen redraw (codex's main screen, not `/status`)
254            // can run for a long time using only cursor-addressing escapes
255            // and never emit a `\n` at all, so "no newline yet" cannot be
256            // trusted to mean "a row is still in progress" indefinitely.
257            // No real quota-state or refusal line approaches this length;
258            // past it, keep only the tail so an indefinitely long redraw
259            // cannot grow this buffer for the life of the session.
260            let mut cut = self.buffer.len() - RATE_LIMIT_FEED_BUFFER_MAX_BYTES;
261            while !self.buffer.is_char_boundary(cut) {
262                cut += 1;
263            }
264            self.buffer.drain(..cut);
265        }
266        info
267    }
268}
269
270/// Well past the longest quota-state or refusal line this detector
271/// recognizes (all under 200 bytes); see `RateLimitFeed::detect`.
272const RATE_LIMIT_FEED_BUFFER_MAX_BYTES: usize = 8192;
273
274#[derive(Default)]
275struct Utf8ChunkDecoder {
276    pending: Vec<u8>,
277}
278
279impl Utf8ChunkDecoder {
280    fn push(&mut self, bytes: &[u8]) -> String {
281        self.pending.extend_from_slice(bytes);
282        let mut decoded = String::new();
283        loop {
284            match std::str::from_utf8(&self.pending) {
285                Ok(text) => {
286                    decoded.push_str(text);
287                    self.pending.clear();
288                    break;
289                }
290                Err(error) => {
291                    let valid = error.valid_up_to();
292                    if valid > 0 {
293                        let text = std::str::from_utf8(&self.pending[..valid])
294                            .expect("validated UTF-8 prefix");
295                        decoded.push_str(text);
296                        self.pending.drain(..valid);
297                        continue;
298                    }
299                    let Some(invalid) = error.error_len() else {
300                        break;
301                    };
302                    decoded.push('\u{fffd}');
303                    self.pending.drain(..invalid.min(self.pending.len()));
304                }
305            }
306        }
307        decoded
308    }
309
310    fn clear(&mut self) {
311        self.pending.clear();
312    }
313}
314
315struct OwnedProviderSession<S> {
316    source: ProviderSource,
317    session: S,
318    events: broadcast::Receiver<AgentEvent>,
319    pending_events: VecDeque<AgentEvent>,
320    /// Already wire-typed `ProviderEvent`s seeded at the spawn site with no
321    /// `AgentEvent` counterpart to carry them through `pending_events` --
322    /// today, only `ProviderEvent::SessionIdentityObserved` for a freshly
323    /// spawned ACP session (see the `TransportKind::Acp` arm of
324    /// `spawn_native`). Drained by `drain_provider_stream` immediately after
325    /// `pending_events` empties and before the live broadcast stream, so an
326    /// event seeded here lands right after whatever `pending_events` seeded
327    /// (`AgentEvent::SessionStart`, chiefly) rather than racing it.
328    pending_provider_events: VecDeque<ProviderEvent>,
329    next_provider_sequence: u64,
330    observed_exit_code: Option<i32>,
331    runtime_policy: ProviderRuntimePolicy,
332}
333
334/// Executes native effects and returns exactly one completion observation for
335/// each accepted effect. Logical lifecycle state remains owned by the engine.
336pub struct NativeEffectShell {
337    catalog: AgentRegistry,
338    legacy_adapters: AdapterRuntimeRegistry<CliTool>,
339    pty_sessions: BTreeMap<NativeSessionKey, OwnedPtySession>,
340    pipe_sessions: BTreeMap<NativeSessionKey, OwnedProviderSession<PipeSession>>,
341    one_shot_sessions: BTreeMap<NativeSessionKey, OwnedProviderSession<NativeOneShotSession>>,
342    acp_sessions: BTreeMap<NativeSessionKey, OwnedProviderSession<AcpSession>>,
343    pending_observations: VecDeque<ObservationEnvelope>,
344    /// Plain efficiency facts from `collect_terminal_frames` and
345    /// `reclassify_foreground` -- see `ShellEfficiencyFacts`'s own doc
346    /// comment for why this crate stops at plain facts rather than
347    /// computing a distribution itself.
348    efficiency_facts: ShellEfficiencyFacts,
349}
350
351impl NativeEffectShell {
352    pub fn new(catalog: AgentRegistry) -> Self {
353        Self::new_with_runtime_adapters(catalog, builtin_legacy_adapter_runtimes())
354    }
355
356    /// Builds a native shell with consumer-provided compatibility runtimes.
357    ///
358    /// The runtime registry is deliberately separate from the declarative
359    /// catalog: both the adapter family and revision must resolve before a
360    /// process is spawned.
361    pub fn new_with_runtime_adapters(
362        catalog: AgentRegistry,
363        legacy_adapters: AdapterRuntimeRegistry<CliTool>,
364    ) -> Self {
365        Self {
366            catalog,
367            legacy_adapters,
368            pty_sessions: BTreeMap::new(),
369            pipe_sessions: BTreeMap::new(),
370            one_shot_sessions: BTreeMap::new(),
371            acp_sessions: BTreeMap::new(),
372            pending_observations: VecDeque::new(),
373            efficiency_facts: ShellEfficiencyFacts::default(),
374        }
375    }
376
377    /// Hand the caller everything `collect_terminal_frames` and
378    /// `reclassify_foreground` recorded since the last call, and reset the
379    /// facts back to empty. Called once per worker-loop iteration by
380    /// `gate4agent-runtime-native::publish_shell_observations`, the only
381    /// place with somewhere to fold these into a distribution.
382    pub fn take_efficiency_facts(&mut self) -> ShellEfficiencyFacts {
383        self.efficiency_facts.take()
384    }
385
386    pub fn active_session_count(&self) -> usize {
387        self.pty_sessions.len()
388            + self.pipe_sessions.len()
389            + self.one_shot_sessions.len()
390            + self.acp_sessions.len()
391    }
392
393    pub fn spawn_operation_id(&self, key: NativeSessionKey) -> Option<OperationId> {
394        self.pty_sessions
395            .get(&key)
396            .map(|owned| owned.spawn_operation_id)
397    }
398
399    pub fn terminal_snapshot(&self, key: NativeSessionKey) -> Result<PtyTerminalSnapshot, String> {
400        self.pty_sessions
401            .get(&key)
402            .ok_or_else(|| missing_session_message(key))?
403            .session
404            .terminal_snapshot()
405            .map_err(|error| error.to_string())
406    }
407
408    pub async fn execute(&mut self, envelope: EffectEnvelope) -> ObservationEnvelope {
409        self.execute_with_environment(envelope, Vec::new()).await
410    }
411
412    /// Backward-compatible name for PTY-only callers. OneShot launches now
413    /// receive the same shell-owned mutations.
414    pub async fn execute_with_pty_env(
415        &mut self,
416        envelope: EffectEnvelope,
417        pty_env: Vec<EnvMutation>,
418    ) -> ObservationEnvelope {
419        self.execute_with_environment(envelope, pty_env).await
420    }
421
422    /// Execute an effect with shell-owned environment injected only into a
423    /// newly spawned provider process. The canonical start request cannot set
424    /// these authority variables itself.
425    pub async fn execute_with_environment(
426        &mut self,
427        envelope: EffectEnvelope,
428        environment: Vec<EnvMutation>,
429    ) -> ObservationEnvelope {
430        self.execute_with_launch_overlay(envelope, environment, Vec::new())
431            .await
432    }
433
434    /// Execute an effect with host-only environment and optional PTY argv
435    /// applied only to a newly spawned provider process.
436    pub async fn execute_with_launch_overlay(
437        &mut self,
438        envelope: EffectEnvelope,
439        environment: Vec<EnvMutation>,
440        extra_args: Vec<OsString>,
441    ) -> ObservationEnvelope {
442        self.execute_with_launch_overlay_and_persistence(
443            envelope,
444            environment,
445            extra_args,
446            OneShotSessionPersistence::Ephemeral,
447        )
448        .await
449    }
450
451    /// Execute an effect with host-only launch mutations and an explicit
452    /// OneShotText session persistence policy.
453    pub async fn execute_with_launch_overlay_and_persistence(
454        &mut self,
455        envelope: EffectEnvelope,
456        environment: Vec<EnvMutation>,
457        extra_args: Vec<OsString>,
458        one_shot_session_persistence: OneShotSessionPersistence,
459    ) -> ObservationEnvelope {
460        self.execute_with_launch_context(
461            envelope,
462            environment,
463            extra_args,
464            one_shot_session_persistence,
465            None,
466        )
467        .await
468    }
469
470    pub async fn execute_with_launch_context(
471        &mut self,
472        envelope: EffectEnvelope,
473        environment: Vec<EnvMutation>,
474        extra_args: Vec<OsString>,
475        one_shot_session_persistence: OneShotSessionPersistence,
476        mcp_server: Option<McpServerSpec>,
477    ) -> ObservationEnvelope {
478        self.execute_with_launch_context_mcp_servers(
479            envelope,
480            environment,
481            extra_args,
482            one_shot_session_persistence,
483            mcp_server.into_iter().collect(),
484        )
485        .await
486    }
487
488    /// Same as [`Self::execute_with_launch_context`], with any number of MCP
489    /// servers for an ACP `session/new` (in order; empty registers none).
490    /// Only the ACP branch reads `mcp_servers`; a PTY or pipe spawn ignores
491    /// it, exactly as the single-server form does.
492    pub async fn execute_with_launch_context_mcp_servers(
493        &mut self,
494        envelope: EffectEnvelope,
495        environment: Vec<EnvMutation>,
496        extra_args: Vec<OsString>,
497        one_shot_session_persistence: OneShotSessionPersistence,
498        mcp_servers: Vec<McpServerSpec>,
499    ) -> ObservationEnvelope {
500        let EffectEnvelope {
501            operation_id,
502            instance_id,
503            generation,
504            effect,
505        } = envelope;
506        let key = NativeSessionKey {
507            instance_id,
508            generation,
509        };
510
511        let observation = {
512            match effect {
513                ControlEffect::Spawn {
514                    agent_id,
515                    transport,
516                    runtime_policy,
517                    request,
518                } => {
519                    self.spawn_native(
520                        key,
521                        operation_id,
522                        NativeSpawnRequest {
523                            agent_id,
524                            transport,
525                            request,
526                            runtime_policy,
527                            launch_extra_args: Vec::new(),
528                            instance_extra_args: extra_args,
529                            resumed_provider_session: None,
530                            one_shot_session_persistence,
531                        },
532                        environment,
533                        mcp_servers,
534                    )
535                    .await
536                }
537                ControlEffect::SpawnResume {
538                    agent_id,
539                    transport,
540                    provider_session,
541                    runtime_policy,
542                    request,
543                } => {
544                    self.spawn_resume(
545                        key,
546                        operation_id,
547                        agent_id,
548                        transport,
549                        provider_session,
550                        runtime_policy,
551                        request,
552                        environment,
553                        extra_args,
554                        one_shot_session_persistence,
555                        mcp_servers,
556                    )
557                    .await
558                }
559                ControlEffect::Stop { force } => self.stop_native(key, force).await,
560                ControlEffect::WriteInput {
561                    input,
562                    required_foreground,
563                } => match self.pty_sessions.get(&key) {
564                    Some(owned) => match required_foreground {
565                        ForegroundRequirement::Any
566                            if matches!(
567                                input.kind(),
568                                PreparedInputKind::TerminalText
569                                    | PreparedInputKind::TerminalBytes
570                                    | PreparedInputKind::TerminalControl
571                            ) =>
572                        {
573                            match owned.session.send_terminal_input(input).await {
574                                Ok(()) => ControlObservation::InputCompleted,
575                                Err(error) => ControlObservation::InputFailed {
576                                    message: error.to_string(),
577                                },
578                            }
579                        }
580                        ForegroundRequirement::Shell
581                            if input.kind() == PreparedInputKind::ShellCommand =>
582                        {
583                            if !owned.runtime_policy.semantic_readiness {
584                                ControlObservation::InputFailed {
585                                    message: "semantic shell input is not admitted by the provider runtime policy"
586                                        .to_owned(),
587                                }
588                            } else {
589                                match owned.session.send_shell_input(input).await {
590                                    Ok(()) => ControlObservation::InputCompleted,
591                                    Err(error) => ControlObservation::InputFailed {
592                                        message: error.to_string(),
593                                    },
594                                }
595                            }
596                        }
597                        ForegroundRequirement::Agent { agent_id }
598                            if matches!(
599                                input.kind(),
600                                PreparedInputKind::InsertDraft
601                                    | PreparedInputKind::SubmitPrompt
602                                    | PreparedInputKind::AgentCommand
603                            ) && &agent_id == owned.session.agent_id() =>
604                        {
605                            if !owned.runtime_policy.semantic_readiness
606                                || !owned.runtime_policy.structured_prompt
607                            {
608                                return completion_observation(
609                                    operation_id,
610                                    instance_id,
611                                    generation,
612                                    ControlObservation::InputFailed {
613                                        message: "semantic input is not admitted by the provider runtime policy"
614                                            .to_owned(),
615                                    },
616                                );
617                            }
618                            let intent = match input.kind() {
619                                PreparedInputKind::InsertDraft
620                                | PreparedInputKind::AgentCommand => ReadinessIntent::DraftPaste,
621                                PreparedInputKind::SubmitPrompt => ReadinessIntent::FollowupPrompt,
622                                PreparedInputKind::ShellCommand
623                                | PreparedInputKind::TerminalText
624                                | PreparedInputKind::TerminalBytes
625                                | PreparedInputKind::TerminalControl => unreachable!(),
626                            };
627                            let Some(spec) = self.catalog.get(&agent_id).cloned() else {
628                                return completion_observation(
629                                    operation_id,
630                                    instance_id,
631                                    generation,
632                                    ControlObservation::InputFailed {
633                                        message: "session agent disappeared from native catalog"
634                                            .to_owned(),
635                                    },
636                                );
637                            };
638                            match wait_for_readiness(&owned.session, &spec, intent, false).await {
639                                Ok(permit) => {
640                                    let result = if input.kind() == PreparedInputKind::AgentCommand
641                                    {
642                                        owned.session.send_agent_command_input(input, permit).await
643                                    } else {
644                                        owned.session.send_prepared_input(input, permit).await
645                                    };
646                                    match result {
647                                        Ok(()) => ControlObservation::InputCompleted,
648                                        Err(error) => ControlObservation::InputFailed {
649                                            message: error.to_string(),
650                                        },
651                                    }
652                                }
653                                Err(message) => ControlObservation::InputFailed { message },
654                            }
655                        }
656                        required_foreground => ControlObservation::InputFailed {
657                            message: format!(
658                                "prepared input kind {:?} does not satisfy route {:?}",
659                                input.kind(),
660                                required_foreground
661                            ),
662                        },
663                    },
664                    None => ControlObservation::InputFailed {
665                        message: "typed PTY input requires a PTY session".to_owned(),
666                    },
667                },
668                ControlEffect::SubmitPrompt { prompt } => match self.acp_sessions.get(&key) {
669                    Some(owned) if !owned.runtime_policy.structured_prompt => {
670                        ControlObservation::InputFailed {
671                            message: "structured prompt is not admitted by the provider runtime policy"
672                                .to_owned(),
673                        }
674                    }
675                    Some(owned) => match submit_acp_prompt(&owned.session, &prompt).await {
676                        Ok(()) => ControlObservation::InputCompleted,
677                        Err(error) => ControlObservation::InputFailed {
678                            message: error.to_string(),
679                        },
680                    },
681                    None => ControlObservation::InputFailed {
682                        message: "semantic follow-up prompts require an ACP session".to_owned(),
683                    },
684                },
685                ControlEffect::Interrupt => match self.acp_sessions.get(&key) {
686                    Some(owned) => match owned.session.cancel().await {
687                        Ok(()) => ControlObservation::InputCompleted,
688                        Err(error) => ControlObservation::InputFailed {
689                            message: error.to_string(),
690                        },
691                    },
692                    None => ControlObservation::InputFailed {
693                        message: "semantic interrupt requires an ACP session".to_owned(),
694                    },
695                },
696                ControlEffect::ResolveInteraction { target, response } => {
697                    resolve_acp_interaction_observation(
698                        self.acp_sessions.get(&key).map(|owned| &owned.session),
699                        target,
700                        response,
701                    )
702                }
703                ControlEffect::SetSessionMode { mode_id } => {
704                    set_acp_session_mode_observation(
705                        self.acp_sessions.get(&key).map(|owned| &owned.session),
706                        mode_id,
707                    )
708                    .await
709                }
710                ControlEffect::SetSessionConfigOption {
711                    option_id,
712                    value_json,
713                } => {
714                    set_acp_session_config_option_observation(
715                        self.acp_sessions.get(&key).map(|owned| &owned.session),
716                        option_id,
717                        value_json,
718                    )
719                    .await
720                }
721                ControlEffect::SetSessionModel { model_id } => {
722                    set_acp_session_model_observation(
723                        self.acp_sessions.get(&key).map(|owned| &owned.session),
724                        model_id,
725                    )
726                }
727                ControlEffect::Resize { size } if !size.is_valid() => {
728                    ControlObservation::ResizeFailed {
729                        message: "terminal size is outside the supported range".to_owned(),
730                    }
731                }
732                ControlEffect::Resize { size } => match self.pty_sessions.get(&key) {
733                    Some(owned) => match owned.session.resize(size.rows, size.columns).await {
734                        Ok(()) => ControlObservation::ResizeCompleted { size },
735                        Err(error) => ControlObservation::ResizeFailed {
736                            message: error.to_string(),
737                        },
738                    },
739                    None => ControlObservation::ResizeFailed {
740                        message: "terminal resize requires a PTY session".to_owned(),
741                    },
742                },
743                ControlEffect::ObserveForeground => match self.pty_sessions.get(&key) {
744                    Some(owned) => match owned.session.observe_foreground().await {
745                        Ok(observation) => ControlObservation::ForegroundObserved {
746                            process: canonical_foreground(
747                                owned.session.agent_id().clone(),
748                                &observation,
749                            ),
750                        },
751                        Err(error) => ControlObservation::ForegroundFailed {
752                            message: error.to_string(),
753                        },
754                    },
755                    None => ControlObservation::ForegroundFailed {
756                        message: "foreground observation requires a PTY session".to_owned(),
757                    },
758                },
759                ControlEffect::ProbeCapabilities { .. } => {
760                    ControlObservation::CapabilityProbeFailed {
761                        failure: CapabilityProbeFailure::ExecutorUnavailable,
762                    }
763                }
764                ControlEffect::DiscoverHistory { .. } | ControlEffect::LoadHistory { .. } => {
765                    ControlObservation::HistoryFailed {
766                        message: "history effects require the dedicated native history authority"
767                            .to_owned(),
768                    }
769                }
770                ControlEffect::AuthorizeResume { .. } => ControlObservation::ResumeFailed {
771                    message: "resume authorization requires the dedicated native authority"
772                        .to_owned(),
773                },
774            }
775        };
776
777        completion_observation(operation_id, instance_id, generation, observation)
778    }
779
780    async fn spawn_native(
781        &mut self,
782        key: NativeSessionKey,
783        operation_id: OperationId,
784        spawn: NativeSpawnRequest,
785        pty_env: Vec<EnvMutation>,
786        mcp_servers: Vec<McpServerSpec>,
787    ) -> ControlObservation {
788        let NativeSpawnRequest {
789            agent_id,
790            transport,
791            request,
792            runtime_policy,
793            mut launch_extra_args,
794            instance_extra_args,
795            resumed_provider_session,
796            one_shot_session_persistence,
797        } = spawn;
798        if let Err(message) =
799            validate_instance_launch_arguments(&agent_id, transport, &instance_extra_args)
800        {
801            return ControlObservation::SpawnFailed { message };
802        }
803        if let Err(message) = validate_spawn_runtime_policy(
804            runtime_policy,
805            transport,
806            request.initial_prompt.is_some(),
807            resumed_provider_session.is_some(),
808        ) {
809            return ControlObservation::SpawnFailed { message };
810        }
811        if self.session_exists(key) {
812            return ControlObservation::SpawnFailed {
813                message: format!(
814                    "native session {:?}/{:?} already exists",
815                    key.instance_id, key.generation
816                ),
817            };
818        }
819        if !request.terminal_size.is_valid() {
820            return ControlObservation::SpawnFailed {
821                message: "terminal size is outside the supported range".to_owned(),
822            };
823        }
824        if request.working_directory.is_empty()
825            || request.working_directory.len() > WORKING_DIRECTORY_MAX_BYTES
826            || request.working_directory.contains('\0')
827        {
828            return ControlObservation::SpawnFailed {
829                message: "working directory is invalid".to_owned(),
830            };
831        }
832        let Some(spec) = self.catalog.get(&agent_id).cloned() else {
833            return ControlObservation::SpawnFailed {
834                message: format!("agent '{agent_id}' is absent from native catalog"),
835            };
836        };
837        let working_dir = PathBuf::from(&request.working_directory);
838
839        match transport {
840            TransportKind::Pty if !spec.capabilities.transports.pty => {
841                ControlObservation::SpawnFailed {
842                    message: format!("agent '{agent_id}' does not support PTY transport"),
843                }
844            }
845            TransportKind::Pty => {
846                // Only the interactive PTY path renders anything to color;
847                // the Pipe/OneShotText arm below spawns a plain pipe with
848                // no terminal device behind it, so `pty_env` is left as the
849                // caller passed it there.
850                let pty_env = with_pty_terminal_capability_defaults(pty_env);
851                let fresh_provider_session = prepare_fresh_pty_provider_session(
852                    spec.capabilities.transports.pty_adapter.as_ref(),
853                    resumed_provider_session.is_some(),
854                    runtime_policy.provider_session_identity,
855                    &mut launch_extra_args,
856                );
857                launch_extra_args.extend(instance_extra_args);
858                let mut authoritative_provider_session = resumed_provider_session
859                    .clone()
860                    .or(fresh_provider_session);
861                let probe_kimi_identity = should_probe_pty_identity(
862                    runtime_policy,
863                    spec.capabilities.transports.pty_adapter.as_ref(),
864                    authoritative_provider_session.is_some(),
865                    "kimi",
866                );
867                let probe_codex_identity = should_probe_pty_identity(
868                    runtime_policy,
869                    spec.capabilities.transports.pty_adapter.as_ref(),
870                    authoritative_provider_session.is_some(),
871                    "codex",
872                );
873                // This is the last point before the OS-level PTY spawn where
874                // the program and its arguments are still plain, structured
875                // data (`spec.launch.program`/`fixed_args` are catalog
876                // constants; `launch_extra_args` is the dynamic, per-session
877                // portion). Provider secrets are environment-only by this
878                // repo's own convention (never argv, see `gate4agent/CLAUDE.md`),
879                // so `fixed_args` needs no redaction; `launch_extra_args`
880                // still gets a defensive per-token credential-shape check
881                // in case a provider CLI's own argv convention differs.
882                // The initial prompt itself is arbitrary-length user text,
883                // not an operational argument, so only its presence is
884                // logged, never its contents.
885                tracing::info!(
886                    agent_id = %agent_id,
887                    instance_id = ?key.instance_id,
888                    generation = ?key.generation,
889                    terminal_size = ?request.terminal_size,
890                    program = %spec.launch.program,
891                    fixed_args = ?spec.launch.fixed_args,
892                    extra_args = ?redact_provider_arguments(&launch_extra_args),
893                    has_initial_prompt = request.initial_prompt.is_some(),
894                    "spawning provider process over a PTY",
895                );
896                match PtySession::spawn_agent_with_size(
897                    &spec,
898                    LaunchRequest {
899                        working_dir,
900                        env: pty_env,
901                        platform: RuntimePlatform::current(),
902                        prompt: request.initial_prompt,
903                        session_options: request.session_options,
904                        extra_args: launch_extra_args,
905                    },
906                    request.terminal_size.rows,
907                    request.terminal_size.columns,
908                )
909                .await
910                {
911                Ok(mut session) => {
912                    if probe_kimi_identity {
913                        match probe_fresh_kimi_session_identity(&session, &spec).await {
914                            Ok(Some(identity)) => authoritative_provider_session = Some(identity),
915                            Ok(None) => {}
916                            Err(error) => {
917                                let message = match session.shutdown().await {
918                                    Ok(_) => error,
919                                    Err(shutdown_error) => {
920                                        format!("{error}; PTY cleanup failed: {shutdown_error}")
921                                    }
922                                };
923                                return ControlObservation::SpawnFailed { message };
924                            }
925                        }
926                    }
927                    if probe_codex_identity {
928                        match probe_fresh_codex_session_identity(&session, &spec).await {
929                            Ok(Some(identity)) => authoritative_provider_session = Some(identity),
930                            Ok(None) => {}
931                            Err(error) => {
932                                let message = match session.shutdown().await {
933                                    Ok(_) => error,
934                                    Err(shutdown_error) => {
935                                        format!("{error}; PTY cleanup failed: {shutdown_error}")
936                                    }
937                                };
938                                return ControlObservation::SpawnFailed { message };
939                            }
940                        }
941                    }
942                    if let Err(error) = deliver_pending_initial_prompt(&mut session, &spec).await {
943                        let message = match session.shutdown().await {
944                            Ok(_) => error,
945                            Err(shutdown_error) => {
946                                format!("{error}; PTY cleanup failed: {shutdown_error}")
947                            }
948                        };
949                        return ControlObservation::SpawnFailed { message };
950                    }
951                    let process_id = session.root_pid();
952                    let provider = match spec.capabilities.transports.pty_adapter.as_ref() {
953                        _ if !should_attach_pty_provider_stream(runtime_policy) => None,
954                        Some(adapter) => {
955                            let tool = match self
956                                .legacy_adapters
957                                .resolve(AdapterFamily::PtySemantic, adapter)
958                            {
959                                Ok(tool) => *tool,
960                                Err(error) => {
961                                    let _ = session.shutdown().await;
962                                    return ControlObservation::SpawnFailed {
963                                        message: error.to_string(),
964                                    };
965                                }
966                            };
967                            match session.attach_events(session.beginning_cursor()) {
968                                Ok(attachment) => {
969                                    let mut pending_events = VecDeque::new();
970                                    let mut provider_session_started = false;
971                                    if let Some(identity) = authoritative_provider_session {
972                                        pending_events.push_back(ProviderEvent::SessionStarted {
973                                            session_id: identity.id.clone(),
974                                            model: String::new(),
975                                            tools: Vec::new(),
976                                        });
977                                        pending_events.push_back(
978                                            ProviderEvent::SessionIdentityObserved { identity },
979                                        );
980                                        provider_session_started = true;
981                                    }
982                                    let is_kimi = tool == CliTool::KimiCode;
983                                    Some(OwnedPtyProvider {
984                                        source: ProviderSource {
985                                            family: AdapterFamily::PtySemantic,
986                                            binding: adapter.clone(),
987                                        },
988                                        receiver: attachment.receiver,
989                                        replay: attachment.replay.into(),
990                                        pending_events,
991                                        utf8: Utf8ChunkDecoder::default(),
992                                        pipeline: Mutex::new(create_pipeline(tool)),
993                                        rate_limits: RateLimitFeed::new_for_tool(tool),
994                                        kimi_identity: (runtime_policy.provider_session_identity
995                                            && is_kimi
996                                            && !provider_session_started)
997                                            .then(KimiPtySessionIdentityExtractor::default),
998                                        semantic_events: runtime_policy.semantic_readiness,
999                                        provider_session_started,
1000                                        next_provider_sequence: 1,
1001                                    })
1002                                }
1003                                Err(error) => {
1004                                    let _ = session.shutdown().await;
1005                                    return ControlObservation::SpawnFailed {
1006                                        message: error.to_string(),
1007                                    };
1008                                }
1009                            }
1010                        }
1011                        None => None,
1012                    };
1013                    self.pty_sessions.insert(
1014                        key,
1015                        OwnedPtySession {
1016                            session,
1017                            spawn_operation_id: operation_id,
1018                            last_terminal_sequence: 0,
1019                            terminal_stale_published: false,
1020                            runtime_policy,
1021                            provider,
1022                            agent_id,
1023                            last_screen_gate: None,
1024                            last_screen_failure: None,
1025                            last_foreground_verdict: None,
1026                            last_screen_state: PtyScreenState::default(),
1027                            ever_reached_ready: false,
1028                            screen_had_content: false,
1029                            // Armed immediately -- the first
1030                            // `reclassify_foreground` tick after spawn
1031                            // probes this session right away rather than
1032                            // waiting a full `FOREGROUND_RECLASSIFY_INTERVAL`.
1033                            next_foreground_probe: Some(Instant::now()),
1034                        },
1035                    );
1036                    ControlObservation::Spawned { process_id }
1037                }
1038                    Err(error) => {
1039                        let message = error.to_string();
1040                        tracing::warn!(
1041                            agent_id = %agent_id,
1042                            instance_id = ?key.instance_id,
1043                            generation = ?key.generation,
1044                            program = %spec.launch.program,
1045                            fixed_args = ?spec.launch.fixed_args,
1046                            cause = %message,
1047                            "provider process failed to start",
1048                        );
1049                        ControlObservation::SpawnFailed { message }
1050                    }
1051                }
1052            }
1053            TransportKind::Pipe => {
1054                let Some(pipe_spec) = spec.capabilities.transports.pipe.as_ref() else {
1055                    return ControlObservation::SpawnFailed {
1056                        message: format!("agent '{agent_id}' does not support Pipe transport"),
1057                    };
1058                };
1059                let prompt = request.initial_prompt.unwrap_or_default();
1060                if pipe_spec.protocol == PipeProtocol::OneShotText {
1061                    let Some(binding) = spec.capabilities.adapters.one_shot.as_ref() else {
1062                        return ControlObservation::SpawnFailed {
1063                            message: format!(
1064                                "agent '{agent_id}' does not declare OneShot capability"
1065                            ),
1066                        };
1067                    };
1068                    if binding != &pipe_spec.adapter {
1069                        return ControlObservation::SpawnFailed {
1070                            message: format!(
1071                                "agent '{agent_id}' has mismatched OneShot transport bindings"
1072                            ),
1073                        };
1074                    }
1075                    return match NativeOneShotSession::spawn_with_environment_and_persistence(
1076                        &spec,
1077                        binding,
1078                        &prompt,
1079                        request.session_options.as_ref(),
1080                        &working_dir,
1081                        &pty_env,
1082                        one_shot_session_persistence,
1083                    )
1084                    .await
1085                    {
1086                        Ok(session) => {
1087                            let process_id = session.process_id();
1088                            let events = session.subscribe();
1089                            self.one_shot_sessions.insert(
1090                                key,
1091                                OwnedProviderSession {
1092                                    source: ProviderSource {
1093                                        family: AdapterFamily::OneShot,
1094                                        binding: binding.clone(),
1095                                    },
1096                                    session,
1097                                    events,
1098                                    pending_events: VecDeque::new(),
1099                                    pending_provider_events: VecDeque::new(),
1100                                    next_provider_sequence: 1,
1101                                    observed_exit_code: None,
1102                                    runtime_policy,
1103                                },
1104                            );
1105                            ControlObservation::Spawned { process_id }
1106                        }
1107                        Err(error) => ControlObservation::SpawnFailed {
1108                            message: error.to_string(),
1109                        },
1110                    };
1111                }
1112                let tool = match self
1113                    .legacy_adapters
1114                    .resolve(AdapterFamily::Pipe, &pipe_spec.adapter)
1115                {
1116                    Ok(tool) => *tool,
1117                    Err(error) => {
1118                        return ControlObservation::SpawnFailed {
1119                            message: error.to_string(),
1120                        }
1121                    }
1122                };
1123                let source = ProviderSource {
1124                    family: AdapterFamily::Pipe,
1125                    binding: pipe_spec.adapter.clone(),
1126                };
1127                let config = SessionConfig {
1128                    tool,
1129                    working_dir,
1130                    env_vars: Vec::new(),
1131                    name: None,
1132                };
1133                if resumed_provider_session.is_some() && pipe_spec.launch_override.is_some() {
1134                    return ControlObservation::SpawnFailed {
1135                        message: format!(
1136                            "agent '{agent_id}' cannot resume through a catalog launch override"
1137                        ),
1138                    };
1139                }
1140                let mut options = PipeProcessOptions::default();
1141                if let Some(identity) = resumed_provider_session.as_ref() {
1142                    options.claude.resume_session_id = Some(identity.id.clone());
1143                }
1144                let spawned = match pipe_spec.launch_override.as_ref() {
1145                    Some(launch) => {
1146                        PipeSession::spawn_with_launch(
1147                            config,
1148                            &prompt,
1149                            launch,
1150                            pipe_spec.prompt_delivery,
1151                        )
1152                        .await
1153                    }
1154                    None => {
1155                        PipeSession::spawn(config, &prompt, options).await
1156                    }
1157                };
1158                match spawned {
1159                    Ok(session) => {
1160                        let process_id = session.process_id();
1161                        let events = session.subscribe();
1162                        let pending_events = if pipe_spec.protocol == PipeProtocol::SemanticNdjson {
1163                            VecDeque::from([AgentEvent::SessionStart {
1164                                session_id: session.session_id().to_owned(),
1165                                model: String::new(),
1166                                tools: Vec::new(),
1167                            }])
1168                        } else {
1169                            VecDeque::new()
1170                        };
1171                        self.pipe_sessions.insert(
1172                            key,
1173                            OwnedProviderSession {
1174                                source,
1175                                session,
1176                                events,
1177                                pending_events,
1178                                pending_provider_events: VecDeque::new(),
1179                                next_provider_sequence: 1,
1180                                observed_exit_code: None,
1181                                runtime_policy,
1182                            },
1183                        );
1184                        ControlObservation::Spawned { process_id }
1185                    }
1186                    Err(error) => ControlObservation::SpawnFailed {
1187                        message: error.to_string(),
1188                    },
1189                }
1190            }
1191            TransportKind::Acp => {
1192                let Some(acp_spec) = spec.capabilities.transports.acp else {
1193                    return ControlObservation::SpawnFailed {
1194                        message: format!("agent '{agent_id}' does not support ACP transport"),
1195                    };
1196                };
1197                let tool = match self
1198                    .legacy_adapters
1199                    .resolve(AdapterFamily::Acp, &acp_spec.adapter)
1200                {
1201                    Ok(tool) => *tool,
1202                    Err(error) => {
1203                        return ControlObservation::SpawnFailed {
1204                            message: error.to_string(),
1205                        }
1206                    }
1207                };
1208                let source = ProviderSource {
1209                    family: AdapterFamily::Acp,
1210                    binding: acp_spec.adapter.clone(),
1211                };
1212                // ACP is the transport this project opens programmatically --
1213                // unlike a PTY, there is no human at a terminal to pick
1214                // permission flags. Measured live: both running ACP adapters
1215                // (claude, codex) came up with no `--permission-mode` flag
1216                // reaching them at all and no permission request ever
1217                // appearing, because `npx`-wrapped specs never receive one
1218                // (`applicable_approval_args`, `src/acp/spawn.rs`) -- the
1219                // adapter simply started in its own default, confirmed on
1220                // the wire as `mode:Mode="auto"`, which approves itself.
1221                // Argv was fiction for ACP; the level lives in `session/
1222                // set_mode` instead now, for every provider, npx-wrapped or
1223                // the vendor's own binary alike -- one mechanism per
1224                // transport (`applicable_approval_args` never forwards an
1225                // approval flag to an ACP-spawned process any more).
1226                //
1227                // `required_acp_mode` resolves the concrete ACP mode id this
1228                // level needs from `gate4agent_catalog::approval_level_
1229                // resolution`'s own `acp_mode_id` column, and refuses BEFORE
1230                // a process is even spawned whenever no mechanism exists to
1231                // enforce the request: `ApprovalLevelResolution::Unsupported`
1232                // (today, `grok`/`kimi` at `ReadOnly`), or a `Supported` row
1233                // this catalog has no sourced ACP mode id for yet (today,
1234                // every level on `codex`/`grok`/`kimi` except `Unmanaged`).
1235                // Silently proceeding either way would spawn the vendor's
1236                // own default instead -- a wider authority than requested,
1237                // the exact defect this rewrite closes. `Unmanaged` is the
1238                // one level that legitimately resolves to "apply nothing" --
1239                // it imposes nothing by definition.
1240                let acp_mode_id = match required_acp_mode(&agent_id, request.approval_level) {
1241                    Ok(mode_id) => mode_id,
1242                    Err(message) => return ControlObservation::SpawnFailed { message },
1243                };
1244                // The MCP-server door (gate4agent-arc-mailbox-and-task-layer
1245                // Slice A(ii)): `mcp_servers` carries the node's resolved MCP
1246                // server overlay (primary first, then any additional ACP
1247                // servers) whenever one was prepared for this spawn,
1248                // transport-agnostic same as every other launch-profile
1249                // mutation -- see `mcp_server_acp_entry`'s own doc comment.
1250                // `None` when the node prepared none, which keeps
1251                // `mcp_servers` empty and changes nothing else.
1252                let mcp_servers: Vec<McpServerConfig> =
1253                    mcp_servers.iter().map(mcp_server_acp_entry).collect();
1254                if !mcp_servers.is_empty() {
1255                    // State-change line: this is the point measured live to
1256                    // be silently empty on the wire before the ACP v1 shape
1257                    // fix (`McpServerConfig`, `src/acp/protocol.rs`) -- a
1258                    // nameless, map-shaped entry the agent's own adapter
1259                    // dropped before ever registering it, so `tools/list`
1260                    // never ran. Names only, never `env` (may carry
1261                    // tokens/endpoints).
1262                    tracing::info!(
1263                        agent_id = %agent_id,
1264                        instance_id = ?key.instance_id,
1265                        mcp_server_names = ?mcp_servers.iter().map(McpServerConfig::name).collect::<Vec<_>>(),
1266                        "acp session/new carries {} mcp server(s)",
1267                        mcp_servers.len(),
1268                    );
1269                }
1270                // Codex station network_access first slice: argv-only `-c`
1271                // overlays arrive as instance_extra_args (same channel as
1272                // catalog windows_wsl_setup). Merge after approval flags.
1273                let mut approval_level_args =
1274                    acp_approval_level_args(&agent_id, request.approval_level);
1275                for argument in &instance_extra_args {
1276                    approval_level_args.push(argument.to_string_lossy().into_owned());
1277                }
1278                let acp_options = AcpSessionOptions {
1279                    host_policy: host_policy_for_approval_level(request.approval_level),
1280                    // Empty for an agent that announced an `acp_mode_id` for
1281                    // this level: that one is applied through
1282                    // `session/set_mode` below, once the handshake is up,
1283                    // and its argv stays clean (see this branch's own
1284                    // comment above and `applicable_approval_args`,
1285                    // `src/acp/spawn.rs`). An agent that announced NO mode
1286                    // has no such mechanism -- measured 2026-09-09, kimi
1287                    // announces none at any level, so an empty argv left it
1288                    // running at the vendor's own default and it refused
1289                    // every `g4a_*` MCP tool call at its OWN approval
1290                    // prompt without ever sending the host a
1291                    // `session/request_permission`. For that shape argv is
1292                    // the only lever there is. Codex `-c` network overlays
1293                    // may still append via `instance_extra_args` above.
1294                    approval_level_args,
1295                    defer_permission_requests: defers_permission_requests(
1296                        &agent_id,
1297                        request.approval_level,
1298                    ),
1299                    mcp_servers,
1300                    ..AcpSessionOptions::default()
1301                };
1302                let spawned = match acp_spec.launch_override.as_ref() {
1303                    Some(launch) => {
1304                        AcpSession::spawn_with_launch(tool, &working_dir, acp_options, launch)
1305                            .await
1306                    }
1307                    None => AcpSession::spawn(tool, &working_dir, acp_options).await,
1308                };
1309                match spawned {
1310                    Ok(session) => {
1311                        // Subscribe before session/load: history is replayed before its reply.
1312                        let events = session.subscribe();
1313                        tracing::info!(capabilities = ?session.capability_names(),
1314                            "ACP initialize capabilities");
1315                        if let Some(identity) = resumed_provider_session.as_ref() {
1316                            if !session.supports_load_session() {
1317                                let _ = session.kill().await;
1318                                return ControlObservation::SpawnFailed {
1319                                    message: "ACP session/load unsupported".to_owned(),
1320                                };
1321                            }
1322                            if let Err(error) = session.load_session(&identity.id).await {
1323                                let _ = session.kill().await;
1324                                return ControlObservation::SpawnFailed { message: error.to_string() };
1325                            }
1326                        }
1327                        if let Some(mode_id) = acp_mode_id.as_ref() {
1328                            if let Err(message) =
1329                                apply_acp_approval_mode(&session, mode_id, request.approval_level)
1330                                    .await
1331                            {
1332                                let _ = session.kill().await;
1333                                return ControlObservation::SpawnFailed { message };
1334                            }
1335                        }
1336                        let process_id = session.process_id();
1337                        let session_id = session
1338                            .acp_session_id()
1339                            .await
1340                            .unwrap_or_else(|| session.session_id().to_owned());
1341                        // Binds a freshly created record from `IdentityPending`
1342                        // to `Live` (`gate4agent-node`'s `reconcile_managed_
1343                        // record` on `ProviderEvent::SessionIdentityObserved`)
1344                        // as soon as the session exists, mirroring the PTY
1345                        // path's own identity seeding
1346                        // (`prepare_fresh_pty_provider_session`/
1347                        // `probe_fresh_*_session_identity`) for the transport
1348                        // ACP's own spec makes this a protocol MUST for:
1349                        // `session/new` MUST return a `sessionId`, and both
1350                        // shipped adapters map it onto the provider's own
1351                        // durable session id (`AcpSession::
1352                        // provider_reported_session_id`'s own doc comment).
1353                        //
1354                        // Gated on `runtime_policy.provider_session_identity`
1355                        // -- the same capability the PTY path checks before
1356                        // treating any identity as authoritative -- so a
1357                        // spawn that never asked for identity tracking stays
1358                        // silent rather than warning on every ACP session
1359                        // whose caller has no interest in one.
1360                        //
1361                        // `provider_reported_session_id` (NOT `session_id`
1362                        // above) is the signal here: `session_id` already
1363                        // falls back to the host-local id the moment the
1364                        // agent's `session/new` response carries no
1365                        // `sessionId`, so it can never itself distinguish "the
1366                        // agent reported one" from "the agent violated ACP's
1367                        // MUST and this build filled in its own" -- exactly
1368                        // the distinction the `IdentityPending` refusal
1369                        // downstream depends on.
1370                        let identity_observed = if runtime_policy.provider_session_identity {
1371                            match session.provider_reported_session_id().await {
1372                                Some(id) => Some(ProviderEvent::SessionIdentityObserved {
1373                                    identity: ProviderSessionIdentity {
1374                                        key: ProviderSessionKey::SessionId,
1375                                        id,
1376                                        transcript_path: None,
1377                                    },
1378                                }),
1379                                None => {
1380                                    tracing::warn!(
1381                                        agent_id = %agent_id,
1382                                        adapter = %acp_spec.adapter.id,
1383                                        "ACP session/new returned no sessionId; provider \
1384                                         session identity stays IdentityPending",
1385                                    );
1386                                    None
1387                                }
1388                            }
1389                        } else {
1390                            None
1391                        };
1392                        if let Some(prompt) = request.initial_prompt {
1393                            if let Err(error) = session.start_prompt(&prompt).await {
1394                                let _ = session.kill().await;
1395                                return ControlObservation::SpawnFailed {
1396                                    message: error.to_string(),
1397                                };
1398                            }
1399                        }
1400                        // Read before `session` moves into the map below.
1401                        let announced_mode = session.current_mode_id();
1402                        self.acp_sessions.insert(
1403                            key,
1404                            OwnedProviderSession {
1405                                source,
1406                                session,
1407                                events,
1408                                pending_events: {
1409                                    let mut seeded = VecDeque::from([AgentEvent::SessionStart {
1410                                        session_id,
1411                                        model: String::new(),
1412                                        tools: Vec::new(),
1413                                    }]);
1414                                    // Announce the mode catalogue once, at
1415                                    // session start.
1416                                    //
1417                                    // `ModeCatalog` reaches the operator only
1418                                    // from a `ModeChanged`, so without this it
1419                                    // is emitted solely when a mode CHANGES --
1420                                    // and an operator cannot change a mode
1421                                    // without knowing an id, which is what the
1422                                    // catalogue carries. That is a closed
1423                                    // loop: the one thing needed to ask is
1424                                    // only published in reply to asking.
1425                                    //
1426                                    // Both halves are handshake facts, not
1427                                    // inventions: `available_modes` is the
1428                                    // list the agent returned from
1429                                    // `session/new`, and `current_mode_id` is
1430                                    // what it said it is in right now. Seeding
1431                                    // them as a `ModeChanged` is a small
1432                                    // misnomer -- nothing changed -- but the
1433                                    // payload is the state, and the operator
1434                                    // needs the state before it can ever
1435                                    // change.
1436                                    if let Some(mode_id) = announced_mode {
1437                                        seeded.push_back(AgentEvent::ModeChanged { mode_id });
1438                                    }
1439                                    seeded
1440                                },
1441                                pending_provider_events: VecDeque::from_iter(identity_observed),
1442                                next_provider_sequence: 1,
1443                                observed_exit_code: None,
1444                                runtime_policy,
1445                            },
1446                        );
1447                        ControlObservation::Spawned { process_id }
1448                    }
1449                    Err(error) => ControlObservation::SpawnFailed {
1450                        message: error.to_string(),
1451                    },
1452                }
1453            }
1454        }
1455    }
1456
1457    async fn spawn_resume(
1458        &mut self,
1459        key: NativeSessionKey,
1460        operation_id: OperationId,
1461        agent_id: AgentId,
1462        transport: TransportKind,
1463        provider_session: gate4agent_types::ProviderSessionIdentity,
1464        runtime_policy: ProviderRuntimePolicy,
1465        request: ResumeLaunchRequest,
1466        pty_env: Vec<EnvMutation>,
1467        instance_extra_args: Vec<OsString>,
1468        one_shot_session_persistence: OneShotSessionPersistence,
1469        mcp_servers: Vec<McpServerSpec>,
1470    ) -> ControlObservation {
1471        if let Err(message) = validate_spawn_runtime_policy(
1472            runtime_policy,
1473            transport,
1474            request.initial_prompt.is_some(),
1475            true,
1476        ) {
1477            return ControlObservation::SpawnFailed { message };
1478        }
1479        if let Err(error) = request.validate() {
1480            return ControlObservation::SpawnFailed {
1481                message: error.to_string(),
1482            };
1483        }
1484        let Some(spec) = self.catalog.get(&agent_id) else {
1485            return ControlObservation::SpawnFailed {
1486                message: format!("agent '{agent_id}' is absent from native catalog"),
1487            };
1488        };
1489        let Some(binding) = spec.capabilities.adapters.resume.as_ref() else {
1490            return ControlObservation::SpawnFailed {
1491                message: format!("agent '{agent_id}' does not declare Resume capability"),
1492            };
1493        };
1494        let plan = match build_resume_plan_for_identity(&binding.id, &provider_session) {
1495            Ok(Some(plan)) => plan,
1496            Ok(None) => {
1497                return ControlObservation::SpawnFailed {
1498                    message: format!("agent '{agent_id}' has no live Resume plan"),
1499                }
1500            }
1501            Err(error) => {
1502                return ControlObservation::SpawnFailed {
1503                    message: error.to_string(),
1504                }
1505            }
1506        };
1507        if transport == TransportKind::Pipe {
1508            let Some(pipe) = spec.capabilities.transports.pipe.as_ref() else {
1509                return ControlObservation::SpawnFailed {
1510                    message: format!("agent '{agent_id}' does not support Pipe transport"),
1511                };
1512            };
1513            if pipe.protocol != PipeProtocol::StructuredJsonl {
1514                return ControlObservation::SpawnFailed {
1515                    message: format!(
1516                        "agent '{agent_id}' does not expose a resumable structured Pipe contract"
1517                    ),
1518                };
1519            }
1520        }
1521        let start = StartRequest {
1522            working_directory: request.working_directory,
1523            terminal_size: request.terminal_size,
1524            initial_prompt: request.initial_prompt,
1525            // A resume reattaches to a provider session that already has a
1526            // process running with whatever argv it was originally spawned
1527            // with -- there is no fresh CLI invocation here to apply an
1528            // approval level to, the same reasoning that leaves
1529            // `session_options` unset on a resume above.
1530            session_options: None,
1531            approval_level: ApprovalLevel::default(),
1532        };
1533        self.spawn_native(
1534            key,
1535            operation_id,
1536            NativeSpawnRequest {
1537                agent_id,
1538                transport,
1539                request: start,
1540                runtime_policy,
1541                launch_extra_args: if transport == TransportKind::Pty {
1542                    plan.args.into_iter().map(OsString::from).collect()
1543                } else {
1544                    Vec::new()
1545                },
1546                instance_extra_args,
1547                resumed_provider_session: Some(provider_session),
1548                one_shot_session_persistence,
1549            },
1550            pty_env,
1551            mcp_servers,
1552        )
1553        .await
1554    }
1555
1556    async fn stop_native(&mut self, key: NativeSessionKey, force: bool) -> ControlObservation {
1557        if let Some(owned) = self.pty_sessions.remove(&key) {
1558            let shutdown = owned.session.shutdown().await;
1559            return match shutdown {
1560                Ok(outcome) => ControlObservation::StopCompleted {
1561                    forced: force || outcome.termination.is_some(),
1562                    exit_code: outcome.exit_code,
1563                    // The last classification this session ever computed --
1564                    // stamped through unchanged, same as every other frame;
1565                    // nothing observes this session again after this point.
1566                    final_terminal: Some(terminal_frame(outcome.terminal, owned.last_screen_state.clone())),
1567                },
1568                Err(error) => {
1569                    eprintln!(
1570                        "[gate4agent-shell-native] PTY stop failed for {key:?} (force={force}): {error}",
1571                    );
1572                    ControlObservation::StopFailed {
1573                        message: error.to_string(),
1574                    }
1575                }
1576            };
1577        }
1578        if let Some(owned) = self.pipe_sessions.remove(&key) {
1579            // `PipeSession::stop` reads `force`: `false` waits up to
1580            // `PIPE_GRACEFUL_STOP_BOUND_SECS` for the process to exit on its
1581            // own (stdin is already closed by spawn time for every
1582            // supported CLI, so this is "let the run finish" rather than a
1583            // new signal) before falling back to a kill; `true` kills
1584            // immediately, same as the old unconditional `kill()` call this
1585            // replaces. `Err(_) if reader_finished()` below is the race
1586            // where a `force = true` kill loses to the process already
1587            // having exited on its own between the map lookup and the kill
1588            // attempt -- `stop`'s own graceful path already reports that
1589            // case as `Ok` with `forced: false`, so this arm is only ever
1590            // reached on the `force = true` side of `stop`.
1591            return match owned.session.stop(force).await {
1592                Ok(outcome) => ControlObservation::StopCompleted {
1593                    forced: outcome.forced,
1594                    exit_code: outcome.exit_code.or(owned.observed_exit_code),
1595                    final_terminal: None,
1596                },
1597                Err(_) if owned.session.reader_finished() => ControlObservation::StopCompleted {
1598                    forced: false,
1599                    exit_code: owned.observed_exit_code,
1600                    final_terminal: None,
1601                },
1602                Err(error) => ControlObservation::StopFailed {
1603                    message: error.to_string(),
1604                },
1605            };
1606        }
1607        if let Some(mut owned) = self.one_shot_sessions.remove(&key) {
1608            return match owned.session.kill().await {
1609                Ok(()) => ControlObservation::StopCompleted {
1610                    forced: true,
1611                    exit_code: owned.observed_exit_code,
1612                    final_terminal: None,
1613                },
1614                Err(_) if owned.session.reader_finished() => ControlObservation::StopCompleted {
1615                    forced: false,
1616                    exit_code: owned.observed_exit_code,
1617                    final_terminal: None,
1618                },
1619                Err(error) => ControlObservation::StopFailed {
1620                    message: error.to_string(),
1621                },
1622            };
1623        }
1624        if let Some(owned) = self.acp_sessions.remove(&key) {
1625            // `AcpSession::stop` reads `force`: `false` closes stdin and
1626            // waits up to `ACP_GRACEFUL_STOP_BOUND_SECS` for the adapter to
1627            // exit on its own before falling back to a kill; `true` kills
1628            // immediately, same as the old unconditional `kill()` call this
1629            // replaces. `Err(_) if reader_finished()` below is the race
1630            // where a `force = true` kill loses to the process already
1631            // having exited on its own between the map lookup and the kill
1632            // attempt -- `stop`'s own graceful path already reports that
1633            // case as `Ok` with `forced: false`, so this arm is only ever
1634            // reached on the `force = true` side of `stop`.
1635            return match owned.session.stop(force).await {
1636                Ok(outcome) => ControlObservation::StopCompleted {
1637                    forced: outcome.forced,
1638                    exit_code: outcome.exit_code.or(owned.observed_exit_code),
1639                    final_terminal: None,
1640                },
1641                Err(_) if owned.session.reader_finished() => ControlObservation::StopCompleted {
1642                    forced: false,
1643                    exit_code: owned.observed_exit_code,
1644                    final_terminal: None,
1645                },
1646                Err(error) => ControlObservation::StopFailed {
1647                    message: error.to_string(),
1648                },
1649            };
1650        }
1651        // A kill this function skips entirely -- nothing owns `key` in any
1652        // transport map -- must say so out loud: silently returning
1653        // `StopFailed` here left no trail at the point where the skip
1654        // actually happened, only a message string several layers removed
1655        // from anyone watching this process's own output.
1656        eprintln!("[gate4agent-shell-native] stop skipped: no session owns {key:?} in any transport map");
1657        ControlObservation::StopFailed {
1658            message: missing_session_message(key),
1659        }
1660    }
1661
1662    fn session_exists(&self, key: NativeSessionKey) -> bool {
1663        self.pty_sessions.contains_key(&key)
1664            || self.pipe_sessions.contains_key(&key)
1665            || self.one_shot_sessions.contains_key(&key)
1666            || self.acp_sessions.contains_key(&key)
1667    }
1668
1669    /// Convert naturally exited PTY children into generation-bound lifecycle
1670    /// observations. Runtime ticks call this before accepting new commands.
1671    pub async fn collect_exits(&mut self) -> Vec<ObservationEnvelope> {
1672        let completed: Vec<_> = self
1673            .pty_sessions
1674            .iter()
1675            .filter_map(|(key, owned)| owned.session.reader_finished().then_some(*key))
1676            .collect();
1677        let mut observations = Vec::with_capacity(completed.len());
1678        for key in completed {
1679            let owned = self
1680                .pty_sessions
1681                .remove(&key)
1682                .expect("completed key came from the owned session map");
1683            let last_screen_state = owned.last_screen_state.clone();
1684            let (exit_code, final_terminal) = match owned.session.shutdown().await {
1685                Ok(outcome) => (
1686                    outcome.exit_code,
1687                    Some(terminal_frame(outcome.terminal, last_screen_state)),
1688                ),
1689                Err(_) => (None, None),
1690            };
1691            observations.push(ObservationEnvelope {
1692                operation_id: None,
1693                instance_id: key.instance_id,
1694                generation: key.generation,
1695                observation: ControlObservation::ProcessExited {
1696                    exit_code,
1697                    final_terminal,
1698                },
1699            });
1700        }
1701        collect_provider_exits(&mut self.pipe_sessions, &mut observations, |session| {
1702            session.reader_finished()
1703        });
1704        collect_provider_exits(&mut self.one_shot_sessions, &mut observations, |session| {
1705            session.reader_finished()
1706        });
1707        collect_provider_exits(&mut self.acp_sessions, &mut observations, |session| {
1708            session.reader_finished()
1709        });
1710        observations
1711    }
1712
1713    /// Drain normalized provider events without mixing them with replaceable
1714    /// terminal frames. Broadcast lag is converted into an explicit stale gap.
1715    pub fn collect_provider_events(&mut self) -> Vec<ObservationEnvelope> {
1716        let mut observations = self.pending_observations.drain(..).collect::<Vec<_>>();
1717        for (key, owned) in &mut self.pty_sessions {
1718            if let Some(provider) = &mut owned.provider {
1719                drain_pty_provider(*key, provider, &mut observations);
1720            }
1721        }
1722        collect_provider_map(&mut self.pipe_sessions, &mut observations, |_| Vec::new());
1723        collect_provider_map(&mut self.one_shot_sessions, &mut observations, |_| Vec::new());
1724        // Retire deferred permission requests whose deadline has passed,
1725        // BEFORE draining -- so the `RpcIncomingRequest` each expiry emits is
1726        // picked up by the very same drain rather than waiting a whole tick
1727        // to be reported.
1728        //
1729        // This call is what makes the deadline real. Without it a deferred
1730        // request has a `deadline` field nobody ever reads, and a session
1731        // whose operator never answers waits forever on a promise the code
1732        // makes and never keeps -- the agent blocked on a permission it will
1733        // never be told about. Deferral is only safe because this runs on
1734        // every tick; nothing else in the process calls it.
1735        for owned in self.acp_sessions.values() {
1736            owned.session.expire_deadlines();
1737        }
1738        collect_provider_map(&mut self.acp_sessions, &mut observations, AcpSession::available_modes);
1739        observations
1740    }
1741
1742    /// Capture only changed terminal frames. Snapshot failures become an
1743    /// explicit stale observation once, until a later successful frame heals it.
1744    ///
1745    /// The sequence is checked BEFORE the capture, not after. This runs on
1746    /// the per-session worker tick (20ms, so ~50 times a second per live
1747    /// PTY session), and `terminal_state` is not a cheap read: it renders
1748    /// the visible screen twice and clones the whole `vt100::Screen` to
1749    /// walk its scrollback row by row. Asking it first and comparing
1750    /// sequences afterwards meant every idle session rebuilt its entire
1751    /// screen fifty times a second purely to discover nothing had changed,
1752    /// and then dropped the result -- with a couple of dozen sessions open
1753    /// that is the machine's time, all of it wasted. `terminal_sequence`
1754    /// answers the same question by reading one integer.
1755    pub fn collect_terminal_frames(&mut self) -> Vec<ObservationEnvelope> {
1756        let mut observations = Vec::new();
1757        // Split borrows taken up front: the loop below needs a mutable
1758        // borrow of `pty_sessions` for its whole body, and `efficiency_facts`
1759        // is a disjoint field this function also writes to on every branch
1760        // -- see `ShellEfficiencyFacts`'s own doc comment for why this crate
1761        // is the one recording facts rather than a distribution.
1762        let pty_sessions = &mut self.pty_sessions;
1763        let efficiency_facts = &mut self.efficiency_facts;
1764        for (key, owned) in pty_sessions {
1765            if terminal_state_capture_should_skip(
1766                owned.session.terminal_sequence(),
1767                owned.last_terminal_sequence,
1768            ) {
1769                efficiency_facts.record_terminal_state_skip();
1770                continue;
1771            }
1772            let capture_start = Instant::now();
1773            let terminal_state = owned.session.terminal_state();
1774            efficiency_facts.record_terminal_state_capture(capture_start.elapsed());
1775            match terminal_state {
1776                Ok(snapshot) if snapshot.sequence > owned.last_terminal_sequence => {
1777                    owned.last_terminal_sequence = snapshot.sequence;
1778                    owned.terminal_stale_published = false;
1779
1780                    // `snapshot.contents` is already in memory for the
1781                    // `TerminalFrame` below, so both text matchers run for
1782                    // free here -- no extra syscall, no extra capture.
1783                    owned.last_screen_gate = startup_operator_gate(&snapshot.contents);
1784                    // `screen_failure`'s markers are crash SHAPES, and as
1785                    // raw bytes those are indistinguishable from an agent
1786                    // choosing to render the same text while explaining or
1787                    // running someone else's failure. Before this
1788                    // generation has ever rendered its own UI, nothing else
1789                    // could have put a crash banner on the screen, so the
1790                    // marker genuinely means the CLI failed to come up;
1791                    // once it has been `Ready`, the identical bytes are
1792                    // ordinary content, not state, so the matcher is not
1793                    // even run.
1794                    owned.last_screen_failure =
1795                        screen_failure_for_generation(&snapshot.contents, owned.ever_reached_ready);
1796                    let merged = classify_pty_screen_state(
1797                        owned.last_foreground_verdict.as_ref(),
1798                        owned.last_screen_gate.as_ref(),
1799                        owned.last_screen_failure,
1800                    );
1801                    // Arm the crash-marker window only on a `Ready` that had
1802                    // SOMETHING on screen. `Ready` is proved by foreground
1803                    // process identity, so it lands within a frame or two of
1804                    // spawn, while the terminal is still blank -- measured at
1805                    // frame 2 for all four providers. Arming on that blank
1806                    // frame closed the window before any failure text could
1807                    // exist: Grok without a key prints `API key required` at
1808                    // frame 4 and sat at `Ready` forever, because the matcher
1809                    // for it was never reached. A blank screen is not evidence
1810                    // the agent came up, so it must not retire the detector.
1811                    if !snapshot.contents.trim().is_empty() {
1812                        owned.screen_had_content = true;
1813                    }
1814                    if merged == PtyScreenState::Ready && owned.screen_had_content {
1815                        owned.ever_reached_ready = true;
1816                    }
1817                    if merged != owned.last_screen_state {
1818                        if foreground_probe_rearms_immediately(&owned.last_screen_state, &merged) {
1819                            owned.next_foreground_probe = Some(Instant::now());
1820                        }
1821                        owned.last_screen_state = merged.clone();
1822                        observations.push(ObservationEnvelope {
1823                            operation_id: None,
1824                            instance_id: key.instance_id,
1825                            generation: key.generation,
1826                            observation: ControlObservation::ScreenState {
1827                                state: merged.clone(),
1828                            },
1829                        });
1830                    }
1831
1832                    let frame = terminal_frame(snapshot, merged);
1833                    efficiency_facts.record_terminal_frame_published(terminal_frame_byte_len(&frame));
1834                    observations.push(ObservationEnvelope {
1835                        operation_id: None,
1836                        instance_id: key.instance_id,
1837                        generation: key.generation,
1838                        observation: ControlObservation::TerminalFrame { frame },
1839                    });
1840                }
1841                Ok(_) => {}
1842                Err(error) if !owned.terminal_stale_published => {
1843                    owned.terminal_stale_published = true;
1844                    observations.push(ObservationEnvelope {
1845                        operation_id: None,
1846                        instance_id: key.instance_id,
1847                        generation: key.generation,
1848                        observation: ControlObservation::TerminalStale {
1849                            message: error.to_string(),
1850                        },
1851                    });
1852                }
1853                Err(_) => {}
1854            }
1855        }
1856        observations
1857    }
1858
1859    /// Refresh the foreground half of `PtyScreenState` for whichever
1860    /// sessions are due, per `next_foreground_probe`.
1861    ///
1862    /// Deliberately not folded into `collect_terminal_frames`: that method
1863    /// is synchronous and only pays for a real capture when the terminal
1864    /// sequence says the screen changed, but
1865    /// `PtySession::observe_foreground_timed` is async and walks the live OS
1866    /// process tree
1867    /// (`CreateToolhelp32Snapshot` on Windows) unconditionally every time
1868    /// it is called. Running that walk once per changed frame would scale
1869    /// a syscall with output rate -- exactly the cost
1870    /// `collect_terminal_frames`'s own sequence gate exists to avoid. The
1871    /// cost here is bounded by the count of sessions NOT currently
1872    /// `Ready`, never by output rate and never by total session count: a
1873    /// session that reaches `Ready` disarms itself (see
1874    /// `foreground_probe_schedule`) and is never probed again until its
1875    /// text disagrees.
1876    pub async fn reclassify_foreground(&mut self) -> Vec<ObservationEnvelope> {
1877        let catalog = &self.catalog;
1878        let now = Instant::now();
1879        let due: Vec<NativeSessionKey> = self
1880            .pty_sessions
1881            .iter()
1882            .filter(|(_, owned)| owned.next_foreground_probe.is_some_and(|at| now >= at))
1883            .map(|(key, _)| *key)
1884            .collect();
1885
1886        let mut observations = Vec::new();
1887        for key in due {
1888            let Some(owned) = self.pty_sessions.get_mut(&key) else {
1889                continue;
1890            };
1891            let probe_result = owned.session.observe_foreground_timed().await;
1892            match probe_result {
1893                Ok((observation, timing)) => {
1894                    // Recorded on success only: `timing` covers all three
1895                    // components (queue, lock wait, walk) exactly when the
1896                    // walk itself ran to completion and returned a real
1897                    // observation. On error (see below) the walk may have
1898                    // failed partway through, in the mutex, or never been
1899                    // dispatched at all (`spawn_blocking` panicked), so
1900                    // there is no single component that is reliably "the
1901                    // cost of this probe" to attribute a failure to -- unlike
1902                    // `terminal_state_capture`, which always completes or
1903                    // never starts, a foreground probe can fail after
1904                    // dispatch, after acquiring the lock, or during the walk,
1905                    // and only the success path knows which.
1906                    self.efficiency_facts.record_foreground_probe(timing);
1907                    let verdict = match catalog.get(&owned.agent_id) {
1908                        Some(spec) => resolve_foreground_verdict(
1909                            spec,
1910                            &observation,
1911                            RuntimePlatform::current(),
1912                        ),
1913                        // The catalog is loaded once at startup and does not
1914                        // shrink at runtime; this branch exists only so a
1915                        // hypothetical gap fails toward the conservative
1916                        // "not confirmed as the agent" reading rather than
1917                        // panicking or silently keeping a stale verdict.
1918                        None => ForegroundVerdict::Foreign {
1919                            process: observation.observed_process.clone(),
1920                        },
1921                    };
1922                    owned.last_foreground_verdict = Some(verdict);
1923                    let merged = classify_pty_screen_state(
1924                        owned.last_foreground_verdict.as_ref(),
1925                        owned.last_screen_gate.as_ref(),
1926                        owned.last_screen_failure,
1927                    );
1928                    // A foreground-only transition into `Ready` (text was
1929                    // already clean; only the process signal was missing)
1930                    // must ALSO close the `screen_failure` window for
1931                    // future text passes -- see `collect_terminal_frames`.
1932                    if merged == PtyScreenState::Ready && owned.screen_had_content {
1933                        owned.ever_reached_ready = true;
1934                    }
1935                    if merged != owned.last_screen_state {
1936                        owned.last_screen_state = merged.clone();
1937                        observations.push(ObservationEnvelope {
1938                            operation_id: None,
1939                            instance_id: key.instance_id,
1940                            generation: key.generation,
1941                            observation: ControlObservation::ScreenState { state: merged },
1942                        });
1943                    }
1944                    owned.next_foreground_probe =
1945                        match foreground_probe_schedule(&owned.last_screen_state) {
1946                            ForegroundProbeSchedule::Disarmed => None,
1947                            ForegroundProbeSchedule::Armed => {
1948                                Some(now + FOREGROUND_RECLASSIFY_INTERVAL)
1949                            }
1950                        };
1951                }
1952                Err(_) => {
1953                    // A failed OS process-tree walk is `Unknown`'s territory
1954                    // -- it says nothing was confirmed, not that the
1955                    // process is wrong. Leave whatever verdict/state is
1956                    // already recorded alone and simply try again next
1957                    // cadence rather than fabricating a `NotAgent` verdict
1958                    // or a `Ready` one.
1959                    owned.next_foreground_probe = Some(now + FOREGROUND_RECLASSIFY_INTERVAL);
1960                }
1961            }
1962        }
1963        observations
1964    }
1965}
1966
1967/// ConPTY does not populate `TERM`/`COLORTERM` in the environment it hands
1968/// to a spawned child; a provider CLI reads exactly those two variables to
1969/// decide whether the terminal in front of it renders color, so a
1970/// Windows-hosted PTY session comes up monochrome unless something else
1971/// supplies them. These are the values truecolor-capable terminals
1972/// (xterm.js, WezTerm, ...) advertise about themselves.
1973const PTY_TERM_DEFAULT_KEY: &str = "TERM";
1974const PTY_TERM_DEFAULT_VALUE: &str = "xterm-256color";
1975const PTY_COLORTERM_DEFAULT_KEY: &str = "COLORTERM";
1976const PTY_COLORTERM_DEFAULT_VALUE: &str = "truecolor";
1977
1978/// Fill in the PTY terminal-capability defaults above for whichever of the
1979/// two keys the caller has not already mutated. A caller-supplied
1980/// `EnvMutation` for `TERM`/`COLORTERM` -- whether it sets or removes the
1981/// variable -- always wins: this only appends a default into a gap, it
1982/// never overwrites or reorders an existing entry.
1983fn with_pty_terminal_capability_defaults(mut pty_env: Vec<EnvMutation>) -> Vec<EnvMutation> {
1984    let already_mutated = |env: &[EnvMutation], key: &str| {
1985        env.iter()
1986            .any(|mutation| mutation.key.as_os_str() == OsStr::new(key))
1987    };
1988    if !already_mutated(&pty_env, PTY_TERM_DEFAULT_KEY) {
1989        pty_env.push(EnvMutation {
1990            key: OsString::from(PTY_TERM_DEFAULT_KEY),
1991            value: Some(OsString::from(PTY_TERM_DEFAULT_VALUE)),
1992        });
1993    }
1994    if !already_mutated(&pty_env, PTY_COLORTERM_DEFAULT_KEY) {
1995        pty_env.push(EnvMutation {
1996            key: OsString::from(PTY_COLORTERM_DEFAULT_KEY),
1997            value: Some(OsString::from(PTY_COLORTERM_DEFAULT_VALUE)),
1998        });
1999    }
2000    pty_env
2001}
2002
2003fn missing_session_message(key: NativeSessionKey) -> String {
2004    format!(
2005        "native session {:?}/{:?} does not exist",
2006        key.instance_id, key.generation
2007    )
2008}
2009
2010/// Map the spawn request's `ApprovalLevel` to the ACP host authority mode
2011/// that answers `session/request_permission` for the SAME session -- the
2012/// PTY transport lets a human at the keyboard pick their own agent's
2013/// permission flags (see `gate4agent_catalog::LaunchRequest`, which carries
2014/// no approval axis at all), but ACP is opened by this process with nobody
2015/// at a terminal, so it is the one transport where `approval_level` also has
2016/// to steer the host side of the session, not just the spawned process's own
2017/// argv (`approval_level_args`).
2018///
2019/// `FullAuto` must never land on a refusing `HostPolicy` (`ReadOnly` or
2020/// `Deny`): that combination launches the process believing it holds full
2021/// autonomy while every host permission request it makes gets silently
2022/// refused, which is worse than either policy alone -- so `FullAuto` maps to
2023/// `HostPolicy::Yolo`, the one mode that grants everything without asking.
2024/// `ReadOnly` maps to `HostPolicy::ReadOnly` for the same reason in reverse.
2025///
2026/// `Moderate` has no dedicated `HostPolicy` variant -- ACP's four host modes
2027/// are coarser than the three managed `ApprovalLevel` steps -- so it falls
2028/// back to `HostPolicy::Auto`, the same mode `Unmanaged` ("impose nothing")
2029/// uses. Both already mean "allow reads, writes, and execution, but decide
2030/// per request rather than blanket-granting" (see `HostPolicy::Auto`'s own
2031/// doc comment), which is the correct non-extreme default whether the
2032/// request asked for a deliberate middle ground or asked for nothing to be
2033/// imposed at all.
2034fn host_policy_for_approval_level(level: ApprovalLevel) -> HostPolicy {
2035    match level {
2036        ApprovalLevel::FullAuto => HostPolicy::Yolo,
2037        ApprovalLevel::ReadOnly => HostPolicy::ReadOnly,
2038        ApprovalLevel::Moderate | ApprovalLevel::Unmanaged => HostPolicy::Auto,
2039    }
2040}
2041
2042/// Whether a session at this approval level parks a `session/request_
2043/// permission` for an operator instead of answering it from policy on the
2044/// spot (`AcpSessionOptions::defer_permission_requests`).
2045///
2046/// Reads `asks_for_permission` straight off
2047/// `gate4agent_catalog::approval_level_resolution` -- the provider's own
2048/// vendor mode, declared beside its flag -- rather than matching on the
2049/// `ApprovalLevel`'s name. That distinction used to matter in practice: this
2050/// function previously matched on the level alone and assumed `ReadOnly`
2051/// never asks, but claude's `ReadOnly` launched `--permission-mode default`,
2052/// claude's own **interactive** mode, which asks about everything. A live
2053/// run under that flag produced a completed tool call and zero
2054/// `host-request-observed` because deferral was off for the one level that
2055/// was actually asking. `approval_level_resolution`'s `ReadOnly` row for
2056/// claude now launches `plan` (which genuinely never asks) instead, so the
2057/// caller (this transport's own ACP spawn branch) must already have refused
2058/// the spawn outright for any provider `approval_level_resolution` marks
2059/// `Unsupported` for this level -- see that call site -- before this
2060/// function is reached; `Unsupported` here is defensive-only and defers,
2061/// the conservative choice, rather than assuming silence.
2062///
2063/// `Unmanaged` always resolves `asks_for_permission: false` -- it decides
2064/// `session/request_permission` immediately (auto-approve) rather than
2065/// parking it, since some providers' ACP clients won't wait out a deferred
2066/// decision (kimi reports the call as refused). The managed levels'
2067/// `asks_for_permission` still varies per provider and per level -- that is
2068/// a fact about today's four providers' vendor modes, not a rule this
2069/// function encodes; a fifth provider or a vendor mode change could shift it
2070/// without this function's logic changing at all, which is the point of
2071/// reading the catalog instead of the level.
2072fn defers_permission_requests(agent_id: &AgentId, level: ApprovalLevel) -> bool {
2073    match approval_level_resolution(agent_id, level) {
2074        ApprovalLevelResolution::Supported {
2075            asks_for_permission,
2076            ..
2077        } => asks_for_permission,
2078        ApprovalLevelResolution::Unsupported => true,
2079    }
2080}
2081
2082/// How long [`apply_acp_approval_mode`] waits, after a successful
2083/// `session/set_mode` RPC ack, for the agent's own `current_mode_update`
2084/// notification to corroborate it. Bounded because the notification is
2085/// documented as optional -- `AcpSession::set_mode`'s own doc comment: "an
2086/// agent is not required to also send one after acking this call" -- so an
2087/// agent that never sends it must never stall a spawn indefinitely. The RPC
2088/// ack itself (checked before this wait starts) is the authoritative
2089/// confirmation; this wait is corroboration only, and a timeout here does
2090/// not undo it.
2091const ACP_MODE_CONFIRMATION_TIMEOUT: Duration = Duration::from_secs(5);
2092
2093/// Resolve the concrete ACP mode id [`apply_acp_approval_mode`] must confirm
2094/// and apply for `agent_id` at `level`, or the exact refusal message when no
2095/// mechanism exists to enforce it at all.
2096///
2097/// Outcomes:
2098/// - `Ok(Some(id))` — catalog named a sourced `acp_mode_id`; spawn applies it
2099///   via `session/set_mode` (claude/codex managed levels today).
2100/// - `Ok(None)` for [`ApprovalLevel::Unmanaged`] — imposes nothing.
2101/// - `Ok(None)` when the level is `Supported` with `acp_mode_id: None` **and**
2102///   non-empty vendor `args` — argv is the only lever left (grok FullAuto /
2103///   Moderate; kimi FullAuto). `acp_approval_level_args` carries those flags
2104///   into the process ahead of the ACP subcommand.
2105/// - `Err` for [`ApprovalLevelResolution::Unsupported`] (e.g. grok ReadOnly)
2106///   or a `Supported` row with neither mode id nor flags (kimi Moderate /
2107///   ReadOnly today): refuse rather than launch at the vendor default
2108///   (`mode:Mode="auto"`), which approves itself.
2109fn required_acp_mode(agent_id: &AgentId, level: ApprovalLevel) -> Result<Option<ModeId>, String> {
2110    let (acp_mode_id, carries_argv_flags) = match approval_level_resolution(agent_id, level) {
2111        ApprovalLevelResolution::Unsupported => (None, false),
2112        ApprovalLevelResolution::Supported { acp_mode_id, args, .. } => {
2113            (acp_mode_id, !args.is_empty())
2114        }
2115    };
2116    match (acp_mode_id, level) {
2117        (Some(mode_id), _) => Ok(Some(mode_id)),
2118        (None, ApprovalLevel::Unmanaged) => Ok(None),
2119        // No mode, but the level carries vendor flags: `acp_approval_level_args`
2120        // puts those in the agent's own argv, so the level IS applied and this
2121        // is not a launch at the vendor's default. The refusal below exists to
2122        // stop a session running at wider authority than asked for -- it must
2123        // not also block the one mechanism that narrows it. Measured
2124        // 2026-09-09: kimi announces no ACP modes at all, so before this every
2125        // level but `Unmanaged` refused outright and its own `--yolo` was
2126        // unreachable.
2127        (None, _) if carries_argv_flags => Ok(None),
2128        // opencode / MiniMax Code: the only approval gate is the host's own
2129        // `session/request_permission` policy, which `FullAuto` already
2130        // drives to auto-approve (`asks_for_permission: false`), so the
2131        // level IS applied without a mode or a flag.
2132        (None, ApprovalLevel::FullAuto) if acp_full_auto_is_host_policy(agent_id) => Ok(None),
2133        (None, _) => Err(format!(
2134            "agent '{agent_id}' has no verified ACP mode for {level:?} and the level carries no \
2135             vendor flags to apply through argv either; refusing rather than launching at the \
2136             vendor's own (wider-authority) default"
2137        )),
2138    }
2139}
2140
2141/// The vendor approval flags an ACP-spawned agent needs in its own argv.
2142///
2143/// Exactly the complement of [`required_acp_mode`]: a level that resolved an
2144/// `acp_mode_id` is applied over the wire by `session/set_mode`, so that
2145/// agent's argv stays clean and this returns nothing. A level that resolved
2146/// NO mode has no wire mechanism at all, and returning nothing there means
2147/// launching at the vendor's own default -- the exact wider-authority defect
2148/// the mode machinery exists to close, just reached from the other side.
2149///
2150/// Measured 2026-09-09: every kimi row carries `acp_mode_id: None` (kimi.exe
2151/// 0.29.0 announces no modes), so kimi ran at its own default and refused
2152/// every `g4a_*` MCP tool call at its internal approval prompt without ever
2153/// sending the host a `session/request_permission` -- unreachable by policy,
2154/// by deferral, and by `set_mode` alike. Its `FullAuto` row already carries
2155/// the flag that turns that gate off (`--yolo`); it simply never reached the
2156/// process.
2157fn acp_approval_level_args(agent_id: &AgentId, level: ApprovalLevel) -> Vec<String> {
2158    match approval_level_resolution(agent_id, level) {
2159        ApprovalLevelResolution::Supported { args, acp_mode_id: None, .. } => args,
2160        ApprovalLevelResolution::Supported { acp_mode_id: Some(_), .. } => Vec::new(),
2161        ApprovalLevelResolution::Unsupported => Vec::new(),
2162    }
2163}
2164
2165/// Named refusal for [`apply_acp_approval_mode`]: `level` resolved a real
2166/// catalog `acp_mode_id`, but this agent's own `session/new` handshake never
2167/// announced a mode with that id -- so the mechanism that would apply it
2168/// (`session/set_mode`) has nothing to call. Refusing by name, carrying
2169/// exactly what the agent DID offer, is the alternative to the defect this
2170/// whole rewrite exists to close: silently leaving the session running at
2171/// whichever mode the agent came up in on its own.
2172#[derive(Debug)]
2173struct ApprovalLevelNotOfferedByAgent {
2174    level: ApprovalLevel,
2175    offered: Vec<String>,
2176}
2177
2178impl std::fmt::Display for ApprovalLevelNotOfferedByAgent {
2179    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2180        write!(
2181            formatter,
2182            "ApprovalLevelNotOfferedByAgent {{ level: {:?}, offered: {:?} }}",
2183            self.level, self.offered
2184        )
2185    }
2186}
2187
2188/// `None` when `offered` (the agent's own `session/new` mode catalog) names
2189/// `mode_id`; `Some(message)` -- an [`ApprovalLevelNotOfferedByAgent`],
2190/// stringified -- when it does not. A free function, independent of a live
2191/// [`AcpSession`], so the refusal can be exercised directly against a
2192/// fixture mode list rather than only through a real spawn.
2193fn approval_level_not_offered_message(
2194    level: ApprovalLevel,
2195    mode_id: &ModeId,
2196    offered: &[SessionMode],
2197) -> Option<String> {
2198    if offered.iter().any(|mode| mode.id == mode_id.as_str()) {
2199        None
2200    } else {
2201        Some(
2202            ApprovalLevelNotOfferedByAgent {
2203                level,
2204                offered: offered.iter().map(|mode| mode.id.clone()).collect(),
2205            }
2206            .to_string(),
2207        )
2208    }
2209}
2210
2211/// Apply `mode_id` to a freshly handshaken ACP session (Item 2 of the
2212/// `session/set_mode` approval-level rewrite): refuse by name
2213/// (`approval_level_not_offered_message`) when the agent's own `session/new`
2214/// mode catalog never named this id, otherwise call `session/set_mode` and
2215/// wait, bounded by [`ACP_MODE_CONFIRMATION_TIMEOUT`], for the agent's own
2216/// `current_mode_update` to corroborate it -- only then is the session
2217/// considered up at the requested level.
2218///
2219/// The RPC ack from `AcpSession::set_mode` is the authoritative
2220/// confirmation (it already updates the session's own cached
2221/// `current_mode_id` synchronously on success, and an agent rejecting an
2222/// unknown mode id returns an RPC error there, not a silent no-op); the wait
2223/// on this function's own subscription is corroboration only. A provider
2224/// that never sends `current_mode_update` at all -- permitted by the ACP
2225/// spec -- times out here and the spawn still proceeds, because the RPC ack
2226/// that already succeeded is not undone by a notification that was never
2227/// guaranteed in the first place.
2228async fn apply_acp_approval_mode(
2229    session: &AcpSession,
2230    mode_id: &ModeId,
2231    level: ApprovalLevel,
2232) -> Result<(), String> {
2233    if let Some(message) =
2234        approval_level_not_offered_message(level, mode_id, &session.available_modes())
2235    {
2236        return Err(message);
2237    }
2238
2239    // Subscribed BEFORE `set_mode` is sent, so a fast `current_mode_update`
2240    // cannot race ahead of this receiver's creation and be missed.
2241    let mut confirmation = session.subscribe();
2242    session
2243        .set_mode(mode_id.as_str())
2244        .await
2245        .map_err(|error| format!("session/set_mode to '{mode_id}' failed: {error}"))?;
2246
2247    let _ = tokio::time::timeout(ACP_MODE_CONFIRMATION_TIMEOUT, async {
2248        loop {
2249            match confirmation.recv().await {
2250                Ok(AgentEvent::ModeChanged { mode_id: changed }) if changed == mode_id.as_str() => {
2251                    return;
2252                }
2253                Ok(_) => continue,
2254                Err(_) => return,
2255            }
2256        }
2257    })
2258    .await;
2259
2260    Ok(())
2261}
2262
2263fn validate_spawn_runtime_policy(
2264    policy: ProviderRuntimePolicy,
2265    transport: TransportKind,
2266    has_initial_prompt: bool,
2267    is_resume: bool,
2268) -> Result<(), String> {
2269    policy
2270        .validate()
2271        .map_err(|error| format!("provider runtime policy is invalid: {error}"))?;
2272    // ACP speaks a structured protocol over stdio, not a PTY -- none of the
2273    // capabilities below describe anything that exists for it; they all
2274    // gate inferring provider state from terminal text. The transport-
2275    // support gate for ACP already lives in the kernel
2276    // (`spec.capabilities.transports.acp.is_some()`), so this PTY-semantic
2277    // policy simply does not apply here. Mirrors `gate4agent-runtime-native`'s
2278    // `validate_effect_runtime_policy`, which enforces the same rule one
2279    // layer up.
2280    if transport != TransportKind::Acp {
2281        require_runtime_capability(policy, ProviderRuntimeCapability::RawPtyLifecycle)?;
2282        if transport != TransportKind::Pty {
2283            require_runtime_capability(policy, ProviderRuntimeCapability::SemanticReadiness)?;
2284        }
2285        if has_initial_prompt {
2286            require_runtime_capability(policy, ProviderRuntimeCapability::SemanticReadiness)?;
2287            require_runtime_capability(policy, ProviderRuntimeCapability::StructuredPrompt)?;
2288        }
2289        if is_resume && has_initial_prompt {
2290            require_runtime_capability(policy, ProviderRuntimeCapability::ProviderSessionIdentity)?;
2291            require_runtime_capability(policy, ProviderRuntimeCapability::SemanticResume)?;
2292        }
2293    }
2294    Ok(())
2295}
2296
2297
2298fn is_codex_config_c_overlay_args(arguments: &[OsString]) -> bool {
2299    if arguments.is_empty() || arguments.len() % 2 != 0 {
2300        return false;
2301    }
2302    arguments.chunks_exact(2).all(|pair| {
2303        pair[0].as_os_str() == "-c"
2304            && pair[1]
2305                .to_str()
2306                .is_some_and(|value| !value.is_empty() && value.contains('=') && !value.contains('\0'))
2307    })
2308}
2309
2310fn validate_instance_launch_arguments(
2311    agent_id: &AgentId,
2312    transport: TransportKind,
2313    arguments: &[OsString],
2314) -> Result<(), String> {
2315    if arguments.is_empty() {
2316        return Ok(());
2317    }
2318    let acp_codex_c_overlay = transport == TransportKind::Acp
2319        && agent_id.as_str() == "codex"
2320        && is_codex_config_c_overlay_args(arguments);
2321    if transport != TransportKind::Pty && !acp_codex_c_overlay {
2322        return Err(
2323            "native instance launch arguments require PTY transport (or Codex -c overlays on ACP)"
2324                .to_owned(),
2325        );
2326    }
2327    if arguments.len() > INSTANCE_LAUNCH_ARGS_MAX {
2328        return Err("native instance launch argument count exceeds its bound".to_owned());
2329    }
2330    let mut total_bytes = 0usize;
2331    for argument in arguments {
2332        let argument = argument.to_string_lossy();
2333        if argument.contains('\0') {
2334            return Err("native instance launch argument is invalid".to_owned());
2335        }
2336        if argument.len() > INSTANCE_LAUNCH_ARG_MAX_BYTES {
2337            return Err("native instance launch argument exceeds its bound".to_owned());
2338        }
2339        total_bytes = total_bytes.saturating_add(argument.len());
2340        if total_bytes > INSTANCE_LAUNCH_ARGS_TOTAL_MAX_BYTES {
2341            return Err("native instance launch argument payload exceeds its bound".to_owned());
2342        }
2343        if agent_id.as_str() == "claude"
2344            && RESERVED_CLAUDE_LAUNCH_FLAGS.iter().any(|reserved| {
2345                argument == *reserved
2346                    || (reserved.starts_with("--")
2347                        && argument
2348                            .strip_prefix(reserved)
2349                            .is_some_and(|suffix| suffix.starts_with('=')))
2350                    || (reserved.len() == 2
2351                        && argument
2352                            .strip_prefix(reserved)
2353                            .is_some_and(|suffix| {
2354                                !suffix.is_empty() && !suffix.starts_with('-')
2355                            }))
2356            })
2357        {
2358            return Err(
2359                "native instance launch arguments conflict with Claude session, resume, or prompt authority"
2360                    .to_owned(),
2361            );
2362        }
2363    }
2364    Ok(())
2365}
2366
2367/// True if `value` has the shape of a bearer credential rather than an
2368/// ordinary CLI flag, path, or session identifier.
2369///
2370/// Gate4Agent's own secrets are environment-only and never argv (see
2371/// `gate4agent/CLAUDE.md`), so this should not fire for anything this repo
2372/// itself constructs. It exists as defense-in-depth against a provider CLI
2373/// whose own argv convention accepts a credential positionally. The check is
2374/// deliberately keyword/prefix-based rather than an entropy heuristic: a
2375/// generic "long hex/base64 string" rule would also catch legitimate,
2376/// diagnostically valuable arguments such as a resume session UUID -- which
2377/// is also why [`has_prefixed_hex64_credential_shape`] requires the leading
2378/// `<prefix>_` before it will call a bare hex string a credential at all.
2379fn argument_looks_like_credential(value: &str) -> bool {
2380    const CREDENTIAL_PREFIXES: &[&str] = &["sk-", "sk_", "ghp_", "gho_", "ghs_", "xox", "bearer "];
2381    const CREDENTIAL_MARKERS: &[&str] = &[
2382        "apikey", "api_key", "api-key", "secret", "password", "passwd", "token=",
2383    ];
2384    let lower = value.to_ascii_lowercase();
2385    CREDENTIAL_PREFIXES
2386        .iter()
2387        .any(|prefix| lower.starts_with(prefix))
2388        || CREDENTIAL_MARKERS
2389            .iter()
2390            .any(|marker| lower.contains(marker))
2391        || has_prefixed_hex64_credential_shape(&lower)
2392}
2393
2394/// True if `value` is exactly a short lowercase-alphanumeric prefix (2-8
2395/// characters), an underscore, and 64 lowercase hex characters -- the shape
2396/// every gate4agent-owned or caller-owned bearer credential uses (e.g. the
2397/// hatchery operator token, `g4aho_` + 64 hex, or the H3B local-capability
2398/// token, `g4ah3_` + 64 hex), regardless of which prefix a particular caller
2399/// picks. A bare 64-hex digest with no prefix is deliberately excluded: a
2400/// commit hash, a SHA-256 checksum, or a session digest is legitimate,
2401/// diagnostically valuable argument text, not a credential.
2402fn has_prefixed_hex64_credential_shape(lower: &str) -> bool {
2403    let Some((prefix, digest)) = lower.split_once('_') else {
2404        return false;
2405    };
2406    (2..=8).contains(&prefix.len())
2407        && prefix
2408            .bytes()
2409            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
2410        && digest.len() == 64
2411        && digest
2412            .bytes()
2413            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
2414}
2415
2416/// Renders one provider-CLI argument for a log line: verbatim unless it
2417/// matches [`argument_looks_like_credential`], in which case it is replaced
2418/// with a fixed placeholder rather than printed.
2419fn redact_provider_argument(value: &OsStr) -> String {
2420    let text = value.to_string_lossy();
2421    if argument_looks_like_credential(&text) {
2422        "[redacted-credential-shaped-argument]".to_owned()
2423    } else {
2424        text.into_owned()
2425    }
2426}
2427
2428/// Renders a full provider-CLI argument list for a log line, redacting any
2429/// individual argument that looks like a credential.
2430fn redact_provider_arguments(values: &[OsString]) -> Vec<String> {
2431    values.iter().map(|value| redact_provider_argument(value)).collect()
2432}
2433
2434fn require_runtime_capability(
2435    policy: ProviderRuntimePolicy,
2436    capability: ProviderRuntimeCapability,
2437) -> Result<(), String> {
2438    if policy.admits(capability) {
2439        Ok(())
2440    } else {
2441        Err(format!(
2442            "provider runtime capability {capability:?} is not admitted"
2443        ))
2444    }
2445}
2446
2447fn should_attach_pty_provider_stream(policy: ProviderRuntimePolicy) -> bool {
2448    policy.semantic_readiness || policy.provider_session_identity
2449}
2450
2451fn should_probe_pty_identity(
2452    policy: ProviderRuntimePolicy,
2453    adapter: Option<&gate4agent_types::AdapterBinding>,
2454    authoritative_identity_present: bool,
2455    expected_adapter: &str,
2456) -> bool {
2457    !authoritative_identity_present
2458        && policy.semantic_readiness
2459        && policy.structured_prompt
2460        && policy.provider_session_identity
2461        && adapter.is_some_and(|adapter| adapter.id.as_str() == expected_adapter)
2462}
2463
2464fn prepare_fresh_pty_provider_session(
2465    adapter: Option<&gate4agent_types::AdapterBinding>,
2466    is_resume: bool,
2467    identity_permitted: bool,
2468    launch_extra_args: &mut Vec<OsString>,
2469) -> Option<ProviderSessionIdentity> {
2470    let adapter = adapter?;
2471    if is_resume || !identity_permitted || adapter.id.as_str() != "claude-code" {
2472        return None;
2473    }
2474    let identity = ProviderSessionIdentity {
2475        key: ProviderSessionKey::SessionId,
2476        id: Uuid::new_v4().to_string(),
2477        transcript_path: None,
2478    };
2479    launch_extra_args.push(OsString::from("--session-id"));
2480    launch_extra_args.push(OsString::from(&identity.id));
2481    Some(identity)
2482}
2483
2484fn drain_pty_provider(
2485    key: NativeSessionKey,
2486    provider: &mut OwnedPtyProvider,
2487    observations: &mut Vec<ObservationEnvelope>,
2488) {
2489    while let Some(event) = provider.pending_events.pop_front() {
2490        push_provider_observation(key, provider, event, observations);
2491    }
2492
2493    loop {
2494        let envelope = match provider.replay.pop_front() {
2495            Some(envelope) => Some(envelope),
2496            None => provider.receiver.try_recv().unwrap_or_default(),
2497        };
2498        let Some(envelope) = envelope else {
2499            break;
2500        };
2501        match envelope.event {
2502            PtyEvent::Output(data) => {
2503                let raw = provider.utf8.push(&data);
2504                if raw.is_empty() {
2505                    continue;
2506                }
2507                if provider.semantic_events {
2508                    if let Some(info) = provider.rate_limits.detect(&raw) {
2509                        push_provider_observation(
2510                            key,
2511                            provider,
2512                            rate_limit_event(info),
2513                            observations,
2514                        );
2515                    }
2516                }
2517                let identity = provider
2518                    .kimi_identity
2519                    .as_mut()
2520                    .and_then(|extractor| extractor.push(&raw));
2521                if let Some(identity) = identity {
2522                    if !provider.provider_session_started {
2523                        push_provider_observation(
2524                            key,
2525                            provider,
2526                            ProviderEvent::SessionStarted {
2527                                session_id: identity.id.clone(),
2528                                model: String::new(),
2529                                tools: Vec::new(),
2530                            },
2531                            observations,
2532                        );
2533                        provider.provider_session_started = true;
2534                    }
2535                    push_provider_observation(
2536                        key,
2537                        provider,
2538                        ProviderEvent::SessionIdentityObserved { identity },
2539                        observations,
2540                    );
2541                }
2542                if provider.semantic_events {
2543                    let messages = provider
2544                        .pipeline
2545                        .get_mut()
2546                        .unwrap_or_else(|poisoned| poisoned.into_inner())
2547                        .process(&raw);
2548                    for message in messages {
2549                        if let Some(event) = parsed_provider_event(message) {
2550                            push_provider_observation(key, provider, event, observations);
2551                        }
2552                    }
2553                }
2554            }
2555            PtyEvent::DataGap {
2556                from_sequence,
2557                to_sequence,
2558                ..
2559            } => {
2560                provider.utf8.clear();
2561                if let Some(extractor) = &mut provider.kimi_identity {
2562                    extractor.reset_stream();
2563                }
2564                provider
2565                    .pipeline
2566                    .get_mut()
2567                    .unwrap_or_else(|poisoned| poisoned.into_inner())
2568                    .clear();
2569                let missed = to_sequence
2570                    .checked_sub(from_sequence)
2571                    .and_then(|difference| difference.checked_add(1));
2572                if let Some((source_sequence, missed)) = missed.and_then(|missed| {
2573                    reserve_provider_gap_sequence(&mut provider.next_provider_sequence, missed)
2574                        .map(|source_sequence| (source_sequence, missed))
2575                }) {
2576                    observations.push(ObservationEnvelope {
2577                        operation_id: None,
2578                        instance_id: key.instance_id,
2579                        generation: key.generation,
2580                        observation: ControlObservation::ProviderGap {
2581                            source: provider.source.clone(),
2582                            source_sequence,
2583                            missed,
2584                        },
2585                    });
2586                }
2587            }
2588            PtyEvent::ReaderError { message } | PtyEvent::OperatorActionRequired { message } => {
2589                push_provider_observation(
2590                    key,
2591                    provider,
2592                    ProviderEvent::Error { message },
2593                    observations,
2594                );
2595            }
2596            PtyEvent::Started
2597            | PtyEvent::Resized(_)
2598            | PtyEvent::ForegroundProcess(_)
2599            | PtyEvent::SnapshotAvailable { .. }
2600            | PtyEvent::Exited { .. } => {}
2601        }
2602    }
2603}
2604
2605fn push_provider_observation(
2606    key: NativeSessionKey,
2607    provider: &mut OwnedPtyProvider,
2608    event: ProviderEvent,
2609    observations: &mut Vec<ObservationEnvelope>,
2610) {
2611    let sequence = provider.next_provider_sequence;
2612    provider.next_provider_sequence = provider.next_provider_sequence.saturating_add(1);
2613    observations.push(ObservationEnvelope {
2614        operation_id: None,
2615        instance_id: key.instance_id,
2616        generation: key.generation,
2617        observation: ControlObservation::ProviderEvent {
2618            source: provider.source.clone(),
2619            sequence,
2620            event,
2621        },
2622    });
2623}
2624
2625fn reserve_provider_gap_sequence(next_sequence: &mut u64, missed: u64) -> Option<u64> {
2626    if missed == 0 {
2627        return None;
2628    }
2629    let Some(source_sequence) = missed
2630        .checked_sub(1)
2631        .and_then(|offset| next_sequence.checked_add(offset))
2632    else {
2633        *next_sequence = u64::MAX;
2634        return None;
2635    };
2636    let Some(next) = source_sequence.checked_add(1) else {
2637        *next_sequence = u64::MAX;
2638        return None;
2639    };
2640    *next_sequence = next;
2641    Some(source_sequence)
2642}
2643
2644fn parsed_provider_event(message: ParsedMessage) -> Option<ProviderEvent> {
2645    match message.class {
2646        MessageClass::AiResponse => Some(ProviderEvent::Text {
2647            text: message.content,
2648            is_delta: message.metadata.is_partial,
2649        }),
2650        MessageClass::ThinkingIndicator => Some(ProviderEvent::Thinking {
2651            text: message.content,
2652        }),
2653        MessageClass::Error => Some(ProviderEvent::Error {
2654            message: message.content,
2655        }),
2656        MessageClass::PromptReady => Some(ProviderEvent::Ready),
2657        MessageClass::ToolApproval => Some(ProviderEvent::InteractionRequested {
2658            request_id: None,
2659            interaction_kind: ProviderInteractionKind::Approval,
2660            tool_name: message
2661                .metadata
2662                .tool_name
2663                .unwrap_or_else(|| "unknown".to_owned()),
2664            // A PTY screen has no structured title or option list to read
2665            // off it the way ACP's `session/request_permission` does --
2666            // this source has none, not a dropped one.
2667            title: None,
2668            prompt: message.content,
2669            options: Vec::new(),
2670            agent_id: None,
2671        }),
2672        MessageClass::InfoMessage
2673        | MessageClass::UiElement
2674        | MessageClass::UserEcho
2675        | MessageClass::Menu
2676        | MessageClass::Raw => None,
2677    }
2678}
2679
2680fn rate_limit_event(info: gate4agent::core::types::RateLimitInfo) -> ProviderEvent {
2681    ProviderEvent::RateLimited {
2682        limit_type: provider_rate_limit_kind(info.limit_type),
2683        resets_at: info.resets_at.map(|value| value.to_rfc3339()),
2684        usage_percent: info.usage_percent.map(|value| value.to_string()),
2685        raw_message: info.raw_message,
2686    }
2687}
2688
2689/// Map `gate4agent`'s `HostRequestDecision`/`HostDecisionAuthority` onto
2690/// this crate's wire-typed `ProviderHostRequestDecision`/
2691/// `ProviderHostDecisionAuthority` -- `gate4agent-types` cannot depend on
2692/// `gate4agent` (see that crate's own `CLAUDE.md`), so the conversion lives
2693/// here, the shell that already depends on both. A plain match, not
2694/// `format!("{:?}", ..)`: the wire carries the typed value itself.
2695fn provider_host_request_decision(decision: HostRequestDecision) -> ProviderHostRequestDecision {
2696    match decision {
2697        HostRequestDecision::Granted { by } => {
2698            ProviderHostRequestDecision::Granted { by: provider_host_decision_authority(by) }
2699        }
2700        HostRequestDecision::Denied { by } => {
2701            ProviderHostRequestDecision::Denied { by: provider_host_decision_authority(by) }
2702        }
2703        HostRequestDecision::Deferred => ProviderHostRequestDecision::Deferred,
2704    }
2705}
2706
2707fn provider_host_decision_authority(by: HostDecisionAuthority) -> ProviderHostDecisionAuthority {
2708    match by {
2709        HostDecisionAuthority::Gate => ProviderHostDecisionAuthority::Gate,
2710        HostDecisionAuthority::Policy => ProviderHostDecisionAuthority::Policy,
2711        HostDecisionAuthority::Operator => ProviderHostDecisionAuthority::Operator,
2712        HostDecisionAuthority::DeadlinePolicy => ProviderHostDecisionAuthority::DeadlinePolicy,
2713    }
2714}
2715
2716/// Map `gate4agent`'s `HostRequestOutcome` onto this crate's wire-typed
2717/// `ProviderHostRequestOutcome` -- same reason `provider_host_request_
2718/// decision` exists rather than a `From` impl on either side. Carried
2719/// through verbatim, the same convention `reason` already follows on this
2720/// mapping: bounding happens at `ProviderEvent::validate_ingress`
2721/// (`PROVIDER_EVENT_TEXT_MAX_BYTES`, rejecting rather than truncating), not
2722/// here.
2723fn provider_host_request_outcome(outcome: HostRequestOutcome) -> ProviderHostRequestOutcome {
2724    match outcome {
2725        HostRequestOutcome::Executed => ProviderHostRequestOutcome::Executed,
2726        HostRequestOutcome::Failed { error } => ProviderHostRequestOutcome::Failed { error },
2727    }
2728}
2729
2730/// Map the detector's own `RateLimitType` onto the wire-typed
2731/// `ProviderRateLimitKind`. A plain match, not `format!("{:?}", ..)`: the
2732/// wire carries the typed value itself, not a Debug-rendering of it.
2733fn provider_rate_limit_kind(
2734    limit_type: gate4agent::core::types::RateLimitType,
2735) -> ProviderRateLimitKind {
2736    use gate4agent::core::types::RateLimitType;
2737    match limit_type {
2738        RateLimitType::Session => ProviderRateLimitKind::Session,
2739        RateLimitType::Daily => ProviderRateLimitKind::Daily,
2740        RateLimitType::Weekly => ProviderRateLimitKind::Weekly,
2741        RateLimitType::Unknown => ProviderRateLimitKind::Unknown,
2742    }
2743}
2744
2745/// `mode_catalogue` reads the mode catalogue off `owned.session` for
2746/// transports that have one -- only `AcpSession::available_modes()` does
2747/// (see `provider_event`'s doc comment); `collect_provider_map`'s two
2748/// non-ACP call sites pass `|_| Vec::new()` since their `AgentEvent` stream
2749/// never carries `ModeChanged` in the first place.
2750fn collect_provider_map<S>(
2751    sessions: &mut BTreeMap<NativeSessionKey, OwnedProviderSession<S>>,
2752    observations: &mut Vec<ObservationEnvelope>,
2753    mode_catalogue: impl Fn(&S) -> Vec<SessionMode>,
2754) {
2755    for (key, owned) in sessions {
2756        let available_modes = mode_catalogue(&owned.session);
2757        drain_provider_stream(
2758            *key,
2759            &owned.source,
2760            &mut owned.events,
2761            &mut owned.pending_events,
2762            &mut owned.pending_provider_events,
2763            &mut owned.next_provider_sequence,
2764            Some(&mut owned.observed_exit_code),
2765            observations,
2766            &available_modes,
2767        );
2768    }
2769}
2770
2771/// Pushes one already-sequenced `ProviderEvent` onto `observations`, sharing
2772/// the same per-session `next_provider_sequence` counter regardless of which
2773/// of `drain_provider_stream`'s three sources (`pending_events` mapped
2774/// through `provider_event`, raw `pending_provider_events`, or the live
2775/// broadcast stream) produced it -- so sequence numbers stay contiguous
2776/// across all three.
2777fn push_sequenced_provider_event(
2778    key: NativeSessionKey,
2779    source: &ProviderSource,
2780    next_provider_sequence: &mut u64,
2781    observations: &mut Vec<ObservationEnvelope>,
2782    event: ProviderEvent,
2783) {
2784    let sequence = *next_provider_sequence;
2785    *next_provider_sequence = next_provider_sequence.saturating_add(1);
2786    observations.push(ObservationEnvelope {
2787        operation_id: None,
2788        instance_id: key.instance_id,
2789        generation: key.generation,
2790        observation: ControlObservation::ProviderEvent {
2791            source: source.clone(),
2792            sequence,
2793            event,
2794        },
2795    });
2796}
2797
2798fn drain_provider_stream(
2799    key: NativeSessionKey,
2800    source: &ProviderSource,
2801    events: &mut broadcast::Receiver<AgentEvent>,
2802    pending_events: &mut VecDeque<AgentEvent>,
2803    pending_provider_events: &mut VecDeque<ProviderEvent>,
2804    next_provider_sequence: &mut u64,
2805    mut observed_exit_code: Option<&mut Option<i32>>,
2806    observations: &mut Vec<ObservationEnvelope>,
2807    available_modes: &[SessionMode],
2808) {
2809    loop {
2810        // `pending_events` (seeded `AgentEvent`s, e.g. `SessionStart`) drains
2811        // first and fully, in order; only once it is empty does
2812        // `pending_provider_events` (seeded raw `ProviderEvent`s, e.g.
2813        // `SessionIdentityObserved`, with no `AgentEvent` counterpart to
2814        // carry them) get a turn, and only once THAT is empty does this fall
2815        // through to the live broadcast stream -- so anything seeded at the
2816        // spawn site always reaches `observations` ahead of anything the
2817        // provider itself emits afterwards, and in the exact relative order
2818        // the spawn site seeded it in.
2819        if let Some(event) = pending_events.pop_front() {
2820            match event {
2821                AgentEvent::Exited { code } => {
2822                    if let Some(exit_code) = observed_exit_code.as_deref_mut() {
2823                        *exit_code = Some(code);
2824                    }
2825                }
2826                event => {
2827                    if let Some(event) = provider_event(event, available_modes) {
2828                        push_sequenced_provider_event(
2829                            key,
2830                            source,
2831                            next_provider_sequence,
2832                            observations,
2833                            event,
2834                        );
2835                    }
2836                }
2837            }
2838            continue;
2839        }
2840        if let Some(event) = pending_provider_events.pop_front() {
2841            push_sequenced_provider_event(key, source, next_provider_sequence, observations, event);
2842            continue;
2843        }
2844        match events.try_recv() {
2845            Ok(AgentEvent::Exited { code }) => {
2846                if let Some(exit_code) = observed_exit_code.as_deref_mut() {
2847                    *exit_code = Some(code);
2848                }
2849            }
2850            Ok(event) => {
2851                if let Some(event) = provider_event(event, available_modes) {
2852                    push_sequenced_provider_event(
2853                        key,
2854                        source,
2855                        next_provider_sequence,
2856                        observations,
2857                        event,
2858                    );
2859                }
2860            }
2861            Err(broadcast::error::TryRecvError::Lagged(missed)) => {
2862                if let Some(source_sequence) =
2863                    reserve_provider_gap_sequence(next_provider_sequence, missed)
2864                {
2865                    observations.push(ObservationEnvelope {
2866                        operation_id: None,
2867                        instance_id: key.instance_id,
2868                        generation: key.generation,
2869                        observation: ControlObservation::ProviderGap {
2870                            source: source.clone(),
2871                            source_sequence,
2872                            missed,
2873                        },
2874                    });
2875                }
2876            }
2877            Err(broadcast::error::TryRecvError::Empty | broadcast::error::TryRecvError::Closed) => {
2878                break
2879            }
2880        }
2881    }
2882}
2883
2884fn collect_provider_exits<S>(
2885    sessions: &mut BTreeMap<NativeSessionKey, OwnedProviderSession<S>>,
2886    observations: &mut Vec<ObservationEnvelope>,
2887    finished: impl Fn(&S) -> bool,
2888) {
2889    let completed: Vec<_> = sessions
2890        .iter()
2891        .filter_map(|(key, owned)| {
2892            (owned.observed_exit_code.is_some() || finished(&owned.session)).then_some(*key)
2893        })
2894        .collect();
2895    for key in completed {
2896        let owned = sessions
2897            .remove(&key)
2898            .expect("completed provider key came from the owned session map");
2899        observations.push(ObservationEnvelope {
2900            operation_id: None,
2901            instance_id: key.instance_id,
2902            generation: key.generation,
2903            observation: ControlObservation::ProcessExited {
2904                exit_code: owned.observed_exit_code,
2905                final_terminal: None,
2906            },
2907        });
2908    }
2909}
2910
2911/// Prefix tags [`encode_rpc_request_id`] / [`decode_rpc_request_id`] use to
2912/// keep an `RpcId::Number` and an `RpcId::String` from colliding once both
2913/// are flattened into the bare `Option<String>` that
2914/// `ProviderEvent::InteractionRequested::request_id` and
2915/// `ProviderInteractionTarget::provider_request_id` carry.
2916const RPC_REQUEST_ID_NUMBER_PREFIX: &str = "number:";
2917const RPC_REQUEST_ID_STRING_PREFIX: &str = "string:";
2918
2919/// Encode a JSON-RPC id as the `request_id` string carried on
2920/// `ProviderEvent::InteractionRequested` -- minted once, in `provider_event`'s
2921/// `AgentEvent::RpcIncomingRequest` arm, the moment a `session/request_
2922/// permission` call is first reported `HostRequestDecision::Deferred`. Read
2923/// back by [`decode_rpc_request_id`] when a later `ResolveInteraction`
2924/// effect needs to find this exact pending request again in
2925/// `AcpSession::resolve_pending_request` (`gate4agent::acp::session`).
2926///
2927/// Tagged rather than a bare `to_string()`: an agent-issued
2928/// `RpcId::Number(42)` and `RpcId::String("42".into())` are different ids on
2929/// the wire and must not collide into the same encoded string.
2930fn encode_rpc_request_id(id: &RpcId) -> String {
2931    match id {
2932        RpcId::Number(number) => format!("{RPC_REQUEST_ID_NUMBER_PREFIX}{number}"),
2933        RpcId::String(value) => format!("{RPC_REQUEST_ID_STRING_PREFIX}{value}"),
2934    }
2935}
2936
2937/// Inverse of [`encode_rpc_request_id`]. `None` covers both an unrecognized
2938/// tag and a `number:` tag whose remainder does not parse as a `u64` --
2939/// either way, not an id this process ever minted, so there is nothing to
2940/// look up in `AcpSession`'s pending-request map.
2941fn decode_rpc_request_id(raw: &str) -> Option<RpcId> {
2942    if let Some(number) = raw.strip_prefix(RPC_REQUEST_ID_NUMBER_PREFIX) {
2943        return number.parse::<u64>().ok().map(RpcId::Number);
2944    }
2945    raw.strip_prefix(RPC_REQUEST_ID_STRING_PREFIX)
2946        .map(|value| RpcId::String(value.to_owned()))
2947}
2948
2949/// Resolve a `ControlEffect::ResolveInteraction` naming exactly why it
2950/// could not be routed, when it could not be -- see
2951/// `docs/gate4agent/plans/gate4agent-acp-control-plane-on-the-wire-2026-09-02.md`
2952/// §4a-§5, where this is called "the deferral organ, not the plumbing" that
2953/// was still missing.
2954///
2955/// `session` is `None` for every transport this crate owns other than a
2956/// live ACP session for `key` -- PTY and pipe sessions never defer a
2957/// `session/request_permission` call in the first place (only
2958/// `AcpSessionOptions::defer_permission_requests` does, and that field only
2959/// exists on `AcpSessionOptions`), so there is never anything for them to
2960/// resolve here.
2961fn resolve_acp_interaction_observation(
2962    session: Option<&AcpSession>,
2963    target: ProviderInteractionTarget,
2964    response: ProviderInteractionResponse,
2965) -> ControlObservation {
2966    let interaction_id = target.interaction_id;
2967    let fail = |message: String| ControlObservation::InteractionResolutionFailed {
2968        interaction_id,
2969        message,
2970    };
2971    let Some(session) = session else {
2972        return fail("semantic interaction resolution requires an ACP session".to_owned());
2973    };
2974    let Some(provider_request_id) = target.provider_request_id.as_deref() else {
2975        return fail("ACP interaction resolution requires a provider request id".to_owned());
2976    };
2977    let Some(id) = decode_rpc_request_id(provider_request_id) else {
2978        return fail(format!(
2979            "ACP interaction resolution request id {provider_request_id:?} is not a valid JSON-RPC id"
2980        ));
2981    };
2982    match resolve_acp_permission_interaction(session, &id, response) {
2983        Ok(()) => ControlObservation::InteractionResolutionCompleted { interaction_id },
2984        Err(message) => fail(message),
2985    }
2986}
2987
2988/// Route an operator's `ProviderInteractionResponse` for a deferred ACP
2989/// `session/request_permission` call into
2990/// `AcpSession::resolve_pending_request_as` (`gate4agent::acp::session`).
2991///
2992/// The operator states an intent, not an option id, and that is deliberate:
2993/// an ACP agent offers whatever subset of the four `PermissionOptionKind`
2994/// values it likes, and an `optionId` it never offered is ignored rather
2995/// than refused -- so a fabricated one would grant nothing while reporting
2996/// success. Selecting a REAL offered option is therefore
2997/// `AcpSession`'s job, since it is the side that holds the pending request's
2998/// own params; it walks the same preference order `HostPolicy` walks,
2999/// through one shared selector, so an approval means the same thing whether
3000/// policy or a human produced it. If the agent offered nothing in the
3001/// requested direction the answer is `Cancelled`, which every ACP agent
3002/// accepts as complete.
3003///
3004/// This is also why the wire verb carries a `ProviderInteractionResponse` --
3005/// the same approve/deny vocabulary a PTY interaction uses -- rather than an
3006/// ACP-specific option id: all three chains say the same thing to an
3007/// operator, and only the ACP path has to know what an option id is.
3008///
3009/// `Answer` never applies here: ACP `session/request_permission` only ever
3010/// offers allow/deny options, never a free-text one.
3011fn resolve_acp_permission_interaction(
3012    session: &AcpSession,
3013    id: &RpcId,
3014    response: ProviderInteractionResponse,
3015) -> Result<(), String> {
3016    let choice = match response {
3017        ProviderInteractionResponse::ApproveOnce => OperatorPermissionChoice::Approve,
3018        ProviderInteractionResponse::Deny => OperatorPermissionChoice::Reject,
3019        ProviderInteractionResponse::Answer { .. } => {
3020            return Err("ACP permission interactions do not accept free-text answers".to_owned())
3021        }
3022    };
3023    session.resolve_pending_request_as(id, choice).map_err(|error| error.to_string())
3024}
3025
3026/// Resolve a `ControlEffect::SetSessionMode` against a live ACP session's
3027/// own advertised mode catalogue, naming exactly why it could not be
3028/// routed when it could not be -- same refusal-by-name discipline as
3029/// [`resolve_acp_interaction_observation`].
3030///
3031/// There is no `supports_*` probe for session modes (unlike
3032/// `AcpSession::supports_session_list` and its siblings): the ACP
3033/// `sessionCapabilities` flags block carries no `modes` key at all, so the
3034/// mode catalogue seeded at handshake (`AcpSession::available_modes`) IS
3035/// the capability signal -- empty means the agent never advertised any
3036/// modes, non-empty-but-missing-this-id means it advertised modes but not
3037/// this one.
3038async fn set_acp_session_mode_observation(
3039    session: Option<&AcpSession>,
3040    mode_id: String,
3041) -> ControlObservation {
3042    let Some(session) = session else {
3043        return ControlObservation::SessionModeSetFailed {
3044            message: "session mode switch requires an ACP session".to_owned(),
3045        };
3046    };
3047    let catalogue = session.available_modes();
3048    if catalogue.is_empty() {
3049        return ControlObservation::SessionModeSetFailed {
3050            message: "the provider announces no session-mode capability".to_owned(),
3051        };
3052    }
3053    if !catalogue.iter().any(|mode| mode.id == mode_id) {
3054        return ControlObservation::SessionModeSetFailed {
3055            message: format!("the provider never offered mode {mode_id:?}"),
3056        };
3057    }
3058    match session.set_mode(&mode_id).await {
3059        Ok(()) => ControlObservation::SessionModeSet { mode_id },
3060        Err(error) => ControlObservation::SessionModeSetFailed {
3061            message: error.to_string(),
3062        },
3063    }
3064}
3065
3066/// Resolve a `ControlEffect::SetSessionConfigOption` against a live ACP
3067/// session's own advertised config-option catalogue -- same capability
3068/// reasoning as [`set_acp_session_mode_observation`] (no dedicated
3069/// `supports_*` probe; the catalogue seeded at handshake, `AcpSession::
3070/// config_options`, is the capability signal).
3071///
3072/// `value_json` arrives already validated as parseable JSON at the wire
3073/// boundary (`gate4agent-node-protocol`'s `deserialize_acp_config_value_
3074/// json`) and bounds-checked again at the engine
3075/// (`gate4agent_types::validate_session_config_value_json`), but is only
3076/// ever carried as text up to here -- `gate4agent-types` does not depend on
3077/// `serde_json`. Parsing it into the `serde_json::Value` `AcpSession::
3078/// set_config_option` actually takes is this function's job; the target
3079/// type is inferred from that call rather than named directly, so this
3080/// crate never needs its own `serde_json` dependency.
3081async fn set_acp_session_config_option_observation(
3082    session: Option<&AcpSession>,
3083    option_id: String,
3084    value_json: String,
3085) -> ControlObservation {
3086    let Some(session) = session else {
3087        return ControlObservation::SessionConfigOptionSetFailed {
3088            message: "session config-option switch requires an ACP session".to_owned(),
3089        };
3090    };
3091    let catalogue = session.config_options();
3092    if catalogue.is_empty() {
3093        return ControlObservation::SessionConfigOptionSetFailed {
3094            message: "the provider announces no session config-option capability".to_owned(),
3095        };
3096    }
3097    if !catalogue.iter().any(|option| option.id == option_id) {
3098        return ControlObservation::SessionConfigOptionSetFailed {
3099            message: format!("the provider never offered config option {option_id:?}"),
3100        };
3101    }
3102    let value = match value_json.parse() {
3103        Ok(value) => value,
3104        Err(error) => {
3105            return ControlObservation::SessionConfigOptionSetFailed {
3106                message: format!("session config option value is not valid JSON: {error}"),
3107            }
3108        }
3109    };
3110    match session.set_config_option(&option_id, value).await {
3111        Ok(()) => ControlObservation::SessionConfigOptionSet { option_id },
3112        Err(error) => ControlObservation::SessionConfigOptionSetFailed {
3113            message: error.to_string(),
3114        },
3115    }
3116}
3117
3118/// Resolve a `ControlEffect::SetSessionModel`. Unlike session modes and
3119/// config options, `AcpSession` exposes no setter at all for this --
3120/// `available_models`/`current_model_id` observe Grok's vendor `_x.ai/
3121/// models/update` catalogue, but no live capture has ever shown a
3122/// host-invocable RPC to request a switch (ACP proper has no `session/
3123/// set_model`, and no vendor extension for one has been verified). Refuses
3124/// by name rather than fabricate a call the crate documented it would
3125/// never invent -- see `ControlCommand::SetSessionModel`'s doc comment.
3126fn set_acp_session_model_observation(
3127    session: Option<&AcpSession>,
3128    model_id: String,
3129) -> ControlObservation {
3130    if session.is_none() {
3131        return ControlObservation::SessionModelSetFailed {
3132            message: "session model switch requires an ACP session".to_owned(),
3133        };
3134    }
3135    ControlObservation::SessionModelSetFailed {
3136        message: format!(
3137            "this provider offers no host-invocable model-switch method (requested model {model_id:?})"
3138        ),
3139    }
3140}
3141
3142/// Maps one `AgentEvent` onto the wire-typed `ProviderEvent`. `available_
3143/// modes` is used ONLY by the `AgentEvent::ModeChanged` arm -- it carries
3144/// the mode catalogue `AcpSession::available_modes()` read at handshake
3145/// (`session/new`), so a mode change reports the SAME catalogue the agent
3146/// actually offered, not just the id that changed. Every other arm ignores
3147/// it; passing `&[]` from a non-ACP transport (which never emits
3148/// `ModeChanged` in the first place -- see `update_to_event`'s
3149/// `CurrentModeUpdate` arm, `gate4agent`'s `src/acp/protocol.rs`) changes
3150/// nothing observable.
3151/// Maps `gate4agent`'s own `StopReason` onto the wire-typed
3152/// `ProviderStopReason` mirror -- see that type's own doc comment for why
3153/// this crate keeps a second copy rather than sharing one.
3154fn map_provider_stop_reason(reason: StopReason) -> ProviderStopReason {
3155    match reason {
3156        StopReason::EndTurn => ProviderStopReason::EndTurn,
3157        StopReason::MaxTokens => ProviderStopReason::MaxTokens,
3158        StopReason::MaxTurnRequests => ProviderStopReason::MaxTurnRequests,
3159        StopReason::Refusal => ProviderStopReason::Refusal,
3160        StopReason::Cancelled => ProviderStopReason::Cancelled,
3161        StopReason::Other(value) => ProviderStopReason::Other { value },
3162        StopReason::ProviderError { code, message, vendor_code } => {
3163            ProviderStopReason::ProviderError { code, message, vendor_code }
3164        }
3165    }
3166}
3167
3168fn provider_event(event: AgentEvent, available_modes: &[SessionMode]) -> Option<ProviderEvent> {
3169    match event {
3170        AgentEvent::SessionStart {
3171            session_id,
3172            model,
3173            tools,
3174        } => Some(ProviderEvent::SessionStarted {
3175            session_id,
3176            model,
3177            tools,
3178        }),
3179        AgentEvent::Text { text, is_delta } => Some(ProviderEvent::Text { text, is_delta }),
3180        AgentEvent::Thinking { text } => Some(ProviderEvent::Thinking { text }),
3181        AgentEvent::ToolStart { id, name, input } => Some(ProviderEvent::ToolStarted {
3182            id,
3183            name,
3184            input_json: input.to_string(),
3185            agent_id: None,
3186        }),
3187        AgentEvent::ToolResult {
3188            id,
3189            output,
3190            is_error,
3191            duration_ms,
3192            non_execution_kind,
3193        } => Some(ProviderEvent::ToolCompleted {
3194            id,
3195            output,
3196            is_error,
3197            duration_ms,
3198            agent_id: None,
3199            non_execution_kind,
3200        }),
3201        AgentEvent::TurnComplete {
3202            input_tokens,
3203            output_tokens,
3204            cache_read_tokens,
3205            cache_write_tokens,
3206            reasoning_tokens,
3207            context_window,
3208            is_cumulative,
3209        } => Some(ProviderEvent::TurnCompleted {
3210            usage: TokenUsage {
3211                input_tokens,
3212                output_tokens,
3213                cache_read_tokens,
3214                cache_write_tokens,
3215                reasoning_tokens,
3216                context_window,
3217            },
3218            is_cumulative,
3219        }),
3220        AgentEvent::ContextWindowUsage { usage } => {
3221            Some(ProviderEvent::ContextWindowUsage {
3222                usage: ProviderContextWindowUsage {
3223                    uncached_input_tokens: usage.uncached_input_tokens,
3224                    cache_read_tokens: usage.cache_read_tokens,
3225                    cache_write_tokens: usage.cache_write_tokens,
3226                    output_tokens: usage.output_tokens,
3227                    unattributed_tokens: usage.unattributed_tokens,
3228                    used_tokens: usage.used_tokens,
3229                    capacity_tokens: usage.capacity_tokens,
3230                },
3231            })
3232        }
3233        AgentEvent::SessionEnd {
3234            result,
3235            cost_usd,
3236            is_error,
3237            stop_reason,
3238        } => Some(ProviderEvent::SessionEnded {
3239            result,
3240            cost_usd: cost_usd.map(|cost| cost.to_string()),
3241            is_error,
3242            stop_reason: stop_reason.map(map_provider_stop_reason),
3243        }),
3244        AgentEvent::Error { message } => Some(ProviderEvent::Error { message }),
3245        // ACP-only: `acp::session::AcpSession::start_prompt` synthesizes
3246        // this locally when a `session/prompt` call ends without a success
3247        // response (an agent RPC error, the session closing mid-call, or
3248        // `prompt_timeout` elapsing) -- see that event's own doc comment.
3249        // `ProviderEvent::TurnInterrupted` carries no `reason` field (it
3250        // predates this source and is also used by a PTY-side interrupt
3251        // with no text of its own to attach), so the reason is logged here
3252        // rather than silently dropped -- this is the one place downstream
3253        // of the ACP session that ever sees it.
3254        AgentEvent::TurnInterrupted { reason } => {
3255            tracing::warn!(reason = %reason, "acp turn interrupted");
3256            Some(ProviderEvent::TurnInterrupted)
3257        }
3258        AgentEvent::PtyParsed(message) => parsed_provider_event(message),
3259        AgentEvent::PtyReady => Some(ProviderEvent::Ready),
3260        AgentEvent::PtyToolApproval {
3261            tool_name,
3262            description,
3263        } => Some(ProviderEvent::InteractionRequested {
3264            request_id: None,
3265            interaction_kind: ProviderInteractionKind::Approval,
3266            tool_name,
3267            // A PTY screen has no structured title or option list to read
3268            // off it the way ACP's `session/request_permission` does --
3269            // this source has none, not a dropped one.
3270            title: None,
3271            prompt: description.unwrap_or_default(),
3272            options: Vec::new(),
3273            agent_id: None,
3274        }),
3275        AgentEvent::RateLimit(info) => Some(rate_limit_event(info)),
3276        // A `session/request_permission` call the host left `Deferred` (see
3277        // `AcpSessionOptions::defer_permission_requests`) is the one host
3278        // request an operator can actually act on -- so, ONLY for that
3279        // first, deferred sighting of a given id, this becomes an
3280        // `InteractionRequested` carrying the id (`encode_rpc_request_id`)
3281        // instead of the audit-only `HostRequestObserved` every other host
3282        // request becomes. The SAME id's eventual `Granted`/`Denied`
3283        // (`HostRequestDecision`'s doc comment on `Deferred`) still falls
3284        // through to `HostRequestObserved` below, exactly as before -- see
3285        // `docs/gate4agent/plans/gate4agent-acp-control-plane-on-the-wire-2026-09-02.md`
3286        // §4a.2, which is what this replaces (`id: _`, the id silently
3287        // dropped, so an ACP permission request never became an
3288        // `InteractionRequested` at all).
3289        AgentEvent::RpcIncomingRequest {
3290            id,
3291            method,
3292            params,
3293            decision,
3294            // A `Deferred` sighting never carries a reason -- nothing has
3295            // decided this request yet (see `AgentEvent::
3296            // RpcIncomingRequest`'s own doc comment).
3297            reason: _,
3298            // Nothing has run yet either -- always `Executed` for a
3299            // `Deferred` sighting (see `HostRequestOutcome`'s own doc
3300            // comment).
3301            outcome: _,
3302        } if method == "session/request_permission"
3303            && matches!(decision, HostRequestDecision::Deferred) =>
3304        {
3305            let tool_call = params.as_ref().and_then(|params| params.get("toolCall"));
3306            let field = |name: &str| {
3307                tool_call
3308                    .and_then(|tool_call| tool_call.get(name))
3309                    .and_then(|value| value.as_str())
3310                    .filter(|value| !value.is_empty())
3311                    .map(str::to_owned)
3312            };
3313            // `kind` is the tool's CLASS (`execute`, `edit`, `read`, ...) and
3314            // `title` is the human sentence describing this particular call.
3315            // They are two different things and the operator needs both: the
3316            // class is what the node hashes into `tool_class` for the
3317            // observation, and the title is the actual question. Putting the
3318            // title in `tool_name` and leaving `prompt` empty -- which is
3319            // what this did -- showed the operator a correlation id and a
3320            // sentence-shaped tool name, and never the question itself.
3321            let title = field("title");
3322            // The agent's own offered options -- read straight off the top-
3323            // level `options` array `PermissionRequestParams::options`
3324            // names in `src/acp/protocol.rs` (`option_id`/`name`/`kind`,
3325            // each `PermissionOption` field's own verified wire name:
3326            // `optionId`/`name`/`kind`), not `toolCall` -- `options` is a
3327            // sibling of `toolCall` on the request, not nested under it.
3328            // `kind` is carried verbatim as the ACP wire's own snake_case
3329            // string (`allow_once`, `reject_always`, ...); nothing here
3330            // reinterprets it. Without this the operator is choosing
3331            // approve/deny from a list they cannot see -- survivable for
3332            // two options, a guess for three or more.
3333            let options: Vec<ProviderInteractionOption> = params
3334                .as_ref()
3335                .and_then(|params| params.get("options"))
3336                .and_then(|options| options.as_array())
3337                .map(|options| {
3338                    options
3339                        .iter()
3340                        .filter_map(|option| {
3341                            let option_id = option.get("optionId")?.as_str()?.to_owned();
3342                            let name = option.get("name")?.as_str()?.to_owned();
3343                            let kind = option.get("kind")?.as_str()?.to_owned();
3344                            Some(ProviderInteractionOption { option_id, name, kind })
3345                        })
3346                        .collect()
3347                })
3348                .unwrap_or_default();
3349            Some(ProviderEvent::InteractionRequested {
3350                request_id: Some(encode_rpc_request_id(&id)),
3351                interaction_kind: ProviderInteractionKind::Approval,
3352                tool_name: field("kind").unwrap_or(method),
3353                title,
3354                prompt: field("title").unwrap_or_default(),
3355                options,
3356                agent_id: None,
3357            })
3358        }
3359        AgentEvent::RpcIncomingRequest {
3360            id: _,
3361            method,
3362            params,
3363            decision,
3364            // `outcome` distinguishes a `Granted` request that ran cleanly
3365            // from one that was authorized and then failed WHILE EXECUTING
3366            // (`HostRequestOutcome::Failed` -- e.g. a `terminal/create`
3367            // spawn error; see that type's own doc comment). Carried
3368            // through, never dropped: an execution failure must reach the
3369            // operator as `Granted` + `Failed { error }`, not an
3370            // undifferentiated `Granted` that silently swallows the
3371            // failure text.
3372            outcome,
3373            reason,
3374        } => Some(ProviderEvent::HostRequestObserved {
3375            method,
3376            params_json: params.map(|value| value.to_string()).unwrap_or_default(),
3377            decision: provider_host_request_decision(decision),
3378            outcome: provider_host_request_outcome(outcome),
3379            reason,
3380        }),
3381        AgentEvent::RpcNotification { method, params } => {
3382            Some(ProviderEvent::UnrecognizedNotification {
3383                method,
3384                payload_json: params.to_string(),
3385            })
3386        }
3387        AgentEvent::Started { .. } | AgentEvent::Exited { .. } | AgentEvent::PtyRaw { .. } => None,
3388        AgentEvent::UserMessage { text, is_delta } => {
3389            Some(ProviderEvent::UserMessage { text, is_delta })
3390        }
3391        AgentEvent::Plan { steps } => Some(ProviderEvent::Plan {
3392            steps: steps.into_iter().map(provider_plan_step).collect(),
3393        }),
3394        AgentEvent::AvailableCommandsUpdate { commands } => {
3395            Some(ProviderEvent::AvailableCommandsUpdated {
3396                commands: commands
3397                    .into_iter()
3398                    .map(|command| ProviderAvailableCommand {
3399                        name: command.name,
3400                        description: command.description,
3401                        input_hint: command.input_hint,
3402                    })
3403                    .collect(),
3404            })
3405        }
3406        AgentEvent::ModeChanged { mode_id } => Some(ProviderEvent::ModeChanged {
3407            mode_id,
3408            available: available_modes.iter().cloned().map(provider_mode_info).collect(),
3409        }),
3410        AgentEvent::SessionInfoUpdate { title } => {
3411            Some(ProviderEvent::SessionInfoUpdated { title })
3412        }
3413        AgentEvent::UsageUpdate {
3414            used_tokens,
3415            context_window,
3416            cost_amount,
3417            cost_currency,
3418        } => Some(ProviderEvent::UsageUpdated {
3419            used_tokens,
3420            context_window,
3421            cost_amount: cost_amount.map(|amount| amount.to_string()),
3422            cost_currency,
3423        }),
3424        AgentEvent::ConfigOptionsUpdate { options } => Some(ProviderEvent::ConfigOptionsUpdated {
3425            options: options.into_iter().map(provider_config_option).collect(),
3426        }),
3427        // Grok vendor `_x.ai/*` extensions (see `gate4agent::acp::protocol::
3428        // parse_vendor_notification`) -- not yet bridged to `ProviderEvent`.
3429        // No `ProviderEvent` variant exists for any of these today; adding
3430        // one is a separate, larger change across this crate's validation
3431        // (`ProviderEventValidationError`), the observation pipeline, and
3432        // the TUI, not part of parsing the ACP wire itself.
3433        AgentEvent::ModelsUpdate { .. }
3434        | AgentEvent::ProviderModelChanged { .. }
3435        | AgentEvent::SettingsUpdate { .. }
3436        | AgentEvent::HookExecutionUpdate { .. }
3437        | AgentEvent::McpServersUpdate { .. }
3438        | AgentEvent::McpInitProgress { .. }
3439        | AgentEvent::McpInitialized { .. }
3440        | AgentEvent::AnnouncementsUpdate { .. } => None,
3441    }
3442}
3443
3444/// Map the ACP wire priority onto the typed `ProviderPlanPriority`. A
3445/// plain match, not `format!("{:?}", ..)` -- see `provider_rate_limit_kind`
3446/// for why: the wire carries the typed value itself.
3447fn provider_plan_priority(priority: gate4agent::core::types::PlanStepPriority) -> ProviderPlanPriority {
3448    use gate4agent::core::types::PlanStepPriority;
3449    match priority {
3450        PlanStepPriority::High => ProviderPlanPriority::High,
3451        PlanStepPriority::Medium => ProviderPlanPriority::Medium,
3452        PlanStepPriority::Low => ProviderPlanPriority::Low,
3453    }
3454}
3455
3456/// Map the ACP wire status onto the typed `ProviderPlanStatus`.
3457fn provider_plan_status(status: gate4agent::core::types::PlanStepStatus) -> ProviderPlanStatus {
3458    use gate4agent::core::types::PlanStepStatus;
3459    match status {
3460        PlanStepStatus::Pending => ProviderPlanStatus::Pending,
3461        PlanStepStatus::InProgress => ProviderPlanStatus::InProgress,
3462        PlanStepStatus::Completed => ProviderPlanStatus::Completed,
3463    }
3464}
3465
3466fn provider_plan_step(step: gate4agent::core::types::PlanStep) -> ProviderPlanStep {
3467    ProviderPlanStep {
3468        content: step.content,
3469        priority: provider_plan_priority(step.priority),
3470        status: provider_plan_status(step.status),
3471    }
3472}
3473
3474/// Maps one ACP `SessionMode` (`gate4agent::acp::protocol::SessionMode`,
3475/// `session/new`'s `modes.availableModes`) onto the wire-typed
3476/// `ProviderModeInfo` carried on `ProviderEvent::ModeChanged::available`.
3477fn provider_mode_info(mode: SessionMode) -> ProviderModeInfo {
3478    ProviderModeInfo {
3479        id: mode.id,
3480        name: mode.name,
3481        description: mode.description,
3482    }
3483}
3484
3485/// Map the ACP wire config-option kind onto the typed
3486/// `ProviderConfigOptionKind`.
3487fn provider_config_option_kind(
3488    kind: gate4agent::core::types::ConfigOptionKind,
3489) -> ProviderConfigOptionKind {
3490    use gate4agent::core::types::ConfigOptionKind;
3491    match kind {
3492        ConfigOptionKind::Select => ProviderConfigOptionKind::Select,
3493        ConfigOptionKind::Boolean => ProviderConfigOptionKind::Boolean,
3494        ConfigOptionKind::Unknown => ProviderConfigOptionKind::Unknown,
3495    }
3496}
3497
3498/// `gate4agent-types` is a pure data contract and does not depend on
3499/// `serde_json`, so the option's current value and each choice's value --
3500/// both `serde_json::Value` in `gate4agent::core::types::ConfigOptionInfo`
3501/// -- cross the boundary pre-serialized to JSON text, same convention as
3502/// `ToolStarted::input_json` above.
3503fn provider_config_option(option: gate4agent::core::types::ConfigOptionInfo) -> ProviderConfigOption {
3504    ProviderConfigOption {
3505        id: option.id,
3506        name: option.name,
3507        description: option.description,
3508        category: option.category,
3509        kind: provider_config_option_kind(option.kind),
3510        value_json: option.value.to_string(),
3511        choices: option
3512            .choices
3513            .into_iter()
3514            .map(|choice| ProviderConfigChoice {
3515                value_json: choice.value.to_string(),
3516                label: choice.label,
3517            })
3518            .collect(),
3519    }
3520}
3521
3522fn builtin_legacy_adapter_runtimes() -> AdapterRuntimeRegistry<CliTool> {
3523    // Each of the four fleet providers registers only the transport families
3524    // it actually declares in the built-in adapter registry -- Grok, for
3525    // instance, is ACP-only and has no `PtySemantic`/`Pipe` descriptor.
3526    // Absence of a family for a given provider is not an error; only a
3527    // duplicate registration is.
3528    let definitions = [
3529        ("claude-code", CliTool::ClaudeCode),
3530        ("codex", CliTool::Codex),
3531        ("kimi", CliTool::KimiCode),
3532        ("grok", CliTool::Grok),
3533        ("opencode", CliTool::Opencode),
3534        ("mcode", CliTool::Mcode),
3535    ];
3536    let mut runtimes = AdapterRuntimeRegistry::default();
3537    for (id, tool) in definitions {
3538        for family in [
3539            AdapterFamily::PtySemantic,
3540            AdapterFamily::Pipe,
3541            AdapterFamily::Acp,
3542        ] {
3543            let Some(binding) = builtin_adapter_registry().binding(family, id) else {
3544                continue;
3545            };
3546            runtimes
3547                .insert(family, binding.clone(), tool)
3548                .expect("built-in native adapter runtime must be unique");
3549        }
3550    }
3551
3552    runtimes
3553}
3554
3555fn terminal_frame(snapshot: PtyTerminalSnapshot, screen_state: PtyScreenState) -> TerminalFrame {
3556    TerminalFrame {
3557        sequence: snapshot.sequence,
3558        size: TerminalSize {
3559            rows: snapshot.size.rows,
3560            columns: snapshot.size.cols,
3561        },
3562        cursor_row: snapshot.cursor.0,
3563        cursor_column: snapshot.cursor.1,
3564        contents: snapshot.contents,
3565        formatted: snapshot.formatted,
3566        scrollback_formatted: snapshot.scrollback_formatted,
3567        alternate_screen: snapshot.alternate_screen,
3568        mouse_protocol_enabled: snapshot.mouse_protocol_enabled,
3569        mouse_protocol_encoding: match snapshot.mouse_protocol_encoding {
3570            PtyMouseProtocolEncoding::Default => TerminalMouseProtocolEncoding::Default,
3571            PtyMouseProtocolEncoding::Utf8 => TerminalMouseProtocolEncoding::Utf8,
3572            PtyMouseProtocolEncoding::Sgr => TerminalMouseProtocolEncoding::Sgr,
3573        },
3574        // Carried through unchanged from the PTY snapshot -- this crate does
3575        // not restamp it, see `TerminalFrame::produced_at_unix_ms`'s own doc.
3576        produced_at_unix_ms: snapshot.produced_at_unix_ms,
3577        screen_state,
3578        // Known at capture time: `PtyTerminalSnapshot::bracketed_paste` is
3579        // read off the same `vt100::Screen` as `contents`/`formatted`, so
3580        // `Some` here always means "sampled", never "unknown" -- see
3581        // `TerminalFrame::bracketed_paste`'s own doc for what `None` means.
3582        bracketed_paste: Some(snapshot.bracketed_paste),
3583    }
3584}
3585
3586/// Whether the cheap `terminal_sequence()` gate should skip the expensive
3587/// `terminal_state()` call outright -- true exactly when the sequence read
3588/// is no newer than what this session already captured. An `Err` from the
3589/// cheap read does NOT skip: it falls through so the real call is attempted
3590/// (and reports its own failure through the normal `terminal_state()`
3591/// error path), matching the pre-instrumentation behaviour of the
3592/// `matches!` this replaces.
3593fn terminal_state_capture_should_skip<E>(sequence: Result<u64, E>, last_captured: u64) -> bool {
3594    matches!(sequence, Ok(sequence) if sequence <= last_captured)
3595}
3596
3597/// Total wire-relevant byte size of one [`TerminalFrame`] -- `formatted`
3598/// plus every row of `scrollback_formatted` summed. This is exactly what
3599/// gets handed to the c2 relay/harness/operator wire per frame (`contents`
3600/// never leaves the node), which is why it is the number the frame-bytes
3601/// distribution reports.
3602fn terminal_frame_byte_len(frame: &TerminalFrame) -> u64 {
3603    let scrollback_bytes: usize = frame.scrollback_formatted.iter().map(Vec::len).sum();
3604    (frame.formatted.len() + scrollback_bytes) as u64
3605}
3606
3607fn canonical_foreground(
3608    agent_id: AgentId,
3609    observation: &PtyForegroundObservation,
3610) -> ForegroundProcess {
3611    let kind = if observation.readiness.process_name.as_deref() == Some(agent_id.as_str()) {
3612        ForegroundProcessKind::Agent { agent_id }
3613    } else if observation.readiness.is_shell {
3614        ForegroundProcessKind::Shell
3615    } else {
3616        ForegroundProcessKind::Other
3617    };
3618    ForegroundProcess {
3619        root_process_id: observation.root_pid,
3620        process_id: observation.observed_pid,
3621        process_name: observation.observed_process.clone(),
3622        kind,
3623    }
3624}
3625
3626fn completion_observation(
3627    operation_id: OperationId,
3628    instance_id: AgentInstanceId,
3629    generation: SessionGeneration,
3630    observation: ControlObservation,
3631) -> ObservationEnvelope {
3632    ObservationEnvelope {
3633        operation_id: Some(operation_id),
3634        instance_id,
3635        generation,
3636        observation,
3637    }
3638}
3639
3640async fn wait_for_readiness(
3641    session: &PtySession,
3642    spec: &AgentSpec,
3643    intent: ReadinessIntent,
3644    detect_startup_gates: bool,
3645) -> Result<ReadinessPermit, String> {
3646    let started = Instant::now();
3647    let (terminal, attachment) = attach_readiness_boundary(session)?;
3648    let mut receiver = attachment.receiver;
3649    let mut tracker = ReadinessTracker::new(spec, RuntimePlatform::current(), intent);
3650    let mut diagnostics = ReadinessDiagnostics {
3651        draft_signal: Some(spec.readiness.draft_signal),
3652        ..ReadinessDiagnostics::default()
3653    };
3654    seed_readiness_from_terminal(
3655        &terminal,
3656        &mut tracker,
3657        &mut diagnostics,
3658        elapsed_ms(started),
3659    )?;
3660    let interval = Duration::from_millis(spec.readiness.poll_interval_ms.max(1));
3661    let mut next_probe = Instant::now();
3662
3663    for event in attachment.replay {
3664        observe_readiness_event(
3665            &mut tracker,
3666            &mut diagnostics,
3667            event.event,
3668            elapsed_ms(started),
3669        )?;
3670        if detect_startup_gates {
3671            ensure_no_readiness_operator_gate(&diagnostics, spec)?;
3672            ensure_no_startup_operator_gate(session, spec)?;
3673        }
3674    }
3675
3676    loop {
3677        if detect_startup_gates {
3678            ensure_no_startup_operator_gate(session, spec)?;
3679        }
3680        if Instant::now() >= next_probe {
3681            let foreground = session
3682                .observe_foreground()
3683                .await
3684                .map_err(|error| error.to_string())?;
3685            diagnostics.observe_foreground(&foreground.readiness);
3686            tracker.observe_foreground(&foreground.readiness, elapsed_ms(started));
3687            next_probe = Instant::now() + interval;
3688        }
3689        tracker.poll(elapsed_ms(started));
3690        if readiness_complete(tracker.status(), &diagnostics)? {
3691            if detect_startup_gates {
3692                ensure_no_startup_operator_gate(session, spec)?;
3693            }
3694            return tracker
3695                .into_permit()
3696                .ok_or_else(|| "ready tracker did not issue a permit".to_owned());
3697        }
3698
3699        let wait = next_probe.saturating_duration_since(Instant::now());
3700        match tokio::time::timeout(wait, receiver.recv()).await {
3701            Ok(Ok(event)) => {
3702                if matches!(&event.event, PtyEvent::DataGap { .. }) {
3703                    let (terminal, attachment) = attach_readiness_boundary(session)?;
3704                    receiver = attachment.receiver;
3705                    tracker = ReadinessTracker::new(
3706                        spec,
3707                        RuntimePlatform::current(),
3708                        intent,
3709                    );
3710                    diagnostics = ReadinessDiagnostics {
3711                        draft_signal: Some(spec.readiness.draft_signal),
3712                        ..ReadinessDiagnostics::default()
3713                    };
3714                    seed_readiness_from_terminal(
3715                        &terminal,
3716                        &mut tracker,
3717                        &mut diagnostics,
3718                        elapsed_ms(started),
3719                    )?;
3720                    for retained in attachment.replay {
3721                        observe_readiness_event(
3722                            &mut tracker,
3723                            &mut diagnostics,
3724                            retained.event,
3725                            elapsed_ms(started),
3726                        )?;
3727                    }
3728                } else {
3729                    observe_readiness_event(
3730                        &mut tracker,
3731                        &mut diagnostics,
3732                        event.event,
3733                        elapsed_ms(started),
3734                    )?;
3735                }
3736                if detect_startup_gates {
3737                    ensure_no_readiness_operator_gate(&diagnostics, spec)?;
3738                    ensure_no_startup_operator_gate(session, spec)?;
3739                }
3740            }
3741            Ok(Err(error)) => return Err(error.to_string()),
3742            Err(_) => {
3743                tracker.poll(elapsed_ms(started));
3744            }
3745        }
3746        if readiness_complete(tracker.status(), &diagnostics)? {
3747            if detect_startup_gates {
3748                ensure_no_startup_operator_gate(session, spec)?;
3749            }
3750            return tracker
3751                .into_permit()
3752                .ok_or_else(|| "ready tracker did not issue a permit".to_owned());
3753        }
3754    }
3755}
3756
3757fn attach_readiness_boundary(
3758    session: &PtySession,
3759) -> Result<(PtyTerminalSnapshot, PtyAttachment), String> {
3760    let terminal = session.terminal_state().map_err(|error| error.to_string())?;
3761    let cursor = PtyReplayCursor {
3762        provider_revision: terminal.provider_revision.clone(),
3763        generation: terminal.generation,
3764        next_sequence: terminal.sequence.saturating_add(1).max(1),
3765    };
3766    let attachment = session
3767        .attach_events(cursor)
3768        .map_err(|error| error.to_string())?;
3769    Ok((terminal, attachment))
3770}
3771
3772fn seed_readiness_from_terminal(
3773    terminal: &PtyTerminalSnapshot,
3774    tracker: &mut ReadinessTracker<'_>,
3775    diagnostics: &mut ReadinessDiagnostics,
3776    elapsed_ms: u64,
3777) -> Result<(), String> {
3778    const ENABLE_BRACKETED_PASTE: &[u8] = b"\x1b[?2004h";
3779    if terminal.bracketed_paste {
3780        diagnostics.observe_output(ENABLE_BRACKETED_PASTE);
3781        tracker.observe_output(ENABLE_BRACKETED_PASTE, elapsed_ms);
3782    }
3783    if !terminal.formatted.is_empty() {
3784        diagnostics.observe_output(&terminal.formatted);
3785        tracker.observe_output(&terminal.formatted, elapsed_ms);
3786    }
3787    Ok(())
3788}
3789
3790const STARTUP_GATE_SETTLE_MS: u64 = 350;
3791const STARTUP_GATE_POLL_MS: u64 = 25;
3792/// Steady-state cadence for `NativeEffectShell::reclassify_foreground`.
3793///
3794/// `wait_for_readiness` already polls the foreground far tighter than this
3795/// during startup (`spec.readiness.poll_interval_ms`, 150ms by default),
3796/// because a session takes at most a few seconds to come up and getting
3797/// that window right matters. This constant is not that -- it governs the
3798/// STEADY STATE: a session that has been sitting non-`Ready` for a long
3799/// time, which is exactly the incident this module fixes (an update
3800/// screen with nobody watching it). A session that reaches `Ready` stops
3801/// being probed at all (see `foreground_probe_schedule`), so the cost of
3802/// this interval is bounded by the count of sessions that are NOT
3803/// `Ready`, never by output rate and never by total session count. One
3804/// process-tree walk a second for a handful of stuck sessions is ample.
3805const FOREGROUND_RECLASSIFY_INTERVAL: Duration = Duration::from_secs(1);
3806// Codex rust-v0.144.0 keeps Enter in newline mode for 120 ms after
3807// Windows paste-burst activity. Wait beyond that window only after the TUI
3808// visibly incorporates the deferred initial prompt.
3809const CODEX_PASTE_ENTER_SUPPRESSION_MS: u64 = 120;
3810const CODEX_POST_RENDER_MARGIN_MS: u64 = 30;
3811const CODEX_SESSION_STATUS_PROBE_TIMEOUT_MS: u64 = 5_000;
3812const KIMI_SESSION_STATUS_PROBE_TIMEOUT_MS: u64 = 5_000;
3813
3814async fn probe_fresh_codex_session_identity(
3815    session: &PtySession,
3816    spec: &AgentSpec,
3817) -> Result<Option<ProviderSessionIdentity>, String> {
3818    let permit = match wait_for_readiness(session, spec, ReadinessIntent::DraftPaste, true).await {
3819        Ok(permit) => permit,
3820        Err(_) => return Ok(None),
3821    };
3822    if wait_for_startup_operator_gate(session, spec).await.is_err() {
3823        return Ok(None);
3824    }
3825    let baseline = session
3826        .terminal_state()
3827        .map_err(|error| error.to_string())?;
3828    let mut extractor = CodexPtySessionIdentityExtractor::default();
3829    session
3830        .send_input_action(
3831            InputAction::AgentCommand(AgentCommand {
3832                agent_id: spec.id.clone(),
3833                name: "status".to_owned(),
3834                arguments: Vec::new(),
3835            }),
3836            permit,
3837        )
3838        .await
3839        .map_err(|error| format!("Codex /status identity probe failed: {error}"))?;
3840
3841    let deadline = Instant::now()
3842        + Duration::from_millis(
3843            spec.readiness
3844                .timeout_ms
3845                .min(CODEX_SESSION_STATUS_PROBE_TIMEOUT_MS)
3846                .max(1),
3847        );
3848    loop {
3849        let snapshot = session
3850            .terminal_state()
3851            .map_err(|error| error.to_string())?;
3852        if snapshot.sequence > baseline.sequence {
3853            if let Some(identity) = extractor.observe_screen(&snapshot.contents) {
3854                return Ok(Some(identity));
3855            }
3856        }
3857        if Instant::now() >= deadline {
3858            return Ok(None);
3859        }
3860        tokio::time::sleep(Duration::from_millis(STARTUP_GATE_POLL_MS)).await;
3861    }
3862}
3863
3864async fn probe_fresh_kimi_session_identity(
3865    session: &PtySession,
3866    spec: &AgentSpec,
3867) -> Result<Option<ProviderSessionIdentity>, String> {
3868    let permit = match wait_for_readiness(
3869        session,
3870        spec,
3871        ReadinessIntent::FollowupPrompt,
3872        true,
3873    )
3874    .await
3875    {
3876        Ok(permit) => permit,
3877        Err(_) => return Ok(None),
3878    };
3879    if wait_for_startup_operator_gate(session, spec).await.is_err() {
3880        return Ok(None);
3881    }
3882    let baseline = session
3883        .terminal_state()
3884        .map_err(|error| error.to_string())?;
3885    let mut extractor = KimiPtySessionIdentityExtractor::default();
3886    if let Some(identity) = extractor.observe_screen(&baseline.contents) {
3887        return Ok(Some(identity));
3888    }
3889    session
3890        .send_input_action(
3891            InputAction::SubmitPrompt(PromptPayload {
3892                text: "/status".to_owned(),
3893                framing: PromptFraming::BracketedPaste,
3894            }),
3895            permit,
3896        )
3897        .await
3898        .map_err(|error| format!("Kimi /status identity probe failed: {error}"))?;
3899
3900    let deadline = Instant::now()
3901        + Duration::from_millis(
3902            spec.readiness
3903                .timeout_ms
3904                .min(KIMI_SESSION_STATUS_PROBE_TIMEOUT_MS)
3905                .max(1),
3906        );
3907    loop {
3908        let snapshot = session
3909            .terminal_state()
3910            .map_err(|error| error.to_string())?;
3911        if snapshot.sequence > baseline.sequence {
3912            if let Some(identity) = extractor.observe_screen(&snapshot.contents) {
3913                return Ok(Some(identity));
3914            }
3915        }
3916        if Instant::now() >= deadline {
3917            return Ok(None);
3918        }
3919        tokio::time::sleep(Duration::from_millis(STARTUP_GATE_POLL_MS)).await;
3920    }
3921}
3922
3923async fn deliver_pending_initial_prompt(
3924    session: &mut PtySession,
3925    spec: &AgentSpec,
3926) -> Result<(), String> {
3927    if session.pending_followup_prompt().is_none() {
3928        return Ok(());
3929    }
3930    let mut permit =
3931        wait_for_readiness(session, spec, ReadinessIntent::FollowupPrompt, true).await?;
3932    wait_for_startup_operator_gate(session, spec).await?;
3933    let render_confirmed_submit = spec.id.as_str() == "claude"
3934        || (RuntimePlatform::current() == RuntimePlatform::Windows
3935            && spec.id.as_str() == "codex");
3936    if render_confirmed_submit {
3937        let prompt = session
3938            .pending_followup_prompt()
3939            .ok_or_else(|| "deferred initial prompt disappeared before paste".to_owned())?
3940            .to_owned();
3941        let baseline = session
3942            .terminal_state()
3943            .map_err(|error| error.to_string())?;
3944        let inserted = session
3945            .insert_pending_followup_prompt(PromptFraming::BracketedPaste, &permit)
3946            .await
3947            .map_err(|error| error.to_string())?;
3948        if !inserted {
3949            return Err("deferred initial prompt was not inserted".to_owned());
3950        }
3951        wait_for_prompt_render(
3952            session,
3953            spec,
3954            &prompt,
3955            &baseline,
3956            spec.readiness.timeout_ms,
3957        )
3958        .await?;
3959        if RuntimePlatform::current() == RuntimePlatform::Windows && spec.id.as_str() == "codex" {
3960            tokio::time::sleep(Duration::from_millis(
3961                CODEX_PASTE_ENTER_SUPPRESSION_MS + CODEX_POST_RENDER_MARGIN_MS,
3962            ))
3963            .await;
3964        }
3965        permit = wait_for_readiness(session, spec, ReadinessIntent::FollowupPrompt, true).await?;
3966        wait_for_startup_operator_gate(session, spec).await?;
3967    }
3968    ensure_no_startup_operator_gate(session, spec)?;
3969    let submitted = session
3970        .submit_pending_followup(PromptFraming::BracketedPaste, permit)
3971        .await
3972        .map_err(|error| error.to_string())?;
3973    if !submitted {
3974        return Err("deferred initial prompt disappeared before delivery".to_owned());
3975    }
3976    Ok(())
3977}
3978
3979async fn wait_for_prompt_render(
3980    session: &PtySession,
3981    spec: &AgentSpec,
3982    prompt: &str,
3983    baseline: &PtyTerminalSnapshot,
3984    timeout_ms: u64,
3985) -> Result<(), String> {
3986    let probe = prompt_render_probe(&gate4agent_types::sanitize_prompt_text(prompt));
3987    let deadline = Instant::now() + Duration::from_millis(timeout_ms.max(1));
3988    loop {
3989        let snapshot = session.terminal_state().map_err(|error| error.to_string())?;
3990        if let Some(gate) = startup_operator_gate(&snapshot.contents) {
3991            return Err(startup_operator_error(spec, &gate));
3992        }
3993        if prompt_rendered(&snapshot, baseline, &probe) {
3994            return Ok(());
3995        }
3996        if Instant::now() >= deadline {
3997            let tail = terminal_tail(&snapshot.contents);
3998            let compact_tail = compact_alphanumeric(&tail);
3999            let baseline_tail = terminal_tail(&baseline.contents).to_ascii_lowercase();
4000            let normalized_tail = tail.to_ascii_lowercase();
4001            let retained = render_ack_event_summary(session, baseline.sequence);
4002            let foreground = session.observe_foreground().await.ok();
4003            let foreground_name = foreground
4004                .as_ref()
4005                .and_then(|observation| observation.readiness.process_name.as_deref())
4006                .map(safe_process_label)
4007                .unwrap_or_else(|| "none".to_owned());
4008            let child_live = retained.exit_code.is_none() && foreground.is_some();
4009            return Err(format!(
4010                "agent '{}' initial prompt paste was not rendered before submit; Enter was not sent (baseline_sequence={} current_sequence={} sequence_delta={} cursor_changed={} bracketed_baseline={} bracketed_current={} tail_chars={} probe_chars={} probe_match={} placeholder_baseline={} placeholder_current={} child_live={} foreground={} retained_output={} retained_foreground={} retained_snapshots={} retained_resized={} retained_gaps={} retained_reader_errors={} retained_operator_actions={} retained_exit_code={} output_flags={})",
4011                spec.id,
4012                baseline.sequence,
4013                snapshot.sequence,
4014                snapshot.sequence.saturating_sub(baseline.sequence),
4015                snapshot.cursor != baseline.cursor,
4016                baseline.bracketed_paste,
4017                snapshot.bracketed_paste,
4018                tail.chars().count(),
4019                probe.chars().count(),
4020                !probe.is_empty() && compact_tail.contains(&probe),
4021                paste_placeholder_visible(&baseline_tail),
4022                paste_placeholder_visible(&normalized_tail),
4023                child_live,
4024                foreground_name,
4025                retained.output,
4026                retained.foreground,
4027                retained.snapshots,
4028                retained.resized,
4029                retained.gaps,
4030                retained.reader_errors,
4031                retained.operator_actions,
4032                retained
4033                    .exit_code
4034                    .map_or_else(|| "none".to_owned(), |code| code.to_string()),
4035                if retained.output_flags.is_empty() {
4036                    "none".to_owned()
4037                } else {
4038                    retained.output_flags.join(",")
4039                },
4040            ));
4041        }
4042        tokio::time::sleep(Duration::from_millis(STARTUP_GATE_POLL_MS)).await;
4043    }
4044}
4045
4046#[derive(Default)]
4047struct RenderAckEventSummary {
4048    output: usize,
4049    foreground: usize,
4050    snapshots: usize,
4051    resized: usize,
4052    gaps: usize,
4053    reader_errors: usize,
4054    operator_actions: usize,
4055    exit_code: Option<i32>,
4056    output_flags: Vec<&'static str>,
4057}
4058
4059fn render_ack_event_summary(session: &PtySession, baseline_sequence: u64) -> RenderAckEventSummary {
4060    let mut summary = RenderAckEventSummary::default();
4061    let Ok(attachment) = session.attach_retained_events() else {
4062        return summary;
4063    };
4064    for envelope in attachment
4065        .replay
4066        .into_iter()
4067        .filter(|envelope| envelope.sequence > baseline_sequence)
4068    {
4069        match envelope.event {
4070            PtyEvent::Output(bytes) => {
4071                summary.output = summary.output.saturating_add(1);
4072                observe_render_ack_output_flags(&mut summary.output_flags, &bytes);
4073            }
4074            PtyEvent::ForegroundProcess(_) => {
4075                summary.foreground = summary.foreground.saturating_add(1);
4076            }
4077            PtyEvent::SnapshotAvailable { .. } => {
4078                summary.snapshots = summary.snapshots.saturating_add(1);
4079            }
4080            PtyEvent::Resized(_) => {
4081                summary.resized = summary.resized.saturating_add(1);
4082            }
4083            PtyEvent::DataGap { .. } => {
4084                summary.gaps = summary.gaps.saturating_add(1);
4085            }
4086            PtyEvent::ReaderError { .. } => {
4087                summary.reader_errors = summary.reader_errors.saturating_add(1);
4088            }
4089            PtyEvent::OperatorActionRequired { .. } => {
4090                summary.operator_actions = summary.operator_actions.saturating_add(1);
4091            }
4092            PtyEvent::Exited { code } => summary.exit_code = Some(code),
4093            PtyEvent::Started => {}
4094        }
4095    }
4096    summary
4097}
4098
4099fn observe_render_ack_output_flags(flags: &mut Vec<&'static str>, bytes: &[u8]) {
4100    let normalized = String::from_utf8_lossy(bytes).to_ascii_lowercase();
4101    for (label, marker) in [
4102        ("error", "error"),
4103        ("panic", "panic"),
4104        ("fatal", "fatal"),
4105        ("login", "login"),
4106        ("auth", "auth"),
4107        ("permission", "permission"),
4108        ("rate-limit", "rate limit"),
4109        ("usage-limit", "usage limit"),
4110        ("update", "update"),
4111        ("working", "working"),
4112        ("thinking", "thinking"),
4113    ] {
4114        if normalized.contains(marker) && !flags.contains(&label) {
4115            flags.push(label);
4116        }
4117    }
4118}
4119
4120fn safe_process_label(process_name: &str) -> String {
4121    process_name
4122        .chars()
4123        .take(64)
4124        .map(|character| {
4125            if character.is_ascii_alphanumeric() || matches!(character, '.' | '_' | '-') {
4126                character
4127            } else {
4128                '?'
4129            }
4130        })
4131        .collect()
4132}
4133
4134fn prompt_rendered(
4135    snapshot: &PtyTerminalSnapshot,
4136    baseline: &PtyTerminalSnapshot,
4137    probe: &str,
4138) -> bool {
4139    if snapshot.sequence <= baseline.sequence {
4140        return false;
4141    }
4142    let tail = terminal_tail(&snapshot.contents);
4143    let compact = compact_alphanumeric(&tail);
4144    if !probe.is_empty() && compact.contains(probe) {
4145        return true;
4146    }
4147    let normalized_tail = tail.to_ascii_lowercase();
4148    let normalized_baseline = terminal_tail(&baseline.contents).to_ascii_lowercase();
4149    paste_placeholder_visible(&normalized_tail)
4150        && !paste_placeholder_visible(&normalized_baseline)
4151}
4152
4153fn paste_placeholder_visible(normalized_tail: &str) -> bool {
4154    // Codex collapses larger pastes as `[Pasted Content ...]`; Claude 2.1.223
4155    // uses `[Pasted text #N ...]`. Treat only those vendor-owned render
4156    // markers as proof that the TUI consumed the bracketed paste.
4157    normalized_tail.contains("[pasted content")
4158        || normalized_tail.contains("[pasted text #")
4159}
4160
4161fn terminal_tail(contents: &str) -> String {
4162    let mut lines = contents.lines().rev().take(12).collect::<Vec<_>>();
4163    lines.reverse();
4164    lines.join("\n")
4165}
4166
4167fn prompt_render_probe(prompt: &str) -> String {
4168    let compact = compact_alphanumeric(prompt);
4169    let chars = compact.chars().collect::<Vec<_>>();
4170    chars[chars.len().saturating_sub(32)..].iter().collect()
4171}
4172
4173fn compact_alphanumeric(value: &str) -> String {
4174    value
4175        .chars()
4176        .filter(|character| character.is_alphanumeric())
4177        .flat_map(char::to_lowercase)
4178        .collect()
4179}
4180
4181async fn wait_for_startup_operator_gate(
4182    session: &PtySession,
4183    spec: &AgentSpec,
4184) -> Result<(), String> {
4185    let deadline = Instant::now() + Duration::from_millis(STARTUP_GATE_SETTLE_MS);
4186    loop {
4187        ensure_no_startup_operator_gate(session, spec)?;
4188        let now = Instant::now();
4189        if now >= deadline {
4190            return Ok(());
4191        }
4192        tokio::time::sleep(
4193            deadline
4194                .saturating_duration_since(now)
4195                .min(Duration::from_millis(STARTUP_GATE_POLL_MS)),
4196        )
4197        .await;
4198    }
4199}
4200
4201/// Refuses a prompt submission while a known operator gate is on screen.
4202///
4203/// Deliberately checks gates ONLY, never `screen_failure`. A crash banner
4204/// means "the CLI fell over" solely before the agent has rendered its own
4205/// UI; afterwards the identical bytes mean "the agent is showing you a
4206/// crash" -- a test it ran, a traceback it was asked to explain. What
4207/// separates the two is not the text but WHEN it appeared, and this
4208/// function has no way to date its evidence: it holds a screen snapshot
4209/// and a spec, and is called from seven sites spanning both the startup
4210/// window and long-running follow-up delivery. A check that cannot tell
4211/// those apart would refuse work from a perfectly healthy session every
4212/// time its pane happened to show a failing subprocess.
4213///
4214/// The `Failing` classification is not lost by this -- it is computed
4215/// where the window IS known (`collect_terminal_frames`, gated on
4216/// `OwnedPtySession::ever_reached_ready`), published upstream, and enforced
4217/// by the callers that gate dispatch on `PtyScreenState`. Gates are
4218/// different in kind and stay here: a trust or update prompt is legitimate
4219/// at any point in a session's life, so it needs no window to be believed.
4220fn ensure_no_startup_operator_gate(session: &PtySession, spec: &AgentSpec) -> Result<(), String> {
4221    let snapshot = session.terminal_state().map_err(|error| error.to_string())?;
4222    match startup_operator_gate(&snapshot.contents) {
4223        Some(gate) => Err(startup_operator_error(spec, &gate)),
4224        None => Ok(()),
4225    }
4226}
4227
4228fn startup_operator_error(spec: &AgentSpec, gate: &OperatorGateState) -> String {
4229    format!(
4230        "agent '{}' requires operator action at startup ({gate}); initial prompt was not submitted",
4231        spec.id
4232    )
4233}
4234
4235fn ensure_no_readiness_operator_gate(
4236    diagnostics: &ReadinessDiagnostics,
4237    spec: &AgentSpec,
4238) -> Result<(), String> {
4239    match &diagnostics.operator_gate {
4240        Some(gate) => Err(startup_operator_error(spec, gate)),
4241        None => Ok(()),
4242    }
4243}
4244
4245/// Whitespace-collapse and lowercase raw PTY screen text before pattern
4246/// matching. Shared by `startup_operator_gate` and `screen_failure` so the
4247/// two agree on what "the same phrase" means -- if they normalized
4248/// independently, a line-wrap difference or a run of extra spaces could
4249/// make one matcher see a phrase the other misses for no reason connected
4250/// to the actual screen content.
4251fn normalize_screen_text(contents: &str) -> String {
4252    contents
4253        .split_whitespace()
4254        .collect::<Vec<_>>()
4255        .join(" ")
4256        .to_ascii_lowercase()
4257}
4258
4259/// Phrases showing a package manager actively installing or updating a
4260/// package. Generic across npm/pip/yarn/pnpm rather than any one vendor's
4261/// package name, so a wrapper script fronting any provider CLI is
4262/// recognized the same way -- see the `PACKAGE_MANAGER_UPDATE_COMPLETION_MARKERS`
4263/// doc below for why a bare occurrence of one of these alone is not enough.
4264const PACKAGE_MANAGER_INSTALL_MARKERS: &[&str] = &[
4265    "npm install -g",
4266    "npm i -g",
4267    "npm update -g",
4268    "pip install --upgrade",
4269    "pip install -u",
4270    "yarn global add",
4271    "pnpm add -g",
4272];
4273
4274/// Phrases showing the install/update above reached a terminal state and
4275/// wants the CLI relaunched. Required to co-occur with a marker from
4276/// `PACKAGE_MANAGER_INSTALL_MARKERS` so a screen that merely MENTIONS a
4277/// package-manager command (an agent explaining how to install something,
4278/// for instance) never matches on the install phrase alone.
4279const PACKAGE_MANAGER_UPDATE_COMPLETION_MARKERS: &[&str] = &[
4280    "update ran successfully",
4281    "please restart",
4282    "update complete",
4283    "updated successfully",
4284];
4285
4286/// Builds the classified `OperatorGateState` for a matched `kind`/`subject`
4287/// pair, filling `input`/`options` from whatever `parse_operator_gate_options`
4288/// can read off the RAW (un-normalized, multi-line) screen text. Every
4289/// `startup_operator_gate` match arm goes through this one function so
4290/// option-list recognition is uniform across every gate kind rather than
4291/// hand-wired per branch -- a kind this module has not yet seen an option
4292/// layout for simply gets `OperatorGateInput::Unknown` and no options,
4293/// exactly like a kind whose options this parser fails to recognize on a
4294/// given screen; there is no special-casing between "not implemented yet"
4295/// and "not recognized this time".
4296fn operator_gate(kind: OperatorGateKind, subject: OperatorGateSubject, contents: &str) -> OperatorGateState {
4297    let (input, options) = parse_operator_gate_options(contents);
4298    OperatorGateState::new(kind)
4299        .with_subject(subject)
4300        .with_options(input, options)
4301}
4302
4303fn startup_operator_gate(contents: &str) -> Option<OperatorGateState> {
4304    let normalized = normalize_screen_text(contents);
4305    if [
4306        "trust this folder",
4307        "trust the files in this folder",
4308        "trust the contents of this directory",
4309        "do you trust this directory",
4310    ]
4311    .iter()
4312    .any(|marker| normalized.contains(marker))
4313    {
4314        return Some(operator_gate(
4315            OperatorGateKind::WorkspaceTrust,
4316            OperatorGateSubject::Directory { path: None },
4317            contents,
4318        ));
4319    }
4320    if normalized.contains("quick safety check")
4321        && (normalized.contains("yes, i trust this folder")
4322            || normalized.contains("continue without these permissions"))
4323    {
4324        return Some(operator_gate(
4325            OperatorGateKind::WorkspaceTrust,
4326            OperatorGateSubject::Directory { path: None },
4327            contents,
4328        ));
4329    }
4330    // A CLI's own hook-trust prompt at startup (seen from Codex): a set of
4331    // shell hooks it discovered need to be reviewed/trusted before they are
4332    // allowed to run, distinct from `WorkspaceTrust` above -- that gate is
4333    // about trusting the PROJECT DIRECTORY, this one is about trusting
4334    // SHELL HOOKS the CLI found inside it, and an operator reading `kind`
4335    // should be able to tell which question is being asked. Required to
4336    // co-occur with the screen's own "decline" option rather than matching
4337    // on "hooks need review" alone, so an agent's ordinary narration that
4338    // merely uses the word "hooks" (explaining a git hook, a React hook, a
4339    // build hook) never matches: real narration essentially never also
4340    // contains the literal refusal phrasing "continue without trusting"
4341    // this same prompt renders. The number of hooks reported (which varies
4342    // run to run, and is not read into `subject`'s `count` -- no matcher
4343    // here parses it off the screen) plays no part in the match.
4344    if normalized.contains("hooks need review") && normalized.contains("continue without trusting")
4345    {
4346        return Some(operator_gate(
4347            OperatorGateKind::HookTrust,
4348            OperatorGateSubject::Hooks { count: None },
4349            contents,
4350        ));
4351    }
4352    if [
4353        "select authentication method",
4354        "choose how to authenticate",
4355        "no auth type is selected",
4356    ]
4357    .iter()
4358    .any(|marker| normalized.contains(marker))
4359    {
4360        return Some(operator_gate(
4361            OperatorGateKind::Authentication,
4362            OperatorGateSubject::Account,
4363            contents,
4364        ));
4365    }
4366    if normalized.contains("sign in")
4367        && (normalized.contains("openai")
4368            || normalized.contains("chatgpt")
4369            || normalized.contains("codex"))
4370    {
4371        return Some(operator_gate(
4372            OperatorGateKind::Authentication,
4373            OperatorGateSubject::Account,
4374            contents,
4375        ));
4376    }
4377    // Claude's own login-method chooser: a numbered list ("1. Claude ...",
4378    // "2. API usage billing", "3. 3rd-party platform ...") rendered under
4379    // "Select login method:". It shares neither "sign in" nor
4380    // "openai"/"chatgpt"/"codex" with the branch above, so that branch
4381    // never catches it. The phrase itself is specific enough (no ordinary
4382    // agent narration renders this exact prompt line) to stand alone,
4383    // matching the precedent set by "select authentication method" and
4384    // "choose how to authenticate" above.
4385    if normalized.contains("select login method") {
4386        return Some(operator_gate(
4387            OperatorGateKind::Authentication,
4388            OperatorGateSubject::Account,
4389            contents,
4390        ));
4391    }
4392    // Claude's OAuth wait screen: a URL to open in a browser plus a slot to
4393    // paste back the authorization code once that flow completes. Required
4394    // to co-occur with "paste code" (the screen's own field label) rather
4395    // than matching on "sign in" alone -- "sign in" by itself is common
4396    // enough in an agent's ordinary narration to be untrustworthy, the same
4397    // reasoning the branch above already applies via its own companion
4398    // words. No option list is rendered here -- it is one free-text slot,
4399    // not a choice from a list -- so `input` is set directly to
4400    // `TextEntry` rather than routed through `operator_gate`'s option-list
4401    // parser, which would find nothing on this screen shape and fall back
4402    // to `Unknown`.
4403    if normalized.contains("sign in") && normalized.contains("paste code") {
4404        return Some(
4405            OperatorGateState::new(OperatorGateKind::Authentication)
4406                .with_subject(OperatorGateSubject::Account)
4407                .with_options(OperatorGateInput::TextEntry, Vec::new()),
4408        );
4409    }
4410    if normalized.contains("kimi code update available")
4411        && normalized.contains("install update now")
4412    {
4413        return Some(operator_gate(
4414            OperatorGateKind::VendorUpdate,
4415            OperatorGateSubject::Unknown,
4416            contents,
4417        ));
4418    }
4419    // A wrapper script self-updating via a package manager before the real
4420    // CLI ever launches -- the case that produced the incident this module
4421    // fixes: an npm-driven wrapper ran an update to completion and printed
4422    // nothing that looked like the agent, while every consumer still saw a
4423    // live, `status: running` PTY. This shares `VendorUpdate` with the Kimi
4424    // in-app case just above on purpose, not by omission: both are "the CLI
4425    // is updating itself", the only difference is WHICH process drives it
4426    // (the agent's own composer vs. a wrapper script's package-manager
4427    // install), and an operator reading `kind` should see one meaning for
4428    // that fact regardless of which vendor's update mechanism produced it.
4429    if PACKAGE_MANAGER_INSTALL_MARKERS
4430        .iter()
4431        .any(|marker| normalized.contains(marker))
4432        && PACKAGE_MANAGER_UPDATE_COMPLETION_MARKERS
4433            .iter()
4434            .any(|marker| normalized.contains(marker))
4435    {
4436        return Some(operator_gate(
4437            OperatorGateKind::VendorUpdate,
4438            OperatorGateSubject::Unknown,
4439            contents,
4440        ));
4441    }
4442    if normalized.contains("choose the text style that looks best with your terminal") {
4443        return Some(operator_gate(
4444            OperatorGateKind::TerminalAppearance,
4445            OperatorGateSubject::Appearance,
4446            contents,
4447        ));
4448    }
4449    if normalized.contains("welcome to claude code for")
4450        && (normalized.contains("open files") || normalized.contains("selected lines"))
4451    {
4452        return Some(operator_gate(
4453            OperatorGateKind::Onboarding,
4454            OperatorGateSubject::Unknown,
4455            contents,
4456        ));
4457    }
4458    if normalized.contains("welcome to claude code")
4459        && (normalized.contains("press enter") || normalized.contains("enter to continue"))
4460    {
4461        return Some(operator_gate(
4462            OperatorGateKind::Onboarding,
4463            OperatorGateSubject::Unknown,
4464            contents,
4465        ));
4466    }
4467    if normalized.contains("migration") && normalized.contains("enter confirm") && normalized.contains("esc")
4468    {
4469        return Some(operator_gate(
4470            OperatorGateKind::ConfigurationMigration,
4471            OperatorGateSubject::Unknown,
4472            contents,
4473        ));
4474    }
4475    None
4476}
4477
4478/// Reads the recognized on-screen choice list, if any, off the RAW
4479/// (multi-line, un-normalized) screen text -- called uniformly by every
4480/// `startup_operator_gate` match arm through `operator_gate`. Recognizes
4481/// exactly two rendered shapes, both observed verbatim on a live stand:
4482///
4483/// - a NUMBERED list (Codex's hook-trust prompt): each option line starts,
4484///   after an optional leading cursor glyph (`›`) and whitespace, with
4485///   `N.`; `Some` lines from `parse_numbered_gate_option_line` win outright
4486///   over the arrow shape below, so a screen that happens to also contain an
4487///   arrow glyph elsewhere (a Codex composer prompt sharing the pane, say)
4488///   is still read as the numbered list it actually is.
4489/// - an ARROW list (Kimi's workspace-trust prompt): the currently selected
4490///   option carries a leading `❯`; the other options carry no glyph at all,
4491///   so they are told apart from the description line rendered under each
4492///   one (`"Enable project MCP servers. Remembered for this folder."` under
4493///   `"Trust this folder"`, for instance) by `parse_arrow_gate_option_line`'s
4494///   own filter -- see that function's doc comment for the exact rule.
4495///
4496/// Neither line is stable across CLIs, and this parser recognizes nothing
4497/// else: a screen matching neither shape returns `(Unknown, vec![])`, never
4498/// a guess built from partial matches.
4499fn parse_operator_gate_options(contents: &str) -> (OperatorGateInput, Vec<OperatorGateOption>) {
4500    let numbered: Vec<OperatorGateOption> = contents
4501        .lines()
4502        .filter_map(parse_numbered_gate_option_line)
4503        .take(OPERATOR_GATE_OPTIONS_MAX)
4504        .collect();
4505    if !numbered.is_empty() {
4506        return (OperatorGateInput::NumberedList, numbered);
4507    }
4508    let arrow: Vec<OperatorGateOption> = contents
4509        .lines()
4510        .filter_map(parse_arrow_gate_option_line)
4511        .take(OPERATOR_GATE_OPTIONS_MAX)
4512        .collect();
4513    if !arrow.is_empty() {
4514        return (OperatorGateInput::ArrowList, arrow);
4515    }
4516    (OperatorGateInput::Unknown, Vec::new())
4517}
4518
4519/// Parses one line of a numbered option list -- `"› 1. Review hooks"`,
4520/// `"  2. Trust all and continue"` -- into `(selected, text)`. `selected` is
4521/// true only when the line carries the leading `›` cursor glyph Codex draws
4522/// on the highlighted row; every other line in the same list has none.
4523/// Returns `None` for any line that, once a leading glyph is stripped, does
4524/// not start with `<digits>.` -- an instruction line like `"Press enter to
4525/// confirm or esc to go back"` is exactly this shape and is meant to fall
4526/// through untouched.
4527/// Cursor glyphs vendors draw ahead of the selected row of an option list.
4528/// Kept as one set shared by both list parsers: which glyph a vendor picks
4529/// says nothing about whether its list is numbered or marker-only, and
4530/// teaching one parser a glyph the other does not know is exactly how the
4531/// selected row went missing before.
4532const GATE_CURSOR_GLYPHS: [char; 2] = ['\u{203a}', '\u{276f}'];
4533
4534fn parse_numbered_gate_option_line(line: &str) -> Option<OperatorGateOption> {
4535    let trimmed = line.trim_start();
4536    // Vendors mark the cursor row of a NUMBERED list with the marker BEFORE
4537    // the number (`> 2. Dark mode`), and they do not agree on the glyph:
4538    // Codex draws U+203A, Claude draws U+276F, and both appear ahead of the
4539    // digit rather than ahead of the text. Recognizing only one of them cost
4540    // the whole row -- the cursor line failed to parse as an option at all,
4541    // so the list came back one item short and with nothing marked selected,
4542    // observed live on Claude's theme chooser and Codex's login chooser.
4543    let (selected, rest) = match trimmed.strip_prefix(GATE_CURSOR_GLYPHS) {
4544        Some(stripped) => (true, stripped.trim_start()),
4545        None => (false, trimmed),
4546    };
4547    let digits_end = rest.find(|character: char| !character.is_ascii_digit()).unwrap_or(0);
4548    if digits_end == 0 {
4549        return None;
4550    }
4551    let text = rest[digits_end..].strip_prefix('.')?.trim();
4552    if text.is_empty() {
4553        return None;
4554    }
4555    Some(OperatorGateOption {
4556        semantics: classify_operator_gate_option_semantics(text),
4557        text: text.to_owned(),
4558        selected,
4559    })
4560}
4561
4562/// Parses one line of an arrow-navigated option list -- `"❯ Don't trust"`,
4563/// `"  Trust this folder"` -- into `(selected, text)`. `selected` is true
4564/// only when the line carries the leading `❯` cursor glyph.
4565///
4566/// Distinguishing an option TITLE from the description/header/instruction
4567/// prose around it (`"Enable project MCP servers. Remembered for this
4568/// folder."` under `"Trust this folder"`; `"Do you trust the files in this
4569/// folder?"` above it; `"Press enter to confirm or esc to go back"` below a
4570/// DIFFERENT screen's numbered list entirely) cannot rely on the glyph
4571/// alone, since only the currently-selected title ever carries one. A
4572/// candidate line is accepted as an option only if EITHER it carries the
4573/// `❯` marker (the screen's own cursor is unambiguous proof this is a real,
4574/// currently-selected option, whatever its wording), OR it both looks like
4575/// a short menu label rather than a sentence (no `.`, `?`, `!`, or `:`
4576/// anywhere in it -- a description or instruction is a full sentence
4577/// carrying one of these; an option label like `"Trust this folder"` or
4578/// `"Don't trust"` never does) AND its own text uses one of the recognized
4579/// option verbs (`classify_operator_gate_option_semantics` returns
4580/// something other than `Unknown`) -- an unmarked line whose wording this
4581/// module does not recognize as a choice-verb is left as prose rather than
4582/// guessed into an option with `semantics: Unknown`. The arrow-key legend
4583/// itself (`"↑↓ navigate · Enter select · Esc exit"`) is excluded
4584/// explicitly rather than relying on either rule catching it.
4585fn parse_arrow_gate_option_line(line: &str) -> Option<OperatorGateOption> {
4586    let trimmed = line.trim();
4587    if trimmed.is_empty()
4588        || trimmed
4589            .chars()
4590            .any(|character| matches!(character, '.' | '?' | '!' | ':'))
4591    {
4592        return None;
4593    }
4594    let lower = trimmed.to_ascii_lowercase();
4595    if lower.contains('\u{2191}') || lower.contains('\u{2193}') || lower.contains("navigate") {
4596        return None;
4597    }
4598    let (selected, rest) = match trimmed.strip_prefix(GATE_CURSOR_GLYPHS) {
4599        Some(stripped) => (true, stripped.trim()),
4600        None => (false, trimmed),
4601    };
4602    if rest.is_empty() || !rest.chars().any(|character| character.is_alphabetic()) {
4603        return None;
4604    }
4605    let semantics = classify_operator_gate_option_semantics(rest);
4606    if !selected && semantics == OperatorGateOptionSemantics::Unknown {
4607        return None;
4608    }
4609    Some(OperatorGateOption {
4610        semantics,
4611        text: rest.to_owned(),
4612        selected,
4613    })
4614}
4615
4616/// Infers what choosing a given on-screen option does from the verb in its
4617/// OWN text -- never from its position or number, since neither is stable
4618/// across CLIs or screen wraps. Decline phrasing is checked before accept
4619/// phrasing so `"Continue without trusting"` (contains both "continue" and
4620/// "without trusting") reads as `Decline`, matching what the option
4621/// actually does; an option whose text uses none of these verbs classifies
4622/// `Unknown` rather than a guessed default.
4623fn classify_operator_gate_option_semantics(text: &str) -> OperatorGateOptionSemantics {
4624    let lower = text.to_ascii_lowercase();
4625    if lower.contains("review") {
4626        OperatorGateOptionSemantics::Inspect
4627    } else if lower.contains("don't trust")
4628        || lower.contains("do not trust")
4629        || lower.contains("without trusting")
4630        || lower.contains("decline")
4631    {
4632        OperatorGateOptionSemantics::Decline
4633    } else if lower.contains("trust") || lower.contains("continue") || lower.contains("proceed") {
4634        OperatorGateOptionSemantics::Accept
4635    } else if lower.contains("exit") || lower.contains("quit") || lower.contains("cancel") {
4636        OperatorGateOptionSemantics::Exit
4637    } else {
4638        OperatorGateOptionSemantics::Unknown
4639    }
4640}
4641
4642/// True if `line` ends in a bare shell-prompt character -- used only to
4643/// raise confidence on the one `screen_failure` marker
4644/// (`"no such file or directory"`) that is otherwise too generic to trust
4645/// alone; see that bucket's own comment.
4646fn looks_like_shell_prompt_line(line: &str) -> bool {
4647    matches!(line.trim_end().chars().last(), Some('$' | '%' | '#' | '>'))
4648}
4649
4650/// Screens where the foreground process already matches the agent (this is
4651/// NOT the `NotAgent` process-mismatch case) but the screen itself shows
4652/// the process came up wrong or fell over. Nothing typed into THIS screen
4653/// fixes it, which is the line that separates `Failing` from
4654/// `OperatorGate`: a gate is resolved by typing an answer into the pane, a
4655/// failure is not.
4656///
4657/// Every marker here is a crash SHAPE -- a stack-trace banner, a shell's
4658/// own "command not found" line -- and as raw bytes a crash shape is
4659/// indistinguishable from an agent CHOOSING to render that same text while
4660/// explaining, or running, someone else's failure (`cargo test` hitting a
4661/// failing assertion, a script the agent ran that threw, a bug report it
4662/// was asked to read). Text alone cannot tell "the CLI crashed" from "the
4663/// CLI is showing you a crash" -- both put identical bytes on screen. The
4664/// one window where these markers ARE trustworthy is before this
4665/// generation's session has ever reached `Ready`: with no prior render of
4666/// the agent's own UI, there is nothing else on the screen that could have
4667/// produced a crash banner, so it genuinely means the launch failed. That
4668/// is why this function's caller in `collect_terminal_frames` stops
4669/// calling it at all once `Ready`, rather than trying to make the matching
4670/// itself tell healthy narration apart from a real crash -- no marker set
4671/// can do that from bytes alone.
4672fn screen_failure(contents: &str) -> Option<&'static str> {
4673    let normalized = normalize_screen_text(contents);
4674
4675    // A language runtime's own uncaught-exception banner -- fixed strings
4676    // a runtime prints verbatim at the head of a crash dump, not phrasing
4677    // a chat transcript would casually reproduce in this exact shape.
4678    // `"fatal error:"` is deliberately NOT included: it is also what a
4679    // C/C++ compiler prints for an ordinary missing-header build error, and
4680    // a wrapper script's build step can emit that while the real CLI still
4681    // comes up fine afterwards -- untrustworthy even in the startup window
4682    // without a second signal this function does not have.
4683    if ["panicked at", "unhandled exception", "traceback (most recent call last)"]
4684        .iter()
4685        .any(|marker| normalized.contains(marker))
4686    {
4687        return Some("crash");
4688    }
4689
4690    // A shell reporting that the launch command itself does not exist.
4691    // The first two are OS/shell-owned sentence shapes on their own. The
4692    // third, `"no such file or directory"`, is common enough in ordinary
4693    // ENOENT discussion that it needs a companion signal -- a line that
4694    // itself ends in a bare shell prompt -- before it counts.
4695    if normalized.contains("command not found")
4696        || normalized.contains("is not recognized as an internal or external command")
4697        || (normalized.contains("no such file or directory")
4698            && contents.lines().any(looks_like_shell_prompt_line))
4699    {
4700        return Some("missing command");
4701    }
4702
4703    // A provider CLI's own missing-credential banner at launch -- Grok with
4704    // no key configured prints exactly this one line and never renders
4705    // anything else again, which makes it a crash SHAPE in the same sense
4706    // as the buckets above: nothing typed into this screen fixes it, only a
4707    // restart with a credential configured. Required to co-occur with the
4708    // literal `GROK_API_KEY` env var name rather than matching "api key
4709    // required" alone -- that phrase in the abstract is common enough in an
4710    // agent's own prose (explaining a DIFFERENT provider's setup, say) to be
4711    // untrustworthy alone; the exact env var name is specific to this one
4712    // banner.
4713    if normalized.contains("api key required") && normalized.contains("grok_api_key") {
4714        return Some("missing api key");
4715    }
4716
4717    None
4718}
4719
4720/// The window gate on `screen_failure`, factored into its own pure
4721/// function so the "stop trusting crash markers once this generation has
4722/// ever been `Ready`" rule is unit-testable without constructing a live
4723/// `OwnedPtySession` (which owns a real PTY and cannot be built in a unit
4724/// test). `collect_terminal_frames` calls this, not `screen_failure`
4725/// directly.
4726fn screen_failure_for_generation(contents: &str, ever_reached_ready: bool) -> Option<&'static str> {
4727    if ever_reached_ready {
4728        None
4729    } else {
4730        screen_failure(contents)
4731    }
4732}
4733
4734/// The foreground half of the classification, resolved by the caller so
4735/// the merge itself stays a pure function.
4736#[derive(Clone, Debug, Eq, PartialEq)]
4737enum ForegroundVerdict {
4738    /// Foreground is the agent's own binary, or a tolerated wrapper.
4739    Agent,
4740    /// Foreground is something else. Carries what was actually seen.
4741    Foreign { process: String },
4742}
4743
4744/// Merge the foreground and text signals into one screen classification.
4745///
4746/// The ORDER below, not the branches, is the part worth reading closely:
4747///
4748/// 1. A foreign foreground wins outright, even over a matching gate or
4749///    failure text pattern, because the process signal is structurally
4750///    exhaustive in the one way that matters -- it never needs to
4751///    recognize an updater's specific wording to say "this is not the
4752///    agent". A vendor wrapper whose text this module's matchers do not
4753///    yet know about still gets caught here.
4754/// 2. With no foreign foreground, `Failing` outranks `OperatorGate`: a
4755///    crashed screen can still have a leftover gate prompt sitting in
4756///    view above the crash dump, and "broken" is the more urgent of the
4757///    two truths for an operator to hear -- reporting "waiting for input"
4758///    about a session that has actually fallen over sends someone to type
4759///    into a pane that cannot use it.
4760/// 3. `OperatorGate` next, for the "resolvable by typing" reason
4761///    documented on `PtyScreenState` itself.
4762/// 4. With no foreground observation at all, the answer is `Unknown`, not
4763///    `Ready` -- a clean text read is NEVER, by itself, proof the screen
4764///    is the agent's. `Ready` requires the foreground to have been
4765///    checked AND to have matched, per the asymmetry documented on
4766///    `PtyScreenState::Ready`.
4767/// 5. Only once foreground is confirmed AND no gate/failure text matched
4768///    does the merge land on `Ready`.
4769fn classify_pty_screen_state(
4770    foreground: Option<&ForegroundVerdict>,
4771    gate: Option<&OperatorGateState>,
4772    failure: Option<&'static str>,
4773) -> PtyScreenState {
4774    if let Some(ForegroundVerdict::Foreign { process }) = foreground {
4775        return PtyScreenState::NotAgent {
4776            observed_process: process.clone(),
4777        };
4778    }
4779    if let Some(reason) = failure {
4780        return PtyScreenState::Failing {
4781            reason: reason.to_owned(),
4782        };
4783    }
4784    if let Some(gate) = gate {
4785        return PtyScreenState::OperatorGate { gate: gate.clone() };
4786    }
4787    if foreground.is_some() {
4788        PtyScreenState::Ready
4789    } else {
4790        PtyScreenState::Unknown
4791    }
4792}
4793
4794/// Resolve what an OS process-tree observation means for classification,
4795/// reusing the exact matchers `ReadinessTracker::observe_foreground` trusts
4796/// at startup so this module's tolerance for a spawning wrapper
4797/// (`node`/`python`/`python3`) never drifts from readiness's own -- a false
4798/// `NotAgent` on a legitimate wrapper would be a regression on what
4799/// readiness already tolerates.
4800///
4801/// Deliberately looser than `ReadinessTracker::observe_foreground` in one
4802/// respect: it does not gate the wrapper tolerance behind
4803/// `has_child_processes`/a poll-count threshold. Those exist there to
4804/// decide "confident enough to flip session status to Running" from a
4805/// process signal ALONE. Here the text signal still has to independently
4806/// agree before the merge can reach `Ready` (see `classify_pty_screen_state`),
4807/// so being more permissive about which process counts as plausible never
4808/// lets a bad screen through on the process signal by itself.
4809fn resolve_foreground_verdict(
4810    spec: &AgentSpec,
4811    observation: &PtyForegroundObservation,
4812    platform: RuntimePlatform,
4813) -> ForegroundVerdict {
4814    let process_name = observation
4815        .readiness
4816        .process_name
4817        .as_deref()
4818        .unwrap_or(observation.observed_process.as_str());
4819    if is_expected_agent_process(spec, process_name, platform)
4820        || is_agent_foreground_wrapper(process_name, platform)
4821    {
4822        ForegroundVerdict::Agent
4823    } else {
4824        ForegroundVerdict::Foreign {
4825            process: observation.observed_process.clone(),
4826        }
4827    }
4828}
4829
4830/// Whether `NativeEffectShell::reclassify_foreground` should schedule
4831/// another probe after a fresh classification, factored out as a small
4832/// pure function so the decision is testable without constructing a live
4833/// `OwnedPtySession` (which owns a real PTY and cannot be built in a unit
4834/// test).
4835#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4836enum ForegroundProbeSchedule {
4837    /// The session reached `Ready` -- stop probing until text disagrees.
4838    Disarmed,
4839    /// Still unresolved, or freshly non-ready -- probe again after the interval.
4840    Armed,
4841}
4842
4843fn foreground_probe_schedule(state: &PtyScreenState) -> ForegroundProbeSchedule {
4844    if matches!(state, PtyScreenState::Ready) {
4845        ForegroundProbeSchedule::Disarmed
4846    } else {
4847        ForegroundProbeSchedule::Armed
4848    }
4849}
4850
4851/// Whether a text-only reclassification that just changed the merged state
4852/// (inside `collect_terminal_frames`) should force the foreground probe due
4853/// immediately, rather than waiting for its normal cadence. Factored out
4854/// for the same testability reason as `foreground_probe_schedule`: a
4855/// session that was `Ready` and whose text just started matching a gate or
4856/// failure pattern needs its foreground re-checked promptly, since the
4857/// last thing anyone probed was clean and the screen no longer agrees.
4858fn foreground_probe_rearms_immediately(previous: &PtyScreenState, next: &PtyScreenState) -> bool {
4859    matches!(previous, PtyScreenState::Ready) && !matches!(next, PtyScreenState::Ready)
4860}
4861
4862fn observe_readiness_event(
4863    tracker: &mut ReadinessTracker<'_>,
4864    diagnostics: &mut ReadinessDiagnostics,
4865    event: PtyEvent,
4866    elapsed_ms: u64,
4867) -> Result<(), String> {
4868    match event {
4869        PtyEvent::Output(data) => {
4870            diagnostics.observe_output(&data);
4871            tracker.observe_output(&data, elapsed_ms);
4872        }
4873        PtyEvent::ForegroundProcess(observation) => {
4874            diagnostics.observe_foreground(&observation.readiness);
4875            tracker.observe_foreground(&observation.readiness, elapsed_ms);
4876        }
4877        PtyEvent::DataGap { .. } => {
4878            return Err("PTY replay gap prevents positive readiness proof".to_owned());
4879        }
4880        PtyEvent::ReaderError { message } | PtyEvent::OperatorActionRequired { message } => {
4881            return Err(message);
4882        }
4883        PtyEvent::Exited { code } => {
4884            return Err(format!("PTY exited with code {code} before readiness"));
4885        }
4886        PtyEvent::Started | PtyEvent::Resized(_) | PtyEvent::SnapshotAvailable { .. } => {}
4887    }
4888    Ok(())
4889}
4890
4891#[derive(Default)]
4892struct ReadinessDiagnostics {
4893    draft_signal: Option<gate4agent_types::DraftReadySignal>,
4894    output_bytes: usize,
4895    output_chunks: usize,
4896    tail: Vec<u8>,
4897    saw_bracketed_paste: bool,
4898    saw_cursor_show: bool,
4899    saw_cursor_hide: bool,
4900    saw_alternate_screen: bool,
4901    saw_clear_screen: bool,
4902    saw_claude_composer: bool,
4903    saw_codex_composer: bool,
4904    saw_named_foreground: bool,
4905    operator_gate: Option<OperatorGateState>,
4906}
4907
4908impl ReadinessDiagnostics {
4909    fn observe_output(&mut self, data: &[u8]) {
4910        const SIGNAL_TAIL_BYTES: usize = 4_096;
4911        self.output_bytes = self.output_bytes.saturating_add(data.len());
4912        self.output_chunks = self.output_chunks.saturating_add(1);
4913        let mut combined = Vec::with_capacity(self.tail.len().saturating_add(data.len()));
4914        combined.extend_from_slice(&self.tail);
4915        combined.extend_from_slice(data);
4916        self.saw_bracketed_paste |= readiness_bytes_contain(&combined, b"\x1b[?2004h");
4917        self.saw_cursor_show |= readiness_bytes_contain(&combined, b"\x1b[?25h");
4918        self.saw_cursor_hide |= readiness_bytes_contain(&combined, b"\x1b[?25l");
4919        self.saw_alternate_screen |= readiness_bytes_contain(&combined, b"\x1b[?1049h");
4920        self.saw_clear_screen |= readiness_bytes_contain(&combined, b"\x1b[2J");
4921        self.saw_claude_composer |= readiness_bytes_contain(&combined, "❯".as_bytes());
4922        self.saw_codex_composer |= readiness_bytes_contain(&combined, "›".as_bytes());
4923        let text = String::from_utf8_lossy(&combined);
4924        self.operator_gate = self
4925            .operator_gate
4926            .take()
4927            .or_else(|| startup_operator_gate(&strip_ansi_codes(&text)));
4928        self.tail = combined[combined.len().saturating_sub(SIGNAL_TAIL_BYTES)..].to_vec();
4929    }
4930
4931    fn observe_foreground(&mut self, foreground: &gate4agent::agent::ForegroundObservation) {
4932        self.saw_named_foreground |= foreground.process_name.is_some();
4933    }
4934
4935    fn summary(&self) -> String {
4936        format!(
4937            "draft_signal={:?} output_bytes={} output_chunks={} named_foreground={} bracketed_paste={} cursor_show={} cursor_hide={} alternate_screen={} clear_screen={} claude_composer={} codex_composer={} csi={}",
4938            self.draft_signal,
4939            self.output_bytes,
4940            self.output_chunks,
4941            self.saw_named_foreground,
4942            self.saw_bracketed_paste,
4943            self.saw_cursor_show,
4944            self.saw_cursor_hide,
4945            self.saw_alternate_screen,
4946            self.saw_clear_screen,
4947            self.saw_claude_composer,
4948            self.saw_codex_composer,
4949            readiness_csi_signatures(&self.tail),
4950        )
4951    }
4952}
4953
4954fn readiness_csi_signatures(bytes: &[u8]) -> String {
4955    let mut signatures = Vec::new();
4956    let mut index = 0;
4957    while index + 2 < bytes.len() && signatures.len() < 32 {
4958        if bytes[index] != 0x1b || bytes[index + 1] != b'[' {
4959            index += 1;
4960            continue;
4961        }
4962        let mut end = index + 2;
4963        while end < bytes.len() && end.saturating_sub(index) <= 24 {
4964            let byte = bytes[end];
4965            if (0x40..=0x7e).contains(&byte) {
4966                let signature = String::from_utf8_lossy(&bytes[index + 2..=end]).into_owned();
4967                if !signatures.iter().any(|existing| existing == &signature) {
4968                    signatures.push(signature);
4969                }
4970                index = end;
4971                break;
4972            }
4973            if !(0x20..=0x3f).contains(&byte) {
4974                break;
4975            }
4976            end += 1;
4977        }
4978        index += 1;
4979    }
4980    if signatures.is_empty() {
4981        "none".to_owned()
4982    } else {
4983        signatures.join("|")
4984    }
4985}
4986
4987fn readiness_bytes_contain(haystack: &[u8], needle: &[u8]) -> bool {
4988    haystack
4989        .windows(needle.len())
4990        .any(|window| window == needle)
4991}
4992
4993fn readiness_complete(
4994    status: ReadinessStatus,
4995    diagnostics: &ReadinessDiagnostics,
4996) -> Result<bool, String> {
4997    match status {
4998        ReadinessStatus::Waiting => Ok(false),
4999        ReadinessStatus::Ready(_) => Ok(true),
5000        ReadinessStatus::TimedOut => Err(format!(
5001            "PTY readiness timed out ({})",
5002            diagnostics.summary()
5003        )),
5004    }
5005}
5006
5007fn elapsed_ms(started: Instant) -> u64 {
5008    u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)
5009}
5010
5011
5012/// Opt-out of mid-turn steering: `queue` sends every follow-up as a plain
5013/// `session/prompt` (the agent then holds it until the running turn ends).
5014pub const ACP_BUSY_PROMPT_ENV: &str = "GATE4AGENT_ACP_BUSY_PROMPT";
5015
5016fn busy_prompt_queues(value: Option<&str>) -> bool {
5017    value.is_some_and(|v| v.trim().eq_ignore_ascii_case("queue"))
5018}
5019
5020/// A follow-up prompt for an ACP session: steered into a running turn when
5021/// the agent supports it (see `AcpSession::submit_prompt`), else a new turn.
5022async fn submit_acp_prompt(session: &gate4agent::acp::AcpSession, prompt: &str) -> Result<(), gate4agent::acp::AcpError> {
5023    if busy_prompt_queues(std::env::var(ACP_BUSY_PROMPT_ENV).ok().as_deref()) {
5024        return session.start_prompt(prompt).await;
5025    }
5026    let delivery = session.submit_prompt(prompt).await?;
5027    match &delivery {
5028        gate4agent::acp::PromptDelivery::Queued { reason } => tracing::info!(
5029            session = session.session_id(),
5030            %reason,
5031            "ACP prompt queued behind the running turn"
5032        ),
5033        other => tracing::debug!(session = session.session_id(), delivery = ?other, "ACP prompt delivered"),
5034    }
5035    Ok(())
5036}
5037
5038#[cfg(test)]
5039mod busy_prompt_env_tests {
5040    use super::busy_prompt_queues;
5041
5042    #[test]
5043    fn only_queue_opts_out_of_steering() {
5044        assert!(busy_prompt_queues(Some("queue")));
5045        assert!(busy_prompt_queues(Some(" QUEUE ")));
5046        assert!(!busy_prompt_queues(Some("steer")));
5047        assert!(!busy_prompt_queues(Some("")));
5048        assert!(!busy_prompt_queues(None));
5049    }
5050}
5051
5052#[cfg(test)]
5053mod tests {
5054    use super::{
5055        acp_approval_level_args,
5056        approval_level_not_offered_message,
5057        classify_operator_gate_option_semantics,
5058        classify_pty_screen_state,
5059        defers_permission_requests,
5060        foreground_probe_rearms_immediately, foreground_probe_schedule,
5061        argument_looks_like_credential, host_policy_for_approval_level,
5062        mcp_server_acp_entry,
5063        parse_operator_gate_options, prepare_fresh_pty_provider_session,
5064        prompt_render_probe, prompt_rendered, required_acp_mode,
5065        reserve_provider_gap_sequence, resolve_foreground_verdict, screen_failure,
5066        screen_failure_for_generation, with_pty_terminal_capability_defaults,
5067        should_attach_pty_provider_stream, should_probe_pty_identity, startup_operator_gate,
5068        terminal_frame, terminal_frame_byte_len, terminal_state_capture_should_skip,
5069        validate_instance_launch_arguments, validate_spawn_runtime_policy,
5070        ForegroundProbeSchedule, ForegroundVerdict, ReadinessDiagnostics, RateLimitFeed,
5071        Utf8ChunkDecoder,
5072    };
5073    use gate4agent::acp::protocol::{McpServerConfig, SessionMode};
5074    use gate4agent::HostPolicy;
5075    use gate4agent_adapters::builtin_adapter_registry;
5076    use gate4agent_catalog::{EnvMutation, McpServerSpec, ModeId};
5077    use gate4agent::agent::ForegroundObservation;
5078    use gate4agent::core::types::{
5079        AgentEvent, ContextWindowUsage as AgentContextWindowUsage, HostDecisionAuthority,
5080        HostRequestDecision, HostRequestOutcome, RateLimitType,
5081    };
5082    use gate4agent::pty::event::PtyMouseProtocolEncoding;
5083    use gate4agent::pty::{PtyForegroundObservation, PtyForegroundSource, RateLimitDetector};
5084    use gate4agent::CliTool;
5085    use gate4agent_types::{
5086        AdapterFamily, AgentId, ApprovalLevel,
5087        HostDecisionAuthority as ProviderHostDecisionAuthority,
5088        HostRequestDecision as ProviderHostRequestDecision,
5089        HostRequestOutcome as ProviderHostRequestOutcome, OperatorGateInput,
5090        OperatorGateKind, OperatorGateOptionSemantics, OperatorGateState, OperatorGateSubject,
5091        ProviderEvent, ProviderInteractionKind, ProviderInteractionOption, ProviderRuntimePolicy,
5092        PtyScreenState, RuntimePlatform, TerminalMouseProtocolEncoding, TransportKind,
5093    };
5094    use std::ffi::{OsStr, OsString};
5095
5096    fn snapshot(sequence: u64, contents: &str) -> super::PtyTerminalSnapshot {
5097        super::PtyTerminalSnapshot {
5098            pty_id: "fixture".to_owned(),
5099            provider_revision: "fixture-r1".to_owned(),
5100            generation: 1,
5101            sequence,
5102            size: gate4agent::pty::PtySize { rows: 24, cols: 80 },
5103            cursor: (0, 0),
5104            bracketed_paste: false,
5105            contents: contents.to_owned(),
5106            formatted: Vec::new(),
5107            scrollback_formatted: Vec::new(),
5108            alternate_screen: false,
5109            mouse_protocol_enabled: false,
5110            mouse_protocol_encoding: PtyMouseProtocolEncoding::Default,
5111            produced_at_unix_ms: 0,
5112        }
5113    }
5114
5115    #[test]
5116    fn terminal_frame_preserves_scrollback_and_terminal_input_metadata() {
5117        let mut snapshot = snapshot(7, "visible");
5118        snapshot.scrollback_formatted = vec![b"older".to_vec()];
5119        snapshot.alternate_screen = true;
5120        snapshot.mouse_protocol_enabled = true;
5121        snapshot.mouse_protocol_encoding = PtyMouseProtocolEncoding::Sgr;
5122        snapshot.produced_at_unix_ms = 1_700_000_000_000;
5123
5124        let frame = terminal_frame(snapshot, PtyScreenState::default());
5125        assert_eq!(frame.scrollback_formatted, vec![b"older".to_vec()]);
5126        assert!(frame.alternate_screen);
5127        assert!(frame.mouse_protocol_enabled);
5128        assert_eq!(frame.mouse_protocol_encoding, TerminalMouseProtocolEncoding::Sgr);
5129        // `terminal_frame` must carry the stamp through, never recompute it.
5130        assert_eq!(frame.produced_at_unix_ms, 1_700_000_000_000);
5131    }
5132
5133    #[test]
5134    fn terminal_frame_byte_len_sums_formatted_and_every_scrollback_row() {
5135        let mut snapshot = snapshot(9, "visible");
5136        snapshot.formatted = b"\x1b[2Jvisible".to_vec();
5137        snapshot.scrollback_formatted =
5138            vec![b"row one".to_vec(), b"row two, longer".to_vec()];
5139        let expected = snapshot.formatted.len()
5140            + snapshot.scrollback_formatted[0].len()
5141            + snapshot.scrollback_formatted[1].len();
5142
5143        let frame = terminal_frame(snapshot, PtyScreenState::default());
5144        assert_eq!(terminal_frame_byte_len(&frame), expected as u64);
5145    }
5146
5147    #[test]
5148    fn the_sequence_gate_skips_only_when_the_sequence_did_not_advance() {
5149        assert!(terminal_state_capture_should_skip(Ok::<u64, ()>(5), 5));
5150        assert!(terminal_state_capture_should_skip(Ok::<u64, ()>(4), 5));
5151        assert!(!terminal_state_capture_should_skip(Ok::<u64, ()>(6), 5));
5152        // A failed cheap read never skips -- the real call is attempted so
5153        // its own error path (stale-published bookkeeping) still runs.
5154        assert!(!terminal_state_capture_should_skip(Err::<u64, ()>(()), 5));
5155    }
5156
5157    #[test]
5158    fn structured_context_usage_maps_without_pty_inference() {
5159        let mapped = super::provider_event(
5160            AgentEvent::ContextWindowUsage {
5161                usage: AgentContextWindowUsage {
5162                    uncached_input_tokens: 70,
5163                    cache_read_tokens: 20,
5164                    cache_write_tokens: 0,
5165                    output_tokens: 10,
5166                    unattributed_tokens: 5,
5167                    used_tokens: 105,
5168                    capacity_tokens: 100,
5169                },
5170            },
5171            &[],
5172        );
5173        assert_eq!(
5174            mapped,
5175            Some(ProviderEvent::ContextWindowUsage {
5176                usage: gate4agent_types::ContextWindowUsage {
5177                    uncached_input_tokens: 70,
5178                    cache_read_tokens: 20,
5179                    cache_write_tokens: 0,
5180                    output_tokens: 10,
5181                    unattributed_tokens: 5,
5182                    used_tokens: 105,
5183                    capacity_tokens: 100,
5184                }
5185            })
5186        );
5187        assert_eq!(
5188            ProviderEvent::ContextWindowUsage {
5189                usage: gate4agent_types::ContextWindowUsage {
5190                    uncached_input_tokens: 70,
5191                    cache_read_tokens: 20,
5192                    cache_write_tokens: 0,
5193                    output_tokens: 10,
5194                    unattributed_tokens: 5,
5195                    used_tokens: 104,
5196                    capacity_tokens: 100,
5197                },
5198            }
5199            .validate_ingress(),
5200            Err(gate4agent_types::ProviderEventValidationError::ContextWindowSegmentsMismatch {
5201                segment_sum: 105,
5202                used_tokens: 104,
5203            })
5204        );
5205        assert!(
5206            super::provider_event(AgentEvent::PtyRaw { data: b"105/100".to_vec() }, &[]).is_none()
5207        );
5208    }
5209
5210    /// `AgentEvent::TurnInterrupted` (synthesized by `acp::session::
5211    /// AcpSession::start_prompt` when a `session/prompt` call ends without a
5212    /// success response) must reach `ProviderEvent::TurnInterrupted` --
5213    /// `gate4agent-engine`'s snapshot reducer is the one place that resets
5214    /// `ProviderActivity` away from `Blocked` back to `Idle` for it, closing
5215    /// the stuck-forever "turn in flight" bug measured live against
5216    /// codex-acp 1.10.0 (a `session/prompt` RPC error left every subsequent
5217    /// prompt refused for the rest of the session).
5218    #[test]
5219    fn turn_interrupted_maps_to_the_provider_event_that_unblocks_the_next_prompt() {
5220        let mapped = super::provider_event(
5221            AgentEvent::TurnInterrupted {
5222                reason: "session/prompt timed out after 120s".to_owned(),
5223            },
5224            &[],
5225        );
5226        assert_eq!(mapped, Some(ProviderEvent::TurnInterrupted));
5227    }
5228
5229    #[test]
5230    fn tool_result_non_execution_kind_carries_through_to_tool_completed() {
5231        let mapped = super::provider_event(
5232            AgentEvent::ToolResult {
5233                id: "t1".to_owned(),
5234                output: "denied".to_owned(),
5235                is_error: true,
5236                duration_ms: None,
5237                non_execution_kind: Some("permission-rule".to_owned()),
5238            },
5239            &[],
5240        );
5241        assert_eq!(
5242            mapped,
5243            Some(ProviderEvent::ToolCompleted {
5244                id: "t1".to_owned(),
5245                output: "denied".to_owned(),
5246                is_error: true,
5247                duration_ms: None,
5248                agent_id: None,
5249                non_execution_kind: Some("permission-rule".to_owned()),
5250            })
5251        );
5252    }
5253
5254    #[test]
5255    fn session_end_stop_reason_carries_through_to_session_ended() {
5256        use gate4agent::StopReason;
5257
5258        let refusal = super::provider_event(
5259            AgentEvent::SessionEnd {
5260                result: "refusal".to_owned(),
5261                cost_usd: None,
5262                is_error: true,
5263                stop_reason: Some(StopReason::Refusal),
5264            },
5265            &[],
5266        );
5267        assert_eq!(
5268            refusal,
5269            Some(ProviderEvent::SessionEnded {
5270                result: "refusal".to_owned(),
5271                cost_usd: None,
5272                is_error: true,
5273                stop_reason: Some(gate4agent_types::ProviderStopReason::Refusal),
5274            })
5275        );
5276
5277        let quota = super::provider_event(
5278            AgentEvent::SessionEnd {
5279                result: "JSON-RPC error -32603: Internal error".to_owned(),
5280                cost_usd: None,
5281                is_error: true,
5282                stop_reason: Some(StopReason::ProviderError {
5283                    code: -32603,
5284                    message: "You've hit your usage limit.".to_owned(),
5285                    vendor_code: Some("usageLimitExceeded".to_owned()),
5286                }),
5287            },
5288            &[],
5289        );
5290        assert_eq!(
5291            quota,
5292            Some(ProviderEvent::SessionEnded {
5293                result: "JSON-RPC error -32603: Internal error".to_owned(),
5294                cost_usd: None,
5295                is_error: true,
5296                stop_reason: Some(gate4agent_types::ProviderStopReason::ProviderError {
5297                    code: -32603,
5298                    message: "You've hit your usage limit.".to_owned(),
5299                    vendor_code: Some("usageLimitExceeded".to_owned()),
5300                }),
5301            })
5302        );
5303    }
5304
5305    #[test]
5306    fn host_request_reaches_the_operator_with_method_and_host_decision() {
5307        let denied = super::provider_event(
5308            AgentEvent::RpcIncomingRequest {
5309                id: gate4agent::rpc::message::RpcId::Number(1),
5310                method: "fs/read_text_file".to_owned(),
5311                params: None,
5312                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Policy },
5313                outcome: HostRequestOutcome::Executed,
5314                reason: None,
5315            },
5316            &[],
5317        );
5318        assert_eq!(
5319            denied,
5320            Some(ProviderEvent::HostRequestObserved {
5321                method: "fs/read_text_file".to_owned(),
5322                params_json: String::new(),
5323                decision: ProviderHostRequestDecision::Denied {
5324                    by: ProviderHostDecisionAuthority::Policy
5325                },
5326                outcome: ProviderHostRequestOutcome::Executed,
5327                reason: None,
5328            })
5329        );
5330
5331        let granted = super::provider_event(
5332            AgentEvent::RpcIncomingRequest {
5333                id: gate4agent::rpc::message::RpcId::Number(2),
5334                method: "terminal/create".to_owned(),
5335                params: None,
5336                decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Policy },
5337                outcome: HostRequestOutcome::Executed,
5338                reason: None,
5339            },
5340            &[],
5341        );
5342        assert_eq!(
5343            granted,
5344            Some(ProviderEvent::HostRequestObserved {
5345                method: "terminal/create".to_owned(),
5346                params_json: String::new(),
5347                decision: ProviderHostRequestDecision::Granted {
5348                    by: ProviderHostDecisionAuthority::Policy
5349                },
5350                outcome: ProviderHostRequestOutcome::Executed,
5351                reason: None,
5352            })
5353        );
5354
5355        // Every authority carries through, not just the outcome -- a gate
5356        // block and an operator's answer must remain distinguishable on the
5357        // wire, and a deadline expiry must never be mistaken for one.
5358        let gate_denied = super::provider_event(
5359            AgentEvent::RpcIncomingRequest {
5360                id: gate4agent::rpc::message::RpcId::Number(3),
5361                method: "terminal/create".to_owned(),
5362                params: None,
5363                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Gate },
5364                outcome: HostRequestOutcome::Executed,
5365                reason: None,
5366            },
5367            &[],
5368        );
5369        assert_eq!(
5370            gate_denied,
5371            Some(ProviderEvent::HostRequestObserved {
5372                method: "terminal/create".to_owned(),
5373                params_json: String::new(),
5374                decision: ProviderHostRequestDecision::Denied {
5375                    by: ProviderHostDecisionAuthority::Gate
5376                },
5377                outcome: ProviderHostRequestOutcome::Executed,
5378                reason: None,
5379            })
5380        );
5381
5382        let operator_granted = super::provider_event(
5383            AgentEvent::RpcIncomingRequest {
5384                id: gate4agent::rpc::message::RpcId::Number(4),
5385                method: "session/request_permission".to_owned(),
5386                params: None,
5387                decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Operator },
5388                outcome: HostRequestOutcome::Executed,
5389                reason: None,
5390            },
5391            &[],
5392        );
5393        assert_eq!(
5394            operator_granted,
5395            Some(ProviderEvent::HostRequestObserved {
5396                method: "session/request_permission".to_owned(),
5397                params_json: String::new(),
5398                decision: ProviderHostRequestDecision::Granted {
5399                    by: ProviderHostDecisionAuthority::Operator
5400                },
5401                outcome: ProviderHostRequestOutcome::Executed,
5402                reason: None,
5403            })
5404        );
5405
5406        let deadline_denied = super::provider_event(
5407            AgentEvent::RpcIncomingRequest {
5408                id: gate4agent::rpc::message::RpcId::Number(5),
5409                method: "session/request_permission".to_owned(),
5410                params: None,
5411                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::DeadlinePolicy },
5412                outcome: HostRequestOutcome::Executed,
5413                reason: None,
5414            },
5415            &[],
5416        );
5417        assert_eq!(
5418            deadline_denied,
5419            Some(ProviderEvent::HostRequestObserved {
5420                method: "session/request_permission".to_owned(),
5421                params_json: String::new(),
5422                decision: ProviderHostRequestDecision::Denied {
5423                    by: ProviderHostDecisionAuthority::DeadlinePolicy
5424                },
5425                outcome: ProviderHostRequestOutcome::Executed,
5426                reason: None,
5427            })
5428        );
5429
5430        // `session/request_permission` + `Deferred` is deliberately absent
5431        // here -- that combination becomes an `InteractionRequested`, not a
5432        // `HostRequestObserved`; see
5433        // `deferred_acp_permission_request_becomes_an_interaction_with_its_id`
5434        // below.
5435    }
5436
5437    /// K1c's split: an authorized (`Granted`) host request that failed
5438    /// WHILE EXECUTING (e.g. a `terminal/create` spawn error) must carry
5439    /// `HostRequestOutcome::Failed` through to `ProviderEvent::
5440    /// HostRequestObserved` verbatim -- never dropped, and never collapsed
5441    /// into `Denied`: the request WAS authorized, only its execution
5442    /// failed.
5443    #[test]
5444    fn granted_host_request_execution_failure_carries_through_as_a_failed_outcome() {
5445        let spawn_error = "terminal/create spawn failed: os error 3";
5446        let mapped = super::provider_event(
5447            AgentEvent::RpcIncomingRequest {
5448                id: gate4agent::rpc::message::RpcId::Number(10),
5449                method: "terminal/create".to_owned(),
5450                params: None,
5451                decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Policy },
5452                outcome: HostRequestOutcome::Failed { error: spawn_error.to_owned() },
5453                reason: None,
5454            },
5455            &[],
5456        );
5457        assert_eq!(
5458            mapped,
5459            Some(ProviderEvent::HostRequestObserved {
5460                method: "terminal/create".to_owned(),
5461                params_json: String::new(),
5462                decision: ProviderHostRequestDecision::Granted {
5463                    by: ProviderHostDecisionAuthority::Policy
5464                },
5465                outcome: ProviderHostRequestOutcome::Failed { error: spawn_error.to_owned() },
5466                reason: None,
5467            })
5468        );
5469        mapped.expect("mapped").validate_ingress().expect("bounded free-text error validates");
5470    }
5471
5472    /// The bug this change fixes: the gate's own refusal text used to be
5473    /// computed, then thrown away -- an observer got the categorical
5474    /// `Denied { by: Gate }` and nothing naming WHY. `reason` now rides the
5475    /// SAME `AgentEvent::RpcIncomingRequest` → `ProviderEvent::
5476    /// HostRequestObserved` mapping every other field already used,
5477    /// verbatim, bounded by `validate_ingress`.
5478    #[test]
5479    fn host_request_reason_carries_through_to_the_operator() {
5480        let gate_text =
5481            "blocked by dangerous-command gate: rule=filesystem-wipe, argument=rm -rf /";
5482        let denied = super::provider_event(
5483            AgentEvent::RpcIncomingRequest {
5484                id: gate4agent::rpc::message::RpcId::Number(9),
5485                method: "terminal/create".to_owned(),
5486                params: None,
5487                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Gate },
5488                outcome: HostRequestOutcome::Executed,
5489                reason: Some(gate_text.to_owned()),
5490            },
5491            &[],
5492        );
5493        assert_eq!(
5494            denied,
5495            Some(ProviderEvent::HostRequestObserved {
5496                method: "terminal/create".to_owned(),
5497                params_json: String::new(),
5498                decision: ProviderHostRequestDecision::Denied {
5499                    by: ProviderHostDecisionAuthority::Gate
5500                },
5501                outcome: ProviderHostRequestOutcome::Executed,
5502                reason: Some(gate_text.to_owned()),
5503            })
5504        );
5505
5506        // `validate_ingress` accepts the reason as ordinary bounded free
5507        // text -- the same bound `ToolCompleted::output` uses, proving this
5508        // is not smuggled through the categorical `Error::detail` field the
5509        // owner's incident named (that validator only accepts `a-z0-9-`).
5510        denied.expect("mapped").validate_ingress().expect("bounded free-text reason validates");
5511    }
5512
5513    #[test]
5514    fn deferred_acp_permission_request_becomes_an_interaction_with_its_id() {
5515        let with_title = super::provider_event(
5516            AgentEvent::RpcIncomingRequest {
5517                id: gate4agent::rpc::message::RpcId::Number(6),
5518                method: "session/request_permission".to_owned(),
5519                params: Some(serde_json::json!({
5520                    "sessionId": "s1",
5521                    "toolCall": {"toolCallId": "t1", "kind": "edit", "title": "Edit src/main.rs"},
5522                    "options": [
5523                        {"optionId": "allow", "name": "Allow", "kind": "allow_once"},
5524                        {"optionId": "reject", "name": "Reject", "kind": "reject_once"},
5525                    ],
5526                })),
5527                decision: HostRequestDecision::Deferred,
5528                outcome: HostRequestOutcome::Executed,
5529                reason: None,
5530            },
5531            &[],
5532        );
5533        // `kind` is the tool CLASS and `title` is the question. They are two
5534        // different things and the operator needs both: putting the title in
5535        // `tool_name` and leaving `prompt` empty -- which this asserted
5536        // before -- showed a correlation id and a sentence-shaped tool name,
5537        // and never the question itself. `title`/`options` now carry the
5538        // agent's own values instead of arriving empty -- the operator's
5539        // approve/deny answer must resolve against an option list they can
5540        // actually see.
5541        assert_eq!(
5542            with_title,
5543            Some(ProviderEvent::InteractionRequested {
5544                request_id: Some("number:6".to_owned()),
5545                interaction_kind: ProviderInteractionKind::Approval,
5546                tool_name: "edit".to_owned(),
5547                title: Some("Edit src/main.rs".to_owned()),
5548                prompt: "Edit src/main.rs".to_owned(),
5549                options: vec![
5550                    ProviderInteractionOption {
5551                        option_id: "allow".to_owned(),
5552                        name: "Allow".to_owned(),
5553                        kind: "allow_once".to_owned(),
5554                    },
5555                    ProviderInteractionOption {
5556                        option_id: "reject".to_owned(),
5557                        name: "Reject".to_owned(),
5558                        kind: "reject_once".to_owned(),
5559                    },
5560                ],
5561                agent_id: None,
5562            })
5563        );
5564
5565        // No `kind` on the wire (or no params at all) -- falls back to the
5566        // method name rather than an empty `tool_name`, which
5567        // `ProviderEvent::validate_ingress` rejects. An absent `title`
5568        // leaves `prompt` empty rather than inventing a question, and no
5569        // params at all means no option list to read, not a dropped one.
5570        let without_title = super::provider_event(
5571            AgentEvent::RpcIncomingRequest {
5572                id: gate4agent::rpc::message::RpcId::String("agent-7".to_owned()),
5573                method: "session/request_permission".to_owned(),
5574                params: None,
5575                decision: HostRequestDecision::Deferred,
5576                outcome: HostRequestOutcome::Executed,
5577                reason: None,
5578            },
5579            &[],
5580        );
5581        assert_eq!(
5582            without_title,
5583            Some(ProviderEvent::InteractionRequested {
5584                request_id: Some("string:agent-7".to_owned()),
5585                interaction_kind: ProviderInteractionKind::Approval,
5586                tool_name: "session/request_permission".to_owned(),
5587                title: None,
5588                prompt: String::new(),
5589                options: Vec::new(),
5590                agent_id: None,
5591            })
5592        );
5593
5594        // The SAME id's eventual outcome (not itself `Deferred` anymore)
5595        // still reaches the operator as the ordinary audit trail, exactly
5596        // as every other host request does.
5597        let resolved = super::provider_event(
5598            AgentEvent::RpcIncomingRequest {
5599                id: gate4agent::rpc::message::RpcId::Number(6),
5600                method: "session/request_permission".to_owned(),
5601                params: None,
5602                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Operator },
5603                outcome: HostRequestOutcome::Executed,
5604                reason: None,
5605            },
5606            &[],
5607        );
5608        assert_eq!(
5609            resolved,
5610            Some(ProviderEvent::HostRequestObserved {
5611                method: "session/request_permission".to_owned(),
5612                params_json: String::new(),
5613                decision: ProviderHostRequestDecision::Denied {
5614                    by: ProviderHostDecisionAuthority::Operator
5615                },
5616                outcome: ProviderHostRequestOutcome::Executed,
5617                reason: None,
5618            })
5619        );
5620    }
5621
5622    #[test]
5623    fn unrecognized_notification_reaches_the_operator_as_a_raw_event_instead_of_vanishing() {
5624        let mapped = super::provider_event(
5625            AgentEvent::RpcNotification {
5626                method: "session/update".to_owned(),
5627                params: Default::default(),
5628            },
5629            &[],
5630        );
5631        assert_eq!(
5632            mapped,
5633            Some(ProviderEvent::UnrecognizedNotification {
5634                method: "session/update".to_owned(),
5635                payload_json: "null".to_owned(),
5636            })
5637        );
5638    }
5639
5640    #[test]
5641    fn pty_terminal_capability_defaults_never_override_a_caller_supplied_term() {
5642        let caller_supplied = vec![EnvMutation {
5643            key: OsString::from("TERM"),
5644            value: Some(OsString::from("dumb")),
5645        }];
5646        let filled = with_pty_terminal_capability_defaults(caller_supplied);
5647
5648        let term_values: Vec<_> = filled
5649            .iter()
5650            .filter(|mutation| mutation.key.as_os_str() == OsStr::new("TERM"))
5651            .collect();
5652        assert_eq!(term_values.len(), 1, "TERM must not be duplicated");
5653        assert_eq!(term_values[0].value.as_deref(), Some(OsStr::new("dumb")));
5654
5655        let colorterm = filled
5656            .iter()
5657            .find(|mutation| mutation.key.as_os_str() == OsStr::new("COLORTERM"))
5658            .expect("COLORTERM default is filled in when the caller left it unset");
5659        assert_eq!(colorterm.value.as_deref(), Some(OsStr::new("truecolor")));
5660    }
5661
5662    // -----------------------------------------------------------------------
5663    // mcp_server_acp_entry — the ACP half of the door
5664    // (gate4agent-arc-mailbox-and-task-layer Slice A(ii))
5665    // -----------------------------------------------------------------------
5666
5667    #[test]
5668    fn mcp_server_acp_entry_translates_a_spec_into_one_stdio_entry() {
5669        let spec = McpServerSpec::new(
5670            "test-mcp-server",
5671            OsString::from("C:\\example\\example-mcp-server.exe"),
5672            vec![OsString::from("--session-proxy")],
5673            vec![
5674                (
5675                    OsString::from("TEST_MCP_SESSION_ENDPOINT"),
5676                    OsString::from("\\\\.\\pipe\\example-mcp-server-s1"),
5677                ),
5678                (
5679                    OsString::from("TEST_MCP_SESSION_TOKEN"),
5680                    OsString::from("tok-abc"),
5681                ),
5682            ],
5683        )
5684        .unwrap();
5685
5686        let server = mcp_server_acp_entry(&spec);
5687        match server {
5688            McpServerConfig::Stdio { name, command, args, env } => {
5689                assert_eq!(name, "test-mcp-server", "ACP v1 requires a name; the adapter registers by it");
5690                assert_eq!(command, "C:\\example\\example-mcp-server.exe");
5691                assert_eq!(args, vec!["--session-proxy".to_string()]);
5692                assert_eq!(env.len(), 2, "exactly the entries the spec was given, nothing else");
5693                assert_eq!(
5694                    env.iter().find(|pair| pair.name == "TEST_MCP_SESSION_ENDPOINT").map(|pair| pair.value.as_str()),
5695                    Some("\\\\.\\pipe\\example-mcp-server-s1")
5696                );
5697                assert_eq!(
5698                    env.iter().find(|pair| pair.name == "TEST_MCP_SESSION_TOKEN").map(|pair| pair.value.as_str()),
5699                    Some("tok-abc")
5700                );
5701            }
5702            McpServerConfig::Sse { .. } => panic!("expected Stdio variant"),
5703        }
5704    }
5705
5706    #[test]
5707    fn mcp_server_acp_entry_carries_zero_env_pairs_when_the_spec_carries_none() {
5708        let spec = McpServerSpec::new(
5709            "test-mcp-server",
5710            OsString::from("C:\\example\\example-mcp-server.exe"),
5711            vec![OsString::from("--session-proxy")],
5712            Vec::new(),
5713        )
5714        .unwrap();
5715
5716        let server = mcp_server_acp_entry(&spec);
5717        match server {
5718            McpServerConfig::Stdio { env, .. } => assert!(env.is_empty()),
5719            McpServerConfig::Sse { .. } => panic!("expected Stdio variant"),
5720        }
5721    }
5722
5723    #[test]
5724    fn credential_shape_rule_matches_prefixed_hex64_not_bare_digest_or_uuid() {
5725        let hex64 = "a1b2c3d4e5f6".repeat(5) + "a1b2";
5726        assert_eq!(hex64.len(), 64);
5727
5728        let prefixed_token = format!("g4aho_{hex64}");
5729        assert!(
5730            argument_looks_like_credential(&prefixed_token),
5731            "a short lowercase prefix plus '_' plus 64 lowercase hex chars is a credential"
5732        );
5733
5734        assert!(
5735            !argument_looks_like_credential(&hex64),
5736            "a bare 64-hex digest with no prefix is a legitimate diagnostic, not a credential"
5737        );
5738
5739        assert!(
5740            !argument_looks_like_credential("550e8400-e29b-41d4-a716-446655440000"),
5741            "a UUID must not be mistaken for a prefixed-hex64 credential"
5742        );
5743    }
5744
5745    #[test]
5746    fn native_instance_launch_arguments_fail_closed_before_shell_spawn() {
5747        let claude = AgentId::new("claude").unwrap();
5748        assert_eq!(
5749            validate_instance_launch_arguments(
5750                &claude,
5751                TransportKind::Pipe,
5752                &[OsString::from("--bundle-mode")],
5753            )
5754            .unwrap_err(),
5755            "native instance launch arguments require PTY transport (or Codex -c overlays on ACP)"
5756        );
5757        assert_eq!(
5758            validate_instance_launch_arguments(
5759                &claude,
5760                TransportKind::Pty,
5761                &[OsString::from("--resume=session-secret")],
5762            )
5763            .unwrap_err(),
5764            "native instance launch arguments conflict with Claude session, resume, or prompt authority"
5765        );
5766        assert!(validate_instance_launch_arguments(
5767            &claude,
5768            TransportKind::Pty,
5769            &[
5770                OsString::from("--permission-mode"),
5771                OsString::from("default"),
5772            ],
5773        )
5774        .is_ok());
5775    }
5776
5777    /// Classifies `contents` and returns just the `kind` -- the same check
5778    /// every case below cares about, without repeating `.map(|gate|
5779    /// gate.kind)` at every call site.
5780    fn kind_of(contents: &str) -> Option<OperatorGateKind> {
5781        startup_operator_gate(contents).map(|gate| gate.kind)
5782    }
5783
5784    #[test]
5785    fn startup_operator_gates_are_classified_without_returning_terminal_text() {
5786        assert_eq!(kind_of(" Trust this\nfolder? "), Some(OperatorGateKind::WorkspaceTrust));
5787        assert_eq!(
5788            kind_of("No auth type is selected"),
5789            Some(OperatorGateKind::Authentication)
5790        );
5791        assert_eq!(
5792            kind_of("Sign in with OpenAI to use Codex"),
5793            Some(OperatorGateKind::Authentication)
5794        );
5795        // Claude's login-method chooser and its OAuth code-paste wait
5796        // screen -- both previously misread as `Ready` because neither
5797        // contains "openai"/"chatgpt"/"codex", so the branch above never
5798        // caught them. Verbatim shape from `terminal-read` on a clean
5799        // macOS arm64 stand with no vendor login.
5800        assert_eq!(
5801            kind_of(
5802                "Claude Code can be used with your Claude subscription or billed based on \
5803                 API usage through your Console account.\n\
5804                 Select login method:\n\
5805                 \u{276f} 1. Claude ...\n\
5806                 2. API usage billing\n\
5807                 3. 3rd-party platform \u{b7} Amazon Bedrock ..."
5808            ),
5809            Some(OperatorGateKind::Authentication)
5810        );
5811        assert_eq!(
5812            kind_of(
5813                "Browser didn't open? Use the url below to sign in (c to copy)\n\
5814                 https://claude.com/oauth/authorize?client_id=abc&redirect_uri=https%3A%2F%2Fconsole.anthropic.com&code_challenge=xyz\n\
5815                 Paste code here"
5816            ),
5817            Some(OperatorGateKind::Authentication)
5818        );
5819        // Ordinary narration reusing "sign in" and "paste" separately, but
5820        // never as the screen's own "paste code" field label, must not
5821        // false-positive -- the same companion-word discipline the
5822        // OpenAI/Codex sign-in branch already applies above.
5823        assert_eq!(
5824            kind_of(
5825                "Once you sign in, copy the generated token and paste it into your .env file; \
5826                 no code entry happens on this screen."
5827            ),
5828            None
5829        );
5830        assert_eq!(
5831            kind_of("Kimi Code Update Available\nInstall update now (0.32.0)\nEnter confirm"),
5832            Some(OperatorGateKind::VendorUpdate)
5833        );
5834        assert_eq!(
5835            kind_of(
5836                "Welcome to Claude Code\nChoose the text style that looks best with your terminal"
5837            ),
5838            Some(OperatorGateKind::TerminalAppearance)
5839        );
5840        assert_eq!(
5841            kind_of(
5842                "Welcome to Claude Code for VS Code\nClaude has context of open files and selected lines"
5843            ),
5844            Some(OperatorGateKind::Onboarding)
5845        );
5846        assert_eq!(
5847            kind_of("Welcome to Claude Code\n❯ Press Enter to continue"),
5848            Some(OperatorGateKind::Onboarding)
5849        );
5850        assert_eq!(kind_of("Welcome to Claude Code\n❯ ready\nEnter to send"), None);
5851        assert_eq!(
5852            kind_of(
5853                "Quick safety check: Is this a project you trust?\nYes, I trust this folder\nNo, continue without these permissions"
5854            ),
5855            Some(OperatorGateKind::WorkspaceTrust)
5856        );
5857        assert_eq!(kind_of("ready for a prompt"), None);
5858        // Regression test for the incident this module fixes: a provider
5859        // CLI's wrapper self-updated via npm before the real agent ever
5860        // launched, and every consumer saw `status: running` on a live PTY
5861        // that was actually showing this text. Verbatim transcript.
5862        assert_eq!(
5863            kind_of(
5864                "Updating Codex via `npm install -g @openai/codex`...\n\
5865                 npm warn cleanup Failed to remove some directories\n\
5866                 Update ran successfully! Please restart Codex."
5867            ),
5868            Some(OperatorGateKind::VendorUpdate)
5869        );
5870        // Regression test for the live-stand incident this branch fixes:
5871        // Codex's startup hook-trust prompt was classified `Ready` because
5872        // no marker recognized it, so a prompt injected into the PTY landed
5873        // in this blocking select-list instead of the agent. Verbatim
5874        // transcript from `terminal-read`, 40x120 -- note this capture wraps
5875        // the `› 1. Review hooks` marker onto the end of the preceding
5876        // sentence, so it is deliberately NOT the clean list shape the
5877        // dedicated option-parsing tests below assert on; this test only
5878        // pins the `kind`, same as it always has.
5879        assert_eq!(
5880            kind_of(
5881                "  Hooks need review\n\
5882                   6 hooks are new or changed.\n\
5883                   Hooks can run outside the sandbox after you trust them.\u{203a} 1. Review hooks\n\
5884                   2. Trust all and continue\n\
5885                   3. Continue without trusting (hooks won't run)  Press enter to confirm or esc to go back"
5886            ),
5887            Some(OperatorGateKind::HookTrust)
5888        );
5889        // Same screen, different hook count -- the match must not depend on
5890        // the number.
5891        assert_eq!(
5892            kind_of(
5893                "  Hooks need review\n\
5894                   42 hooks are new or changed.\n\
5895                   Hooks can run outside the sandbox after you trust them.\u{203a} 1. Review hooks\n\
5896                   2. Trust all and continue\n\
5897                   3. Continue without trusting (hooks won't run)  Press enter to confirm or esc to go back"
5898            ),
5899            Some(OperatorGateKind::HookTrust)
5900        );
5901        // Ordinary agent narration that happens to mention hooks and trust
5902        // must NOT be classified as this gate -- it lacks the screen's own
5903        // "continue without trusting" refusal phrasing.
5904        assert_eq!(
5905            kind_of(
5906                "I reviewed the pre-commit hooks in this repo and they look safe to trust; \
5907                 I'll leave the hooks config as-is and continue with the refactor."
5908            ),
5909            None
5910        );
5911    }
5912
5913    /// Codex's hook-trust prompt rendered as a clean numbered list (the
5914    /// shape actually described by the task this parser was written for,
5915    /// as opposed to the line-wrapped capture pinned by `kind` alone
5916    /// above): `parse_operator_gate_options` reads all three choices, marks
5917    /// the `›`-prefixed one selected, and infers accept/inspect/decline
5918    /// from each option's own verb -- never from its number or position.
5919    #[test]
5920    fn startup_operator_gate_parses_a_numbered_hook_trust_option_list() {
5921        let contents = "Hooks need review\n\
5922             \u{203a} 1. Review hooks\n  \
5923             2. Trust all and continue\n  \
5924             3. Continue without trusting (hooks won't run)\n\
5925             Press enter to confirm or esc to go back";
5926        let gate = startup_operator_gate(contents).expect("hook trust must classify");
5927        assert_eq!(gate.kind, OperatorGateKind::HookTrust);
5928        assert_eq!(gate.input, OperatorGateInput::NumberedList);
5929        assert_eq!(
5930            gate.options,
5931            vec![
5932                gate4agent_types::OperatorGateOption {
5933                    text: "Review hooks".to_owned(),
5934                    semantics: OperatorGateOptionSemantics::Inspect,
5935                    selected: true,
5936                },
5937                gate4agent_types::OperatorGateOption {
5938                    text: "Trust all and continue".to_owned(),
5939                    semantics: OperatorGateOptionSemantics::Accept,
5940                    selected: false,
5941                },
5942                gate4agent_types::OperatorGateOption {
5943                    text: "Continue without trusting (hooks won't run)".to_owned(),
5944                    semantics: OperatorGateOptionSemantics::Decline,
5945                    selected: false,
5946                },
5947            ],
5948        );
5949    }
5950
5951    /// Kimi's workspace-trust prompt rendered as an arrow-navigated list
5952    /// with a description line under each title: `parse_operator_gate_options`
5953    /// reads the two TITLES ("Trust this folder", "Don't trust") as options,
5954    /// marks the `❯`-prefixed one selected, and does NOT mistake either
5955    /// description line (both full sentences, ending in `.`) for a third
5956    /// and fourth option.
5957    #[test]
5958    fn startup_operator_gate_parses_an_arrow_workspace_trust_option_list() {
5959        let contents = "Do you trust the files in this folder?\n  \
5960             Trust this folder\n  \
5961             Enable project MCP servers. Remembered for this folder.\n\u{276f} \
5962             Don't trust\n  \
5963             Exit Kimi Code. Asked again next launch.\n  \
5964             \u{2191}\u{2193} navigate \u{b7} Enter select \u{b7} Esc exit";
5965        let gate = startup_operator_gate(contents).expect("workspace trust must classify");
5966        assert_eq!(gate.kind, OperatorGateKind::WorkspaceTrust);
5967        assert_eq!(gate.input, OperatorGateInput::ArrowList);
5968        assert_eq!(
5969            gate.options,
5970            vec![
5971                gate4agent_types::OperatorGateOption {
5972                    text: "Trust this folder".to_owned(),
5973                    semantics: OperatorGateOptionSemantics::Accept,
5974                    selected: false,
5975                },
5976                gate4agent_types::OperatorGateOption {
5977                    text: "Don't trust".to_owned(),
5978                    semantics: OperatorGateOptionSemantics::Decline,
5979                    selected: true,
5980                },
5981            ],
5982        );
5983    }
5984
5985    /// A matched gate whose screen carries no recognized option list (every
5986    /// other `kind` this module classifies today) must NOT invent one --
5987    /// `input` stays `Unknown` and `options` stays empty, never a guess.
5988    #[test]
5989    fn startup_operator_gate_without_a_recognized_option_list_reports_unknown_input() {
5990        let gate = startup_operator_gate("No auth type is selected")
5991            .expect("authentication must classify");
5992        assert_eq!(gate.kind, OperatorGateKind::Authentication);
5993        assert_eq!(gate.input, OperatorGateInput::Unknown);
5994        assert!(gate.options.is_empty());
5995    }
5996
5997    /// Claude's login-method chooser renders its selected row with a `❯`
5998    /// cursor glyph where Codex draws `›`, and both sit AHEAD of the number rather
5999    /// than ahead of the text. `parse_numbered_gate_option_line` knew only
6000    /// Codex's glyph, so the cursor row failed to parse as an option at
6001    /// all: the list came back one item short AND with nothing marked
6002    /// selected -- observed live on this screen and on Codex's own login
6003    /// chooser. Both glyphs are read now, so all three options are present
6004    /// and the cursor row carries `selected`.
6005    #[test]
6006    fn startup_operator_gate_parses_claudes_login_method_chooser_including_its_cursor_row() {
6007        let contents = "Select login method:\n\
6008             \u{276f} 1. Claude ...\n\
6009             2. API usage billing\n\
6010             3. 3rd-party platform \u{b7} Amazon Bedrock ...";
6011        let gate = startup_operator_gate(contents).expect("authentication must classify");
6012        assert_eq!(gate.kind, OperatorGateKind::Authentication);
6013        assert_eq!(gate.subject, OperatorGateSubject::Account);
6014        assert_eq!(gate.input, OperatorGateInput::NumberedList);
6015        assert_eq!(
6016            gate.options,
6017            vec![
6018                gate4agent_types::OperatorGateOption {
6019                    text: "Claude ...".to_owned(),
6020                    semantics: OperatorGateOptionSemantics::Unknown,
6021                    selected: true,
6022                },
6023                gate4agent_types::OperatorGateOption {
6024                    text: "API usage billing".to_owned(),
6025                    semantics: OperatorGateOptionSemantics::Unknown,
6026                    selected: false,
6027                },
6028                gate4agent_types::OperatorGateOption {
6029                    text: "3rd-party platform \u{b7} Amazon Bedrock ...".to_owned(),
6030                    semantics: OperatorGateOptionSemantics::Unknown,
6031                    selected: false,
6032                },
6033            ],
6034        );
6035    }
6036
6037    /// Claude's OAuth wait screen has no option list at all -- a URL to
6038    /// open and one free-text slot to paste the resulting code back into --
6039    /// so `input` is `TextEntry` with no options, never routed through the
6040    /// numbered/arrow option-list parser.
6041    #[test]
6042    fn startup_operator_gate_oauth_wait_screen_reports_text_entry_input() {
6043        let contents = "Browser didn't open? Use the url below to sign in (c to copy)\n\
6044             https://claude.com/oauth/authorize?client_id=abc&redirect_uri=https%3A%2F%2Fconsole.anthropic.com&code_challenge=xyz\n\
6045             Paste code here";
6046        let gate = startup_operator_gate(contents).expect("oauth wait screen must classify");
6047        assert_eq!(gate.kind, OperatorGateKind::Authentication);
6048        assert_eq!(gate.subject, OperatorGateSubject::Account);
6049        assert_eq!(gate.input, OperatorGateInput::TextEntry);
6050        assert!(gate.options.is_empty());
6051    }
6052
6053    /// `parse_operator_gate_options` is the parser both dedicated tests
6054    /// above exercise indirectly through `startup_operator_gate`; this pins
6055    /// it directly against the same two shapes so a regression in the
6056    /// standalone parser is caught even if some future `kind` branch stops
6057    /// calling it through `operator_gate`.
6058    #[test]
6059    fn parse_operator_gate_options_recognizes_numbered_and_arrow_shapes_and_nothing_else() {
6060        assert_eq!(
6061            parse_operator_gate_options("Press enter to confirm or esc to go back"),
6062            (OperatorGateInput::Unknown, Vec::new()),
6063        );
6064        let (input, options) = parse_operator_gate_options(
6065            "\u{203a} 1. Review hooks\n  2. Trust all and continue",
6066        );
6067        assert_eq!(input, OperatorGateInput::NumberedList);
6068        assert_eq!(options.len(), 2);
6069        let (input, options) = parse_operator_gate_options(
6070            "  Trust this folder\n  Enable project MCP servers. Remembered for this folder.\n\u{276f} Don't trust",
6071        );
6072        assert_eq!(input, OperatorGateInput::ArrowList);
6073        assert_eq!(options.len(), 2);
6074    }
6075
6076    #[test]
6077    fn classify_operator_gate_option_semantics_reads_the_verb_not_the_position() {
6078        assert_eq!(
6079            classify_operator_gate_option_semantics("Review hooks"),
6080            OperatorGateOptionSemantics::Inspect,
6081        );
6082        assert_eq!(
6083            classify_operator_gate_option_semantics("Trust all and continue"),
6084            OperatorGateOptionSemantics::Accept,
6085        );
6086        assert_eq!(
6087            classify_operator_gate_option_semantics("Continue without trusting (hooks won't run)"),
6088            OperatorGateOptionSemantics::Decline,
6089        );
6090        assert_eq!(
6091            classify_operator_gate_option_semantics("Don't trust"),
6092            OperatorGateOptionSemantics::Decline,
6093        );
6094        assert_eq!(
6095            classify_operator_gate_option_semantics("Exit Kimi Code"),
6096            OperatorGateOptionSemantics::Exit,
6097        );
6098        assert_eq!(
6099            classify_operator_gate_option_semantics("Something unrecognized"),
6100            OperatorGateOptionSemantics::Unknown,
6101        );
6102    }
6103
6104    #[test]
6105    fn screen_failure_recognizes_crash_and_missing_command_banners() {
6106        assert_eq!(
6107            screen_failure("thread 'main' panicked at 'index out of bounds', src/main.rs:12:5"),
6108            Some("crash")
6109        );
6110        assert_eq!(
6111            screen_failure("Traceback (most recent call last):\n  File \"a.py\", line 1"),
6112            Some("crash")
6113        );
6114        assert_eq!(
6115            screen_failure("bash: fooagent: command not found"),
6116            Some("missing command")
6117        );
6118        assert_eq!(
6119            screen_failure("C:\\workspace> fooagent\n'fooagent' is not recognized as an internal or external command"),
6120            Some("missing command")
6121        );
6122        assert_eq!(
6123            screen_failure(
6124                "workspace/project $ fooagent: no such file or directory\nworkspace/project $"
6125            ),
6126            Some("missing command")
6127        );
6128        // Bare ENOENT prose with no trailing shell-prompt line is exactly
6129        // the generic case this bucket must NOT fire on alone.
6130        assert_eq!(
6131            screen_failure("The build log mentions no such file or directory near line 40."),
6132            None
6133        );
6134        // `"fatal error:"` was deliberately dropped: a build step inside a
6135        // wrapper script can print this while the real CLI still comes up
6136        // fine, so it is not a crash SHAPE this function trusts at all.
6137        assert_eq!(
6138            screen_failure("fooagent-installer: fatal error: missing header <stdio.h>"),
6139            None
6140        );
6141    }
6142
6143    #[test]
6144    fn screen_failure_recognizes_grok_missing_api_key_banner() {
6145        // Verbatim transcript: Grok launched with no credential configured
6146        // prints exactly this one line and never renders anything else --
6147        // no gate to answer, no crash trace, just a dead PTY a blind
6148        // `Ready` write would silently swallow.
6149        assert_eq!(
6150            screen_failure(
6151                "\u{274c} Error: API key required. Set GROK_API_KEY environment variable, \
6152                 use --api-key flag, or set \"apiKey\" field in ~/.grok/user-settings.json"
6153            ),
6154            Some("missing api key")
6155        );
6156        // Generic prose about needing an API key, with no vendor-specific
6157        // env var name, must not false-positive -- an agent explaining a
6158        // DIFFERENT provider's setup routinely says exactly this.
6159        assert_eq!(
6160            screen_failure(
6161                "You'll need an API key for this provider before it works; check the docs \
6162                 for how to configure one."
6163            ),
6164            None
6165        );
6166    }
6167
6168    #[test]
6169    fn screen_failure_no_longer_has_an_authentication_expired_bucket() {
6170        // Two common words matched anywhere on one 80x24 screen is not a
6171        // signal -- an agent's own prose explaining an auth bug ("the
6172        // token has expired") used to flip a healthy session to `Failing`.
6173        // The bucket is gone entirely, not narrowed.
6174        assert_eq!(
6175            screen_failure("Your session token has expired. Please re-authenticate."),
6176            None
6177        );
6178        assert_eq!(
6179            screen_failure("The stored credential was revoked by the workspace admin."),
6180            None
6181        );
6182    }
6183
6184    #[test]
6185    fn screen_failure_does_not_false_positive_on_an_agent_narrating_an_error() {
6186        // The false-positive direction matters more than coverage here: an
6187        // agent CLI renders arbitrary text back at a human, including logs
6188        // and error messages it was asked to explain. None of the phrases
6189        // below are in the exact failure SHAPE this module matches on.
6190        let narration = "I looked at the traceback you pasted -- it's a Python \
6191             exception, a plain ValueError from a retry loop, not a real crash. \
6192             Our harness logs the word fatal in its own banner for visibility, \
6193             but nothing actually panicked. The command definitely exists; it \
6194             just needed different flags, and your token is still valid.";
6195        assert_eq!(screen_failure(narration), None);
6196    }
6197
6198    #[test]
6199    fn screen_failure_for_generation_ignores_every_marker_once_the_session_was_ever_ready() {
6200        // Each of these is a screen from a HEALTHY, already-`Ready` session
6201        // whose own routine work happens to render a crash-shaped string.
6202        // This is the regression this whole gate exists to close: before
6203        // it, every one of these flipped a working session to `Failing`.
6204        let shell_command_not_found = "$ frobnicate --help\nbash: frobnicate: command not found\n$";
6205        assert_eq!(
6206            screen_failure_for_generation(shell_command_not_found, true),
6207            None
6208        );
6209
6210        let python_traceback_from_a_ran_script = "$ python broken.py\n\
6211             Traceback (most recent call last):\n  File \"broken.py\", line 3, in <module>\n\
6212             ValueError: bad input\n$";
6213        assert_eq!(
6214            screen_failure_for_generation(python_traceback_from_a_ran_script, true),
6215            None
6216        );
6217
6218        let cargo_test_panic = "running 1 test\n\
6219             error[E0308]: mismatched types\n\
6220             thread 'tests::it_fails' panicked at 'assertion failed', src/lib.rs:9:5\n\
6221             test result: FAILED. 0 passed; 1 failed";
6222        assert_eq!(screen_failure_for_generation(cargo_test_panic, true), None);
6223
6224        let agent_narrating_an_expired_token = "The API token has expired; \
6225             I revoked the old credential and issued a new one for you.";
6226        assert_eq!(
6227            screen_failure_for_generation(agent_narrating_an_expired_token, true),
6228            None
6229        );
6230
6231        // Pin the narrowing from the other side too: the exact same
6232        // screens are still real evidence of a broken LAUNCH inside the
6233        // startup window, before this generation has ever rendered its
6234        // own UI.
6235        assert_eq!(
6236            screen_failure_for_generation(shell_command_not_found, false),
6237            Some("missing command")
6238        );
6239        assert_eq!(
6240            screen_failure_for_generation(python_traceback_from_a_ran_script, false),
6241            Some("crash")
6242        );
6243        assert_eq!(screen_failure_for_generation(cargo_test_panic, false), Some("crash"));
6244    }
6245
6246    #[test]
6247    fn classify_pty_screen_state_lets_a_foreign_process_win_over_a_matching_gate_text() {
6248        // The process signal outranks the text signal outright: it does not
6249        // need to recognize an updater's specific wording to know the
6250        // screen is not the agent's, so it wins even when the text ALSO
6251        // happens to match a known gate pattern.
6252        let foreign = ForegroundVerdict::Foreign {
6253            process: "npm".to_owned(),
6254        };
6255        assert_eq!(
6256            classify_pty_screen_state(Some(&foreign), None, None),
6257            PtyScreenState::NotAgent {
6258                observed_process: "npm".to_owned()
6259            }
6260        );
6261        let vendor_update_gate = OperatorGateState::new(OperatorGateKind::VendorUpdate);
6262        assert_eq!(
6263            classify_pty_screen_state(Some(&foreign), Some(&vendor_update_gate), None),
6264            PtyScreenState::NotAgent {
6265                observed_process: "npm".to_owned()
6266            }
6267        );
6268    }
6269
6270    #[test]
6271    fn classify_pty_screen_state_reports_a_gate_only_when_foreground_matches() {
6272        let authentication_gate = OperatorGateState::new(OperatorGateKind::Authentication);
6273        assert_eq!(
6274            classify_pty_screen_state(Some(&ForegroundVerdict::Agent), Some(&authentication_gate), None),
6275            PtyScreenState::OperatorGate {
6276                gate: authentication_gate.clone()
6277            }
6278        );
6279    }
6280
6281    #[test]
6282    fn classify_pty_screen_state_reports_failing_for_a_matched_foreground() {
6283        assert_eq!(
6284            classify_pty_screen_state(Some(&ForegroundVerdict::Agent), None, Some("crash")),
6285            PtyScreenState::Failing {
6286                reason: "crash".to_owned()
6287            }
6288        );
6289    }
6290
6291    #[test]
6292    fn classify_pty_screen_state_prefers_failing_over_a_co_occurring_gate() {
6293        // Pins the precedence: a crashed screen can still carry a leftover
6294        // gate prompt above the crash dump, and `Failing` is the more
6295        // urgent of the two truths.
6296        let authentication_gate = OperatorGateState::new(OperatorGateKind::Authentication);
6297        assert_eq!(
6298            classify_pty_screen_state(
6299                Some(&ForegroundVerdict::Agent),
6300                Some(&authentication_gate),
6301                Some("crash")
6302            ),
6303            PtyScreenState::Failing {
6304                reason: "crash".to_owned()
6305            }
6306        );
6307    }
6308
6309    #[test]
6310    fn classify_pty_screen_state_reaches_ready_only_with_matched_foreground_and_clean_text() {
6311        assert_eq!(
6312            classify_pty_screen_state(Some(&ForegroundVerdict::Agent), None, None),
6313            PtyScreenState::Ready
6314        );
6315    }
6316
6317    #[test]
6318    fn classify_pty_screen_state_never_reaches_ready_without_a_foreground_observation() {
6319        // The one case that must never regress: a clean text read alone is
6320        // never proof of `Ready`.
6321        assert_eq!(classify_pty_screen_state(None, None, None), PtyScreenState::Unknown);
6322    }
6323
6324    #[test]
6325    fn resolve_foreground_verdict_tolerates_a_spawning_wrapper_like_readiness_does() {
6326        // The fixture spec's `expected_processes` does not name "node", so
6327        // this only passes if the wrapper-tolerance branch (mirroring
6328        // `ReadinessTracker::observe_foreground`'s own `node`/`python`/
6329        // `python3` tolerance) is actually what resolves it -- proving the
6330        // existing wrapper tolerance is not regressed. Fed into
6331        // `classify_pty_screen_state` with clean text, this is what reaches
6332        // `Ready` rather than `NotAgent` for a legitimate spawning wrapper.
6333        let spec = gate4agent_testkit::interactive_agent_spec();
6334        let observation = PtyForegroundObservation {
6335            root_pid: 1,
6336            observed_pid: 2,
6337            observed_process: "node".to_owned(),
6338            readiness: ForegroundObservation {
6339                process_name: Some("node".to_owned()),
6340                has_child_processes: true,
6341                is_shell: false,
6342            },
6343            source: PtyForegroundSource::ProcessTree,
6344        };
6345        let verdict = resolve_foreground_verdict(&spec, &observation, RuntimePlatform::current());
6346        assert_eq!(verdict, ForegroundVerdict::Agent);
6347        assert_eq!(
6348            classify_pty_screen_state(Some(&verdict), None, None),
6349            PtyScreenState::Ready
6350        );
6351    }
6352
6353    #[test]
6354    fn foreground_probe_disarms_only_once_ready_and_rearms_on_a_fresh_gate() {
6355        assert_eq!(
6356            foreground_probe_schedule(&PtyScreenState::Ready),
6357            ForegroundProbeSchedule::Disarmed
6358        );
6359        assert_eq!(
6360            foreground_probe_schedule(&PtyScreenState::Unknown),
6361            ForegroundProbeSchedule::Armed
6362        );
6363        assert_eq!(
6364            foreground_probe_schedule(&PtyScreenState::OperatorGate {
6365                gate: OperatorGateState::new(OperatorGateKind::VendorUpdate)
6366            }),
6367            ForegroundProbeSchedule::Armed
6368        );
6369    }
6370
6371    #[test]
6372    fn text_only_gate_transition_rearms_the_probe_only_when_leaving_ready() {
6373        let gate = PtyScreenState::OperatorGate {
6374            gate: OperatorGateState::new(OperatorGateKind::VendorUpdate),
6375        };
6376        assert!(foreground_probe_rearms_immediately(
6377            &PtyScreenState::Ready,
6378            &gate
6379        ));
6380        // Was never `Ready` in the first place -- nothing to rearm early
6381        // for, the session's normal cadence already has it covered.
6382        assert!(!foreground_probe_rearms_immediately(
6383            &PtyScreenState::Unknown,
6384            &gate
6385        ));
6386    }
6387
6388    #[test]
6389    fn readiness_diagnostics_detects_an_ansi_split_gate_without_exposing_text() {
6390        let mut diagnostics = ReadinessDiagnostics::default();
6391        diagnostics.observe_output(b"\x1b[31mNo auth ");
6392        diagnostics.observe_output(b"\x1b[0mtype is selected");
6393        assert_eq!(
6394            diagnostics.operator_gate.as_ref().map(|gate| gate.kind),
6395            Some(OperatorGateKind::Authentication)
6396        );
6397        assert!(!diagnostics.summary().contains("No auth"));
6398    }
6399
6400    #[test]
6401    fn semantic_utf8_decoder_preserves_codepoints_split_across_pty_reads() {
6402        let mut decoder = Utf8ChunkDecoder::default();
6403        let bytes = "ready Привет".as_bytes();
6404        let split = bytes
6405            .windows(2)
6406            .position(|window| window[0] >= 0x80 && window[1] >= 0x80)
6407            .expect("Cyrillic text contains adjacent UTF-8 bytes")
6408            + 1;
6409        let first = decoder.push(&bytes[..split]);
6410        let second = decoder.push(&bytes[split..]);
6411        assert_eq!(format!("{first}{second}"), "ready Привет");
6412        assert!(!first.contains('\u{fffd}'));
6413        assert!(!second.contains('\u{fffd}'));
6414    }
6415
6416    #[test]
6417    fn semantic_utf8_decoder_replaces_invalid_bytes_without_stalling() {
6418        let mut decoder = Utf8ChunkDecoder::default();
6419        assert_eq!(decoder.push(b"ok\xfftail"), "ok\u{fffd}tail");
6420        assert_eq!(decoder.push(" Привет".as_bytes()), " Привет");
6421    }
6422
6423    #[test]
6424    fn fresh_claude_pty_preassigns_the_exact_vendor_session_id_argv() {
6425        let claude = builtin_adapter_registry()
6426            .binding(AdapterFamily::PtySemantic, "claude-code")
6427            .expect("Claude PTY binding");
6428        let mut args = Vec::new();
6429        let identity = prepare_fresh_pty_provider_session(Some(claude), false, true, &mut args)
6430            .expect("fresh Claude provider identity");
6431        let parsed = uuid::Uuid::parse_str(&identity.id).expect("valid Claude UUID");
6432        assert_eq!(parsed.get_version_num(), 4);
6433        assert_eq!(identity.key, gate4agent_types::ProviderSessionKey::SessionId);
6434        assert!(identity.transcript_path.is_none());
6435        assert_eq!(args, [OsString::from("--session-id"), OsString::from(identity.id)]);
6436    }
6437
6438    #[test]
6439    fn fresh_codex_and_resumed_claude_do_not_preassign_a_second_identity() {
6440        let adapters = builtin_adapter_registry();
6441        let codex = adapters
6442            .binding(AdapterFamily::PtySemantic, "codex")
6443            .expect("Codex PTY binding");
6444        let claude = adapters
6445            .binding(AdapterFamily::PtySemantic, "claude-code")
6446            .expect("Claude PTY binding");
6447        let mut codex_args = Vec::new();
6448        assert!(prepare_fresh_pty_provider_session(Some(codex), false, true, &mut codex_args)
6449            .is_none());
6450        assert!(codex_args.is_empty());
6451
6452        let mut resume_args = vec![OsString::from("--resume"), OsString::from("vendor-id")];
6453        assert!(prepare_fresh_pty_provider_session(Some(claude), true, true, &mut resume_args)
6454            .is_none());
6455        assert_eq!(
6456            resume_args,
6457            [OsString::from("--resume"), OsString::from("vendor-id")]
6458        );
6459    }
6460
6461    #[test]
6462    fn raw_pty_policy_omits_all_identity_and_semantic_startup_paths() {
6463        let adapters = builtin_adapter_registry();
6464        let claude = adapters
6465            .binding(AdapterFamily::PtySemantic, "claude-code")
6466            .expect("Claude PTY binding");
6467        let codex = adapters
6468            .binding(AdapterFamily::PtySemantic, "codex")
6469            .expect("Codex PTY binding");
6470        let kimi = adapters
6471            .binding(AdapterFamily::PtySemantic, "kimi")
6472            .expect("Kimi PTY binding");
6473        let policy = ProviderRuntimePolicy::raw_pty();
6474        let mut args = Vec::new();
6475
6476        assert!(prepare_fresh_pty_provider_session(Some(claude), false, false, &mut args)
6477            .is_none());
6478        assert!(args.is_empty());
6479        assert!(!should_probe_pty_identity(policy, Some(codex), false, "codex"));
6480        assert!(!should_probe_pty_identity(policy, Some(kimi), false, "kimi"));
6481        assert!(!should_attach_pty_provider_stream(policy));
6482    }
6483
6484    #[test]
6485    fn identity_probe_requires_structured_prompt_for_codex_and_kimi() {
6486        let adapters = builtin_adapter_registry();
6487        let codex = adapters
6488            .binding(AdapterFamily::PtySemantic, "codex")
6489            .expect("Codex PTY binding");
6490        let kimi = adapters
6491            .binding(AdapterFamily::PtySemantic, "kimi")
6492            .expect("Kimi PTY binding");
6493        let without_structured_prompt =
6494            ProviderRuntimePolicy::new(true, true, false, true, false, false)
6495                .expect("identity observation policy without structured prompt");
6496
6497        assert!(!should_probe_pty_identity(
6498            without_structured_prompt,
6499            Some(codex),
6500            false,
6501            "codex",
6502        ));
6503        assert!(!should_probe_pty_identity(
6504            without_structured_prompt,
6505            Some(kimi),
6506            false,
6507            "kimi",
6508        ));
6509
6510        let with_structured_prompt =
6511            ProviderRuntimePolicy::new(true, true, true, true, false, false)
6512                .expect("identity probe policy");
6513        assert!(should_probe_pty_identity(
6514            with_structured_prompt,
6515            Some(codex),
6516            false,
6517            "codex",
6518        ));
6519        assert!(should_probe_pty_identity(
6520            with_structured_prompt,
6521            Some(kimi),
6522            false,
6523            "kimi",
6524        ));
6525    }
6526
6527    #[test]
6528    fn runtime_policy_admits_raw_native_resume_but_denies_unverified_prompt_injection() {
6529        let raw = ProviderRuntimePolicy::raw_pty();
6530        assert!(validate_spawn_runtime_policy(raw, TransportKind::Pty, false, false).is_ok());
6531        assert!(validate_spawn_runtime_policy(raw, TransportKind::Pty, true, false)
6532            .unwrap_err()
6533            .contains("SemanticReadiness"));
6534        assert!(validate_spawn_runtime_policy(raw, TransportKind::Pty, false, true).is_ok());
6535        assert!(validate_spawn_runtime_policy(raw, TransportKind::Pty, true, true)
6536            .unwrap_err()
6537            .contains("SemanticReadiness"));
6538
6539        let resume_without_prompt =
6540            ProviderRuntimePolicy::new(true, false, false, true, true, false)
6541                .expect("identity and resume policy");
6542        assert!(validate_spawn_runtime_policy(
6543            resume_without_prompt,
6544            TransportKind::Pty,
6545            false,
6546            true,
6547        )
6548        .is_ok());
6549        assert!(validate_spawn_runtime_policy(
6550            resume_without_prompt,
6551            TransportKind::Pty,
6552            true,
6553            true,
6554        )
6555        .unwrap_err()
6556        .contains("SemanticReadiness"));
6557    }
6558
6559    #[test]
6560    fn acp_transport_bypasses_the_pty_semantic_policy_gate_pty_and_pipe_still_enforce_it() {
6561        // A provider that speaks ACP and nothing else (no raw PTY, no
6562        // verified terminal semantics) admits none of these capabilities --
6563        // exactly grok's real policy. `TransportKind::Acp` must not care:
6564        // ACP has no terminal to infer state from, so none of this policy
6565        // applies to it.
6566        let no_pty_capabilities_at_all = ProviderRuntimePolicy::new(
6567            false, false, false, false, false, false,
6568        )
6569        .expect("an all-false policy is internally valid");
6570        assert!(validate_spawn_runtime_policy(
6571            no_pty_capabilities_at_all,
6572            TransportKind::Acp,
6573            false,
6574            false,
6575        )
6576        .is_ok());
6577        // The same all-false policy is still correctly refused for Pty and
6578        // Pipe -- this fix narrows the gate to skip Acp specifically, it
6579        // does not weaken it for the transports that do need it.
6580        assert!(validate_spawn_runtime_policy(
6581            no_pty_capabilities_at_all,
6582            TransportKind::Pty,
6583            false,
6584            false,
6585        )
6586        .unwrap_err()
6587        .contains("RawPtyLifecycle"));
6588        assert!(validate_spawn_runtime_policy(
6589            no_pty_capabilities_at_all,
6590            TransportKind::Pipe,
6591            false,
6592            false,
6593        )
6594        .unwrap_err()
6595        .contains("RawPtyLifecycle"));
6596    }
6597
6598    #[test]
6599    fn prompt_render_probe_ignores_terminal_wrapping_and_uses_the_tail() {
6600        let prompt = "prefix with spaces\nand punctuation: final-render-token-1234567890";
6601        let probe = prompt_render_probe(prompt);
6602        assert!("screen prefix with spaces and punctuation final render token 1234567890"
6603            .chars()
6604            .filter(|character| character.is_alphanumeric())
6605            .flat_map(char::to_lowercase)
6606            .collect::<String>()
6607            .contains(&probe));
6608        assert!(probe.chars().count() <= 32);
6609    }
6610
6611    #[test]
6612    fn prompt_render_requires_new_sequence_and_visible_tail_evidence() {
6613        let probe = prompt_render_probe("final render token");
6614        let baseline = snapshot(7, "old composer");
6615        assert!(!prompt_rendered(
6616            &snapshot(7, "final\nrender\ntoken"),
6617            &baseline,
6618            &probe
6619        ));
6620        assert!(!prompt_rendered(
6621            &snapshot(8, "unrelated redraw"),
6622            &baseline,
6623            &probe
6624        ));
6625        assert!(prompt_rendered(
6626            &snapshot(8, "composer\nfinal\nrender\ntoken"),
6627            &baseline,
6628            &probe
6629        ));
6630        assert!(prompt_rendered(
6631            &snapshot(8, "composer [Pasted Content 4096 chars]"),
6632            &baseline,
6633            &probe
6634        ));
6635        assert!(prompt_rendered(
6636            &snapshot(8, "composer [Pasted text #1 +6 lines]"),
6637            &baseline,
6638            &probe
6639        ));
6640    }
6641
6642    #[test]
6643    fn an_existing_paste_placeholder_cannot_pass_on_an_unrelated_redraw() {
6644        let probe = prompt_render_probe("a new long prompt");
6645        assert!(!prompt_rendered(
6646            &snapshot(8, "composer [Pasted Content 4096 chars]\nunrelated redraw"),
6647            &snapshot(7, "composer [Pasted Content 4096 chars]"),
6648            &probe
6649        ));
6650        assert!(!prompt_rendered(
6651            &snapshot(8, "composer [Pasted text #1 +6 lines]\nunrelated redraw"),
6652            &snapshot(7, "composer [Pasted text #1 +6 lines]"),
6653            &probe
6654        ));
6655    }
6656
6657    #[test]
6658    fn punctuation_only_prompt_cannot_pass_on_an_unrelated_redraw() {
6659        let probe = prompt_render_probe("!?---");
6660        assert!(probe.is_empty());
6661        assert!(!prompt_rendered(
6662            &snapshot(2, "unrelated redraw"),
6663            &snapshot(1, "old composer"),
6664            &probe
6665        ));
6666    }
6667
6668    #[test]
6669    fn prompt_probe_matches_the_sanitized_terminal_payload() {
6670        let prompt = "payload\u{1b}tail";
6671        let sanitized = gate4agent_types::sanitize_prompt_text(prompt);
6672        let probe = prompt_render_probe(&sanitized);
6673        assert!(prompt_rendered(
6674            &snapshot(2, "composer payload<ESC>tail"),
6675            &snapshot(1, "old composer"),
6676            &probe
6677        ));
6678    }
6679
6680    #[test]
6681    fn lag_and_data_gap_reserve_missed_provider_source_positions() {
6682        let mut next = 7;
6683        assert_eq!(reserve_provider_gap_sequence(&mut next, 3), Some(9));
6684        assert_eq!(next, 10);
6685        assert_eq!(reserve_provider_gap_sequence(&mut next, 0), None);
6686        assert_eq!(next, 10);
6687
6688        next = u64::MAX;
6689        assert_eq!(reserve_provider_gap_sequence(&mut next, 1), None);
6690        assert_eq!(next, u64::MAX);
6691    }
6692
6693    // --- RateLimitFeed: ANSI-stripping and chunk reassembly ---
6694    //
6695    // Regression coverage for a live-stand defect: `provider.rate_limits`
6696    // used to be a bare `RateLimitDetector` fed the RAW PTY stream, escape
6697    // codes and all. codex's own `/status` render puts `\x1b[m` between
6698    // `limit:` and the progress bar, and `\x1b[2m` between `left` and
6699    // `(resets ...)` -- both inside gaps the quota-state regex's `\s*`
6700    // cannot see through -- so not one quota-state fact was ever observed
6701    // on a real run, despite the pattern being correct on clean text.
6702
6703    /// The exact live bytes from the coordinator's capture (real `\x1b[m`
6704    /// and `\x1b[2m`, real `\r\n`), transcribed verbatim.
6705    const CODEX_STATUS_RAW_ANSI: &str = "│  5h limit:             \x1b[m[████████████████████] 100% left\x1b[2m (resets 00:08 on 31 Aug) │\r\n│  Weekly limit:         \x1b[m[████████████████████] 100% left\x1b[2m (resets 19:08 on 6 Sep)  │";
6706
6707    #[test]
6708    fn bare_detector_misses_the_live_ansi_sample_that_rate_limit_feed_catches() {
6709        // This is the defect itself: matching the untouched raw stream
6710        // fails on real codex output, exactly as observed live.
6711        let bare = RateLimitDetector::new_for_tool(CliTool::Codex);
6712        assert!(bare.detect(CODEX_STATUS_RAW_ANSI).is_none());
6713
6714        // `RateLimitFeed` strips ANSI (via `VteParser`) before matching,
6715        // so the same bytes must now be recognized.
6716        let mut feed = RateLimitFeed::new_for_tool(CliTool::Codex);
6717        let info = feed
6718            .detect(CODEX_STATUS_RAW_ANSI)
6719            .expect("quota-state line must be recognized once ANSI is stripped");
6720        assert_eq!(info.limit_type, RateLimitType::Session);
6721        assert_eq!(info.usage_percent, Some(0.0));
6722        assert_eq!(info.resets_at_text.as_deref(), Some("00:08 on 31 Aug"));
6723    }
6724
6725    #[test]
6726    fn rate_limit_feed_reassembles_a_quota_state_line_split_mid_escape_and_mid_row() {
6727        // A live PTY chunk boundary has no reason to land anywhere
6728        // convenient -- here it falls INSIDE the `\x1b[2m` escape itself
6729        // (right after the ESC byte), on top of splitting the row.
6730        let first =
6731            "│  5h limit:             \x1b[m[████████████████████] 100% left\x1b";
6732        let second = "[2m (resets 00:08 on 31 Aug) │\r\n";
6733
6734        let mut feed = RateLimitFeed::new_for_tool(CliTool::Codex);
6735        assert!(
6736            feed.detect(first).is_none(),
6737            "the row is not complete yet, so nothing should match on the first chunk"
6738        );
6739        let info = feed
6740            .detect(second)
6741            .expect("the row completes once the second chunk arrives");
6742        assert_eq!(info.limit_type, RateLimitType::Session);
6743        assert_eq!(info.resets_at_text.as_deref(), Some("00:08 on 31 Aug"));
6744    }
6745
6746    #[test]
6747    fn rate_limit_feed_strips_ansi_before_matching_a_colored_failure_message() {
6748        // Failure patterns run through the same `RateLimitFeed::detect`
6749        // entry point as quota-state ones, so a vendor coloring its own
6750        // refusal text must not defeat detection either.
6751        let raw = "\x1b[31mError: rate limit exceeded\x1b[0m. Please wait.";
6752        let mut feed = RateLimitFeed::new_for_tool(CliTool::Codex);
6753        let info = feed
6754            .detect(raw)
6755            .expect("a colored refusal message must still be recognized");
6756        assert_eq!(info.limit_type, RateLimitType::Unknown);
6757    }
6758
6759    #[test]
6760    fn rate_limit_feed_bounds_its_buffer_across_a_newline_free_redraw() {
6761        // A full-screen redraw with no `\n` at all (cursor-addressing
6762        // only) must not grow the pending-line buffer without bound for
6763        // as long as it runs -- and a real line must still be caught once
6764        // it finally arrives.
6765        let mut feed = RateLimitFeed::new_for_tool(CliTool::Codex);
6766        let noise = "x".repeat(super::RATE_LIMIT_FEED_BUFFER_MAX_BYTES * 3);
6767        assert!(feed.detect(&noise).is_none());
6768        assert!(feed.buffer.len() <= super::RATE_LIMIT_FEED_BUFFER_MAX_BYTES);
6769
6770        let info = feed
6771            .detect(CODEX_STATUS_RAW_ANSI)
6772            .expect("a real quota-state line must still be recognized after the noise");
6773        assert_eq!(info.limit_type, RateLimitType::Session);
6774    }
6775
6776    // -----------------------------------------------------------------------
6777    // host_policy_for_approval_level -- ApprovalLevel -> HostPolicy for ACP
6778    // -----------------------------------------------------------------------
6779
6780    #[test]
6781    fn full_auto_maps_to_the_permissive_host_policy() {
6782        // The one combination that must never happen is `FullAuto` paired
6783        // with a refusing `HostPolicy` -- the process believes it has full
6784        // autonomy while the host silently refuses it.
6785        assert_eq!(host_policy_for_approval_level(ApprovalLevel::FullAuto), HostPolicy::Yolo);
6786    }
6787
6788    #[test]
6789    fn read_only_maps_to_the_read_only_host_policy() {
6790        assert_eq!(
6791            host_policy_for_approval_level(ApprovalLevel::ReadOnly),
6792            HostPolicy::ReadOnly
6793        );
6794    }
6795
6796    #[test]
6797    fn moderate_and_unmanaged_both_fall_back_to_the_default_host_policy() {
6798        assert_eq!(host_policy_for_approval_level(ApprovalLevel::Moderate), HostPolicy::Auto);
6799        assert_eq!(host_policy_for_approval_level(ApprovalLevel::Unmanaged), HostPolicy::Auto);
6800        assert_eq!(HostPolicy::default(), HostPolicy::Auto);
6801    }
6802
6803    #[test]
6804    fn no_approval_level_ever_maps_to_a_refusing_policy_except_read_only_itself() {
6805        // Guards the "never full auto + refusing host" invariant generally:
6806        // `Deny` must never be reachable from this mapping at all -- it is
6807        // not one of the four `ApprovalLevel` outcomes, only `ReadOnly`'s
6808        // own deliberate restriction is.
6809        for level in [
6810            ApprovalLevel::FullAuto,
6811            ApprovalLevel::Moderate,
6812            ApprovalLevel::ReadOnly,
6813            ApprovalLevel::Unmanaged,
6814        ] {
6815            assert_ne!(
6816                host_policy_for_approval_level(level),
6817                HostPolicy::Deny,
6818                "{level:?} must never map to HostPolicy::Deny"
6819            );
6820        }
6821    }
6822
6823    // -----------------------------------------------------------------------
6824    // defers_permission_requests -- reads `asks_for_permission` off the
6825    // catalog's per-(provider, level) vendor-mode table instead of matching
6826    // on the ApprovalLevel's own name (the bug this whole axis exists to
6827    // remove -- see the function's own doc comment).
6828    // -----------------------------------------------------------------------
6829
6830    #[test]
6831    fn defers_permission_requests_matches_the_verified_provider_table() {
6832        // Source of truth: `gate4agent_catalog::launch::approval_level_resolution`
6833        // at HEAD (commit 7b6a8d2) and
6834        // `docs/gate4agent/audits/gate4agent-acp-slice1-proof-2026-09-02.md`
6835        // (session/new modes measured live, 2026-09-02).
6836        let claude = AgentId::new("claude").unwrap();
6837        assert!(!defers_permission_requests(&claude, ApprovalLevel::FullAuto));
6838        assert!(defers_permission_requests(&claude, ApprovalLevel::Moderate));
6839        // claude's `ReadOnly` now launches `default` (`plan` neither refuses
6840        // nor asks over ACP, measured twice) -- claude's own interactive
6841        // mode, which does ask about every write.
6842        assert!(defers_permission_requests(&claude, ApprovalLevel::ReadOnly));
6843        // `Unmanaged` never defers: it decides `session/request_permission`
6844        // immediately (auto-approve), since some providers' ACP clients
6845        // won't wait out a parked decision.
6846        assert!(!defers_permission_requests(&claude, ApprovalLevel::Unmanaged));
6847
6848        let codex = AgentId::new("codex").unwrap();
6849        assert!(!defers_permission_requests(&codex, ApprovalLevel::FullAuto));
6850        // codex's `Moderate` ACP mode (`agent`, "Approve for me") wrote and
6851        // reported success with no `session/request_permission` at all --
6852        // measured live, unlike the PTY `on-request` flag it shares a row
6853        // with.
6854        assert!(!defers_permission_requests(&codex, ApprovalLevel::Moderate));
6855        assert!(defers_permission_requests(&codex, ApprovalLevel::ReadOnly));
6856        // `Unmanaged` never defers -- see the claude row's comment above.
6857        assert!(!defers_permission_requests(&codex, ApprovalLevel::Unmanaged));
6858
6859        let grok = AgentId::new("grok").unwrap();
6860        assert!(!defers_permission_requests(&grok, ApprovalLevel::FullAuto));
6861        assert!(defers_permission_requests(&grok, ApprovalLevel::Moderate));
6862        // `ReadOnly` is `Unsupported` for grok -- the ACP spawn branch must
6863        // already have refused the session before this function would ever
6864        // see it live; the conservative fallback here still defers.
6865        assert!(defers_permission_requests(&grok, ApprovalLevel::ReadOnly));
6866        // `Unmanaged` never defers -- see the claude row's comment above.
6867        assert!(!defers_permission_requests(&grok, ApprovalLevel::Unmanaged));
6868
6869        let kimi = AgentId::new("kimi").unwrap();
6870        assert!(!defers_permission_requests(&kimi, ApprovalLevel::FullAuto));
6871        // kimi's `Moderate` ACP mode is genuinely named `auto` and wrote
6872        // silently, measured live -- it does not ask.
6873        assert!(!defers_permission_requests(&kimi, ApprovalLevel::Moderate));
6874        // kimi's `ReadOnly` ACP mode (`plan`) refuses silently rather than
6875        // asking -- measured live, a write outside the working directory
6876        // produced no question at all.
6877        assert!(!defers_permission_requests(&kimi, ApprovalLevel::ReadOnly));
6878        // `Unmanaged` never defers -- see the claude row's comment above.
6879        assert!(!defers_permission_requests(&kimi, ApprovalLevel::Unmanaged));
6880    }
6881
6882    // -----------------------------------------------------------------------
6883    // required_acp_mode / approval_level_not_offered_message -- Item 3's
6884    // table: one row per provider x level, plus the regression guard that
6885    // `auto` is unreachable without an explicit choice.
6886    // -----------------------------------------------------------------------
6887
6888    fn session_mode(id: &str) -> SessionMode {
6889        SessionMode { id: id.to_owned(), name: id.to_owned(), description: None }
6890    }
6891
6892    #[test]
6893    fn required_acp_mode_matches_the_sourced_table() {
6894        // Source of truth: `gate4agent_catalog::launch::approval_level_resolution`
6895        // at HEAD (commit 7b6a8d2) and
6896        // `docs/gate4agent/audits/gate4agent-acp-slice1-proof-2026-09-02.md`
6897        // (session/new modes measured live, 2026-09-02).
6898        let claude = AgentId::new("claude").unwrap();
6899        assert_eq!(
6900            required_acp_mode(&claude, ApprovalLevel::FullAuto),
6901            Ok(Some(ModeId::new("bypassPermissions")))
6902        );
6903        assert_eq!(
6904            required_acp_mode(&claude, ApprovalLevel::Moderate),
6905            Ok(Some(ModeId::new("acceptEdits")))
6906        );
6907        // measured live: `plan` neither refuses nor asks over ACP, so
6908        // `ReadOnly` moved to `default`, the one claude mode where both an
6909        // in-cwd and an out-of-cwd write raised `session/request_permission`.
6910        assert_eq!(
6911            required_acp_mode(&claude, ApprovalLevel::ReadOnly),
6912            Ok(Some(ModeId::new("default")))
6913        );
6914        assert_eq!(required_acp_mode(&claude, ApprovalLevel::Unmanaged), Ok(None));
6915
6916        let codex = AgentId::new("codex").unwrap();
6917        assert_eq!(
6918            required_acp_mode(&codex, ApprovalLevel::FullAuto),
6919            Ok(Some(ModeId::new("agent-full-access")))
6920        );
6921        assert_eq!(
6922            required_acp_mode(&codex, ApprovalLevel::Moderate),
6923            Ok(Some(ModeId::new("agent")))
6924        );
6925        assert_eq!(
6926            required_acp_mode(&codex, ApprovalLevel::ReadOnly),
6927            Ok(Some(ModeId::new("read-only")))
6928        );
6929        assert_eq!(required_acp_mode(&codex, ApprovalLevel::Unmanaged), Ok(None));
6930
6931        // kimi: `acp_mode_id` is `None` for every managed level -- measured
6932        // 2026-09-05, `kimi.exe` 0.29.0's `session/new` result carries
6933        // `configOptions` (a `model` select) and no `modes` field at all.
6934        // The 2026-09-02 `yolo`/`auto`/`plan` measurement this table used to
6935        // pin was a different build: the npm shell shim running under WSL
6936        // interop, not this native binary.
6937        // `FullAuto` is the one kimi level that carries vendor flags
6938        // (`--yolo`), so argv applies it and there is nothing left to refuse;
6939        // `Moderate`/`ReadOnly` carry none (their `--auto`/`--plan` remain
6940        // UNCONFIRMED under `kimi acp`) and still refuse, because for those
6941        // no mechanism exists at all.
6942        let kimi = AgentId::new("kimi").unwrap();
6943        assert_eq!(required_acp_mode(&kimi, ApprovalLevel::FullAuto), Ok(None));
6944        assert_eq!(
6945            acp_approval_level_args(&kimi, ApprovalLevel::FullAuto),
6946            vec!["--auto".to_owned()],
6947            "kimi's FullAuto must reach the process through argv, since it has no ACP mode"
6948        );
6949        for level in [ApprovalLevel::Moderate, ApprovalLevel::ReadOnly] {
6950            assert!(
6951                required_acp_mode(&kimi, level).is_err(),
6952                "kimi at {level:?} has neither a sourced ACP mode id nor vendor flags, so it must refuse"
6953            );
6954        }
6955        assert_eq!(required_acp_mode(&kimi, ApprovalLevel::Unmanaged), Ok(None));
6956
6957        // gemini: every managed level rides an announced ACP mode
6958        // (`session/set_mode`); argv stays clean over ACP.
6959        let gemini = AgentId::new("gemini").unwrap();
6960        for (level, mode) in [
6961            (ApprovalLevel::FullAuto, "yolo"),
6962            (ApprovalLevel::Moderate, "autoEdit"),
6963            (ApprovalLevel::ReadOnly, "plan"),
6964        ] {
6965            assert_eq!(required_acp_mode(&gemini, level), Ok(Some(ModeId::new(mode))));
6966            assert!(acp_approval_level_args(&gemini, level).is_empty());
6967        }
6968        // cursor-agent: FullAuto is `--force` on argv (its ACP modes are
6969        // execution modes, none of them "run everything"); the narrower
6970        // levels ride the announced `agent` / `plan` modes.
6971        let cursor = AgentId::new("cursor-agent").unwrap();
6972        assert_eq!(required_acp_mode(&cursor, ApprovalLevel::FullAuto), Ok(None));
6973        assert_eq!(acp_approval_level_args(&cursor, ApprovalLevel::FullAuto), vec!["--force".to_owned()]);
6974        assert_eq!(
6975            required_acp_mode(&cursor, ApprovalLevel::Moderate),
6976            Ok(Some(ModeId::new("agent")))
6977        );
6978        assert_eq!(
6979            required_acp_mode(&cursor, ApprovalLevel::ReadOnly),
6980            Ok(Some(ModeId::new("plan")))
6981        );
6982        assert!(!defers_permission_requests(&cursor, ApprovalLevel::FullAuto));
6983        assert!(defers_permission_requests(&gemini, ApprovalLevel::Moderate));
6984        assert!(
6985            acp_approval_level_args(&kimi, ApprovalLevel::Unmanaged).is_empty(),
6986            "Unmanaged imposes nothing, so it must add no argv flags either"
6987        );
6988
6989        // grok: `acp_mode_id` is `None` for every managed level (no live
6990        // mode catalogue sourced yet — slice-1 skipped grok). `FullAuto` and
6991        // `Moderate` are `Supported` with argv flags, so they resolve
6992        // `Ok(None)` and apply through argv; `ReadOnly` is outright
6993        // `Unsupported` and refuses. Flag spellings for FullAuto remain
6994        // UNCONFIRMED against Grok Build's own CLI surface (catalog docs).
6995        let grok = AgentId::new("grok").unwrap();
6996        assert_eq!(required_acp_mode(&grok, ApprovalLevel::FullAuto), Ok(None));
6997        assert_eq!(
6998            acp_approval_level_args(&grok, ApprovalLevel::FullAuto),
6999            vec!["--always-approve".to_owned()],
7000        );
7001        assert_eq!(required_acp_mode(&grok, ApprovalLevel::Moderate), Ok(None));
7002        assert_eq!(
7003            acp_approval_level_args(&grok, ApprovalLevel::Moderate),
7004            vec!["--permission-mode".to_owned(), "auto".to_owned()],
7005        );
7006        assert!(
7007            required_acp_mode(&grok, ApprovalLevel::ReadOnly).is_err(),
7008            "grok at ReadOnly is Unsupported outright, so it must refuse"
7009        );
7010        assert_eq!(required_acp_mode(&grok, ApprovalLevel::Unmanaged), Ok(None));
7011    }
7012
7013    /// The regression guard for the whole change: no provider x level may
7014    /// silently resolve to nothing (which would leave the session running
7015    /// at the agent's own default, e.g. the live-measured `auto`) unless the
7016    /// level itself is `Unmanaged`. Every other level is either a concrete
7017    /// mode id or an outright refusal. kimi no longer has an exception here:
7018    /// measured 2026-09-05, `kimi.exe` 0.29.0 offers no ACP modes at all, so
7019    /// every one of its managed levels now refuses (`Err`) rather than
7020    /// sourcing a mode id -- the `Moderate` row's `auto` exception this
7021    /// guard used to carry was the 2026-09-02 npm-shim-under-WSL-interop
7022    /// measurement, a different build.
7023    #[test]
7024    fn required_acp_mode_never_silently_permits_auto_except_for_unmanaged() {
7025        for id in ["claude", "codex", "grok", "kimi"] {
7026            let agent = AgentId::new(id).unwrap();
7027            for level in [ApprovalLevel::FullAuto, ApprovalLevel::Moderate, ApprovalLevel::ReadOnly] {
7028                match required_acp_mode(&agent, level) {
7029                    Ok(Some(mode_id)) => assert_ne!(
7030                        mode_id.as_str(),
7031                        "auto",
7032                        "{id} at {level:?} must never silently resolve the vendor's own default 'auto'"
7033                    ),
7034                    Ok(None) => assert!(
7035                        !acp_approval_level_args(&agent, level).is_empty(),
7036                        "{id} at {level:?} resolved Ok(None) while carrying no vendor flags -- \
7037                         that leaves the session at the agent's own default. Only Unmanaged, or a \
7038                         level argv actually applies, may resolve to no mode"
7039                    ),
7040                    Err(_) => {} // refused outright -- also never reaches `auto`
7041                }
7042            }
7043            assert_eq!(
7044                required_acp_mode(&agent, ApprovalLevel::Unmanaged),
7045                Ok(None),
7046                "{id}: Unmanaged is the one level allowed to apply nothing"
7047            );
7048        }
7049    }
7050
7051    /// opencode / MiniMax Code: no ACP modes and no argv lever (measured
7052    /// 2026-10-23); `FullAuto` is applied by the host auto-approving
7053    /// `session/request_permission`, every narrower level refuses by name.
7054    #[test]
7055    fn opencode_and_mcode_acp_approval_is_host_policy_full_auto_only() {
7056        for id in ["opencode", "mcode"] {
7057            let agent = AgentId::new(id).unwrap();
7058            assert_eq!(required_acp_mode(&agent, ApprovalLevel::FullAuto), Ok(None), "{id}");
7059            assert!(acp_approval_level_args(&agent, ApprovalLevel::FullAuto).is_empty());
7060            assert_eq!(required_acp_mode(&agent, ApprovalLevel::Unmanaged), Ok(None), "{id}");
7061            assert!(required_acp_mode(&agent, ApprovalLevel::Moderate).is_err(), "{id}");
7062            assert!(required_acp_mode(&agent, ApprovalLevel::ReadOnly).is_err(), "{id}");
7063        }
7064    }
7065
7066    #[test]
7067    fn approval_level_not_offered_message_refuses_by_name_and_lists_what_was_offered() {
7068        let offered = vec![session_mode("bypassPermissions"), session_mode("default")];
7069        let mode_id = ModeId::new("plan");
7070        let message = approval_level_not_offered_message(ApprovalLevel::ReadOnly, &mode_id, &offered)
7071            .expect("'plan' was not among the offered modes");
7072        assert!(message.contains("ApprovalLevelNotOfferedByAgent"));
7073        assert!(message.contains("bypassPermissions"));
7074        assert!(message.contains("default"));
7075        assert!(message.contains("ReadOnly"));
7076    }
7077
7078    #[test]
7079    fn approval_level_not_offered_message_is_none_when_the_agent_announced_it() {
7080        let offered = vec![session_mode("plan")];
7081        let mode_id = ModeId::new("plan");
7082        assert_eq!(
7083            approval_level_not_offered_message(ApprovalLevel::ReadOnly, &mode_id, &offered),
7084            None
7085        );
7086    }
7087
7088    #[test]
7089    fn approval_level_not_offered_message_handles_an_agent_that_announces_no_modes_at_all() {
7090        let mode_id = ModeId::new("bypassPermissions");
7091        let message = approval_level_not_offered_message(ApprovalLevel::FullAuto, &mode_id, &[])
7092            .expect("an empty mode catalog never offers anything");
7093        assert!(message.contains("ApprovalLevelNotOfferedByAgent"));
7094        assert!(message.contains("offered: []"));
7095    }
7096
7097    // -----------------------------------------------------------------------
7098    // stop_native — pipe_sessions branch reads `force`.
7099    //
7100    // Regression coverage: this branch used to call
7101    // `owned.session.kill().await` unconditionally, so no headless Pipe run
7102    // could ever end any way other than a forced kill regardless of what the
7103    // caller asked for. `PipeSession::stop`'s own unit tests (`gate4agent`'s
7104    // `pipe::session::tests`) cover the graceful-wait/bound-elapse timing in
7105    // depth; these two only prove the NEW wiring in `stop_native` itself:
7106    // `force` reaches `PipeSession::stop`, and its `PipeStopOutcome` maps
7107    // onto `ControlObservation::StopCompleted` correctly. Built by inserting
7108    // directly into `pipe_sessions` (private field, visible to this child
7109    // module) rather than through `execute()`/`EffectEnvelope`, so this does
7110    // not depend on the catalog/spawn-plan machinery at all.
7111    // -----------------------------------------------------------------------
7112
7113    use super::{NativeEffectShell, NativeSessionKey, OwnedProviderSession};
7114    use gate4agent_catalog::{AgentRegistry as FixtureAgentRegistry, AgentSpec as FixtureAgentSpec};
7115    use gate4agent_types::ControlObservation;
7116    use std::collections::VecDeque;
7117
7118    fn fixture_pipe_key() -> NativeSessionKey {
7119        NativeSessionKey {
7120            instance_id: gate4agent_types::AgentInstanceId(9_001),
7121            generation: gate4agent_types::SessionGeneration(1),
7122        }
7123    }
7124
7125    fn fixture_pipe_source() -> gate4agent_types::ProviderSource {
7126        gate4agent_types::ProviderSource {
7127            family: AdapterFamily::Pipe,
7128            binding: gate4agent_types::AdapterBinding::new(
7129                gate4agent_types::AdapterId::new("fixture").unwrap(),
7130                "1",
7131                gate4agent_types::AdapterVerification::SyntheticFixture,
7132            )
7133            .unwrap(),
7134        }
7135    }
7136
7137    #[cfg(windows)]
7138    fn fixture_graceful_exit_launch() -> gate4agent_types::LaunchSpec {
7139        gate4agent_types::LaunchSpec {
7140            program: "powershell.exe".to_owned(),
7141            fixed_args: vec![
7142                "-NoProfile".to_owned(),
7143                "-NonInteractive".to_owned(),
7144                "-Command".to_owned(),
7145                "[Console]::In.ReadToEnd() | Out-Null; exit 0".to_owned(),
7146            ],
7147        }
7148    }
7149
7150    #[cfg(not(windows))]
7151    fn fixture_graceful_exit_launch() -> gate4agent_types::LaunchSpec {
7152        gate4agent_types::LaunchSpec {
7153            program: "sh".to_owned(),
7154            fixed_args: vec!["-c".to_owned(), "cat >/dev/null; exit 0".to_owned()],
7155        }
7156    }
7157
7158    #[cfg(windows)]
7159    fn fixture_ignore_stdin_launch() -> gate4agent_types::LaunchSpec {
7160        gate4agent_types::LaunchSpec {
7161            program: "powershell.exe".to_owned(),
7162            fixed_args: vec![
7163                "-NoProfile".to_owned(),
7164                "-NonInteractive".to_owned(),
7165                "-Command".to_owned(),
7166                "Start-Sleep -Seconds 30".to_owned(),
7167            ],
7168        }
7169    }
7170
7171    #[cfg(not(windows))]
7172    fn fixture_ignore_stdin_launch() -> gate4agent_types::LaunchSpec {
7173        gate4agent_types::LaunchSpec {
7174            program: "sh".to_owned(),
7175            fixed_args: vec!["-c".to_owned(), "sleep 30".to_owned()],
7176        }
7177    }
7178
7179    async fn spawn_fixture_pipe_shell(
7180        launch: gate4agent_types::LaunchSpec,
7181    ) -> (NativeEffectShell, NativeSessionKey) {
7182        let session = gate4agent::PipeSession::spawn_with_launch(
7183            gate4agent::core::types::SessionConfig::default(),
7184            "prompt",
7185            &launch,
7186            gate4agent_types::PipePromptDelivery::StdinClose,
7187        )
7188        .await
7189        .expect("fixture pipe process must spawn");
7190        let events = session.subscribe();
7191        let key = fixture_pipe_key();
7192        let mut shell = NativeEffectShell::new(
7193            FixtureAgentRegistry::new(std::iter::empty::<FixtureAgentSpec>())
7194                .expect("empty fixture catalog"),
7195        );
7196        shell.pipe_sessions.insert(
7197            key,
7198            OwnedProviderSession {
7199                source: fixture_pipe_source(),
7200                session,
7201                events,
7202                pending_events: VecDeque::new(),
7203                pending_provider_events: VecDeque::new(),
7204                next_provider_sequence: 1,
7205                observed_exit_code: None,
7206                runtime_policy: gate4agent_types::ProviderRuntimePolicy::none(),
7207            },
7208        );
7209        (shell, key)
7210    }
7211
7212    #[tokio::test]
7213    async fn stop_native_pipe_session_reports_the_real_exit_code_when_not_forced() {
7214        let (mut shell, key) = spawn_fixture_pipe_shell(fixture_graceful_exit_launch()).await;
7215
7216        match shell.stop_native(key, false).await {
7217            ControlObservation::StopCompleted {
7218                forced, exit_code, ..
7219            } => {
7220                assert!(!forced, "a process that exits on its own must not be forced");
7221                assert_eq!(exit_code, Some(0));
7222            }
7223            other => panic!("expected StopCompleted, got {other:?}"),
7224        }
7225    }
7226
7227    #[tokio::test]
7228    async fn stop_native_pipe_session_force_true_kills_immediately_without_waiting() {
7229        let (mut shell, key) = spawn_fixture_pipe_shell(fixture_ignore_stdin_launch()).await;
7230
7231        let start = std::time::Instant::now();
7232        match shell.stop_native(key, true).await {
7233            ControlObservation::StopCompleted { forced, .. } => {
7234                assert!(forced, "force=true must always report forced");
7235            }
7236            other => panic!("expected StopCompleted, got {other:?}"),
7237        }
7238        assert!(
7239            start.elapsed()
7240                < std::time::Duration::from_secs(gate4agent::pipe::PIPE_GRACEFUL_STOP_BOUND_SECS),
7241            "force=true must not wait out the graceful bound"
7242        );
7243    }
7244
7245    // -------------------------------------------------------------------
7246    // stop_native -- acp_sessions branch reads `force`.
7247    //
7248    // Regression coverage: this branch used to call
7249    // `owned.session.kill().await` unconditionally after an optional
7250    // `session/cancel`, so `forced` was always `true` regardless of what
7251    // the caller asked for. Fixture mirrors `gate4agent::acp::session`'s
7252    // own `AcpSession::stop` unit tests (which cover the graceful-wait/
7253    // bound-elapse timing in depth): a minimal handshake responder that
7254    // answers `initialize`/`session/new` and exits 0 on stdin EOF. This
7255    // test only proves the NEW wiring in `stop_native` itself: `force`
7256    // reaches `AcpSession::stop`, and its `AcpStopOutcome` maps onto
7257    // `ControlObservation::StopCompleted` correctly.
7258    // -------------------------------------------------------------------
7259
7260    #[cfg(windows)]
7261    fn acp_fixture_launch() -> gate4agent_types::LaunchSpec {
7262        gate4agent_types::LaunchSpec {
7263            program: "powershell.exe".to_owned(),
7264            fixed_args: vec![
7265                "-NoLogo".to_owned(),
7266                "-NoProfile".to_owned(),
7267                "-NonInteractive".to_owned(),
7268                "-ExecutionPolicy".to_owned(),
7269                "Bypass".to_owned(),
7270                "-Command".to_owned(),
7271                ACP_HANDSHAKE_SCRIPT.to_owned(),
7272            ],
7273        }
7274    }
7275
7276    #[cfg(not(windows))]
7277    fn acp_fixture_launch() -> gate4agent_types::LaunchSpec {
7278        gate4agent_types::LaunchSpec {
7279            program: "python3".to_owned(),
7280            fixed_args: vec!["-u".to_owned(), "-c".to_owned(), ACP_HANDSHAKE_SCRIPT.to_owned()],
7281        }
7282    }
7283
7284    #[cfg(windows)]
7285    const ACP_HANDSHAKE_SCRIPT: &str = r#"[Console]::OutputEncoding=[Text.Encoding]::UTF8
7286function Write-JsonLine($value) { [Console]::WriteLine(($value | ConvertTo-Json -Compress -Depth 12)) }
7287$initialize = [Console]::ReadLine() | ConvertFrom-Json
7288Write-JsonLine @{jsonrpc='2.0';id=$initialize.id;result=@{}}
7289$newSession = [Console]::ReadLine() | ConvertFrom-Json
7290Write-JsonLine @{jsonrpc='2.0';id=$newSession.id;result=@{sessionId='fixture-acp-session'}}
7291while ($true) {
7292    $line = [Console]::ReadLine()
7293    if ($null -eq $line) { exit 0 }
7294}"#;
7295    #[cfg(not(windows))]
7296    const ACP_HANDSHAKE_SCRIPT: &str = r#"import json,sys
7297def read_message():
7298 line=sys.stdin.readline()
7299 if not line: return None
7300 return json.loads(line)
7301def write_message(message):
7302 print(json.dumps(message),flush=True)
7303
7304initialize=read_message()
7305write_message({'jsonrpc':'2.0','id':initialize.get('id'),'result':{}})
7306new_session=read_message()
7307write_message({'jsonrpc':'2.0','id':new_session.get('id'),'result':{'sessionId':'fixture-acp-session'}})
7308while True:
7309 msg=read_message()
7310 if msg is None:
7311  sys.exit(0)"#;
7312
7313    fn fixture_acp_key() -> NativeSessionKey {
7314        NativeSessionKey {
7315            instance_id: gate4agent_types::AgentInstanceId(9_002),
7316            generation: gate4agent_types::SessionGeneration(1),
7317        }
7318    }
7319
7320    fn fixture_acp_source() -> gate4agent_types::ProviderSource {
7321        gate4agent_types::ProviderSource {
7322            family: AdapterFamily::Acp,
7323            binding: gate4agent_types::AdapterBinding::new(
7324                gate4agent_types::AdapterId::new("fixture").unwrap(),
7325                "1",
7326                gate4agent_types::AdapterVerification::SyntheticFixture,
7327            )
7328            .unwrap(),
7329        }
7330    }
7331
7332    async fn spawn_fixture_acp_shell() -> (NativeEffectShell, NativeSessionKey) {
7333        let session = gate4agent::acp::AcpSession::spawn_with_launch(
7334            gate4agent::CliTool::ClaudeCode,
7335            &std::env::current_dir().expect("cwd"),
7336            gate4agent::acp::AcpSessionOptions::default(),
7337            &acp_fixture_launch(),
7338        )
7339        .await
7340        .expect("fixture ACP handshake must succeed");
7341        let events = session.subscribe();
7342        let key = fixture_acp_key();
7343        let mut shell = NativeEffectShell::new(
7344            FixtureAgentRegistry::new(std::iter::empty::<FixtureAgentSpec>())
7345                .expect("empty fixture catalog"),
7346        );
7347        shell.acp_sessions.insert(
7348            key,
7349            OwnedProviderSession {
7350                source: fixture_acp_source(),
7351                session,
7352                events,
7353                pending_events: VecDeque::new(),
7354                pending_provider_events: VecDeque::new(),
7355                next_provider_sequence: 1,
7356                observed_exit_code: None,
7357                runtime_policy: gate4agent_types::ProviderRuntimePolicy::none(),
7358            },
7359        );
7360        (shell, key)
7361    }
7362
7363    #[tokio::test]
7364    async fn stop_native_acp_session_reports_the_real_exit_code_when_not_forced() {
7365        let (mut shell, key) = spawn_fixture_acp_shell().await;
7366
7367        match shell.stop_native(key, false).await {
7368            ControlObservation::StopCompleted {
7369                forced, exit_code, ..
7370            } => {
7371                assert!(!forced, "a process that exits on its own must not be forced");
7372                assert_eq!(exit_code, Some(0));
7373            }
7374            other => panic!("expected StopCompleted, got {other:?}"),
7375        }
7376    }
7377
7378    // -------------------------------------------------------------------
7379    // spawn_native -- ACP branch: `ProviderEvent::SessionIdentityObserved`.
7380    //
7381    // Regression coverage for the defect this carries fixed: nothing on the
7382    // ACP path ever emitted `SessionIdentityObserved`, so a managed session
7383    // record for an ACP-spawned agent could never leave
7384    // `ManagedSessionState::IdentityPending` (`gate4agent-node`'s
7385    // `reconcile_managed_record` binds the identity ONLY on that event).
7386    // Built through the full `execute()`/`EffectEnvelope` path (unlike
7387    // `spawn_fixture_acp_shell` above, which inserts an already-spawned
7388    // session directly into `acp_sessions`) so these tests exercise the
7389    // ACTUAL `TransportKind::Acp` arm of `spawn_native`, not a stand-in for
7390    // it -- the same synthetic stdio handshake fixture, extended with a
7391    // second script that omits `sessionId` to name the ACP-MUST violation
7392    // this whole feature exists to survive.
7393    // -------------------------------------------------------------------
7394
7395    #[cfg(windows)]
7396    fn acp_fixture_launch_no_session_id() -> gate4agent_types::LaunchSpec {
7397        gate4agent_types::LaunchSpec {
7398            program: "powershell.exe".to_owned(),
7399            fixed_args: vec![
7400                "-NoLogo".to_owned(),
7401                "-NoProfile".to_owned(),
7402                "-NonInteractive".to_owned(),
7403                "-ExecutionPolicy".to_owned(),
7404                "Bypass".to_owned(),
7405                "-Command".to_owned(),
7406                ACP_HANDSHAKE_SCRIPT_NO_SESSION_ID.to_owned(),
7407            ],
7408        }
7409    }
7410
7411    #[cfg(not(windows))]
7412    fn acp_fixture_launch_no_session_id() -> gate4agent_types::LaunchSpec {
7413        gate4agent_types::LaunchSpec {
7414            program: "python3".to_owned(),
7415            fixed_args: vec![
7416                "-u".to_owned(),
7417                "-c".to_owned(),
7418                ACP_HANDSHAKE_SCRIPT_NO_SESSION_ID.to_owned(),
7419            ],
7420        }
7421    }
7422
7423    #[cfg(windows)]
7424    const ACP_HANDSHAKE_SCRIPT_NO_SESSION_ID: &str = r#"[Console]::OutputEncoding=[Text.Encoding]::UTF8
7425function Write-JsonLine($value) { [Console]::WriteLine(($value | ConvertTo-Json -Compress -Depth 12)) }
7426$initialize = [Console]::ReadLine() | ConvertFrom-Json
7427Write-JsonLine @{jsonrpc='2.0';id=$initialize.id;result=@{}}
7428$newSession = [Console]::ReadLine() | ConvertFrom-Json
7429Write-JsonLine @{jsonrpc='2.0';id=$newSession.id;result=@{}}
7430while ($true) {
7431    $line = [Console]::ReadLine()
7432    if ($null -eq $line) { exit 0 }
7433}"#;
7434    #[cfg(not(windows))]
7435    const ACP_HANDSHAKE_SCRIPT_NO_SESSION_ID: &str = r#"import json,sys
7436def read_message():
7437 line=sys.stdin.readline()
7438 if not line: return None
7439 return json.loads(line)
7440def write_message(message):
7441 print(json.dumps(message),flush=True)
7442
7443initialize=read_message()
7444write_message({'jsonrpc':'2.0','id':initialize.get('id'),'result':{}})
7445new_session=read_message()
7446write_message({'jsonrpc':'2.0','id':new_session.get('id'),'result':{}})
7447while True:
7448 msg=read_message()
7449 if msg is None:
7450  sys.exit(0)"#;
7451
7452    fn fixture_acp_spawn_agent_id() -> AgentId {
7453        AgentId::new("claude").expect("builtin catalog names 'claude'")
7454    }
7455
7456    /// Clones the REAL built-in `claude` spec (so `capabilities.transports.acp`
7457    /// carries the same `AdapterBinding` the default `legacy_adapters`
7458    /// registry (`NativeEffectShell::new`) already resolves) and overrides
7459    /// only `launch_override`, so `spawn_native` execs the synthetic stdio
7460    /// fixture above instead of a real `claude` binary.
7461    fn fixture_acp_spawn_agent_spec(launch: gate4agent_types::LaunchSpec) -> FixtureAgentSpec {
7462        let mut spec = gate4agent_catalog::builtin_registry()
7463            .get(&fixture_acp_spawn_agent_id())
7464            .cloned()
7465            .expect("builtin catalog must declare claude");
7466        spec.capabilities
7467            .transports
7468            .acp
7469            .as_mut()
7470            .expect("claude must declare ACP capability")
7471            .launch_override = Some(launch);
7472        spec
7473    }
7474
7475    fn fixture_acp_spawn_key() -> NativeSessionKey {
7476        NativeSessionKey {
7477            instance_id: gate4agent_types::AgentInstanceId(9_101),
7478            generation: gate4agent_types::SessionGeneration(1),
7479        }
7480    }
7481
7482    /// Spawns through the full `execute()`/`EffectEnvelope` path with
7483    /// `ApprovalLevel::Unmanaged` -- the one level `required_acp_mode`
7484    /// resolves to `Ok(None)` for every agent, so the spawn never calls
7485    /// `session/set_mode` against a fixture that only answers `initialize`/
7486    /// `session/new`.
7487    async fn spawn_native_acp_fixture(
7488        launch: gate4agent_types::LaunchSpec,
7489        provider_session_identity: bool,
7490    ) -> (NativeEffectShell, NativeSessionKey, ControlObservation) {
7491        let mut policy = ProviderRuntimePolicy::none();
7492        policy.provider_session_identity = provider_session_identity;
7493        let key = fixture_acp_spawn_key();
7494        let mut shell = NativeEffectShell::new(
7495            FixtureAgentRegistry::new([fixture_acp_spawn_agent_spec(launch)])
7496                .expect("single-agent fixture catalog"),
7497        );
7498        let envelope = gate4agent_types::EffectEnvelope {
7499            operation_id: gate4agent_types::OperationId(1),
7500            instance_id: key.instance_id,
7501            generation: key.generation,
7502            effect: gate4agent_types::ControlEffect::Spawn {
7503                agent_id: fixture_acp_spawn_agent_id(),
7504                transport: TransportKind::Acp,
7505                runtime_policy: policy,
7506                request: gate4agent_types::StartRequest {
7507                    working_directory: std::env::current_dir()
7508                        .expect("cwd")
7509                        .to_string_lossy()
7510                        .into_owned(),
7511                    terminal_size: gate4agent_types::TerminalSize {
7512                        rows: 24,
7513                        columns: 80,
7514                    },
7515                    initial_prompt: None,
7516                    session_options: None,
7517                    approval_level: ApprovalLevel::Unmanaged,
7518                },
7519            },
7520        };
7521        let observation = shell.execute(envelope).await.observation;
7522        (shell, key, observation)
7523    }
7524
7525    #[tokio::test]
7526    async fn acp_spawn_with_a_real_sessionid_emits_session_identity_observed_after_session_start() {
7527        let (mut shell, key, spawned) =
7528            spawn_native_acp_fixture(acp_fixture_launch(), true).await;
7529        match spawned {
7530            ControlObservation::Spawned { .. } => {}
7531            other => panic!("expected Spawned, got {other:?}"),
7532        }
7533
7534        let mut provider_events = shell
7535            .collect_provider_events()
7536            .into_iter()
7537            .filter_map(|envelope| match envelope.observation {
7538                ControlObservation::ProviderEvent { event, .. } => Some(event),
7539                _ => None,
7540            });
7541
7542        match provider_events.next() {
7543            Some(ProviderEvent::SessionStarted { .. }) => {}
7544            other => panic!("expected SessionStarted first, got {other:?}"),
7545        }
7546        match provider_events.next() {
7547            Some(ProviderEvent::SessionIdentityObserved { identity }) => {
7548                assert_eq!(identity.key, gate4agent_types::ProviderSessionKey::SessionId);
7549                assert_eq!(identity.id, "fixture-acp-session");
7550                assert!(identity.transcript_path.is_none());
7551            }
7552            other => panic!("expected SessionIdentityObserved second, got {other:?}"),
7553        }
7554        assert!(
7555            provider_events.next().is_none(),
7556            "expected exactly one SessionIdentityObserved and nothing after it"
7557        );
7558
7559        let _ = shell.stop_native(key, true).await;
7560    }
7561
7562    #[tokio::test]
7563    async fn acp_spawn_with_no_sessionid_emits_no_session_identity_observed() {
7564        let (mut shell, key, spawned) =
7565            spawn_native_acp_fixture(acp_fixture_launch_no_session_id(), true).await;
7566        match spawned {
7567            ControlObservation::Spawned { .. } => {}
7568            other => panic!("expected Spawned, got {other:?}"),
7569        }
7570
7571        let provider_events: Vec<_> = shell
7572            .collect_provider_events()
7573            .into_iter()
7574            .filter_map(|envelope| match envelope.observation {
7575                ControlObservation::ProviderEvent { event, .. } => Some(event),
7576                _ => None,
7577            })
7578            .collect();
7579
7580        assert!(
7581            provider_events
7582                .iter()
7583                .any(|event| matches!(event, ProviderEvent::SessionStarted { .. })),
7584            "expected SessionStarted even when the agent reported no sessionId, got {provider_events:?}"
7585        );
7586        assert!(
7587            !provider_events
7588                .iter()
7589                .any(|event| matches!(event, ProviderEvent::SessionIdentityObserved { .. })),
7590            "an agent that violates ACP's sessionId MUST must not be granted an identity: \
7591             got {provider_events:?}"
7592        );
7593
7594        let _ = shell.stop_native(key, true).await;
7595    }
7596}
7597
7598#[cfg(test)]
7599mod resume_tests;