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