Skip to main content

supercode_harness/
runtime.rs

1//! Primitive live-runtime contracts and the Codex app-server reference adapter.
2//!
3//! These APIs control harness-native sessions; they do not emulate terminal
4//! keystrokes and do not claim to attach to an arbitrary already-running TUI.
5
6use std::collections::{BTreeMap, HashMap};
7use std::path::{Path, PathBuf};
8use std::process::Stdio;
9use std::sync::Arc;
10use std::time::Duration;
11
12use async_trait::async_trait;
13use serde::{Deserialize, Serialize};
14use serde_json::{json, Value};
15use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
16use tokio::process::{Child, ChildStdin, Command};
17use tokio::sync::{mpsc, oneshot, Mutex};
18
19use crate::{Error, HarnessId, Result};
20
21mod adapters;
22mod hosted;
23#[cfg(feature = "adapter-api")]
24mod supercode_http;
25pub(crate) use adapters::generated_session_id;
26pub use adapters::{
27    AcpRuntimeBackend, ClaudeCodeRuntimeBackend, OpenCodeRuntimeBackend, PiRuntimeBackend,
28};
29pub use hosted::{HostedHarnessConnection, HostedHarnessRuntime};
30#[cfg(feature = "adapter-api")]
31pub use supercode_http::SupercodeHttpRuntimeBackend;
32
33/// Mechanical facts an adapter can guarantee.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct RuntimeCapabilities {
36    /// Can create a fresh harness-native session.
37    pub start_session: bool,
38    /// Can resume a harness-native persisted session by id.
39    pub resume_session: bool,
40    /// Can join an arbitrary already-running harness process.
41    pub attach_existing_process: bool,
42    /// Can send user input through a structured protocol.
43    pub send_input: bool,
44    /// Can receive structured live events.
45    pub stream_events: bool,
46    /// Can interrupt an in-flight turn.
47    pub interrupt: bool,
48    /// Can redirect an in-flight turn without interrupting it.
49    #[serde(default)]
50    pub steer: bool,
51    /// Can answer protocol requests such as approvals or elicitation.
52    pub respond_to_requests: bool,
53}
54
55/// Executable configuration used to launch one adapter endpoint.
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct RuntimeLaunch {
58    /// Executable name or path.
59    pub program: String,
60    /// Arguments passed before adapter-generated protocol arguments.
61    pub arguments: Vec<String>,
62    /// Extra environment variables.
63    pub env: BTreeMap<String, String>,
64}
65
66/// Connect to an already-running harness endpoint instead of spawning one.
67///
68/// The registry stores where the endpoint and its credential live — the
69/// harness's own config file — never the values themselves. The service
70/// resolves them when it opens the connection, so a rotated token or a moved
71/// gateway is picked up on the next open without a registry change.
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73pub struct RuntimeConnectLaunch {
74    /// Harness config file holding the endpoint; a leading `~/` expands to the
75    /// caller's home directory at resolve time.
76    pub config_path: String,
77    /// JSON pointer to the endpoint address inside the config file.
78    pub address_pointer: String,
79    /// Optional JSON pointer to a PORT number in the config file, consulted
80    /// when `address_pointer` names nothing: the address becomes that port on
81    /// loopback under `default_address`'s scheme. Harnesses like openclaw
82    /// configure a bare `gateway.port`, never a full URL.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub port_pointer: Option<String>,
85    /// Optional fallback endpoint when neither pointer resolves — the
86    /// harness's documented out-of-the-box endpoint. With this set, a missing
87    /// or pointer-less config is the harness "running on defaults", not an
88    /// error.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub default_address: Option<String>,
91    /// Optional JSON pointer to the bearer credential inside the config file.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub auth_pointer: Option<String>,
94    /// Protocol spoken at the endpoint.
95    pub protocol: String,
96}
97
98/// Bearer credential whose `Debug` output never contains the secret.
99#[derive(Clone, PartialEq, Eq)]
100pub struct BearerToken(String);
101
102impl BearerToken {
103    /// Wrap a resolved credential.
104    pub fn new(secret: impl Into<String>) -> Self {
105        Self(secret.into())
106    }
107
108    /// The secret itself, for constructing an Authorization header.
109    pub fn secret(&self) -> &str {
110        &self.0
111    }
112}
113
114impl std::fmt::Debug for BearerToken {
115    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        formatter.write_str("BearerToken(<redacted>)")
117    }
118}
119
120/// Endpoint and credential resolved from a [`RuntimeConnectLaunch`].
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct ResolvedRuntimeConnection {
123    /// Concrete endpoint address.
124    pub address: String,
125    /// Bearer credential when the launch declares one.
126    pub auth: Option<BearerToken>,
127}
128
129impl RuntimeConnectLaunch {
130    /// Resolve the endpoint address and credential from the harness's config
131    /// file. Fails closed: a declared pointer that does not resolve to a
132    /// non-empty string is an error, and diagnostics name the path and the
133    /// pointer without echoing config contents.
134    pub fn resolve(&self, home: &Path) -> Result<ResolvedRuntimeConnection> {
135        let path = match self.config_path.strip_prefix("~/") {
136            Some(rest) => home.join(rest),
137            None => PathBuf::from(&self.config_path),
138        };
139        // A missing config file is the harness on documented defaults when
140        // the descriptor declares them; otherwise it stays an error.
141        let config: Value = match std::fs::read_to_string(&path) {
142            Ok(raw) => serde_json::from_str(&raw).map_err(|_| {
143                Error::Other(format!(
144                    "connect-mode config {} is not valid JSON",
145                    path.display()
146                ))
147            })?,
148            Err(error) => {
149                if self.default_address.is_some() {
150                    Value::Object(Default::default())
151                } else {
152                    return Err(Error::Other(format!(
153                        "connect-mode config {} is unreadable: {error}",
154                        path.display()
155                    )));
156                }
157            }
158        };
159        let field = |pointer: &str, name: &str| -> Result<String> {
160            match config.pointer(pointer).and_then(Value::as_str) {
161                Some(value) if !value.trim().is_empty() => Ok(value.trim().to_string()),
162                _ => Err(Error::Other(format!(
163                    "connect-mode {name} pointer `{pointer}` does not name a non-empty string in {}",
164                    path.display()
165                ))),
166            }
167        };
168        // Address chain: explicit URL pointer → configured port on loopback →
169        // the descriptor's documented default endpoint.
170        let address = match config
171            .pointer(&self.address_pointer)
172            .and_then(Value::as_str)
173        {
174            Some(value) if !value.trim().is_empty() => value.trim().to_string(),
175            _ => {
176                let from_port = self
177                    .port_pointer
178                    .as_deref()
179                    .and_then(|pointer| config.pointer(pointer))
180                    .and_then(Value::as_u64)
181                    .map(|port| {
182                        let scheme = self
183                            .default_address
184                            .as_deref()
185                            .and_then(|address| address.split_once("://"))
186                            .map(|(scheme, _)| scheme)
187                            .unwrap_or("ws");
188                        format!("{scheme}://127.0.0.1:{port}")
189                    });
190                match from_port.or_else(|| self.default_address.clone()) {
191                    Some(address) => address,
192                    None => {
193                        return Err(Error::Other(format!(
194                            "connect-mode address pointer `{}` does not name a non-empty string in {}",
195                            self.address_pointer,
196                            path.display()
197                        )));
198                    }
199                }
200            }
201        };
202        let mut address = address.trim_end_matches('/').to_string();
203        // Normalize a bare host:port to the endpoint's scheme — configs
204        // routinely omit it and a scheme-less URL makes gateway clients fall
205        // back to their compiled-in default endpoint instead.
206        if !address.contains("://") {
207            let scheme = self
208                .default_address
209                .as_deref()
210                .and_then(|default| default.split_once("://"))
211                .map(|(scheme, _)| scheme)
212                .unwrap_or("ws");
213            address = format!("{scheme}://{address}");
214        }
215        // Auth is optional exactly when the endpoint can run without it: a
216        // declared pointer that resolves to nothing is only an error when no
217        // default endpoint is declared (the original fail-closed contract).
218        let auth = match &self.auth_pointer {
219            Some(pointer) => match config.pointer(pointer).and_then(Value::as_str) {
220                Some(value) if !value.trim().is_empty() => {
221                    Some(BearerToken::new(value.trim().to_string()))
222                }
223                _ if self.default_address.is_some() => None,
224                _ => Some(BearerToken::new(field(pointer, "auth")?)),
225            },
226            None => None,
227        };
228        Ok(ResolvedRuntimeConnection { address, auth })
229    }
230}
231
232/// One stdio MCP server the caller wants mounted into the session it is
233/// starting. Uniform shape; each backend translates it into whatever its own
234/// harness accepts (the ACP backend into `session/new`'s `mcpServers`).
235#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
236pub struct McpServerLaunch {
237    /// Server name the harness registers the tools under.
238    pub name: String,
239    /// Executable to spawn.
240    pub command: String,
241    /// Arguments passed to it.
242    #[serde(default)]
243    pub arguments: Vec<String>,
244    /// Extra environment for the spawned server.
245    #[serde(default)]
246    pub env: BTreeMap<String, String>,
247}
248
249/// Request to create a fresh runtime session.
250#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
251pub struct RuntimeStartRequest {
252    /// Project working directory.
253    pub cwd: PathBuf,
254    /// Optional executable override, primarily for alternate installs/tests.
255    pub launch: Option<RuntimeLaunch>,
256    /// MCP servers to mount into the new session, where the harness's own
257    /// start door carries them. Backends that have no such door ignore it —
258    /// their caller mounts through a config file instead.
259    #[serde(default)]
260    pub mcp_servers: Vec<McpServerLaunch>,
261    /// The harness's approval policy for this session, where its start door takes one (Codex's
262    /// `approvalPolicy` on thread/start and thread/resume, e.g. `untrusted`: every command asks first).
263    /// Absent, the harness's own default.
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub approval_policy: Option<String>,
266}
267
268/// Request to resume or attach through a new adapter connection.
269#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
270pub struct RuntimeAttachRequest {
271    /// Harness-native session/thread id.
272    pub runtime_id: String,
273    /// Optional cwd override accepted by the harness protocol.
274    pub cwd: Option<PathBuf>,
275    /// Optional executable override.
276    pub launch: Option<RuntimeLaunch>,
277    /// MCP servers to mount into the resumed session, exactly as a start
278    /// request mounts them: a session's tools do not survive its process, so
279    /// the caller that resumes it names them again.
280    #[serde(default)]
281    pub mcp_servers: Vec<McpServerLaunch>,
282    /// The harness's approval policy for this session, where its start door takes one (Codex's
283    /// `approvalPolicy` on thread/start and thread/resume, e.g. `untrusted`: every command asks first).
284    /// Absent, the harness's own default.
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    pub approval_policy: Option<String>,
287}
288
289/// Observable endpoint backing a runtime connection.
290#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
291#[serde(tag = "kind", rename_all = "snake_case")]
292pub enum RuntimeEndpoint {
293    /// Child process owned by this connection.
294    LocalProcess {
295        /// Process id when available.
296        pid: Option<u32>,
297        /// Executable plus arguments.
298        command: Vec<String>,
299        /// Native protocol spoken over stdio.
300        protocol: String,
301    },
302    /// Existing HTTP service.
303    Http {
304        /// Service base URL.
305        base_url: String,
306        /// Native protocol name.
307        protocol: String,
308    },
309}
310
311/// Identity returned after a live session is started or resumed.
312#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
313pub struct RuntimeHandle {
314    /// Runtime adapter/harness.
315    pub harness: HarnessId,
316    /// Harness-native live session identity.
317    pub runtime_id: String,
318    /// Concrete endpoint used by this connection.
319    pub endpoint: RuntimeEndpoint,
320}
321
322/// User input accepted by a live runtime.
323#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
324pub struct RuntimeInput {
325    /// Plain text prompt or steering instruction.
326    pub text: String,
327    /// Runtime-resolved image URLs or `data:image/...;base64,...` payloads.
328    ///
329    /// Adapters must either preserve these as native multimodal input or
330    /// reject the turn explicitly; they must never flatten image bytes into
331    /// the text prompt.
332    #[serde(default, skip_serializing_if = "Vec::is_empty")]
333    pub image_urls: Vec<String>,
334}
335
336/// Protocol-neutral envelope around a native live event.
337#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
338pub struct HarnessEvent {
339    /// Canonical SDK sequence when the event originated from an SDK runtime.
340    /// Native harness adapters leave this absent and the service sequences
341    /// their transport stream locally.
342    #[serde(default, skip_serializing_if = "Option::is_none")]
343    pub sequence: Option<u64>,
344    /// Native method/type name, or `request` for a server-initiated request.
345    pub kind: String,
346    /// Lossless native event/request value.
347    pub payload: Value,
348}
349
350/// One connected harness-native runtime session.
351#[async_trait]
352pub trait RuntimeConnection: Send {
353    /// Identity and endpoint of this connection.
354    fn handle(&self) -> &RuntimeHandle;
355    /// Submit structured user input and return the harness-native turn id when
356    /// one is allocated.
357    async fn send_input(&mut self, input: RuntimeInput) -> Result<Option<String>>;
358    /// Wait for the next native live event.
359    async fn next_event(&mut self) -> Result<Option<HarnessEvent>>;
360    /// Interrupt the current turn, when supported.
361    async fn interrupt(&mut self) -> Result<()>;
362    /// Redirect the current turn, when supported.
363    async fn steer(&mut self, _text: String) -> Result<()> {
364        Err(Error::Other(
365            "this runtime cannot steer an active turn".into(),
366        ))
367    }
368    /// Answer a server-initiated protocol request by its native JSON id.
369    async fn respond(&mut self, request_id: Value, response: Value) -> Result<()>;
370    /// Acquire this connection's native controller lease without displacing
371    /// an existing controller.
372    async fn acquire_control(&mut self) -> Result<crate::RuntimeLeaseSnapshot> {
373        Err(Error::Other(
374            "this runtime does not expose controller leases".into(),
375        ))
376    }
377    /// Refresh this connection's observer/controller lease.
378    async fn heartbeat(&mut self) -> Result<crate::RuntimeLeaseSnapshot> {
379        Err(Error::Other(
380            "this runtime does not expose controller leases".into(),
381        ))
382    }
383    /// Detach this exact connection without stopping the native runtime.
384    async fn detach(&mut self) -> Result<crate::RuntimeLeaseSnapshot> {
385        Err(Error::Other(
386            "this runtime does not expose detachable leases".into(),
387        ))
388    }
389    /// Close the adapter-owned transport/process.
390    async fn close(&mut self) -> Result<()>;
391}
392
393/// Factory for starting, resuming, and (where the native protocol permits it)
394/// joining one harness's already-running runtime endpoint.
395#[async_trait]
396pub trait RuntimeBackend: Send + Sync {
397    /// Harness implemented by this backend.
398    fn harness(&self) -> HarnessId;
399    /// Honest mechanical capability report.
400    fn capabilities(&self) -> RuntimeCapabilities;
401    /// Create a fresh harness-native session.
402    async fn start(&self, request: RuntimeStartRequest) -> Result<Box<dyn RuntimeConnection>>;
403    /// Resume a persisted harness-native session through a new protocol
404    /// connection. This does not imply joining the process that originally
405    /// wrote the session.
406    async fn attach(&self, request: RuntimeAttachRequest) -> Result<Box<dyn RuntimeConnection>>;
407    /// Join an already-running harness process or server. Most stock harnesses
408    /// cannot do this; adapters must opt in rather than silently treating a
409    /// persisted resume as a live attach.
410    async fn attach_existing(
411        &self,
412        _request: RuntimeAttachRequest,
413    ) -> Result<Box<dyn RuntimeConnection>> {
414        Err(Error::Other(format!(
415            "{} cannot attach to an already-running process",
416            self.harness().as_str()
417        )))
418    }
419}
420
421/// Codex live-runtime backend using the official `codex app-server` JSONL
422/// protocol (`initialize`, `thread/start|resume`, `turn/start|interrupt`).
423#[derive(Debug, Clone)]
424pub struct CodexRuntimeBackend {
425    launch: RuntimeLaunch,
426}
427
428const CODEX_STARTUP_TIMEOUT: Duration = Duration::from_secs(10);
429
430/// A stock Codex app-server eagerly indexes everything below `CODEX_HOME`
431/// before answering `initialize`. That turns a runtime open into an unbounded
432/// corpus scan for long-time Codex users. Give each connection a private state
433/// database and project only the one native rollout it needs into that home.
434/// The rollout itself is hard-linked, so Codex continues the original inode
435/// rather than a copy that would need lossy reconciliation later.
436#[derive(Debug)]
437struct CodexRuntimeHome {
438    root: PathBuf,
439    native_home: PathBuf,
440}
441
442impl CodexRuntimeHome {
443    fn prepare(launch: &mut RuntimeLaunch, runtime_id: Option<&str>) -> Result<Self> {
444        let native_home = codex_native_home(launch)?;
445        let root = supercode_runtime_root()
446            .join("codex")
447            .join(generated_session_id());
448        std::fs::create_dir_all(&root).map_err(|error| {
449            Error::Other(format!(
450                "could not create isolated Codex runtime home {}: {error}",
451                root.display()
452            ))
453        })?;
454        set_private_directory(&root)?;
455        let root = std::fs::canonicalize(&root)?;
456
457        for entry in [
458            "auth.json",
459            "config.toml",
460            "hooks.json",
461            "models_cache.json",
462            "installation_id",
463            ".personality_migration",
464            ".sandbox_migration",
465            "cache",
466            "generated_images",
467            "mcp-oauth-locks",
468            "memories",
469            "plugins",
470            "rules",
471            "shell_snapshots",
472            "skills",
473            "thread-writer-locks",
474        ] {
475            link_runtime_resource(&native_home.join(entry), &root.join(entry))?;
476        }
477
478        if let Some(runtime_id) = runtime_id {
479            let source = find_codex_rollout(&native_home.join("sessions"), runtime_id)?
480                .ok_or_else(|| {
481                    Error::Other(format!(
482                        "could not find Codex rollout `{runtime_id}` below {}",
483                        native_home.join("sessions").display()
484                    ))
485                })?;
486            let relative = source.strip_prefix(&native_home).map_err(|_| {
487                Error::Other(format!(
488                    "Codex rollout {} is outside native home {}",
489                    source.display(),
490                    native_home.display()
491                ))
492            })?;
493            let projected = root.join(relative);
494            if let Some(parent) = projected.parent() {
495                std::fs::create_dir_all(parent)?;
496            }
497            std::fs::hard_link(&source, &projected).map_err(|error| {
498                Error::Other(format!(
499                    "could not project Codex rollout {} into isolated runtime home: {error}",
500                    source.display()
501                ))
502            })?;
503        }
504
505        launch
506            .env
507            .insert("CODEX_HOME".into(), root.to_string_lossy().into_owned());
508        Ok(Self { root, native_home })
509    }
510
511    fn started_rollout_path(&self, response: &Value) -> Result<PathBuf> {
512        let path = response
513            .pointer("/thread/path")
514            .and_then(Value::as_str)
515            .map(PathBuf::from)
516            .ok_or_else(|| {
517                Error::Other("Codex thread/start response omitted thread.path".into())
518            })?;
519        let relative = path.strip_prefix(&self.root).map_err(|_| {
520            Error::Other(format!(
521                "Codex created rollout {} outside isolated runtime home {}",
522                path.display(),
523                self.root.display()
524            ))
525        })?;
526        if !relative.starts_with("sessions") {
527            return Err(Error::Other(format!(
528                "Codex created non-session rollout {}",
529                path.display()
530            )));
531        }
532        Ok(path)
533    }
534
535    async fn publish_rollout(&self, path: &Path) -> Result<()> {
536        let relative = path.strip_prefix(&self.root).map_err(|_| {
537            Error::Other(format!(
538                "Codex created rollout {} outside isolated runtime home {}",
539                path.display(),
540                self.root.display()
541            ))
542        })?;
543        let publish_deadline = tokio::time::Instant::now() + Duration::from_secs(2);
544        while !path.is_file() {
545            if tokio::time::Instant::now() >= publish_deadline {
546                return Err(Error::Other(format!(
547                    "Codex did not create promised rollout {} within 2s",
548                    path.display()
549                )));
550            }
551            tokio::time::sleep(Duration::from_millis(10)).await;
552        }
553        let native = self.native_home.join(relative);
554        if let Some(parent) = native.parent() {
555            std::fs::create_dir_all(parent)?;
556        }
557        std::fs::hard_link(path, &native).map_err(|error| {
558            Error::Other(format!(
559                "could not publish Codex rollout {} to native home: {error}",
560                path.display()
561            ))
562        })
563    }
564
565    fn cleanup(&self) -> Result<()> {
566        match std::fs::remove_dir_all(&self.root) {
567            Ok(()) => Ok(()),
568            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
569            Err(error) => Err(Error::Other(format!(
570                "could not clean isolated Codex runtime home {}: {error}",
571                self.root.display()
572            ))),
573        }
574    }
575}
576
577impl Drop for CodexRuntimeHome {
578    fn drop(&mut self) {
579        let _ = self.cleanup();
580    }
581}
582
583/// Keeps a runtime's closing diagnostics short enough to read in an error.
584const STDERR_TAIL_LINES: usize = 20;
585const STDERR_TAIL_CHARACTERS: usize = 2_000;
586
587/// Reports a closed protocol together with whatever the runtime last said.
588fn closed_reason(recent_stderr: &std::collections::VecDeque<String>) -> String {
589    if recent_stderr.is_empty() {
590        return "runtime protocol closed".into();
591    }
592    let mut tail = recent_stderr
593        .iter()
594        .map(String::as_str)
595        .collect::<Vec<_>>()
596        .join(" | ");
597    if tail.chars().count() > STDERR_TAIL_CHARACTERS {
598        tail = tail
599            .chars()
600            .take(STDERR_TAIL_CHARACTERS)
601            .collect::<String>()
602            + "…";
603    }
604    format!("runtime protocol closed: {tail}")
605}
606
607fn is_stock_codex_launch(launch: &RuntimeLaunch) -> bool {
608    launch
609        .arguments
610        .iter()
611        .any(|argument| argument == "app-server")
612        && Path::new(&launch.program)
613            .file_name()
614            .and_then(|name| name.to_str())
615            .is_some_and(|name| name == "codex" || name == "codex.exe")
616}
617
618fn codex_native_home(launch: &RuntimeLaunch) -> Result<PathBuf> {
619    launch
620        .env
621        .get("CODEX_HOME")
622        .map(PathBuf::from)
623        .or_else(|| std::env::var_os("CODEX_HOME").map(PathBuf::from))
624        .or_else(|| {
625            std::env::var_os("HOME")
626                .map(PathBuf::from)
627                .map(|home| home.join(".codex"))
628        })
629        .ok_or_else(|| Error::Other("Codex runtime requires CODEX_HOME or HOME".into()))
630}
631
632fn supercode_runtime_root() -> PathBuf {
633    std::env::var_os("SUPERCODE_HOME")
634        .map(PathBuf::from)
635        .or_else(|| {
636            std::env::var_os("HOME")
637                .map(PathBuf::from)
638                .map(|home| home.join(".supercode"))
639        })
640        .unwrap_or_else(|| std::env::temp_dir().join("supercode"))
641        .join("runtime-homes")
642}
643
644fn find_codex_rollout(root: &Path, runtime_id: &str) -> Result<Option<PathBuf>> {
645    let entries = match std::fs::read_dir(root) {
646        Ok(entries) => entries,
647        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
648        Err(error) => return Err(error.into()),
649    };
650    let expected_suffix = format!("-{runtime_id}.jsonl");
651    for entry in entries {
652        let entry = entry?;
653        let kind = entry.file_type()?;
654        if kind.is_dir() {
655            if let Some(path) = find_codex_rollout(&entry.path(), runtime_id)? {
656                return Ok(Some(path));
657            }
658        } else if kind.is_file()
659            && entry
660                .file_name()
661                .to_str()
662                .is_some_and(|name| name.ends_with(&expected_suffix))
663        {
664            return Ok(Some(entry.path()));
665        }
666    }
667    Ok(None)
668}
669
670#[cfg(unix)]
671fn link_runtime_resource(source: &Path, target: &Path) -> Result<()> {
672    use std::os::unix::fs::symlink;
673
674    if source.exists() {
675        symlink(source, target)?;
676    }
677    Ok(())
678}
679
680#[cfg(not(unix))]
681fn link_runtime_resource(source: &Path, target: &Path) -> Result<()> {
682    if source.is_file() {
683        std::fs::copy(source, target)?;
684    }
685    Ok(())
686}
687
688#[cfg(unix)]
689fn set_private_directory(path: &Path) -> Result<()> {
690    use std::os::unix::fs::PermissionsExt;
691
692    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))?;
693    Ok(())
694}
695
696#[cfg(not(unix))]
697fn set_private_directory(_path: &Path) -> Result<()> {
698    Ok(())
699}
700
701impl Default for CodexRuntimeBackend {
702    fn default() -> Self {
703        Self::new()
704    }
705}
706
707impl CodexRuntimeBackend {
708    /// Use `codex app-server` from `PATH`.
709    pub fn new() -> Self {
710        Self {
711            launch: RuntimeLaunch {
712                program: "codex".into(),
713                arguments: vec!["app-server".into()],
714                env: BTreeMap::new(),
715            },
716        }
717    }
718
719    /// Use an explicit command prefix.
720    pub fn with_launch(launch: RuntimeLaunch) -> Self {
721        Self { launch }
722    }
723
724    async fn connect(
725        &self,
726        launch: Option<RuntimeLaunch>,
727        runtime_id: Option<&str>,
728    ) -> Result<(
729        Arc<JsonLineClient>,
730        mpsc::UnboundedReceiver<Value>,
731        RuntimeEndpoint,
732        Option<CodexRuntimeHome>,
733    )> {
734        let mut launch = launch.unwrap_or_else(|| self.launch.clone());
735        let runtime_home = if is_stock_codex_launch(&launch) {
736            Some(CodexRuntimeHome::prepare(&mut launch, runtime_id)?)
737        } else {
738            None
739        };
740        let (client, receiver, endpoint) =
741            JsonLineClient::spawn(&launch, None, false, "codex-app-server-jsonl").await?;
742        tokio::time::timeout(
743            CODEX_STARTUP_TIMEOUT,
744            client.request(
745                "initialize",
746                json!({
747                    "clientInfo": {
748                        "name": "supercode",
749                        "title": "Supercode",
750                        "version": env!("CARGO_PKG_VERSION"),
751                    }
752                }),
753            ),
754        )
755        .await
756        .map_err(|_| Error::Other("Codex app-server initialize timed out after 10s".into()))??;
757        client.notify("initialized", json!({})).await?;
758        Ok((client, receiver, endpoint, runtime_home))
759    }
760
761    async fn open_thread(
762        &self,
763        method: &str,
764        params: Value,
765        launch: Option<RuntimeLaunch>,
766        runtime_id: Option<&str>,
767    ) -> Result<Box<dyn RuntimeConnection>> {
768        let (client, receiver, endpoint, runtime_home) = self.connect(launch, runtime_id).await?;
769        let response = tokio::time::timeout(CODEX_STARTUP_TIMEOUT, client.request(method, params))
770            .await
771            .map_err(|_| Error::Other(format!("Codex {method} timed out after 10s")))??;
772        let thread_id = response
773            .pointer("/thread/id")
774            .and_then(Value::as_str)
775            .ok_or_else(|| Error::Other(format!("Codex {method} response omitted thread.id")))?
776            .to_string();
777        let unpublished_rollout = if method == "thread/start" {
778            runtime_home
779                .as_ref()
780                .map(|home| home.started_rollout_path(&response))
781                .transpose()?
782        } else {
783            None
784        };
785        Ok(Box::new(CodexRuntimeConnection {
786            handle: RuntimeHandle {
787                harness: HarnessId::from(HarnessId::CODEX),
788                runtime_id: thread_id,
789                endpoint,
790            },
791            client,
792            receiver,
793            active_turn: None,
794            runtime_home,
795            unpublished_rollout,
796        }))
797    }
798}
799
800#[async_trait]
801impl RuntimeBackend for CodexRuntimeBackend {
802    fn harness(&self) -> HarnessId {
803        HarnessId::from(HarnessId::CODEX)
804    }
805
806    fn capabilities(&self) -> RuntimeCapabilities {
807        RuntimeCapabilities {
808            start_session: true,
809            resume_session: true,
810            // A new app-server can resume the same stored thread, but stock
811            // Codex does not let it join an arbitrary already-running TUI's
812            // transport/event fanout.
813            attach_existing_process: false,
814            send_input: true,
815            stream_events: true,
816            interrupt: true,
817            steer: true,
818            respond_to_requests: true,
819        }
820    }
821
822    async fn start(&self, request: RuntimeStartRequest) -> Result<Box<dyn RuntimeConnection>> {
823        let mut params = json!({"cwd": request.cwd});
824        if let Some(policy) = request.approval_policy {
825            params["approvalPolicy"] = json!(policy);
826        }
827        self.open_thread("thread/start", params, request.launch, None)
828            .await
829    }
830
831    async fn attach(&self, request: RuntimeAttachRequest) -> Result<Box<dyn RuntimeConnection>> {
832        let mut params = json!({"threadId": request.runtime_id});
833        if let Some(cwd) = request.cwd {
834            params["cwd"] = json!(cwd);
835        }
836        if let Some(policy) = request.approval_policy {
837            params["approvalPolicy"] = json!(policy);
838        }
839        let runtime_id = request.runtime_id.clone();
840        self.open_thread("thread/resume", params, request.launch, Some(&runtime_id))
841            .await
842    }
843}
844
845struct CodexRuntimeConnection {
846    handle: RuntimeHandle,
847    client: Arc<JsonLineClient>,
848    receiver: mpsc::UnboundedReceiver<Value>,
849    active_turn: Option<String>,
850    runtime_home: Option<CodexRuntimeHome>,
851    unpublished_rollout: Option<PathBuf>,
852}
853
854#[async_trait]
855impl RuntimeConnection for CodexRuntimeConnection {
856    fn handle(&self) -> &RuntimeHandle {
857        &self.handle
858    }
859
860    async fn send_input(&mut self, input: RuntimeInput) -> Result<Option<String>> {
861        let mut parts = Vec::new();
862        if !input.text.is_empty() {
863            parts.push(json!({"type": "text", "text": input.text}));
864        }
865        parts.extend(
866            input
867                .image_urls
868                .into_iter()
869                .map(|url| json!({"type": "image", "url": url})),
870        );
871        let response = self
872            .client
873            .request(
874                "turn/start",
875                json!({
876                    "threadId": self.handle.runtime_id,
877                    "input": parts,
878                }),
879            )
880            .await?;
881        let turn_id = response
882            .pointer("/turn/id")
883            .and_then(Value::as_str)
884            .map(str::to_owned);
885        if let (Some(home), Some(path)) = (
886            self.runtime_home.as_ref(),
887            self.unpublished_rollout.as_ref(),
888        ) {
889            home.publish_rollout(path).await?;
890            self.unpublished_rollout = None;
891        }
892        self.active_turn = turn_id.clone();
893        Ok(turn_id)
894    }
895
896    async fn next_event(&mut self) -> Result<Option<HarnessEvent>> {
897        let Some(payload) = self.receiver.recv().await else {
898            return Ok(None);
899        };
900        let kind = payload
901            .get("method")
902            .and_then(Value::as_str)
903            .map(str::to_owned)
904            .unwrap_or_else(|| "protocol".into());
905        if kind == "turn/completed" {
906            self.active_turn = None;
907        }
908        Ok(Some(HarnessEvent {
909            sequence: None,
910            kind,
911            payload,
912        }))
913    }
914
915    async fn interrupt(&mut self) -> Result<()> {
916        let Some(turn_id) = self.active_turn.as_ref() else {
917            return Err(Error::Other("Codex has no active turn to interrupt".into()));
918        };
919        self.client
920            .request(
921                "turn/interrupt",
922                json!({"threadId": self.handle.runtime_id, "turnId": turn_id}),
923            )
924            .await?;
925        Ok(())
926    }
927
928    async fn steer(&mut self, text: String) -> Result<()> {
929        let Some(turn_id) = self.active_turn.as_ref() else {
930            return Err(Error::Other("Codex has no active turn to steer".into()));
931        };
932        self.client
933            .request(
934                "turn/steer",
935                json!({
936                    "threadId": self.handle.runtime_id,
937                    "expectedTurnId": turn_id,
938                    "input": [{"type":"text", "text":text}],
939                }),
940            )
941            .await?;
942        Ok(())
943    }
944
945    async fn respond(&mut self, request_id: Value, response: Value) -> Result<()> {
946        self.client.respond(request_id, response).await
947    }
948
949    async fn close(&mut self) -> Result<()> {
950        self.client.close().await?;
951        if let Some(home) = self.runtime_home.take() {
952            home.cleanup()?;
953        }
954        Ok(())
955    }
956}
957
958type PendingResponse = oneshot::Sender<std::result::Result<Value, String>>;
959type PendingResponses = Arc<Mutex<HashMap<u64, PendingResponse>>>;
960
961/// A spawned child that LEADS its own process group (`process_group(0)`), so
962/// dropping it signals the whole group rather than just the leader.
963///
964/// `kill_on_drop(true)` reaches the direct child only. Harness launchers are
965/// commonly package-manager shims that spawn the real worker — the worker
966/// holding the protocol pipes — so a dropped launcher leaves that worker
967/// running with nothing attached to it. Dropping is not a rare path: it is
968/// what a blown deadline does to a launch or a control call still in flight.
969///
970/// The group is signalled only while `id()` still answers, i.e. while this
971/// process has not been reaped here. A reaped leader's pid can be reused by
972/// an unrelated group, and killing that group would be someone else's
973/// outage; a graceful `close()` that reaped the group therefore makes this
974/// drop a no-op.
975pub(super) struct GroupLeader(Child);
976
977impl std::ops::Deref for GroupLeader {
978    type Target = Child;
979
980    fn deref(&self) -> &Child {
981        &self.0
982    }
983}
984
985impl std::ops::DerefMut for GroupLeader {
986    fn deref_mut(&mut self) -> &mut Child {
987        &mut self.0
988    }
989}
990
991impl Drop for GroupLeader {
992    fn drop(&mut self) {
993        #[cfg(unix)]
994        if let Some(pid) = self.0.id() {
995            crate::lsp::kill_process_group(pid);
996        }
997    }
998}
999
1000pub(super) struct JsonLineClient {
1001    stdin: Mutex<ChildStdin>,
1002    child: Mutex<GroupLeader>,
1003    pending: PendingResponses,
1004    next_id: Mutex<u64>,
1005    include_jsonrpc: bool,
1006    events: mpsc::UnboundedSender<Value>,
1007    process_group: Option<u32>,
1008}
1009
1010impl JsonLineClient {
1011    pub(super) async fn spawn(
1012        launch: &RuntimeLaunch,
1013        cwd: Option<&std::path::Path>,
1014        include_jsonrpc: bool,
1015        protocol: &str,
1016    ) -> Result<(Arc<Self>, mpsc::UnboundedReceiver<Value>, RuntimeEndpoint)> {
1017        let mut command = Command::new(&launch.program);
1018        command
1019            .args(&launch.arguments)
1020            .envs(&launch.env)
1021            .stdin(Stdio::piped())
1022            .stdout(Stdio::piped())
1023            .stderr(Stdio::piped())
1024            .kill_on_drop(true);
1025        // Package-manager shims commonly spawn a native worker. Isolate the
1026        // complete adapter tree so close can reap it instead of orphaning the
1027        // worker with inherited protocol handles.
1028        #[cfg(unix)]
1029        command.process_group(0);
1030        if let Some(cwd) = cwd {
1031            command.current_dir(cwd);
1032        }
1033        let mut child = command.spawn().map_err(|error| {
1034            Error::Other(format!("could not launch {}: {error}", launch.program))
1035        })?;
1036        let pid = child.id();
1037        let stdin = child
1038            .stdin
1039            .take()
1040            .ok_or_else(|| Error::Other("runtime child has no stdin".into()))?;
1041        let stdout = child
1042            .stdout
1043            .take()
1044            .ok_or_else(|| Error::Other("runtime child has no stdout".into()))?;
1045        let stderr = child
1046            .stderr
1047            .take()
1048            .ok_or_else(|| Error::Other("runtime child has no stderr".into()))?;
1049        let pending: PendingResponses = Arc::new(Mutex::new(HashMap::new()));
1050        let (events_tx, events_rx) = mpsc::unbounded_channel();
1051        let reader_events = events_tx.clone();
1052        let reader_pending = pending.clone();
1053        tokio::spawn(async move {
1054            let mut stdout_lines = BufReader::new(stdout).lines();
1055            let mut stderr_lines = BufReader::new(stderr).lines();
1056            let mut stdout_open = true;
1057            let mut stderr_open = true;
1058            // A runtime that dies mid-handshake explains itself on stderr and
1059            // nowhere else. Events reach only an already-started runtime, so
1060            // without this the caller is told the protocol closed and never
1061            // told why.
1062            let mut recent_stderr: std::collections::VecDeque<String> =
1063                std::collections::VecDeque::new();
1064            while stdout_open || stderr_open {
1065                tokio::select! {
1066                    line = stdout_lines.next_line(), if stdout_open => match line {
1067                        Ok(Some(line)) => {
1068                            let Ok(value) = serde_json::from_str::<Value>(&line) else {
1069                                let _ = reader_events.send(json!({"type": "malformed_output", "line": line}));
1070                                continue;
1071                            };
1072                            let response_id = value.get("id").and_then(Value::as_u64);
1073                            let is_response = value.get("result").is_some() || value.get("error").is_some();
1074                            if let Some(id) = response_id.filter(|_| is_response) {
1075                                if let Some(sender) = reader_pending.lock().await.remove(&id) {
1076                                    let result = if let Some(error) = value.get("error") {
1077                                        Err(error.to_string())
1078                                    } else {
1079                                        Ok(value.get("result").cloned().unwrap_or(Value::Null))
1080                                    };
1081                                    let _ = sender.send(result);
1082                                    continue;
1083                                }
1084                            }
1085                            let _ = reader_events.send(value);
1086                        }
1087                        Ok(None) => stdout_open = false,
1088                        Err(error) => {
1089                            let _ = reader_events.send(json!({"type": "transport_error", "message": error.to_string()}));
1090                            stdout_open = false;
1091                        }
1092                    },
1093                    line = stderr_lines.next_line(), if stderr_open => match line {
1094                        Ok(Some(line)) => {
1095                            if !line.trim().is_empty() {
1096                                if recent_stderr.len() == STDERR_TAIL_LINES {
1097                                    recent_stderr.pop_front();
1098                                }
1099                                recent_stderr.push_back(line.clone());
1100                            }
1101                            let _ = reader_events.send(json!({"type": "transport_stderr", "line": line}));
1102                        }
1103                        Ok(None) => stderr_open = false,
1104                        Err(error) => {
1105                            let _ = reader_events.send(json!({"type": "transport_error", "message": error.to_string()}));
1106                            stderr_open = false;
1107                        }
1108                    }
1109                }
1110            }
1111            let _ = reader_events.send(json!({"type": "transport_closed"}));
1112            let reason = closed_reason(&recent_stderr);
1113            let mut pending = reader_pending.lock().await;
1114            for (_, sender) in pending.drain() {
1115                let _ = sender.send(Err(reason.clone()));
1116            }
1117        });
1118        let endpoint = RuntimeEndpoint::LocalProcess {
1119            pid,
1120            command: std::iter::once(launch.program.clone())
1121                .chain(launch.arguments.iter().cloned())
1122                .collect(),
1123            protocol: protocol.into(),
1124        };
1125        Ok((
1126            Arc::new(Self {
1127                stdin: Mutex::new(stdin),
1128                child: Mutex::new(GroupLeader(child)),
1129                pending,
1130                next_id: Mutex::new(1),
1131                include_jsonrpc,
1132                events: events_tx,
1133                process_group: pid,
1134            }),
1135            events_rx,
1136            endpoint,
1137        ))
1138    }
1139
1140    pub(super) async fn request(&self, method: &str, params: Value) -> Result<Value> {
1141        let (_id, rx) = self.begin_request(method, params).await?;
1142        rx.await
1143            .map_err(|_| Error::Other("runtime response channel closed".into()))?
1144            .map_err(|message| {
1145                Error::Other(format!("runtime request `{method}` failed: {message}"))
1146            })
1147    }
1148
1149    pub(super) async fn begin_request(
1150        &self,
1151        method: &str,
1152        params: Value,
1153    ) -> Result<(u64, oneshot::Receiver<std::result::Result<Value, String>>)> {
1154        let id = {
1155            let mut next = self.next_id.lock().await;
1156            let id = *next;
1157            *next += 1;
1158            id
1159        };
1160        let (tx, rx) = oneshot::channel();
1161        self.pending.lock().await.insert(id, tx);
1162        let mut request = json!({"id": id, "method": method, "params": params});
1163        if self.include_jsonrpc {
1164            request["jsonrpc"] = json!("2.0");
1165        }
1166        if let Err(error) = self.write(&request).await {
1167            self.pending.lock().await.remove(&id);
1168            return Err(error);
1169        }
1170        Ok((id, rx))
1171    }
1172
1173    pub(super) async fn notify(&self, method: &str, params: Value) -> Result<()> {
1174        let mut notification = json!({"method": method, "params": params});
1175        if self.include_jsonrpc {
1176            notification["jsonrpc"] = json!("2.0");
1177        }
1178        self.write(&notification).await
1179    }
1180
1181    pub(super) async fn respond(&self, id: Value, result: Value) -> Result<()> {
1182        let mut response = json!({"id": id, "result": result});
1183        if self.include_jsonrpc {
1184            response["jsonrpc"] = json!("2.0");
1185        }
1186        self.write(&response).await
1187    }
1188
1189    async fn write(&self, value: &Value) -> Result<()> {
1190        let mut stdin = self.stdin.lock().await;
1191        stdin.write_all(value.to_string().as_bytes()).await?;
1192        stdin.write_all(b"\n").await?;
1193        stdin.flush().await?;
1194        Ok(())
1195    }
1196
1197    pub(super) fn emit(&self, value: Value) {
1198        let _ = self.events.send(value);
1199    }
1200
1201    pub(super) async fn close(&self) -> Result<()> {
1202        let mut child = self.child.lock().await;
1203        // `process_group` is a pid COPY taken at spawn, and a reaped pid
1204        // belongs to whoever the OS hands it to next. Close is called more
1205        // than once — a hosted runtime closes on shutdown, on transport end,
1206        // and again when its host task exits — so the second call must find
1207        // this child still unreaped here before signalling anything, exactly
1208        // as the raw-line transport does.
1209        if child.try_wait()?.is_some() {
1210            return Ok(());
1211        }
1212        #[cfg(unix)]
1213        {
1214            match self.process_group {
1215                Some(pid) => crate::lsp::kill_process_group(pid),
1216                None => child.kill().await?,
1217            }
1218            tokio::time::timeout(Duration::from_secs(3), child.wait())
1219                .await
1220                .map_err(|_| Error::Other("timed out reaping runtime process group".into()))??;
1221        }
1222        #[cfg(not(unix))]
1223        child.kill().await?;
1224        Ok(())
1225    }
1226}
1227
1228#[cfg(test)]
1229mod tests {
1230    use super::*;
1231
1232    #[test]
1233    fn closed_reason_reports_the_runtime_last_words() {
1234        let mut stderr = std::collections::VecDeque::new();
1235        stderr.push_back("grok: unsupported syscall SYS_execve".to_string());
1236        assert_eq!(
1237            closed_reason(&stderr),
1238            "runtime protocol closed: grok: unsupported syscall SYS_execve",
1239        );
1240    }
1241
1242    #[test]
1243    fn closed_reason_stays_bare_without_stderr() {
1244        assert_eq!(
1245            closed_reason(&std::collections::VecDeque::new()),
1246            "runtime protocol closed",
1247        );
1248    }
1249
1250    #[test]
1251    fn closed_reason_truncates_a_long_tail() {
1252        let mut stderr = std::collections::VecDeque::new();
1253        stderr.push_back("x".repeat(STDERR_TAIL_CHARACTERS + 500));
1254        let reason = closed_reason(&stderr);
1255        assert!(reason.ends_with('…'), "{reason}");
1256        assert_eq!(
1257            reason.chars().count(),
1258            "runtime protocol closed: ".chars().count() + STDERR_TAIL_CHARACTERS + 1,
1259        );
1260    }
1261
1262    fn scratch_home(tag: &str) -> PathBuf {
1263        let dir = std::env::temp_dir().join(format!(
1264            "supercode-connect-launch-{tag}-{}-{}",
1265            std::process::id(),
1266            std::time::SystemTime::now()
1267                .duration_since(std::time::UNIX_EPOCH)
1268                .unwrap()
1269                .as_nanos()
1270        ));
1271        std::fs::create_dir_all(&dir).unwrap();
1272        dir
1273    }
1274
1275    #[test]
1276    fn connect_launch_resolves_address_and_auth_from_the_harness_config() {
1277        let home = scratch_home("resolve");
1278        std::fs::create_dir_all(home.join(".gateway")).unwrap();
1279        std::fs::write(
1280            home.join(".gateway/config.json"),
1281            r#"{"gateway": {"url": "ws://127.0.0.1:18789/", "auth": {"token": "secret-credential"}}}"#,
1282        )
1283        .unwrap();
1284        let launch = RuntimeConnectLaunch {
1285            config_path: "~/.gateway/config.json".into(),
1286            address_pointer: "/gateway/url".into(),
1287            port_pointer: None,
1288            default_address: None,
1289            auth_pointer: Some("/gateway/auth/token".into()),
1290            protocol: "acp-v1-jsonrpc".into(),
1291        };
1292        let resolved = launch.resolve(&home).unwrap();
1293        assert_eq!(resolved.address, "ws://127.0.0.1:18789");
1294        assert_eq!(
1295            resolved.auth.as_ref().unwrap().secret(),
1296            "secret-credential"
1297        );
1298        let debugged = format!("{resolved:?}");
1299        assert!(!debugged.contains("secret-credential"));
1300        assert!(debugged.contains("<redacted>"));
1301    }
1302
1303    #[test]
1304    fn connect_launch_resolution_fails_closed_without_echoing_config_contents() {
1305        let home = scratch_home("fail-closed");
1306        let launch = RuntimeConnectLaunch {
1307            config_path: "~/missing.json".into(),
1308            address_pointer: "/url".into(),
1309            port_pointer: None,
1310            default_address: None,
1311            auth_pointer: None,
1312            protocol: "acp-v1-jsonrpc".into(),
1313        };
1314        assert!(launch.resolve(&home).is_err());
1315
1316        std::fs::write(
1317            home.join("present.json"),
1318            r#"{"url": "", "auth": {"token": "secret-credential"}}"#,
1319        )
1320        .unwrap();
1321        let empty_address = RuntimeConnectLaunch {
1322            config_path: "~/present.json".into(),
1323            address_pointer: "/url".into(),
1324            port_pointer: None,
1325            default_address: None,
1326            auth_pointer: None,
1327            protocol: "acp-v1-jsonrpc".into(),
1328        };
1329        let error = empty_address.resolve(&home).unwrap_err();
1330        assert!(error.to_string().contains("/url"));
1331        assert!(!error.to_string().contains("secret-credential"));
1332
1333        let missing_auth = RuntimeConnectLaunch {
1334            config_path: "~/present.json".into(),
1335            address_pointer: "/auth/token".into(),
1336            port_pointer: None,
1337            default_address: None,
1338            auth_pointer: Some("/absent".into()),
1339            protocol: "acp-v1-jsonrpc".into(),
1340        };
1341        let error = missing_auth.resolve(&home).unwrap_err();
1342        assert!(error.to_string().contains("/absent"));
1343        assert!(!error.to_string().contains("secret-credential"));
1344    }
1345
1346    #[test]
1347    fn connect_launch_round_trips_through_json() {
1348        let launch = RuntimeConnectLaunch {
1349            config_path: "~/.openclaw/openclaw.json".into(),
1350            address_pointer: "/gateway/url".into(),
1351            port_pointer: None,
1352            default_address: None,
1353            auth_pointer: Some("/gateway/token".into()),
1354            protocol: "acp-v1-jsonrpc".into(),
1355        };
1356        let encoded = serde_json::to_value(&launch).unwrap();
1357        let decoded: RuntimeConnectLaunch = serde_json::from_value(encoded).unwrap();
1358        assert_eq!(decoded, launch);
1359        let minimal: RuntimeConnectLaunch = serde_json::from_value(json!({
1360            "config_path": "~/.gateway.json",
1361            "address_pointer": "/url",
1362            "protocol": "http",
1363        }))
1364        .unwrap();
1365        assert_eq!(minimal.auth_pointer, None);
1366    }
1367
1368    #[test]
1369    fn codex_capabilities_do_not_claim_arbitrary_process_attach() {
1370        let capabilities = CodexRuntimeBackend::new().capabilities();
1371        assert!(capabilities.start_session);
1372        assert!(capabilities.resume_session);
1373        assert!(!capabilities.attach_existing_process);
1374        assert!(capabilities.send_input);
1375        assert!(capabilities.stream_events);
1376        assert!(capabilities.interrupt);
1377        assert!(capabilities.steer);
1378    }
1379
1380    #[test]
1381    fn runtime_handle_is_language_neutral_json() {
1382        let handle = RuntimeHandle {
1383            harness: HarnessId::from(HarnessId::CODEX),
1384            runtime_id: "thread-1".into(),
1385            endpoint: RuntimeEndpoint::LocalProcess {
1386                pid: Some(42),
1387                command: vec!["codex".into(), "app-server".into()],
1388                protocol: "codex-app-server-jsonl".into(),
1389            },
1390        };
1391        let encoded = serde_json::to_string(&handle).unwrap();
1392        assert_eq!(
1393            serde_json::from_str::<RuntimeHandle>(&encoded).unwrap(),
1394            handle
1395        );
1396    }
1397
1398    #[cfg(unix)]
1399    #[tokio::test]
1400    async fn codex_adapter_performs_handshake_start_and_turn() {
1401        let script = r#"
1402            i=0
1403            while IFS= read -r line; do
1404              i=$((i + 1))
1405              case "$i" in
1406                1) printf '%s\n' '{"id":1,"result":{"userAgent":"mock"}}' ;;
1407                2) ;;
1408                3) printf '%s\n' '{"id":2,"result":{"thread":{"id":"thr_mock"}}}' ;;
1409                4)
1410                  printf '%s\n' '{"id":3,"result":{"turn":{"id":"turn_mock"}}}'
1411                  printf '%s\n' '{"method":"turn/started","params":{"turn":{"id":"turn_mock"}}}'
1412                  ;;
1413                5) printf '%s\n' '{"id":4,"result":{"turnId":"turn_mock"}}' ;;
1414              esac
1415            done
1416        "#;
1417        let backend = CodexRuntimeBackend::with_launch(RuntimeLaunch {
1418            program: "/bin/sh".into(),
1419            arguments: vec!["-c".into(), script.into()],
1420            env: BTreeMap::new(),
1421        });
1422        let mut connection = backend
1423            .start(RuntimeStartRequest {
1424                cwd: std::env::current_dir().unwrap(),
1425                launch: None,
1426                mcp_servers: Vec::new(),
1427                approval_policy: None,
1428            })
1429            .await
1430            .unwrap();
1431        assert_eq!(connection.handle().runtime_id, "thr_mock");
1432        assert_eq!(
1433            connection
1434                .send_input(RuntimeInput {
1435                    text: "hi".into(),
1436                    image_urls: Vec::new(),
1437                })
1438                .await
1439                .unwrap()
1440                .as_deref(),
1441            Some("turn_mock")
1442        );
1443        connection.steer("focus on tests".into()).await.unwrap();
1444        assert_eq!(
1445            connection.next_event().await.unwrap().unwrap().kind,
1446            "turn/started"
1447        );
1448        connection.close().await.unwrap();
1449    }
1450}