aiterm-mcp 0.70.5 → 0.70.7

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,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.70.7] - 2026-11-10
11
+
12
+ - `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.
13
+ - 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.
14
+ - 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`.
15
+ - 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).
16
+ - `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`).
17
+ - 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).
18
+ - `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`.
19
+ - `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.
20
+ - 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.
21
+ - 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).
22
+
23
+ ## [0.70.6] - 2026-11-10
24
+
25
+ - `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.
26
+ - Windows: input sent while a command runs, or before a pane's first prompt, is typed in the dialect of the shell whose prompt the pane last showed (at first, the shell it was opened with), not in the dialect of psmux's foreground name. That name can be stale (`pwsh` for a Git Bash pane), and bash then read a PowerShell scriptblock (`syntax error near unexpected token [scriptblock]::Create`).
27
+
10
28
  ## [0.70.5] - 2026-11-10
11
29
 
12
30
  - A fresh managed launch (Claude Code, Codex) whose terminal session could not be set up no longer answers `AGENT_RESUME_UNCONFIRMED: 復帰したnative端末の本人性を確認できません`. That one sentence came from fifteen places, on fresh launches as well as resumes, and a fresh launch refused on a Mac terminal on 2026-11-10 could not be traced to its place afterwards. Every such refusal now names its place as `native_reason=<site>`; a failed tmux command adds its name, exit code and first error line, an unreadable creation receipt adds the output size.
@@ -3189,7 +3207,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3189
3207
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3190
3208
  provenance.
3191
3209
 
3192
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.5...HEAD
3210
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.7...HEAD
3211
+ [0.70.7]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.6...v0.70.7
3212
+ [0.70.6]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.5...v0.70.6
3193
3213
  [0.70.5]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.4...v0.70.5
3194
3214
  [0.70.4]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.3...v0.70.4
3195
3215
  [0.70.3]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.2...v0.70.3
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.5** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.70.7** · 動作対象は 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.5** · 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.7** · 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;
@@ -49,6 +50,19 @@ function loadAgentLineageFields(m, required) {
49
50
  delegationAllowed: true,
50
51
  });
51
52
  }
53
+ /** A fork seat's source (ADR 0140). Malformed is refused: dropping it would resume the fork writable. */
54
+ function forkOfField(v) {
55
+ if (v === undefined)
56
+ return {};
57
+ if (!v || typeof v.session_id !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(v.session_id)
58
+ || typeof v.vendor_session_id !== "string" || !UUID_RE.test(v.vendor_session_id)
59
+ || (v.fork_id !== undefined && typeof v.fork_id !== "string") || (v.first_input !== undefined && typeof v.first_input !== "string")
60
+ || !v.write_ban || typeof v.write_ban.path !== "string" || !path.isAbsolute(v.write_ban.path)
61
+ || (v.write_ban.method !== "landlock" && v.write_ban.method !== "seatbelt"))
62
+ throw new AitermError("agent metadata fork_of が不正です", 2);
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 }),
64
+ write_ban: { path: v.write_ban.path, method: v.write_ban.method }, ...(v.first_input === undefined ? {} : { first_input: v.first_input }) } };
65
+ }
52
66
  export function loadAgentMetadata(name) {
53
67
  assertSessionName(name);
54
68
  const dir = agentsDir();
@@ -146,6 +160,7 @@ export function loadAgentMetadata(name) {
146
160
  created_at: typeof m.created_at === "string" ? m.created_at : "",
147
161
  cwd: typeof m.cwd === "string" ? m.cwd : null,
148
162
  ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
163
+ ...forkOfField(m.fork_of),
149
164
  vendor_session_id: m.vendor_session_id,
150
165
  initial_prompt: normalizeInitialPromptState(m.initial_prompt),
151
166
  ...deliveryFields,
@@ -183,6 +198,7 @@ export function loadAgentMetadata(name) {
183
198
  created_at: typeof m.created_at === "string" ? m.created_at : "",
184
199
  cwd: typeof m.cwd === "string" ? m.cwd : null,
185
200
  ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
201
+ ...forkOfField(m.fork_of),
186
202
  vendor_session_id: typeof m.vendor_session_id === "string" ? m.vendor_session_id : null,
187
203
  initial_prompt: normalizeInitialPromptState(m.initial_prompt),
188
204
  ...deliveryFields,
@@ -194,6 +210,8 @@ export function loadAgentMetadata(name) {
194
210
  completion_route: "codex_transcript",
195
211
  ...loadAgentLineageFields(m, true),
196
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 } : {}),
197
215
  codex_home: recordedHome,
198
216
  };
199
217
  }
