aiterm-mcp 0.70.6 → 0.70.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.70.8] - 2026-11-10
11
+
12
+ - Windows forks (x64): `agent_launch.fork_from` now starts the fork with every write inside the project folder refused instead of answering `READONLY_UNENFORCEABLE`. A bundled helper (`native/write-ban/win32-x64/aiterm-write-ban.exe`, about 24 KB, built reproducibly with the Linux ones) runs the CLI under a restricted copy of the user's token with no privileges and an Aiterm marker SID. The project folder carries, once, an inheritable Deny ACE for that marker SID (plus OWNER RIGHTS = READ_CONTROL and WRITE_DAC, so the DACL cannot be rewritten). The ACEs affect no other process, so the main seat writes as before and nothing is cleaned up later. npm shims run through `pwsh -File`. Measured on fox: new file, append, delete, rename, attributes, Set-Acl, icacls, takeown, git and cmd redirects inside were refused; writes outside succeeded. `fork_of.write_ban.method` is `restricted-token`.
13
+ - The Linux terminal runtime now carries its own tmux, so a Linux terminal needs no tmux installed. `aiterm-runtime-<version>-linux-<x64|arm64>.tar.gz` holds `bin/tmux` 3.8, a fully static musl binary (libevent 2.1.13, utf8proc 2.12.0 and ncurses 6.5 linked in, no libc of the terminal), cross-built on the runner with `zig cc` (`ziglang` 0.15.2 from PyPI, as the write-ban helper) from source tarballs pinned by sha256 in `scripts/build-linux-runtime.mjs`. ncurses keeps compiled-in entries for `screen-256color`, `tmux-256color`, `xterm-256color`, `xterm`, `screen`, `tmux`, `linux`, `vt100`, `dumb` and `ansi`, so tmux also starts on a machine without a terminfo database; it still reads the terminal's own database first. `default-terminal` stays `screen-256color`. The runtime `bin` is first on PATH, so seats use it.
14
+ - `provision` no longer checks for tmux on a Linux terminal, and `PROVISION_TMUX_MISSING` is gone (the bootstrap and `runtime-smoke` never answer it). `runtime-smoke` runs the runtime's own `bin/tmux -V` on both systems. The runtime build checks both tmux binaries are static ELF files of the right machine and, for the host architecture, starts a session with no terminfo database in reach. `runtime.yml` installs `ziglang` in the Linux job and no longer installs a system tmux there.
15
+ - Windows: a local Claude Code / Codex launch no longer types the whole PowerShell launch command (several KB with the sub-agent instruction) into the pane. The psmux send worker drains 300 ms per 256 bytes, so that one call took about 6.4 s of a 9.9 s launch (fox, 0.70.7). Aiterm now writes the command to a private 0600 file in its launch state and types one short line that reads it, deletes it and runs it in the pane's scope. The command, its exit tracking and the drains are unchanged. Environment values no longer appear in the pane's scrollback. POSIX launches are unchanged.
16
+ - Windows terminals (x64) can host Claude Code and Codex seats. A terminal whose OpenSSH Server default shell is PowerShell 7, Windows PowerShell 5.1 or `cmd` is no longer refused with `TERMINAL_PLATFORM_UNSUPPORTED` (that code stays for a system that is none of macOS, Linux and Windows). Every command Aiterm sends to a trusted terminal now comes from one builder, `terminalCommand(shell, {posix, windows})`: POSIX terminals get the same `/bin/sh -c` line as before; on Windows the line puts `%USERPROFILE%\.aiterm\runtime\current\bin` first on PATH when it holds `aiterm-mcp.cmd`, allows scripts for that process only (npm's `.ps1` shims), runs `& 'prog' 'arg'...` with every argument single-quoted, and ends with the real exit code (`pwsh -c` alone turns every native failure into 1). A missing `aiterm-*` program prints `<prog>: command not found` and exits 127, so `REMOTE_AITERM_UNAVAILABLE` does not depend on the language of Windows' own error (fox's is Japanese and CP932); the English cmd and PowerShell "is not recognized as ..." texts that name an `aiterm-*` program are classified the same way. `cmd` is not a PowerShell: its body goes through `powershell -EncodedCommand`. This covers the MCP connection (open, private env line, per-call tools), `aiterm-wait`, `aiterm-transcript-read` and `remote_terminal_command`. The platform probe now also fixes the shell kind in the per-ref cache, so no second probe is made.
17
+ - A terminal launch's `cwd` is checked in the terminal's own form: `/...` on macOS and Linux, a drive-absolute `X:\...` on Windows (UNC, device, relative, drive-relative, `/` separators and forbidden characters are `TERMINAL_INVALID`). Without `os` the form is checked against the probed system, still before any session. `path_status`, `make_dir` and `list_dirs` take the same native paths on both sides and need Aiterm 0.70.8 on a Windows terminal (`REMOTE_AITERM_TOO_OLD` otherwise); `list_dirs` on Windows leaves out `$Recycle.Bin` and `System Volume Information` besides dot names.
18
+ - The seat MCP forward keeper holds its reverse forward with a remote command that ends when its stdin closes on every shell: `cat >/dev/null` on POSIX, `[Console]::In.ReadToEnd() | Out-Null` on Windows. It reads the shell from the per-ref cache and probes once when this process has not. A SIGKILLed holder ended the Windows forward within seconds.
19
+ - `remote_terminal_command` `claude_install` on Windows is the official `irm https://claude.ai/install.ps1 | iex` (a failure stops with exit 1 and its message); `claude_version` and `claude_update` are unchanged, and after an install the version is also read from `%USERPROFILE%\.local\bin\claude.exe`.
20
+ - `aiterm-remote-terminal authorize-key --ref R --os windows` appends the held public key on a Windows terminal: to `%ProgramData%\ssh\administrators_authorized_keys` when the user is in Administrators and `sshd_config` still has the default `Match Group administrators` block (the file's ACL is reset to Administrators and SYSTEM only, as sshd requires), else to `%USERPROFILE%\.ssh\authorized_keys`; same duplicate check by key type and blob, UTF-8 without BOM, the file's own line ending. The password login cannot be probed first (no key works yet), so the caller names the system with `--os`; without it, or with `macos` / `linux`, the POSIX script runs as before.
21
+ - `aiterm-remote-terminal provision` installs the runtime on Windows x64 from `aiterm-runtime-<version>-win32-x64.zip` in the same `SHA256SUMS` (now five files), through a PowerShell 5.1 bootstrap that verifies the checksum, extracts with `tar.exe`, runs `runtime-smoke` and repoints a `current` junction (previous kept as `previous`, an old folder in use stays). `runtime-smoke` on Windows checks `psmux -V` by Aiterm's own lookup. `scripts/build-windows-runtime.mjs` builds the zip (official Node win-x64 zip checked against its pinned sha256, the npm package, CRLF `bin\*.cmd` wrappers) and `.github/workflows/runtime.yml` runs it on `windows-latest`; `scripts/upload-runtime-assets.mjs` lists the five assets. The zip carries its own psmux 3.3.8 (`bin\psmux.exe`, the official MIT release, sha256-pinned; the wrappers set `AITERM_PSMUX` to it), so the terminal needs no psmux installed, as Linux needs no tmux.
22
+ - The `CONNECTION_REFUSED` and `TERMINAL_PLATFORM_UNSUPPORTED` sentences for the Owner name the Windows steps (the optional OpenSSH Server feature and the sshd service).
23
+
24
+ ## [0.70.7] - 2026-11-10
25
+
26
+ - `pty_list` seat turns (`aiterm.seat-turns.v1`, BellTeam caller only) add `unread: [session_id]`. It names the terminal-bound sessions whose terminal failed or did not answer within 4 s, so the caller can keep their last state instead of reading them as gone. A session missing from a terminal that did answer is absent, as before.
27
+ - Idle hibernation no longer waits five seconds and then kills the pane's shell. An interactive shell ignores SIGTERM, so once the CLI and its children have exited, the pane root is hung up (SIGHUP), as closing a terminal would. The CLI keeps its full grace. A pane whose root started alone keeps the old TERM, grace, KILL order.
28
+ - Linux fork write-ban no longer needs python3. Aiterm ships a small static Landlock helper for x64 and arm64 (`native/write-ban/`, about 35 KB each, built reproducibly from `native/write-ban/aiterm-write-ban.c` with `scripts/build-write-ban.mjs`), so a fork works on any Linux with Landlock and nothing else installed. Other CPUs answer `READONLY_UNENFORCEABLE`.
29
+ - Linux terminals (x64, arm64) can host Claude Code seats, and Aiterm now checks which system a terminal really is before it connects. `remote_terminal_open` and the launch tools' `terminal` argument take an optional `os` (`macos`, `linux`, `windows`) beside `target` (never inside it, so existing Mac callers stay valid). Before the first terminal call Aiterm probes the system once per binding (the existing shell probe plus `uname -s`) and `remote_terminal_open` returns it as `platform` next to `opened` and `remoteVersion`. A different declared `os` answers `TERMINAL_OS_MISMATCH` (from `remote_terminal_open` and from a launch). A Windows terminal, or any system that is not macOS, Linux or Windows, answers `TERMINAL_PLATFORM_UNSUPPORTED`; Windows terminals come in 0.70.8. Both are refused before any MCP connection and, on a launch, count as not started (`_meta["aiterm/launch_error"]`, `effect: "not_started"`, with a short Japanese sentence for the Owner).
30
+ - `aiterm-remote-terminal provision` installs the runtime on Linux (`uname -m` `x86_64` -> x64, `aarch64`/`arm64` -> arm64) from `aiterm-runtime-<version>-linux-<x64|arm64>.tar.gz` in the same `SHA256SUMS`. The Linux runtime holds the official Node and the published package with the same `bin/` wrappers, and no tmux: seats use the terminal's own. Without `tmux` on the user's login PATH, provision answers `PROVISION_TMUX_MISSING` before it downloads anything (install tmux with the OS package manager); `runtime-smoke` on Linux checks the system tmux. `runtime.yml` now builds darwin on `macos-latest` and linux on `ubuntu-latest` (`scripts/build-linux-runtime.mjs`, no compilation, Node checked against its pinned sha256 and the published `SHASUMS256.txt`) and one publish job attaches the four tarballs and one `SHA256SUMS` over them. Releases published before this one have no Linux assets (`RUNTIME_ARTIFACT_UNAVAILABLE`).
31
+ - A terminal launch needs a POSIX absolute `cwd` on macOS and Linux terminals. The `CONNECTION_REFUSED` sentence for the Owner no longer names only the Mac: it asks to check that the terminal's SSH server is on (Remote Login on a Mac, sshd on Linux).
32
+ - `remote_terminal_command` `claude_install` / `claude_update` on Linux: when `claude` is not on the login PATH after the official installer, the version is read from `$HOME/.local/bin/claude`.
33
+ - `agent_launch` with `harness: "codex-cli"` takes `append_system_prompt` and `mcp_config`, locally and on a terminal, like claude-code. The instructions are appended to the seat's one `-c developer_instructions=` value, after Aiterm's launch marker. Each http server in `mcp_config` becomes a `-c mcp_servers.<name>={url, bearer_token_env_var, env_http_headers, http_headers}`: `Authorization: Bearer ${NAME}` is `bearer_token_env_var`, any other header whose whole value is `${NAME}` is `env_http_headers`, a literal value is `http_headers`. Both are kept in Aiterm's own state (0600 files) and rebuilt on every start and resume, never written to the project or `~/.codex`. Shapes Codex cannot express (a non-http server, extra keys, a header mixing text with `${NAME}`) and a user stdio server of the same name in `config.toml` (a `-c` table merges key by key into it, so it cannot be turned into an http server) are refused before the seat starts. A same-name http server is overridden for this seat; its other headers and timeouts from `config.toml` stay. The instructions (at most 64 KiB) and server URLs are in the Codex argv; secrets must be `${NAME}` references.
34
+ - Terminal seats can run Codex: `agent_launch` with `terminal` accepts `codex-cli` and goes to the terminal's `agent_launch`, which needs Aiterm 0.70.7 on the terminal (`REMOTE_AITERM_TOO_OLD` otherwise, also for a `remote` launch with the Codex fields). The header values moved to the private env line (`${AITERM_MCP_HEADER_n}`) map to `env_http_headers`. `pty_list` `aiterm/seat_turns` rows are the same as for a Claude terminal seat. grok-cli, cursor-cli and antigravity-cli still answer `TERMINAL_HARNESS_UNSUPPORTED`; its `aiterm/launch_error` now carries the requested harness.
35
+ - A launch refused from its arguments alone, before any native or process exists, answers `AGENT_LAUNCH_NOT_STARTED: <reason>` with `_meta["aiterm/launch_error"]` = `{harness, code, phase: "input", effect: "not_started", session_created: false, action}` for every harness: `append_system_prompt`/`mcp_config` on grok-cli, cursor-cli or antigravity-cli, a Codex `mcp_config` that cannot be expressed, `write_scope` on claude-code, `require_existing_resume` with a prompt. Before, the first was a plain text refusal. `phase: "native_create"` stays the rolled-back native creation (0.70.5).
36
+
10
37
  ## [0.70.6] - 2026-11-10
11
38
 
12
39
  - `agent_launch` takes `fork_from: {session_id, fork_id?}` (claude-code, codex-cli). It starts a disposable fork of that seat's latest saved conversation, in the main's cwd and on the main's account, with the main's tools and MCP servers. Every write inside that cwd (the project folder) is refused below the tools for the whole CLI process tree. That covers file tools, shell redirects, git, sqlite and anything else. Everything outside the folder stays writable, and reads, commands, network and MCP are untouched. Linux uses Landlock (unprivileged; works in standard Docker, where bwrap-based sandboxes do not; needs python3). macOS uses `sandbox-exec`. Windows, and any machine where the ban cannot be proven before launch, answers `READONLY_UNENFORCEABLE`, and no seat is created. Claude forks with `--resume <main> --fork-session` under the seat's own session ID. The tools array equals the main's, and the first fork request read about 99% of the main's prompt cache. Codex forks with `codex fork <main>` and is bound by the rollout's `forked_from_id` plus the first input. The receipt adds `fork_of {session_id, vendor_session_id, write_ban {path, method}}`. The seat environment adds `THROUGHLINE_SESSION_KIND=fork`, `THROUGHLINE_PARENT_SESSION_ID` and `THROUGHLINE_FORK_ID`. A resumed fork keeps the ban. Remote and terminal forks need this release on the terminal (`REMOTE_AITERM_TOO_OLD` otherwise) and go through the terminal's `agent_launch`. Refusals: `FORK_INVALID`, `FORK_SOURCE_UNAVAILABLE`, `FORK_UNSUPPORTED`. ADR 0140.
@@ -3194,7 +3221,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3194
3221
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3195
3222
  provenance.
3196
3223
 
3197
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.6...HEAD
3224
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.8...HEAD
3225
+ [0.70.8]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.7...v0.70.8
3226
+ [0.70.7]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.6...v0.70.7
3198
3227
  [0.70.6]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.5...v0.70.6
3199
3228
  [0.70.5]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.4...v0.70.5
3200
3229
  [0.70.4]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.3...v0.70.4
package/README.ja.md CHANGED
@@ -215,7 +215,7 @@ runtime-error store は canonical dotagents config の `collection.enabled: true
215
215
  場合だけ収集し、既定OFF、network送信は行いません。tag起点CIのnpm provenance(OIDC Trusted
216
216
  Publishing)で公開し、GitHub Release が Official MCP Registry を再登録します。
217
217
 
218
- **状態:** 開発継続中 · 現行公開版 **v0.70.6** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.70.8** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
219
219
 
220
220
  ### 更新と巻き戻し
221
221
 
package/README.md CHANGED
@@ -227,7 +227,7 @@ collection is off by default and performs no network I/O. It ships via
227
227
  tag-triggered CI with npm provenance (OIDC Trusted Publishing); the GitHub
228
228
  Release re-registers the Official MCP Registry entry.
229
229
 
230
- **Status:** actively maintained · current public release **v0.70.6** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
230
+ **Status:** actively maintained · current public release **v0.70.8** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
231
231
 
232
232
  ### Update and rollback
233
233
 
@@ -4,6 +4,7 @@ import * as path from "node:path";
4
4
  import { AitermError } from "./errors.js";
5
5
  import { executionNativeBindingSchema } from "./execution-close.js";
6
6
  import { OPERATION_ID_RE, agentManagedClaudeSettingsPath, agentClaudeResultPath, agentClaudeCallerPromptPath, agentClaudeCallerMcpPath } from "./harnesses/claude.js";
7
+ import { agentCodexCallerPromptPath, agentCodexCallerMcpPath } from "./harnesses/codex.js";
7
8
  import { resolveAndValidateGrokAuth } from "./harnesses/grok.js";
8
9
  import { assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, agentEventPath, agentLineageFields, LAUNCH_ID_RE, AGENT_LINEAGE_RE } from "./agent-shared.js";
9
10
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -57,7 +58,7 @@ function forkOfField(v) {
57
58
  || typeof v.vendor_session_id !== "string" || !UUID_RE.test(v.vendor_session_id)
58
59
  || (v.fork_id !== undefined && typeof v.fork_id !== "string") || (v.first_input !== undefined && typeof v.first_input !== "string")
59
60
  || !v.write_ban || typeof v.write_ban.path !== "string" || !path.isAbsolute(v.write_ban.path)
60
- || (v.write_ban.method !== "landlock" && v.write_ban.method !== "seatbelt"))
61
+ || !["landlock", "seatbelt", "restricted-token"].includes(v.write_ban.method))
61
62
  throw new AitermError("agent metadata fork_of が不正です", 2);
62
63
  return { fork_of: { session_id: v.session_id, vendor_session_id: v.vendor_session_id, ...(v.fork_id === undefined ? {} : { fork_id: v.fork_id }),
63
64
  write_ban: { path: v.write_ban.path, method: v.write_ban.method }, ...(v.first_input === undefined ? {} : { first_input: v.first_input }) } };
@@ -209,6 +210,8 @@ export function loadAgentMetadata(name) {
209
210
  completion_route: "codex_transcript",
210
211
  ...loadAgentLineageFields(m, true),
211
212
  node_platform: process.platform,
213
+ ...(m.codex_caller_prompt_file === agentCodexCallerPromptPath(name) ? { codex_caller_prompt_file: m.codex_caller_prompt_file } : {}),
214
+ ...(m.codex_caller_mcp_file === agentCodexCallerMcpPath(name) ? { codex_caller_mcp_file: m.codex_caller_mcp_file } : {}),
212
215
  codex_home: recordedHome,
213
216
  };
214
217
  }
@@ -277,6 +277,16 @@ export function windowsAgentLaunchLine(cwd, env, argv, exited) {
277
277
  const command = parts.join("; ");
278
278
  return exited ? `try { ${command} } finally { [IO.File]::WriteAllText(${psq(exited.file)}, ${psq(exited.launch_id)}) }` : command;
279
279
  }
280
+ /**
281
+ * The one short line typed into a Windows pane instead of the long launch command, which is read
282
+ * from `file` (0600, Aiterm launch state), deleted, and run in the pane's own scope. The psmux
283
+ * worker drains 300 ms per 256 bytes, so a multi-KB line cost 6 s (fox, 0.70.7). Invoke-Expression
284
+ * is not subject to ExecutionPolicy, unlike running a .ps1.
285
+ */
286
+ export function windowsLaunchIndirection(file) {
287
+ const f = `'${file.replace(/'/g, "''")}'`;
288
+ return `$aitermLaunch=[IO.File]::ReadAllText(${f}); Remove-Item -LiteralPath ${f}; Invoke-Expression $aitermLaunch`;
289
+ }
280
290
  /**
281
291
  * Keep accepted shebang wrappers in the same pane, as for control commands.
282
292
  * Invoking .sh directly in PowerShell uses its file association and can open a
package/dist/core.js CHANGED
@@ -53,10 +53,10 @@ import { unfinishedDeliveriesOwnedBy } from "./parent-delivery-owners.js";
53
53
  import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, signalRuntimeProcess, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, macKeepAwakeProcess, processElapsedSeconds } from "./process-runtime.js";
54
54
  import { liveNodeExecutable } from "./live-node.js";
55
55
  import { resolveClaudeConfigurationRoot, withClaudeConfigRoot } from "./claude-config-root.js";
56
- import { probeWriteBan, writeBanPrefix } from "./write-ban.js";
56
+ import { probeWriteBan, writeBanPrefix, windowsWriteBanArgv } from "./write-ban.js";
57
57
  import { AitermError, AgentResumeUnavailableError, AgentResumeError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
58
58
  import { isWin, SOCKDIR, SOCK, tmuxCommand, readOnlyTmuxList, PtyDiagnosticError, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, withNativeSessionSetupRollback, hasNativeSessionSetupRollback, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, rememberPaneShell, } from "./tmux-runtime.js";
59
- import { AGENT_DEFAULT_PREFACE, sleep, currentUid, runtimeStateBase, safeStatSize, readFileRange, writeJson0600, createEmpty0600, shq, LAUNCH_ID_RE, AGENT_LINEAGE_RE, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, publishAgentGeneration, agentMetadataPath, writeAgentMetadata, AGENT_EVENT_TAIL_BYTES, agentLabel, agentHarness, subagentInstruction, } from "./agent-shared.js";
59
+ import { AGENT_DEFAULT_PREFACE, sleep, currentUid, runtimeStateBase, safeStatSize, readFileRange, writeJson0600, writeText0600, createEmpty0600, shq, LAUNCH_ID_RE, AGENT_LINEAGE_RE, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, publishAgentGeneration, agentMetadataPath, writeAgentMetadata, AGENT_EVENT_TAIL_BYTES, agentLabel, agentHarness, subagentInstruction, } from "./agent-shared.js";
60
60
  import { AuthResponseError, authUi, authPromptDigest, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
61
61
  import { processStartIdentity } from "./runtime-error-os.js";
62
62
  import { processStartIdentities } from "./process-start.js";
@@ -65,12 +65,12 @@ import { FastModeError, fastModeFailure } from "./fast-mode.js";
65
65
  import { readFileOrNull, restoreJsonSetting, withUserConfigLock, restoreUserDefaults, keepingUserDefaults, USER_DEFAULT_SETTLE_MS } from "./user-config.js";
66
66
  import { isDeepStrictEqual } from "node:util";
67
67
  import { grokAuthPlan, grokAuthStatus, grokAuthPane, GROK_MODEL_DEFAULTS, realGrokHome, resolveAndValidateGrokAuth, assertGrokModelAvailable, grokModelChoices, grokModelFromFooter, grokFooterModelName, grokModelDefaultsFromBody, restoreGrokModelDefaults, grokEventsTranscript, grokSessionDirectory, latestGrokCompletion, grokTurnSettled, observeGrokDone, buildGrokAgentCmd, grokAgentArgv, grokLaunchNote, grokEnvTokens, grokEnvEntries, grokTuiReady, grokPaneObservation, GROK_INTERRUPT_KEY, grokRateLimitDialog, grokPromptAwaitingAccept, grokUnacceptedPromptRestored, grokStartupAction, grokFooterHasConfiguration, grokTranscriptText, createGrokAgentMetadata, } from "./harnesses/grok.js";
68
- import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexCompletedTurnId, codexWorkingResumeConfiguration, captureCodexRecoveryProof, captureCodexResumeProof, readCodexResumeProof, codexResumeProofDigest, codexRootTranscript, codexRolloutSessionId, codexRunningTurn, codexInterruptionRecord, observeCodexDone, buildCodexAgentCmd, codexAgentArgv, codexResumeArgv, codexLaunchNote, codexPaneObservation, CODEX_INTERRUPT_KEY, codexHelperProcess, codexRateLimitModelSwitchDialog, codexApprovalDialog, codexStartupAction, codexModelChoice, codexEffortChoice, codexMoreReasoningChoice, codexTranscriptText, createCodexAgentMetadata, codexModelChoices, codexFastCommandOffered, codexFooterShowsFast, codexServiceTierNotices, restoreCodexDefaults, restoreCodexDefaultInFile, } from "./harnesses/codex.js";
68
+ import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexCompletedTurnId, codexWorkingResumeConfiguration, captureCodexRecoveryProof, captureCodexResumeProof, readCodexResumeProof, codexResumeProofDigest, codexRootTranscript, codexRolloutSessionId, codexRunningTurn, codexInterruptionRecord, observeCodexDone, buildCodexAgentCmd, codexAgentArgv, codexResumeArgv, writeCodexCallerFiles, refuseCodexCallerInput, codexLaunchNote, codexPaneObservation, CODEX_INTERRUPT_KEY, codexHelperProcess, codexRateLimitModelSwitchDialog, codexApprovalDialog, codexStartupAction, codexModelChoice, codexEffortChoice, codexMoreReasoningChoice, codexTranscriptText, createCodexAgentMetadata, codexModelChoices, codexFastCommandOffered, codexFooterShowsFast, codexServiceTierNotices, restoreCodexDefaults, restoreCodexDefaultInFile, } from "./harnesses/codex.js";
69
69
  import { claudeAuthPlan, claudeAuthStatus, claudeAuthPane, OPERATION_ID_RE, CLAUDE_RESULT_MAX_BYTES, CLAUDE_EFFORTS, agentClaudeOperationPath, agentClaudeApprovalReceiptPath, agentClaudeDispatchReceiptPath, validateOperationId, readClaudeResultText, assertClaudeAuthenticationReady, claudeModelChoices, claudeConfigDir, claudeProjectSlug, claudeFastIndicatorShown, claudeFastResult, buildClaudeAgentCmd, claudeAgentArgv, claudeResumeArgv, claudeLaunchNote, claudePaneObservation, CLAUDE_INTERRUPT_KEY, claudeUsageLimit, claudeLiveSelectMenu, claudeStartupAction, createClaudeAgentMetadata, writeClaudeCallerFiles, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, claudeApiErrorEndingTurn, claudeFailureCategory, } from "./harnesses/claude.js";
70
70
  import { cursorAuthPlan, cursorAuthStatus, cursorAuthPane, bindCursorTranscriptSession, cursorTurnBoundary, latestCursorCompletion, cursorTranscript, cursorTranscriptSessionId, observeCursorDone, cursorTranscriptText, assertCursorAuthenticationReady, assertCursorModelAvailable, cursorModelChoices, cursorModelIsFastVariant, cursorFastParameter, cursorHeaderShowsFast, cursorPickerView, cursorEffortSelected, cursorParameterRows, cursorUserConfigPath, CURSOR_DEFAULT_MODEL_KEYS, realCursorHome, buildCursorAgentCmd, cursorAgentArgv, cursorPromptWithLineage, createCursorAgentMetadata, cursorLaunchNote, cursorEffortNavigation, cursorTuiReady, cursorPaneObservation, CURSOR_INTERRUPT_KEY, cursorPromptHooksRunning, cursorUsageLimit, CURSOR_SUBMIT_SEQUENCE, validateCursorModelEffort, } from "./harnesses/cursor.js";
71
71
  import { interimFromNow, interimFromToken, readInterimWords, recordInterimBoundary } from "./interim-words.js";
72
72
  import { codexSeatTurn, grokSteerAcceptance, observeSteerDone, readSteerEntry, recordSteer } from "./steer-follow.js";
73
- import { resolveAgentBin, resolveThroughlineBin, runThroughlineHandoffContext, isWindowsNativeExecutable, isUsableAgentExecutableFile, agentBinForPaneShell, resolveWinPaneShell, windowsAgentArgv, windowsAgentLaunchLine } from "./agent-resolver.js";
73
+ import { resolveAgentBin, resolveThroughlineBin, runThroughlineHandoffContext, isWindowsNativeExecutable, isUsableAgentExecutableFile, agentBinForPaneShell, resolveWinPaneShell, windowsAgentArgv, windowsAgentLaunchLine, windowsLaunchIndirection } from "./agent-resolver.js";
74
74
  export { AitermError } from "./errors.js";
75
75
  export { tmuxSpawnEnv } from "./tmux-runtime.js";
76
76
  export { agentHarness } from "./agent-shared.js";
@@ -350,6 +350,12 @@ function savedAgentSessionNames() {
350
350
  return match ? [match[1]] : [];
351
351
  }))] : [];
352
352
  }
353
+ /** Windows: the full PowerShell launch command goes to a private file; only the short reader line is typed (and shown). */
354
+ export function windowsLaunchTyped(name, launchId, full) {
355
+ const file = agentMetadataPath(name, launchId) + ".launch.ps1";
356
+ writeText0600(file, full);
357
+ return windowsLaunchIndirection(file);
358
+ }
353
359
  function cleanupAgentState(name) {
354
360
  assertSessionName(name);
355
361
  agentMetadataNegativeCache.delete(name);
@@ -366,6 +372,7 @@ function cleanupAgentState(name) {
366
372
  if (f.endsWith(".agent.json") ||
367
373
  f.endsWith(".active-launch.json") ||
368
374
  f.endsWith(".launch-exited") ||
375
+ f.endsWith(".launch.ps1") ||
369
376
  f.endsWith(".events.jsonl") ||
370
377
  f.endsWith(".activity.jsonl") ||
371
378
  f.endsWith(".resume.json") ||
@@ -385,6 +392,8 @@ function cleanupAgentState(name) {
385
392
  f.endsWith(".claude-mcp.json") ||
386
393
  f.endsWith(".claude-caller-prompt.md") ||
387
394
  f.endsWith(".claude-caller-mcp.json") ||
395
+ f.endsWith(".codex-caller-prompt.md") ||
396
+ f.endsWith(".codex-caller-mcp.json") ||
388
397
  f.endsWith(".launch-env") ||
389
398
  f.endsWith(".claude-result.json") ||
390
399
  f.endsWith(".cursor-result.json") ||
@@ -6874,6 +6883,10 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot) {
6874
6883
  next.claude_caller_prompt_file = previous.claude_caller_prompt_file;
6875
6884
  if (previous.claude_caller_mcp_file)
6876
6885
  next.claude_caller_mcp_file = previous.claude_caller_mcp_file;
6886
+ if (previous.codex_caller_prompt_file)
6887
+ next.codex_caller_prompt_file = previous.codex_caller_prompt_file;
6888
+ if (previous.codex_caller_mcp_file)
6889
+ next.codex_caller_mcp_file = previous.codex_caller_mcp_file;
6877
6890
  if (isWin)
6878
6891
  next.windows_launch_exit_tracked = true;
6879
6892
  if (next.kind === "claude")
@@ -6908,10 +6921,12 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot) {
6908
6921
  if (registerSessionEnvironment(true, name, [...(registeredSessionEnvironment(name) ?? []), ...Object.keys(recipe.environment)]).code !== 0)
6909
6922
  throw uncertain();
6910
6923
  phase = "vendor_start";
6911
- const argv = [...(next.fork_of ? writeBanPrefix(next.fork_of.write_ban) : []),
6912
- ...(next.kind === "claude" ? claudeResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next)
6913
- : codexResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next, recipe.cwd))];
6914
- const full = isWin ? windowsAgentLaunchLine(recipe.cwd, environment, windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), { file: agentMetadataPath(name, next.launch_id) + ".launch-exited", launch_id: next.launch_id })
6924
+ const cliArgv = next.kind === "claude" ? claudeResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next)
6925
+ : codexResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next, recipe.cwd);
6926
+ const argv = [...(next.fork_of && !isWin ? writeBanPrefix(next.fork_of.write_ban) : []), ...cliArgv];
6927
+ const forkBan = next.fork_of?.write_ban;
6928
+ const winArgv = () => (cli => forkBan ? windowsWriteBanArgv(forkBan, cli) : cli)(windowsAgentArgv(cliArgv, () => resolveWinPaneShell("bash")));
6929
+ const full = isWin ? windowsLaunchTyped(name, next.launch_id, windowsAgentLaunchLine(recipe.cwd, environment, winArgv(), { file: agentMetadataPath(name, next.launch_id) + ".launch-exited", launch_id: next.launch_id }))
6915
6930
  : `cd ${shq(recipe.cwd)} && /usr/bin/env ${environment.filter(([, value]) => value === null).map(([key]) => `-u ${shq(key)}`).join(" ")} `
