Repository navigation
[codex] Add env_switch for runtime SSH/Docker execution targets - #1
Open
yukimaru77 wants to merge 17 commits into
Open
yukimaru77 wants to merge 17 commits into
yukimaru77 wants to merge 17 commits into
Conversation
Adds a provision module that bootstraps a version-matched codex exec-server onto a remote target, in the spirit of VS Code Remote SSH: - RemoteLauncher (docker exec -i / ssh -T) with POSIX-safe quoting: ssh re-parses argv on the remote shell, so scripts are collapsed into a single quoted argument (docker passes argv verbatim). - probe() collects uname/arch/HOME and any existing codex install. - ensure_remote_codex() resolves the desired version (exact, host version, or latest release), downloads codex-package-<triple>.tar.gz on the HOST, verifies it against codex-package_SHA256SUMS, then streams the tarball through the launcher's stdin - the remote needs only sh/tar/gzip, no network access or credentials. - EnvironmentManager::upsert_stdio_environment() registers the resulting stdio-transport environment at runtime, mirroring the existing ws-only upsert_environment(). Co-Authored-By: Claude Fable 5 <[email protected]>
Gated behind the under-development feature flag env_switch (default
off). When enabled, the model can call env_switch to move ALL
subsequent exec/file tool calls into a docker container or ssh host,
or back to the local machine - without moving the codex process,
session state, auth, or history.
- env_switch { target: local|docker|ssh, container?, host?, cwd? }
- Provisions a matching codex exec-server on the target via
codex_exec_server::provision (auto-download when absent), registers
a stdio-transport environment, and swaps the thread's environment
selections.
- The switch takes effect on the next turn: the handler defers the
pending continuation to the next turn and interrupts the current one
shortly after the tool output is recorded, so a single turn never
mixes environments.
- Returning to local restores the process's own working directory
rather than carrying the remote cwd back.
- Works identically for root and sub-agent threads.
Co-Authored-By: Claude Fable 5 <[email protected]>
When env_switch moves tool execution into a container or ssh host, the status line now shows where tools are running: gpt-5.5 . docker env-remote-test -> . [whale] env-remote-test gpt-5.5 . ssh dgx -> . [link] dgx Reuses the existing ThreadSettingsUpdated notification: the settings snapshot now carries active_environment_id (None for local), emitted by the env_switch handler after each environment swap. Reverting to local clears the badge and restores the cwd display. Co-Authored-By: Claude Fable 5 <[email protected]>
Security / correctness: - Quote all caller/model-controlled values (cwd, codex path, install paths) interpolated into remote sh -c scripts via posix_single_quote; an attacker-controlled cwd like "/x; rm -rf /" is now a literal dir name, not a command. (ssh AND docker, since both run sh -c.) - Bound every remote subprocess (probe / install / version-check / mkdir) with tokio timeouts so a hung ssh/docker can no longer block the tool call (and turn) forever. - Tie the deferred-continuation self-interrupt to the originating turn's sub_id so it never aborts a turn that already ended naturally. - Make the continuation idempotent (AtomicBool) so a double env_switch in one turn doesn't queue two stale continuations. - Gate the tool on environment_mode.has_environment() like the other environment-aware tools, so it isn't advertised where it can't work. Robustness / networking: - Use the shared codex-client HTTP builder so CODEX_CA_CERTIFICATE and proxy settings are honored when contacting GitHub. - Parse releases/latest with serde (tag_name) instead of a quote-split, and authenticate with GITHUB_TOKEN/GH_TOKEN when present (lifts the 60 req/hr anonymous limit that otherwise breaks provisioning). - Probe before resolving the version: reuse an existing remote binary offline when the policy allows, so a routine switch needs no network. Cleanup: - Single source of truth for version extraction (raw --version parsed in one place); drop the dead argv_prefix; truncate the status-line environment badge like the cwd display; remove a stale scaffolding TODO. Co-Authored-By: Claude Fable 5 <[email protected]>
…rupt) The previous design swapped the thread's sticky environment and forced a self-interrupt + deferred continuation to make the switch take effect, because a turn's environment is frozen at turn start. That interrupt collides with the /goal pursuit loop (and the headless exec loop): the turn is interrupted but the continuation never resumes, so work stalls. Reworked env_switch to be side-effect-free and per-tool-call instead: - env_switch now only provisions + registers the remote codex as a named environment (docker:<c> / ssh:<host>) and returns its id to the model. It does NOT interrupt the turn, swap the default, or schedule a continuation. Removed schedule_continuation, set_thread_environments, and the TurnContext.continuation_scheduled flag entirely. - Tools (shell/exec_command/apply_patch/view_image) carry environment_id whenever the env_switch feature is on, so the model targets a specific environment per call. resolve_tool_environment now falls back to a live EnvironmentManager lookup (with cwd recorded per environment in SessionServices.dynamic_environment_cwds) so a dynamically registered environment is usable in the same turn. - Omitting environment_id keeps running on the local host. A single turn can therefore mix host and container work, and a sub-agent can switch in isolation without affecting main. Verified in the codex TUI: /goal pursuit + switch now completes (no 'Conversation interrupted'), host+container mix in one turn, sub-agent isolated switch, all on a freshly provisioned container. Co-Authored-By: Claude Fable 5 <[email protected]>
Replace the fixed docker|ssh launcher with an ordered list of transport
hops, so environments can be composed to any depth: ssh-then-docker,
ssh-then-ssh-then-docker, etc. The core idea is unchanged - open a pipe
whose stdin/stdout speak the codex exec-server protocol - so nesting is
just building the argv that opens that pipe.
- RemoteLauncher is now a list of hops (Hop = Docker{container} |
Ssh{host}); argv is synthesized by folding inner-to-outer. Docker
prepends "docker exec -i <c>" verbatim (execve, no shell); Ssh wraps
the composed tokens with shell_join (each token POSIX single-quoted)
into one argument the remote login shell re-parses. N ssh layers means
N quoting levels, so metacharacters survive intact to the innermost
sh -c. Both the exec-server run argv and the provision/probe scripts
go through the same fold.
- env_switch tool gains an optional hops array (outer-to-inner;
{type: ssh|docker, host?, container?}); target/container/host remain
as the single-hop shorthand. environment_id reflects the chain, e.g.
"ssh:dgx>docker:c".
Verified in the codex TUI under an active /goal: ssh into a real remote
host (dgx), create an alpine container there, env_switch into that
container via the two-hop chain (auto-provisioning codex inside it),
run hostname into a file and cat it back - third-party confirmed in the
nested container.
Co-Authored-By: Claude Fable 5 <[email protected]>
…hop)
Entering a container that lives inside an environment you already switched
into no longer requires re-spelling the whole chain. env_switch gains:
- `base`: an existing environment_id to extend (parsed back into hops via
RemoteLauncher::from_id, the inverse of id()).
- `extend`: a single hop ({type: ssh|docker, host?, container?}) appended
to the base.
When `extend` is given without `base`, the base defaults to the most recent
launcher for the current thread (a per-thread cursor in SessionServices,
keyed by ThreadId so sub-agents stay isolated). So after switching to
`ssh:dgx`, `extend={docker, envswitch-rel}` yields
`ssh:dgx>docker:envswitch-rel` with no need to repeat the ssh hop.
Absolute modes (hops / target+container/host) are unchanged.
Verified in the codex TUI: switch to a real ssh host, create a container
there, then relative-extend (extend-only, thread cursor) into that
container, run hostname into a file and cat it back; third-party confirmed.
Co-Authored-By: Claude Fable 5 <[email protected]>
…t shell When a command ran in a switched environment it was wrapped in the host login shell (e.g. /bin/zsh -lc ...). Containers/hosts without zsh rejected the first attempt and the model had to retry with an explicit shell. The probe now reports the remote's preferred shell ($SHELL if it resolves, else bash, else sh) as a CODEX_SHELL line; it flows through ProvisionedCodex into a per-environment map (SessionServices.dynamic_environment_shells) and onto the synthesized TurnEnvironment.shell. Both exec paths honor it: - shell_command (to_exec_params) takes an environment_shell. - exec_command (unified_exec) passes the environment's shell as the default shell to get_command (an explicit `shell` arg from the model still wins). The TurnEnvironment.shell field existed but was previously ignored on both paths; this wires it. Verified in the codex TUI: a fresh debian container switch now runs the first exec_command on the remote shell and succeeds on the first try (no /bin/zsh rejection, no retry). Co-Authored-By: Claude Fable 5 <[email protected]>
The env_switch description still said it makes "ALL subsequent tools run in the target environment", which is stale after the item-level redesign and misleads the model into thinking one call switches everything. It also never said WHEN to use the tool, so the model only reached for it when the user named it explicitly. - env_switch description now states the item-level contract (returns an environment_id; pass it per tool call; omit to stay on host; a turn can mix host and remote), and adds an explicit WHEN-TO-USE: call it whenever a task targets files/commands in a container or remote host, without needing the user to mention env_switch. Multi-hop (hops) and relative (base/extend) usage retained. - The environment_id parameter on shell / exec_command / view_image now says to pass the id returned by env_switch (e.g. docker:foo, ssh:dgx>docker:c), instead of the opaque "id from <environment_context>". Verified in the codex TUI: with no mention of env_switch, "write to /root/x in the env-remote-test docker container" made the model call env_switch on its own and run exec_command with environment_id set, succeeding on the first try. Co-Authored-By: Claude Fable 5 <[email protected]>
…obustness) Hardening and correctness pass from a 6-perspective review of the branch. Security (launcher.rs): - Argument-injection fix: insert `--` end-of-options before host/container in every hop, and validate hop values (reject empty, leading `-`, and `>`), so a value like `-oProxyCommand=...` can no longer be parsed as an ssh/docker flag (was local RCE). from_id validates too. - SSH hardening: run ssh with `-T -q -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o LogLevel=ERROR` so connections never hang on a password/host-key prompt and MOTD/banners cannot corrupt the JSON-RPC stdout stream. Correctness (core): - Sub-agent metadata fix: env cwd/shell and the relative-mode launcher cursor moved from per-session SessionServices into the shared EnvironmentManager, so a sub-agent (which shares the manager Arc but gets fresh services) no longer resolves a registered remote env with the host cwd/shell. Metadata is written before the environment is registered to avoid a parallel-call race. - resolve_tool_environment: `local` maps directly to the primary env; a remote env with no recorded cwd falls back to `/` (never the host cwd). - Derive the remote exec-server sandbox/approval flags from the host turn policy instead of hardcoding danger-full-access/never. Robustness (provision): - Stream the package download to a temp file with an incremental SHA-256 and only pipe it to the remote after the digest verifies (O(1) memory, no 85MB buffer racing the 300s timeout). - Map GitHub 403/429 and 404 to actionable errors; normalize version strings before comparison; longer initialize timeout for provisioned stdio; warn on dev-build reuse; surface the provision fallback warning to the model. Cleanup: delete dead emit_thread_settings_applied; honest display-only badge doc; drop duplicate id in the success message; bound the metadata maps. Tests: hop_from_arg validation, EnvironmentManager metadata round-trip, resolve_tool_environment branches, from_id rejection. Co-Authored-By: Claude Fable 5 <[email protected]>
yukimaru77
pushed a commit
that referenced
this pull request
Jun 14, 2026
## Stack 1. [1 of 3] Support long raw TUI goal objectives - openai#27508 2. [2 of 3] Support long pasted text in TUI goals - openai#27509 3. **[3 of 3] Support images in TUI goals** - this PR ## Why The first two PRs make goal definitions resilient to long text, but `/goal` still dropped image inputs from the composer. That meant a user could attach images while defining a goal and the resulting goal continuation would not have any useful reference to those images. Goal state still persists only objective text, so image inputs need to become paths or URLs that the agent can read later. ## What Changed - Extends TUI `GoalDraft` with local image attachments and remote image URLs. - Copies local goal images through the app-server filesystem layer into the managed goal attachment directory, then rewrites active image placeholders to file references. - Appends unplaced local images and remote image URLs to the objective as referenced image files or URLs. - Preserves goal image metadata through live `/goal` submission and queued `/goal` dispatch. ## Verification - Added goal materialization coverage for local image files and remote image URLs. - Added/updated TUI slash-command coverage showing `/goal` drafts include attached images instead of dropping them. ## Manual Testing - Attached an image by bracketed-pasting its local path into a live `/goal` composer. The `[Image #1]` placeholder became a server-host `image-1.png` reference, copied bytes matched exactly, and no attachment was written under the TUI's local home. - Deleted an image placeholder before submitting a small goal and verified no image was copied. - Attached PNG and JPEG files to the same goal. Placeholder order was preserved as `image-1.png` and `image-2.jpg`, and both remote copies matched their source bytes. - Tried extensionless, malformed-extension, and extension/content-mismatched paths; the composer rejected them as image attachments before goal dispatch rather than creating misleading managed image files. - Combined a local image, a large pasted block, and enough raw text to exceed 4,000 characters. The remote attachment directory contained the image, paste sidecar, and `goal-objective.md`; all embedded references used server-host paths and both payloads matched their sources. - Submitted an image replacement while a goal was active, verified no image was copied before confirmation, then canceled and confirmed the attachment count was unchanged.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
Codex can already run against configured execution environments, but those environments have to exist before the session starts. In real remote/container workflows, the useful target is often discovered or created mid-task: an agent SSHes to a host, starts or reuses a Docker container, and then needs to keep editing, testing, or inspecting files there.
Repeating raw
ssh ...ordocker exec ...wrappers keeps that target invisible to Codex's environment-aware tools, TUI status, subagents, and context recovery.env_switchmakes the runtime target a registered execution environment while the main Codex process, auth, session state, skills, and MCP connections stay on the original host.What changed
env_switchtool for registering Docker and SSH execution targets at runtime, plus read-onlyenv_status/env_listtools for recovering visible environment ids after switching, resume, or compaction.env_switchtarget the default for compatible tools that omitenvironment_id, while still allowing per-call explicitenvironment_idoverrides.target=localreturns compatible calls to the local host environment.~/.codex-server/env-switch, separate from any user-installedcodex, and failed version-matched installs fail the switch instead of falling back to an older remote binary.ssh:host>docker:container, and add relativeextendmode for appending one hop to the current environment.env_switchtarget in the TUI status line, preserve it across replay/resume/session refresh, and render nested targets by their innermost environment type (ssh:host>docker:containershows a Docker badge).env_switchinstead of repeated wrappers.Review shape
This PR is a consolidated prototype branch so the whole behavior can be tested end to end in one place. It is not the intended final upstream review shape. If the direction is accepted, I expect to split the work into smaller reviewable branches/PRs in this fork, roughly:
env_switchtool and item-levelenvironment_idsemantics.Validation
just fmtjust test -p codex-core remote_command_advisoryjust test -p codex-core unified_exec_advises_env_switch_after_raw_sshjust test -p codex-core unified_exec_advises_env_switch_with_explicit_environment_idjust test -p codex-tui nested_ssh_docker_environment_id_uses_docker_badgejust test -p codex-tui env_switch_docker_badge_long_name_is_truncated_in_status_linejust test -p codex-tui env_switch_ssh_badge_long_name_is_truncated_in_status_linejust test -p codex-tui badge_testscargo build --bin codexManual E2E coverage included a
/goalrun where the lead agent delegated work to subagents, each subagent registered an SSH target, entered a Docker container through a nested environment id, and completed PyTorch benchmark work inside the container while the TUI showed the active per-subagent execution target.Notes
env_switchfeature flag and is default-off.