package/dist/core.js CHANGED
@@ -53,8 +53,9 @@ 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
57
  import { AitermError, AgentResumeUnavailableError, AgentResumeError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
57
- 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, } from "./tmux-runtime.js";
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";
58
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
60
  import { AuthResponseError, authUi, authPromptDigest, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
60
61
  import { processStartIdentity } from "./runtime-error-os.js";
@@ -64,7 +65,7 @@ import { FastModeError, fastModeFailure } from "./fast-mode.js";
64
65
  import { readFileOrNull, restoreJsonSetting, withUserConfigLock, restoreUserDefaults, keepingUserDefaults, USER_DEFAULT_SETTLE_MS } from "./user-config.js";
65
66
  import { isDeepStrictEqual } from "node:util";
66
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";
67
- import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexCompletedTurnId, codexWorkingResumeConfiguration, captureCodexRecoveryProof, captureCodexResumeProof, readCodexResumeProof, codexResumeProofDigest, codexRootTranscript, 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";
68
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";
69
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";
70
71
  import { interimFromNow, interimFromToken, readInterimWords, recordInterimBoundary } from "./interim-words.js";
@@ -384,6 +385,8 @@ function cleanupAgentState(name) {
384
385
  f.endsWith(".claude-mcp.json") ||
385
386
  f.endsWith(".claude-caller-prompt.md") ||
386
387
  f.endsWith(".claude-caller-mcp.json") ||
388
+ f.endsWith(".codex-caller-prompt.md") ||
389
+ f.endsWith(".codex-caller-mcp.json") ||
387
390
  f.endsWith(".launch-env") ||
388
391
  f.endsWith(".claude-result.json") ||
389
392
  f.endsWith(".cursor-result.json") ||
@@ -775,6 +778,7 @@ function openSessionInternal(name, shell, envVars, preserveAgentState) {
775
778
  break;
776
779
  }
777
780
  }
781
+ rememberPaneShell(nm, shell);
778
782
  return [nm, attachHint(nm)];
779
783
  });
780
784
  }
@@ -6872,6 +6876,10 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot) {
6872
6876
  next.claude_caller_prompt_file = previous.claude_caller_prompt_file;
6873
6877
  if (previous.claude_caller_mcp_file)
6874
6878
  next.claude_caller_mcp_file = previous.claude_caller_mcp_file;
6879
+ if (previous.codex_caller_prompt_file)
6880
+ next.codex_caller_prompt_file = previous.codex_caller_prompt_file;
6881
+ if (previous.codex_caller_mcp_file)
6882
+ next.codex_caller_mcp_file = previous.codex_caller_mcp_file;
6875
6883
  if (isWin)
6876
6884
  next.windows_launch_exit_tracked = true;
6877
6885
  if (next.kind === "claude")
@@ -6880,6 +6888,9 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot) {
6880
6888
  next.codex_home = recipe.configuration_root;
6881
6889
  if (previous.write_scope !== undefined)
6882
6890
  next.write_scope = previous.write_scope;
6891
+ // A resumed fork stays read-only (ADR 0140): argv and env derive from fork_of.
6892
+ if (previous.fork_of)
6893
+ next.fork_of = previous.fork_of;
6883
6894
  writeAgentMetadata(next);
6884
6895
  initializeAgentActivity(next);
6885
6896
  writeAgentResumeRecipe(next, { ...recipe, launch_id: next.launch_id });
@@ -6903,8 +6914,9 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot) {
6903
6914
  if (registerSessionEnvironment(true, name, [...(registeredSessionEnvironment(name) ?? []), ...Object.keys(recipe.environment)]).code !== 0)
6904
6915
  throw uncertain();
6905
6916
  phase = "vendor_start";
6906
- const argv = next.kind === "claude" ? claudeResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next)
6907
- : codexResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next, recipe.cwd);
6917
+ const argv = [...(next.fork_of ? writeBanPrefix(next.fork_of.write_ban) : []),
6918
+ ...(next.kind === "claude" ? claudeResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next)
6919
+ : codexResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next, recipe.cwd))];
6908
6920
  const full = isWin ? windowsAgentLaunchLine(recipe.cwd, environment, windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), { file: agentMetadataPath(name, next.launch_id) + ".launch-exited", launch_id: next.launch_id })