6916
6931
  + `${environment.filter(([, value]) => value !== null).map(([key, value]) => shq(`${key}=${value}`)).join(" ")} ${argv.map(shq).join(" ")}`;
6917
6932
  agentLaunchLines.set(name, atomicShellMultiline(full, shell));
@@ -7786,6 +7801,8 @@ function prepareAgentLaunch(kind, opts = {}) {
7786
7801
  meta.agent_executable = bin;
7787
7802
  if (meta.kind === "claude")
7788
7803
  writeClaudeCallerFiles(meta, opts.append_system_prompt ?? null, opts.mcp_config ?? null);
7804
+ if (meta.kind === "codex")
7805
+ writeCodexCallerFiles(meta, opts.append_system_prompt ?? null, opts.mcp_config ?? null);
7789
7806
  if (opts.fork_of)
7790
7807
  meta.fork_of = opts.fork_of;
7791
7808
  if (isWin && ["claude", "codex", "grok", "antigravity"].includes(kind))
@@ -7829,7 +7846,9 @@ function prepareAgentLaunch(kind, opts = {}) {
7829
7846
  : grokAgentArgv(kind, bin, model, effort, prompt, meta);
7830
7847
  full = windowsAgentLaunchLine(cwd, [
7831
7848
  ...claudeRootEntries, ...(meta?.kind === "grok" ? grokEnvEntries(meta) : []), ...agentEnvEntries(meta, sid, envVars),
7832
- ], windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), meta?.windows_launch_exit_tracked ? { file: agentMetadataPath(sid, meta.launch_id) + ".launch-exited", launch_id: meta.launch_id } : undefined);
7849
+ ], (cli => meta?.fork_of ? windowsWriteBanArgv(meta.fork_of.write_ban, cli) : cli)(windowsAgentArgv(argv, () => resolveWinPaneShell("bash"))), meta?.windows_launch_exit_tracked ? { file: agentMetadataPath(sid, meta.launch_id) + ".launch-exited", launch_id: meta.launch_id } : undefined);
7850
+ if (meta)
7851
+ full = windowsLaunchTyped(sid, meta.launch_id, full);
7833
7852
  }