6909
6921
  : `cd ${shq(recipe.cwd)} && /usr/bin/env ${environment.filter(([, value]) => value === null).map(([key]) => `-u ${shq(key)}`).join(" ")} `
6910
6922
  + `${environment.filter(([, value]) => value !== null).map(([key, value]) => shq(`${key}=${value}`)).join(" ")} ${argv.map(shq).join(" ")}`;
@@ -7522,6 +7534,9 @@ function agentEnvEntries(meta, sid, envVars = []) {
7522
7534
  ["AITERM_AGENT_LINEAGE", meta.lineage ?? `host-root>${meta.kind}:${sid}`],
7523
7535
  ["AITERM_AGENT_DELEGATION_ALLOWED", meta.delegation_allowed === true ? "true" : "false"],
7524
7536
  ["AITERM_STATE_BASE", runtimeStateBase()],
7537
+ // Fork marker for transcript readers (ADR 0140): set before the CLI starts, so every hook inherits it.
7538
+ ...(meta.fork_of ? [["THROUGHLINE_SESSION_KIND", "fork"], ["THROUGHLINE_PARENT_SESSION_ID", meta.fork_of.vendor_session_id],
7539
+ ["THROUGHLINE_FORK_ID", meta.fork_of.fork_id ?? sid]] : []),
7525
7540
  ];
7526
7541
  }
7527
7542
  /** POSIX shellの起動行に前置する環境変数。Grokは自分の認証の正本と自動更新停止の値を、共通の一覧の前に置く。 */
@@ -7777,6 +7792,10 @@ function prepareAgentLaunch(kind, opts = {}) {
7777
7792
  meta.agent_executable = bin;
7778
7793
  if (meta.kind === "claude")
7779
7794
  writeClaudeCallerFiles(meta, opts.append_system_prompt ?? null, opts.mcp_config ?? null);
7795
+ if (meta.kind === "codex")
7796
+ writeCodexCallerFiles(meta, opts.append_system_prompt ?? null, opts.mcp_config ?? null);
7797
+ if (opts.fork_of)
7798
+ meta.fork_of = opts.fork_of;
7780
7799
  if (isWin && ["claude", "codex", "grok", "antigravity"].includes(kind))
7781
7800
  meta.windows_launch_exit_tracked = true;
7782
7801
  if (kind === "claude" || kind === "codex")
@@ -7821,7 +7840,8 @@ function prepareAgentLaunch(kind, opts = {}) {
7821
7840
  ], windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), meta?.windows_launch_exit_tracked ? { file: agentMetadataPath(sid, meta.launch_id) + ".launch-exited", launch_id: meta.launch_id } : undefined);
7822
7841
  }
7823
7842
  else {
7824
- const cmd = buildAgentCmd(kind, binForCmd, model, effort, opts.prompt ?? null, meta, cursorFast);
7843
+ const cmd = (meta?.fork_of ? writeBanPrefix(meta.fork_of.write_ban).map(shq).join(" ") + " " : "")
7844
+ + buildAgentCmd(kind, binForCmd, model, effort, opts.prompt ?? null, meta, cursorFast);
7825
7845
  const envPrefix = (!claudeRoot ? "" : claudeRoot.selector === null ? "unset CLAUDE_CONFIG_DIR && "
7826
7846
  : `CLAUDE_CONFIG_DIR=${shq(claudeRoot.selector)} `) + launchEnvSource(sid, agentEnvEntries(null, sid, envVars)) + agentEnvPrefix(meta, sid);
7827
7847
  const command = cwdForCmd ? `cd ${shq(cwdForCmd)} && ${envPrefix}${cmd}` : `${envPrefix}${cmd}`;
@@ -7951,10 +7971,67 @@ export class AgentLaunchPromptError extends AitermError {
7951
7971
  this.startup = startup;
7952
7972
  }
7953
7973
  }
7974
+ /** Whitespace-free head of a fork's first input; binds a forked Codex rollout, which has no launch marker (ADR 0140). */
7975
+ export function forkInputKey(text) {
7976
+ return (text ?? "").replace(/\s+/gu, "").slice(0, 2000);
7977
+ }
7978
+ /**
7979
+ * Source of a fork (ADR 0140): the main seat's saved conversation, cwd and (Claude) configuration root, plus the
7980
+ * project write-ban proven on this machine. Refusals name what they protect: a fork must never start able to write
7981
+ * the project, and never on another account or conversation.
7982
+ */
7983
+ export function resolveForkSource(kind, from, opts, probe = probeWriteBan) {
7984
+ if (kind !== "claude" && kind !== "codex")
7985
+ throw new AitermError("FORK_UNSUPPORTED: fork_from is available for claude-code and codex-cli (ADR 0140)", 2);
7986
+ if (!opts.prompt?.trim())
7987
+ throw new AitermError("FORK_INVALID: fork_from requires a prompt (the fork's first input)", 2);
7988
+ if (opts.write_scope !== undefined || opts.require_existing_resume || opts.throughline_source_session != null || opts.launch_operation_id != null
7989
+ || opts.configuration_root != null)
7990
+ throw new AitermError("FORK_INVALID: fork_from cannot be combined with write_scope, require_existing_resume, throughline_source_session, launch_operation_id or configuration_root", 2);
7991
+ if (opts.session_name && tryLoadAgentMetadata(opts.session_name))
7992
+ throw new AitermError(`FORK_INVALID: session_name ${opts.session_name} already names a seat`, 2);
7993
+ assertSessionName(from.session_id);
7994
+ const unavailable = (why) => new AitermError(`FORK_SOURCE_UNAVAILABLE: ${from.session_id}: ${why}`, 2);
7995
+ const main = tryLoadAgentMetadata(from.session_id);
7996
+ if (!main || main.kind !== kind || !main.cwd)
7997
+ throw unavailable("no managed seat of this harness");
7998
+ // Codex binds its conversation lazily and may switch it (/new): read the current one without writing the main's record.
7999
+ let rollout = null;
8000
+ try {
8001
+ rollout = main.kind === "codex" ? codexRootTranscript(main) : null;
8002
+ }
8003
+ catch {
8004
+ rollout = null;
8005
+ }
8006
+ const mainVendorId = main.kind === "codex" ? (rollout ? codexRolloutSessionId(main, rollout) : null) : main.vendor_session_id;
8007
+ if (!mainVendorId || (main.kind === "claude" ? !main.claude_home
8008
+ || !fs.existsSync(path.join(main.claude_home, "projects", claudeProjectSlug(main.cwd), `${mainVendorId}.jsonl`)) : !rollout))
8009
+ throw unavailable("the saved conversation file does not exist yet");
8010
+ if (opts.cwd != null && (!fs.existsSync(opts.cwd) || fs.realpathSync(opts.cwd) !== fs.realpathSync(main.cwd)))
8011
+ throw new AitermError("FORK_INVALID: a fork runs in its main seat's cwd; omit cwd", 2);
8012
+ // The main's cwd is the project folder the Owner forbade writing (ADR 0140).
8013
+ const write_ban = probe(main.cwd);
8014
+ let root;
8015
+ if (main.kind === "claude") {
8016
+ try {
8017
+ root = resolveClaudeConfigurationRoot(main.claude_home);
8018
+ }
8019
+ catch {
8020
+ throw unavailable("its configuration root is not an accepted root here");
8021
+ }
8022
+ }
8023
+ const first_input = kind === "codex" ? forkInputKey(opts.prompt) : undefined;
8024
+ return { fork_of: { session_id: from.session_id, vendor_session_id: mainVendorId, ...(from.fork_id ? { fork_id: from.fork_id } : {}),
8025
+ write_ban, ...(first_input ? { first_input } : {}) }, cwd: main.cwd, ...(root ? { root } : {}) };
8026
+ }
7954
8027
  export async function openAgentWithInitialPrompt(kind, opts = {}) {
8028
+ // Caller launch fields: refused from the arguments alone, before any session or file exists (phase "input").
8029
+ if (kind === "codex")
8030
+ refuseCodexCallerInput(opts.append_system_prompt, opts.mcp_config);
8031
+ const fork = opts.fork_from ? resolveForkSource(kind, opts.fork_from, opts) : null;
7955
8032
  if (opts.configuration_root != null && kind !== "claude")
7956
8033
  throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: configuration_rootはclaude-code harnessだけで使えます。", 2);
7957
- const claudeRoot = opts.configuration_root == null ? undefined : resolveClaudeConfigurationRoot(opts.configuration_root);
8034
+ const claudeRoot = fork ? fork.root : opts.configuration_root == null ? undefined : resolveClaudeConfigurationRoot(opts.configuration_root);
7958
8035
  if (opts.session_name)
7959
8036
  await withExecutionNativeAdmission(opts.session_name, () => assertExecutionContext(opts.session_name));
7960
8037
  else
@@ -8059,7 +8136,7 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
8059
8136
  // modelは呼び手の渡した形のまま渡す(空文字の断りはopenAgentがする)。Grokのfastだけ、fast版のIDへ替える。
8060
8137
  model: fastPlan.model !== requestedModel ? fastPlan.model : opts.model ?? null,
8061
8138
  reasoning_effort: opts.reasoning_effort ?? null,
8062
- cwd: opts.cwd ?? null,
8139
+ cwd: fork ? fork.cwd : opts.cwd ?? null,
8063
8140
  prompt: null,
8064
8141
  agent_done: true,
8065
8142
  launch_operation_id: opts.launch_operation_id ?? null,
@@ -8071,6 +8148,7 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
8071
8148
  claude_root: claudeRoot,
8072
8149
  append_system_prompt: opts.append_system_prompt ?? null,
8073
8150
  mcp_config: opts.mcp_config ?? null,
8151
+ ...(fork ? { fork_of: fork.fork_of } : {}),
8074
8152
  };