7834
7853
  else {
7835
7854
  const cmd = (meta?.fork_of ? writeBanPrefix(meta.fork_of.write_ban).map(shq).join(" ") + " " : "")
@@ -8017,6 +8036,9 @@ export function resolveForkSource(kind, from, opts, probe = probeWriteBan) {
8017
8036
  write_ban, ...(first_input ? { first_input } : {}) }, cwd: main.cwd, ...(root ? { root } : {}) };
8018
8037
  }
8019
8038
  export async function openAgentWithInitialPrompt(kind, opts = {}) {
8039
+ // Caller launch fields: refused from the arguments alone, before any session or file exists (phase "input").
8040
+ if (kind === "codex")
8041
+ refuseCodexCallerInput(opts.append_system_prompt, opts.mcp_config);
8020
8042
  const fork = opts.fork_from ? resolveForkSource(kind, opts.fork_from, opts) : null;
8021
8043
  if (opts.configuration_root != null && kind !== "claude")
8022
8044
  throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: configuration_rootはclaude-code harnessだけで使えます。", 2);
package/dist/errors.js CHANGED
@@ -15,6 +15,12 @@ export class AitermError extends Error {
15
15
  this.code = code;
16
16
  }
17
17
  }
18
+ /** An input refusal decided from the launch arguments alone, before any native or process exists (remote-terminal.md R18, phase "input"). */
19
+ export function launchInputRefusal(harness, reason) {
20
+ const error = new AitermError(`AGENT_LAUNCH_NOT_STARTED: ${reason}`, 2);
21
+ error.launchNotStarted = { harness, phase: "input" };
22
+ return error;
23
+ }
18
24
  /** A harness authentication check refused launch before any session creation.
19
25
  * Keep the native CLI's status body and credential diagnostics out of the wire. */