8075
8153
  // GrokとCursorは、起動の --model の値を利用者の既定へ書く(Cursorは版による)。起動の前後で、直前の値へ戻す。
8076
8154
  const launch = () => {
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 {
@@ -365,6 +365,9 @@ export function claudeAgentArgv(bin, model, effort, prompt, meta) {
365
365
  parts.push("--dangerously-skip-permissions", "--setting-sources", "user,project,local", "--settings", meta.claude_settings ?? "", "--session-id", meta.vendor_session_id ?? "", "--append-system-prompt", subagentInstruction(meta, CLAUDE_DELIVERY_NOTES));
366
366
  if (meta.claude_caller_prompt_file)
367
367
  parts.push("--append-system-prompt-file", meta.claude_caller_prompt_file);
368
+ // Fork (ADR 0140): the main's conversation under the seat's own --session-id; tools and MCP stay the main's.
369
+ if (meta.fork_of)
370
+ parts.push("--resume", meta.fork_of.vendor_session_id, "--fork-session");
368
371
  if (meta.claude_caller_mcp_file)
369
372
  parts.push("--mcp-config", meta.claude_caller_mcp_file);
370
373
  }
@@ -381,12 +384,15 @@ export function claudeResumeArgv(bin, model, effort, meta) {
381
384
  if (meta.kind !== "claude" || !meta.vendor_session_id || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(meta.vendor_session_id))
382
385
  throw new AitermError("AGENT_RESUME_UNSUPPORTED: Claudeの保存会話IDを確認できません。", 2);
383
386
  const argv = claudeAgentArgv(bin, model, effort, null, meta);
387
+ // A fork resumes its own conversation: drop `--resume <main> --fork-session`.
388
+ if (meta.fork_of)
389
+ argv.splice(argv.indexOf("--fork-session") - 2, 3);
384
390
  argv[argv.indexOf("--session-id")] = "--resume";
385
391
  return argv;
386
392
  }
387
393
  export function buildClaudeAgentCmd(bin, model, effort, prompt, meta) {
388
394
  const argv = claudeAgentArgv(bin, model, effort, prompt, meta);
389
- const values = new Set(["--setting-sources", "--settings", "--session-id", "--append-system-prompt", "--append-system-prompt-file", "--mcp-config", "--model", "--effort"]);
395
+ const values = new Set(["--setting-sources", "--settings", "--session-id", "--resume", "--append-system-prompt", "--append-system-prompt-file", "--mcp-config", "--model", "--effort"]);
390
396
  return argv.map((arg, index) => index === 0 || values.has(argv[index - 1]) || (prompt && index === argv.length - 1)
391
397
  ? shq(arg) : arg).join(" ");
392
398
  }
@@ -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");
@@ -136,6 +136,12 @@ export function listCodexTranscripts(codexHome) {
136
136
  * - undecided: 書いている途中などで、まだ決められない。
137
137
  * forkedは、ほかの会話から派生した会話(session_metaのforked_from_id)か。派生は元の会話の文を写すので、印だけでは持ち主を決められない。
138
138
  */
139
+ /** A fork's rollout carries no launch marker; it is this launch's when it forks the recorded main and holds the first input (ADR 0140). */
140
+ function codexForkInputSeen(record, meta) {
141
+ const key = meta.fork_of?.first_input;
142
+ return !!key && record?.type === "response_item" && record?.payload?.type === "message" && record?.payload?.role === "user"
143
+ && Array.isArray(record?.payload?.content) && record.payload.content.some((item) => item?.type === "input_text" && typeof item?.text === "string" && item.text.replace(/\s+/gu, "").includes(key));
144
+ }
139
145
  function codexLaunchVerdict(file, meta) {
140
146
  const createdAt = Date.parse(meta.created_at);
141
147
  try {
@@ -169,7 +175,11 @@ function codexLaunchVerdict(file, meta) {
169
175
  if (!rootCli)
170
176
  return { verdict: "other", forked: false };
171
177
  forked = typeof record?.payload?.forked_from_id === "string" && record.payload.forked_from_id !== "";
178
+ if (meta.fork_of && record.payload.forked_from_id !== meta.fork_of.vendor_session_id)
179
+ return { verdict: "other", forked };
172
180
  }
181
+ if (rootCli && forked && codexForkInputSeen(record, meta))
182
+ return { verdict: "match", forked };
173
183
  if (record?.type === "turn_context")
174
184
  firstTurnContext = true;
175
185
  if (record?.type === "response_item" &&
@@ -180,9 +190,12 @@ function codexLaunchVerdict(file, meta) {
180
190
  typeof item?.text === "string" &&
181
191
  item.text.includes(marker));
182
192
  }
183
- if (rootCli && launchMarker)
193
+ if (rootCli && launchMarker && !meta.fork_of)
184
194
  return { verdict: "match", forked };
185
195
  }
196
+ // A fork of the recorded main stays undecided until its first input is written: "other" is memoized for good.
197
+ if (meta.fork_of && rootCli && forked)
198
+ return { verdict: "undecided", forked };
186
199
  return { verdict: rootCli && firstTurnContext ? "other" : "undecided", forked };
187
200
  }
188
201
  export function codexTranscriptMatchesLaunch(file, meta) {
@@ -248,7 +261,7 @@ export function codexBoundTranscript(meta) {
248
261
  return origin.file;
249
262
  const file = findLatestCodexTranscript(meta.codex_home, meta.vendor_session_id);
250
263
  if (origin && (!file || codexTranscriptSessionId(file) !== meta.vendor_session_id
251
- || codexLaunchVerdict(file, meta).verdict !== "match" || codexLaunchVerdict(file, meta).forked))
264
+ || codexLaunchVerdict(file, meta).verdict !== "match" || (codexLaunchVerdict(file, meta).forked && !meta.fork_of)))
252
265
  throw resumeProofUnavailable();
253
266
  return file;
254
267
  }
@@ -531,7 +544,7 @@ function codexNativeRootRecord(meta, requireBoundary) {
531
544
  const lines = readFileRange(file, 0, Math.min(safeStatSize(file), 1024 * 1024)).toString("utf8").split("\n");
532
545
  // The final split element may be incomplete. Never parse that fragment.
533
546
  lines.pop();
534
- let session = null, own = false, root = false;
547
+ let session = null, own = false, root = false, forkOwn = false;
535
548
  for (const line of lines) {
536
549
  if (!line.trim())
537
550
  continue;
@@ -544,7 +557,7 @@ function codexNativeRootRecord(meta, requireBoundary) {
544
557
  }
545
558
  if (record?.type === "session_meta") {
546
559
  if (session !== null || record.payload?.originator !== "codex-tui" || record.payload?.source !== "cli"
547
- || record.payload?.forked_from_id)
560
+ || (record.payload?.forked_from_id && record.payload.forked_from_id !== meta.fork_of?.vendor_session_id))
548
561
  return null;
549
562
  const id = record.payload?.id;
550
563
  if (typeof id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id)
@@ -557,6 +570,8 @@ function codexNativeRootRecord(meta, requireBoundary) {
557
570
  && Array.isArray(record.payload?.content))
558
571
  own ||= record.payload.content.some((item) => (item?.type === "input_text" || item?.type === "output_text") && typeof item.text === "string"
559
572
  && item.text.split(/\r?\n/).includes(marker));
573
+ if (meta.fork_of)
574
+ own = (forkOwn ||= codexForkInputSeen(record, meta));
560
575
  if (root && own && session)
561
576
  return session;
562
577
  }
@@ -880,8 +895,144 @@ export async function observeCodexDone(meta, timeout, requestedCursor, signal) {
880
895
  await sleep(AGENT_DONE_POLL_MS);
881
896
  }
882
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
+ }
883
1033
  export function codexAgentArgv(bin, model, effort, prompt, meta) {
884
- const parts = [bin];
1034
+ // A fork (ADR 0140) starts from the main's conversation; codexResumeArgv drops this pair again.
1035
+ const parts = meta?.kind === "codex" && meta.fork_of ? [bin, "fork", meta.fork_of.vendor_session_id] : [bin];
885
1036
  // `codex --help` で確認した実在フラグ。read-only 宣言だけはCLI sandboxへ落とし、
886
1037
  // launcher自身が実効能力壁を作る。パス説明はCodex CLIに同等のallowlist引数がないため宣言のまま残す。
887
1038
  if (meta?.kind === "codex" && meta.write_scope === "read-only")
@@ -898,8 +1049,12 @@ export function codexAgentArgv(bin, model, effort, prompt, meta) {
898
1049
  if (effort)
899
1050
  parts.push("-c", `model_reasoning_effort=${effort}`);
900
1051
  if (meta?.kind === "codex" && meta.hook_route === "shared_codex_home") {
901
- 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")}` : ""}`);
902
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);
903
1058
  if (prompt)
904
1059
  parts.push(prompt); // 初手プロンプト(任意)
905
1060
  return parts;
@@ -909,7 +1064,7 @@ export function codexResumeArgv(bin, model, effort, meta, cwd) {
909
1064
  if (meta.kind !== "codex" || !meta.vendor_session_id || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(meta.vendor_session_id)
910
1065
  || !path.isAbsolute(cwd) || cwd.includes("\0"))
911
1066
  throw new AitermError("AGENT_RESUME_UNSUPPORTED: Codexの保存会話IDとcwdを確認できません。", 2);
912
- return [bin, "resume", meta.vendor_session_id, ...codexAgentArgv(bin, model, effort, null, meta).slice(1), "--cd", cwd];
1067
+ return [bin, "resume", meta.vendor_session_id, ...codexAgentArgv(bin, model, effort, null, meta).slice(meta.fork_of ? 3 : 1), "--cd", cwd];
913
1068
  }
914
1069
  export function buildCodexAgentCmd(bin, model, effort, prompt, meta) {
915
1070
  const argv = codexAgentArgv(bin, model, effort, prompt, meta);
@@ -917,6 +1072,8 @@ export function buildCodexAgentCmd(bin, model, effort, prompt, meta) {
917
1072
  if (index === 0 || argv[index - 1] === "-m" || (prompt && index === argv.length - 1))
918
1073
  return shq(arg);
919
1074
  if (argv[index - 1] === "-c") {
1075
+ if (arg.startsWith("mcp_servers."))
1076
+ return shq(arg);
920
1077
  for (const key of ["model_reasoning_effort=", "developer_instructions="]) {
921
1078
  if (arg.startsWith(key))
922
1079
  return key + shq(arg.slice(key.length));