20
26
  export class AgentAuthenticationPreflightError extends AitermError {
@@ -7,12 +7,12 @@ import * as os from "node:os";
7
7
  import * as path from "node:path";
8
8
  import { randomBytes, createHash } from "node:crypto";
9
9
  import { z } from "zod";
10
- import { AitermError } from "../errors.js";
10
+ import { AitermError, launchInputRefusal } from "../errors.js";
11
11
  import { spawnAgentControlCommand } from "../agent-resolver.js";
12
12
  import * as steer from "aiterm-steer-delivery";
13
13
  import { AITERM_PROFILE } from "../steer-profile.js";
14
14
  import { catalogInvalid, catalogUnavailable, checkedCatalog } from "../model-catalog.js";
15
- import { shq, subagentInstruction, writeScopeLaunchNote, safeStatSize, readFileRange, sleep, agentMetadataPath, writeAgentMetadata, writeJson0600, agentEventPath, createEmpty0600, agentLineageFields, AGENT_DONE_POLL_MS, AGENT_EVENT_MAX_BYTES, AGENT_EVENT_TAIL_BYTES, AGENT_TURN_BOUNDARY_TAIL_BYTES, readTailLinesNewestFirst, scanLinesNewestFirst, CODEX_TRANSCRIPT_INCREMENT_MAX_BYTES, agentHarness, } from "../agent-shared.js";
15
+ import { shq, subagentInstruction, writeScopeLaunchNote, safeStatSize, readFileRange, sleep, agentMetadataPath, writeAgentMetadata, writeJson0600, agentEventPath, createEmpty0600, agentLineageFields, AGENT_DONE_POLL_MS, AGENT_EVENT_MAX_BYTES, AGENT_EVENT_TAIL_BYTES, AGENT_TURN_BOUNDARY_TAIL_BYTES, readTailLinesNewestFirst, scanLinesNewestFirst, CODEX_TRANSCRIPT_INCREMENT_MAX_BYTES, agentHarness, assertSessionName, agentsDir, } from "../agent-shared.js";
16
16
  import { confirmedAgentResumeRecoveryOrigin, readAgentLifecycle, readAgentResumeRecipe, agentResumeRecipeDigest } from "../agent-lifecycle.js";
17
17
  export function realCodexHome() {
18
18
  return process.env.CODEX_HOME || path.join(process.env.HOME ?? os.homedir(), ".codex");
@@ -895,6 +895,141 @@ export async function observeCodexDone(meta, timeout, requestedCursor, signal) {
895
895
  await sleep(AGENT_DONE_POLL_MS);
896
896
  }
897
897
  }
898
+ // ---- Caller launch fields (launch-identity-input.md "Caller launch fields"): Codex has no file flags, so the two kept
899
+ // files feed `-c developer_instructions=` and `-c mcp_servers.NAME={...}`. Env values are never in them: headers are env names.
900
+ export function agentCodexCallerPromptPath(name) {
901
+ assertSessionName(name);
902
+ return path.join(agentsDir(), `${name}.codex-caller-prompt.md`);
903
+ }
904
+ export function agentCodexCallerMcpPath(name) {
905
+ assertSessionName(name);
906
+ return path.join(agentsDir(), `${name}.codex-caller-mcp.json`);
907
+ }
908
+ // The prompt travels in one argv element (Linux caps one at 128 KiB) and the typed launch line.
909
+ const CODEX_CALLER_PROMPT_MAX = 64 * 1024;
910
+ const MCP_SERVER_NAME = /^[A-Za-z0-9_-]{1,64}$/;
911
+ const HEADER_NAME = /^[A-Za-z0-9-]{1,128}$/;
912
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
913
+ const toml = (value) => JSON.stringify(value); // JSON strings are valid TOML basic strings
914
+ /** `mcp_config` -> one `-c` value per server. Refuses (CODEX_MCP_CONFIG_UNSUPPORTED) what Codex's http server table cannot say. */
915
+ export function codexMcpOverrides(mcp) {
916
+ const refuse = (message) => { throw new AitermError(`CODEX_MCP_CONFIG_UNSUPPORTED: ${message}`, 2); };
917
+ const servers = mcp?.mcpServers;
918
+ if (!mcp || typeof mcp !== "object" || Object.keys(mcp).some(key => key !== "mcpServers") || !servers || typeof servers !== "object" || Array.isArray(servers))
919
+ return refuse("mcp_config must be {mcpServers: {...}}");
920
+ return Object.entries(servers).map(([name, server]) => {
921
+ if (!MCP_SERVER_NAME.test(name))
922
+ return refuse(`server name '${name}' must be letters, digits, '_' or '-'`);
923
+ const spec = server;
924
+ if (!spec || typeof spec !== "object" || Array.isArray(spec))
925
+ return refuse(`server '${name}' must be an object`);
926
+ if (Object.keys(spec).some(key => !["type", "url", "headers"].includes(key)))
927
+ return refuse(`server '${name}' may only have type, url and headers`);
928
+ if (spec.type !== undefined && spec.type !== "http")
929
+ return refuse(`server '${name}': Codex takes only type 'http' here (got '${String(spec.type)}')`);
930
+ let url = null;
931
+ try {
932
+ url = typeof spec.url === "string" ? new URL(spec.url) : null;
933
+ }
934
+ catch { /* refused below */ }
935
+ if (!url || (url.protocol !== "http:" && url.protocol !== "https:"))
936
+ return refuse(`server '${name}': url must be an http(s) URL`);
937
+ const fields = [`url=${toml(spec.url)}`];
938
+ const envHeaders = [], literalHeaders = [], seen = new Set();
939
+ let bearer = null;
940
+ if (spec.headers !== undefined && (!spec.headers || typeof spec.headers !== "object" || Array.isArray(spec.headers)))
941
+ return refuse(`server '${name}': headers must be an object`);
942
+ for (const [header, value] of Object.entries((spec.headers ?? {}))) {
943
+ if (!HEADER_NAME.test(header) || typeof value !== "string")
944
+ return refuse(`server '${name}': header '${header}' must be a plain name with a string value`);
945
+ if (seen.has(header.toLowerCase()))
946
+ return refuse(`server '${name}': header '${header}' is given twice`);
947
+ seen.add(header.toLowerCase());
948
+ const bearerName = header.toLowerCase() === "authorization" ? /^Bearer \$\{([^}]*)\}$/.exec(value)?.[1] : undefined;
949
+ const wholeName = /^\$\{([^}]*)\}$/.exec(value)?.[1];
950
+ if (bearerName !== undefined || wholeName !== undefined) {
951
+ const envName = (bearerName ?? wholeName);
952
+ if (!ENV_NAME.test(envName))
953
+ return refuse(`server '${name}': header '${header}' names an invalid environment variable`);
954
+ if (bearerName !== undefined)
955
+ bearer = envName;
956
+ else
957
+ envHeaders.push(`${toml(header)}=${toml(envName)}`);
958
+ }
959
+ else if (value.includes("${"))
960
+ return refuse(`server '${name}': header '${header}' mixes text with \${NAME}; only the whole value or 'Bearer \${NAME}' can be given`);
961
+ else
962
+ literalHeaders.push(`${toml(header)}=${toml(value)}`);
963
+ }
964
+ if (bearer !== null)
965
+ fields.push(`bearer_token_env_var=${toml(bearer)}`);
966
+ if (envHeaders.length)
967
+ fields.push(`env_http_headers={${envHeaders.join(",")}}`);
968
+ if (literalHeaders.length)
969
+ fields.push(`http_headers={${literalHeaders.join(",")}}`);
970
+ return `mcp_servers.${name}={${fields.join(",")}}`;
971
+ });
972
+ }
973
+ /** Pre-start check of the caller fields for a Codex launch. `-c` merges key by key into a same-name table of
974
+ * config.toml, so an http server of that name is overridden but a user stdio server (`command`) cannot be:
975
+ * Codex would fail to load its config ("url is not supported for stdio"). Refused before anything starts.
976
+ * shortcut: reads only `[mcp_servers.NAME]` section headers, an inline or dotted-key definition is not seen (Codex then refuses at start); upgrade with a TOML parser. */
977
+ export function checkCodexCallerInput(prompt, mcp, codexHome) {
978
+ if (prompt != null && (!prompt.trim() || Buffer.byteLength(prompt, "utf8") > CODEX_CALLER_PROMPT_MAX))
979
+ throw new AitermError("append_system_prompt must be non-empty and at most 64 KiB for codex-cli (it travels in argv)", 2);
980
+ if (mcp == null)
981
+ return;
982
+ const overrides = codexMcpOverrides(mcp);
983
+ let body = "";
984
+ try {
985
+ body = fs.readFileSync(path.join(codexHome, "config.toml"), "utf8");
986
+ }
987
+ catch { /* no user config: nothing to conflict with */ }
988
+ let inside = null;
989
+ const stdio = new Set();
990
+ for (const line of body.split(/\r?\n/)) {
991
+ const header = /^\s*\[\s*mcp_servers\s*\.\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_-]+))\s*\]\s*(?:#.*)?$/.exec(line);
992
+ if (header) {
993
+ inside = header[1] ?? header[2] ?? header[3];
994
+ continue;
995
+ }
996
+ if (/^\s*\[/.test(line)) {
997
+ inside = null;
998
+ continue;
999
+ }
1000
+ if (inside && /^\s*command\s*=/.test(line))
1001
+ stdio.add(inside);
1002
+ }
1003
+ for (const override of overrides) {
1004
+ const name = override.slice("mcp_servers.".length, override.indexOf("="));
1005
+ if (stdio.has(name))
1006
+ throw new AitermError(`CODEX_MCP_SERVER_CONFLICT: ~/.codex/config.toml already defines a stdio MCP server named '${name}', which a -c override cannot turn into an http server; rename it there or use another server name`, 2);
1007
+ }
1008
+ }
1009
+ /** Both caller files, as Claude's writeClaudeCallerFiles: Aiterm state, 0600, never the project or the Codex home. */
1010
+ export function writeCodexCallerFiles(meta, prompt, mcp) {
1011
+ checkCodexCallerInput(prompt, mcp, meta.codex_home ?? realCodexHome());
1012
+ if (prompt !== null) {
1013
+ const file = agentCodexCallerPromptPath(meta.aiterm_session);
1014
+ fs.writeFileSync(file, prompt, { mode: 0o600 });
1015
+ fs.chmodSync(file, 0o600);
1016
+ meta.codex_caller_prompt_file = file;
1017
+ }
1018
+ if (mcp !== null) {
1019
+ const file = agentCodexCallerMcpPath(meta.aiterm_session);
1020
+ writeJson0600(file, mcp);
1021
+ meta.codex_caller_mcp_file = file;
1022
+ }
1023
+ }
1024
+ /** The caller launch fields of a Codex input, refused as a not-started input refusal (phase "input"). */
1025
+ export function refuseCodexCallerInput(prompt, mcp) {
1026
+ try {
1027
+ checkCodexCallerInput(prompt, mcp, realCodexHome());
1028
+ }
1029
+ catch (e) {
1030
+ throw e instanceof AitermError ? launchInputRefusal("codex-cli", e.message) : e;
1031
+ }
1032
+ }
898
1033
  export function codexAgentArgv(bin, model, effort, prompt, meta) {
899
1034
  // A fork (ADR 0140) starts from the main's conversation; codexResumeArgv drops this pair again.
900
1035
  const parts = meta?.kind === "codex" && meta.fork_of ? [bin, "fork", meta.fork_of.vendor_session_id] : [bin];
@@ -914,8 +1049,12 @@ export function codexAgentArgv(bin, model, effort, prompt, meta) {
914
1049
  if (effort)
915
1050
  parts.push("-c", `model_reasoning_effort=${effort}`);
916
1051
  if (meta?.kind === "codex" && meta.hook_route === "shared_codex_home") {
917
- parts.push("-c", `developer_instructions=${subagentInstruction(meta)}`);
1052
+ // Aiterm's marker block stays first; the caller's text joins the same value (a second -c of the key would replace it).
1053
+ parts.push("-c", `developer_instructions=${subagentInstruction(meta)}${meta.codex_caller_prompt_file ? `\n\n${fs.readFileSync(meta.codex_caller_prompt_file, "utf8")}` : ""}`);
918
1054
  }
1055
+ if (meta?.kind === "codex" && meta.codex_caller_mcp_file)
1056
+ for (const override of codexMcpOverrides(JSON.parse(fs.readFileSync(meta.codex_caller_mcp_file, "utf8"))))
1057
+ parts.push("-c", override);
919
1058
  if (prompt)
920
1059
  parts.push(prompt); // 初手プロンプト(任意)
921
1060
  return parts;
@@ -933,6 +1072,8 @@ export function buildCodexAgentCmd(bin, model, effort, prompt, meta) {
933
1072
  if (index === 0 || argv[index - 1] === "-m" || (prompt && index === argv.length - 1))
934
1073
  return shq(arg);
935
1074
  if (argv[index - 1] === "-c") {
1075
+ if (arg.startsWith("mcp_servers."))
1076
+ return shq(arg);
936
1077
  for (const key of ["model_reasoning_effort=", "developer_instructions="]) {
937
1078
  if (arg.startsWith(key))
938
1079
  return key + shq(arg.slice(key.length));