aiterm-mcp 0.70.6 → 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,19 @@ 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
+
10
23
  ## [0.70.6] - 2026-11-10
11
24
 
12
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.
@@ -3194,7 +3207,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3194
3207
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3195
3208
  provenance.
3196
3209
 
3197
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.6...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
3198
3212
  [0.70.6]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.5...v0.70.6
3199
3213
  [0.70.5]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.4...v0.70.5
3200
3214
  [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.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.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.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;
@@ -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
  }
package/dist/core.js CHANGED
@@ -65,7 +65,7 @@ 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";
@@ -385,6 +385,8 @@ function cleanupAgentState(name) {
385
385
  f.endsWith(".claude-mcp.json") ||
386
386
  f.endsWith(".claude-caller-prompt.md") ||
387
387
  f.endsWith(".claude-caller-mcp.json") ||
388
+ f.endsWith(".codex-caller-prompt.md") ||
389
+ f.endsWith(".codex-caller-mcp.json") ||
388
390
  f.endsWith(".launch-env") ||
389
391
  f.endsWith(".claude-result.json") ||
390
392
  f.endsWith(".cursor-result.json") ||
@@ -6874,6 +6876,10 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot) {
6874
6876
  next.claude_caller_prompt_file = previous.claude_caller_prompt_file;
6875
6877
  if (previous.claude_caller_mcp_file)
6876
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;
6877
6883
  if (isWin)
6878
6884
  next.windows_launch_exit_tracked = true;
6879
6885
  if (next.kind === "claude")
@@ -7786,6 +7792,8 @@ function prepareAgentLaunch(kind, opts = {}) {
7786
7792
  meta.agent_executable = bin;
7787
7793
  if (meta.kind === "claude")
7788
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);
7789
7797
  if (opts.fork_of)
7790
7798
  meta.fork_of = opts.fork_of;
7791
7799
  if (isWin && ["claude", "codex", "grok", "antigravity"].includes(kind))
@@ -8017,6 +8025,9 @@ export function resolveForkSource(kind, from, opts, probe = probeWriteBan) {
8017
8025
  write_ban, ...(first_input ? { first_input } : {}) }, cwd: main.cwd, ...(root ? { root } : {}) };
8018
8026
  }
8019
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);
8020
8031
  const fork = opts.fork_from ? resolveForkSource(kind, opts.fork_from, opts) : null;
8021
8032
  if (opts.configuration_root != null && kind !== "claude")
8022
8033
  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));
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { loadAgentMetadata } from "./agent-metadata-reader.js";
3
3
  import { remoteInputDescription, remoteInputSchema, terminalArgumentDescription, terminalArgumentSchema } from "./remote-contract.js";
4
- import { boundTerminalTarget, bindTerminalSession, terminalSeatGroups, ensureSeatForward, extractMcpHeaders, maintainSeatForwards, REMOTE_MINIMUM_VERSION, seatIngressPort, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
4
+ import { boundTerminalTarget, bindTerminalSession, terminalSeatGroups, ensureSeatForward, extractMcpHeaders, maintainSeatForwards, REMOTE_MINIMUM_VERSION, seatIngressPort, checkTerminalPlatform, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
5
5
  import { launchEnvValue } from "./private-env.js";
6
6
  import { AuthResponseError, authUiSchema, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
7
7
  import { configurationRequestSchema, configurationToolOutputSchema, applyConfigurationRequest, reconcileConfigurationRequest } from "./configure-request.js";
8
- import { AitermError, AgentAuthenticationPreflightError, AgentResumeUnavailableError, AgentResumeError } from "./errors.js";
8
+ import { AitermError, AgentAuthenticationPreflightError, AgentResumeUnavailableError, AgentResumeError, launchInputRefusal } from "./errors.js";
9
9
  /**
10
10
  * aiterm-mcp — AI が握るローカル永続端末を stdio MCP サーバとして公開する(Node/TS 版)。
11
11
  *
@@ -20,6 +20,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
20
20
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
21
21
  import { readPrivateEnvLine, setPrivateEnv } from "./private-env.js";
22
22
  import { withTerminalLaunchAction, withErrorCode, launchNotStartedMeta } from "./terminal-launch-error.js";
23
+ import { codexMcpOverrides } from "./harnesses/codex.js";
23
24
  import { CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
24
25
  import { z } from "zod";
25
26
  import { agentModelsResult } from "./model-catalog.js";
@@ -261,7 +262,7 @@ export function createAitermServer(options = {}) {
261
262
  };
262
263
  if (e instanceof AitermError && e.launchNotStarted)
263
264
  return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
264
- _meta: launchNotStartedMeta(e.launchNotStarted.harness) };
265
+ _meta: launchNotStartedMeta(e.launchNotStarted.harness, e.launchNotStarted.phase) };
265
266
  return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true };
266
267
  }
267
268
  /**
@@ -840,15 +841,16 @@ export function createAitermServer(options = {}) {
840
841
  try {
841
842
  const local = core.readSeatTurns(sessions.filter(session => session.harness !== null).map(session => session.session_id));
842
843
  // Terminal seats: the same call relayed with the same _meta; each terminal answers only for its own bound sessions.
843
- // Inside the caller's 5 s pty_list budget (tool catalog timeout_ms): a slow or unreachable terminal contributes no rows.
844
+ // Inside the caller's 5 s pty_list budget (tool catalog timeout_ms): a terminal that fails or is slow contributes
845
+ // no rows, and its sessions are listed in `unread` so the caller keeps their last state instead of reading them as gone.
844
846
  const remote = await Promise.all(terminalSeatGroups().map(({ target, sessions: bound }) => Promise.race([
845
847
  callRemoteTool(target, "pty_list", {}, 4_000, undefined, requestMeta).then(result => {
846
848
  const seats = result._meta?.[SEAT_TURNS_RESULT_META_KEY]?.seats;
847
- return Array.isArray(seats) ? seats.filter((seat) => bound.includes(seat?.session_id)) : [];
848
- }, () => []),
849
- new Promise(resolve => setTimeout(resolve, 4_000, []).unref()),
849
+ return Array.isArray(seats) ? { seats: seats.filter((seat) => bound.includes(seat?.session_id)), unread: [] } : { seats: [], unread: bound };
850
+ }, () => ({ seats: [], unread: bound })),
851
+ new Promise(resolve => setTimeout(resolve, 4_000, { seats: [], unread: bound }).unref()),
850
852
  ])));
851
- return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { ...local, seats: [...local.seats, ...remote.flat()] } } };
853
+ return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { ...local, seats: [...local.seats, ...remote.flatMap(r => r.seats)], unread: remote.flatMap(r => r.unread) } } };
852
854
  }
853
855
  catch (e) {
854
856
  return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { schema: "aiterm.seat-turns.v1", error: e instanceof Error ? e.message : String(e) } } };
@@ -1219,11 +1221,15 @@ export function createAitermServer(options = {}) {
1219
1221
  async function launchRemoteAgent(target, harness, args, extra, privateEnv) {
1220
1222
  if (args.image && args.image.length > 0)
1221
1223
  throw new core.AitermError("REMOTE_IMAGE_UNSUPPORTED: 別端末への画像添付には未対応です", 2);
1222
- // An Aiterm without fork_from would drop it and start a writable seat (ADR 0140): check the version first.
1223
- if (args.fork_from) {
1224
+ // An Aiterm without fork_from would drop it and start a writable seat (ADR 0140), and one without Codex caller fields
1225
+ // would drop or refuse them: check the version first.
1226
+ const needs = args.fork_from ? { minimum: FORK_MINIMUM_VERSION, what: "fork_from" }
1227
+ : harness === "codex-cli" && (args.append_system_prompt !== undefined || args.mcp_config !== undefined)
1228
+ ? { minimum: CODEX_REMOTE_MINIMUM_VERSION, what: "append_system_prompt / mcp_config for codex-cli" } : null;
1229
+ if (needs) {
1224
1230
  const version = (await callRemoteTool(target, "pty_list", {}, 60_000)).remote_version ?? "0.0.0";
1225
- if (!versionAtLeast(version, FORK_MINIMUM_VERSION))
1226
- throw new AitermError(`REMOTE_AITERM_TOO_OLD: the remote runs Aiterm ${version}; fork_from needs ${FORK_MINIMUM_VERSION} or later`, 2);
1231
+ if (!versionAtLeast(version, needs.minimum))
1232
+ throw new AitermError(`REMOTE_AITERM_TOO_OLD: the remote runs Aiterm ${version}; ${needs.what} needs ${needs.minimum} or later`, 2);
1227
1233
  }
1228
1234
  const delivery = args.prompt || args.throughline_source_session ? await deliveryForRequest(extra, true) : null;
1229
1235
  // A terminal's claude_agent takes append_system_prompt / mcp_config since 0.65.0; its agent_launch drops them until this release.
@@ -1259,27 +1265,32 @@ export function createAitermServer(options = {}) {
1259
1265
  }
1260
1266
  /** First release whose agent_launch knows fork_from (ADR 0140). */
1261
1267
  const FORK_MINIMUM_VERSION = "0.70.6";
1268
+ /** First release whose agent_launch takes append_system_prompt / mcp_config for codex-cli, and the first a terminal may run a Codex seat on. */
1269
+ const CODEX_REMOTE_MINIMUM_VERSION = "0.70.7";
1262
1270
  const terminalVersions = new Map();
1263
1271
  /** A seat on a BellTeam terminal (remote-terminal.md "One launch path"). Same launch arguments plus terminal + cwd. */
1264
1272
  async function launchTerminalAgent(harness, terminal, args, extra) {
1265
1273
  try {
1266
1274
  if (args.remote)
1267
1275
  throw new AitermError("TERMINAL_INVALID: use terminal or remote, not both; for a registered terminal pass only terminal", 2);
1268
- if (harness !== "claude-code")
1269
- throw new AitermError(`TERMINAL_HARNESS_UNSUPPORTED: terminal seats support harness claude-code first; ${harness} is not available on a terminal yet`, 2);
1270
- if (typeof args.cwd !== "string" || !args.cwd.startsWith("/"))
1271
- throw new AitermError("TERMINAL_INVALID: cwd is required with terminal: the absolute project folder on that terminal (never launch locally and cd)", 2);
1276
+ if (harness !== "claude-code" && harness !== "codex-cli")
1277
+ throw new AitermError(`TERMINAL_HARNESS_UNSUPPORTED: terminal seats support harnesses claude-code and codex-cli; ${harness} is not available on a terminal yet`, 2);
1278
+ // A declared Windows terminal is refused by the platform check below (0.70.8 brings its path form).
1279
+ if (typeof args.cwd !== "string" || (terminal.os !== "windows" && !args.cwd.startsWith("/")))
1280
+ throw new AitermError("TERMINAL_INVALID: cwd is required with terminal: the absolute POSIX project folder on that terminal, starting with / (never launch locally and cd)", 2);
1272
1281
  if (args.require_existing_resume)
1273
1282
  throw new AitermError("TERMINAL_INVALID: require_existing_resume is local-only", 2);
1274
1283
  const target = terminalRemoteTarget(terminal);
1284
+ await checkTerminalPlatform(target, terminal.os);
1275
1285
  // The private line is sent before the server answers; check its version first so an old one never sees it.
1276
1286
  let version = terminalVersions.get(target.trusted_ref);
1277
1287
  if (!version) {
1278
1288
  version = (await callRemoteTool(target, "pty_list", {}, 60_000)).remote_version ?? "0.0.0";
1279
1289
  terminalVersions.set(target.trusted_ref, version);
1280
1290
  }
1281
- if (!versionAtLeast(version, REMOTE_MINIMUM_VERSION))
1282
- throw new AitermError(`REMOTE_AITERM_TOO_OLD: the terminal runs Aiterm ${version}; ${REMOTE_MINIMUM_VERSION} or later is required (update Aiterm on the terminal)`, 2);
1291
+ const minimum = harness === "codex-cli" ? CODEX_REMOTE_MINIMUM_VERSION : REMOTE_MINIMUM_VERSION;
1292
+ if (!versionAtLeast(version, minimum))
1293
+ throw new AitermError(`REMOTE_AITERM_TOO_OLD: the terminal runs Aiterm ${version}; ${minimum} or later is required (update Aiterm on the terminal)`, 2);
1283
1294
  const privateEnv = {};
1284
1295
  for (const name of args.env_vars ?? []) {
1285
1296
  const value = launchEnvValue(name);
@@ -1291,6 +1302,14 @@ export function createAitermServer(options = {}) {
1291
1302
  const extracted = extractMcpHeaders(mcpConfig);
1292
1303
  Object.assign(privateEnv, extracted.env);
1293
1304
  mcpConfig = extracted.config;
1305
+ // Codex cannot say every header shape: refuse here, not on the terminal after the private line was sent.
1306
+ if (harness === "codex-cli")
1307
+ try {
1308
+ codexMcpOverrides(mcpConfig);
1309
+ }
1310
+ catch (e) {
1311
+ throw launchInputRefusal(harness, e.message);
1312
+ }
1294
1313
  const ingress = seatIngressPort(mcpConfig);
1295
1314
  if (ingress)
1296
1315
  mcpConfig = rewriteSeatMcpConfig(mcpConfig, await ensureSeatForward(target.trusted_ref, ingress));
@@ -1300,10 +1319,10 @@ export function createAitermServer(options = {}) {
1300
1319
  const session = result?.structuredContent?.session_id;
1301
1320
  if (typeof session === "string")
1302
1321
  bindTerminalSession(session, target.trusted_ref);
1303
- return withErrorCode(withTerminalLaunchAction(result));
1322
+ return withErrorCode(withTerminalLaunchAction(result, harness));
1304
1323
  }
1305
1324
  catch (e) {
1306
- return withErrorCode(withTerminalLaunchAction(fail(e)));
1325
+ return withErrorCode(withTerminalLaunchAction(fail(e), harness));
1307
1326
  }
1308
1327
  }
1309
1328
  async function launchAgent(kind, args, extra) {
@@ -1312,10 +1331,10 @@ export function createAitermServer(options = {}) {
1312
1331
  let delivery = null;
1313
1332
  try {
1314
1333
  if (!supportsWriteScope && write_scope !== undefined) {
1315
- throw new core.AitermError("claude-code harnessはwrite_scopeに対応していません。指定を外してください", 2);
1334
+ throw launchInputRefusal(core.agentHarness(kind), "claude-code harnessはwrite_scopeに対応していません。指定を外してください");
1316
1335
  }
1317
1336
  if (require_existing_resume && ((image?.length ?? 0) > 0 || prompt != null || throughline_source_session != null || throughline_supplement_file != null))
1318
- throw new core.AitermError("require_existing_resume is promptless", 2);
1337
+ throw launchInputRefusal(core.agentHarness(kind), "require_existing_resume is promptless");
1319
1338
  if (!require_existing_resume)
1320
1339
  await core.maintainAgentIdleClocks();
1321
1340
  const initialPrompt = image && image.length > 0 ? core.attachImages(prompt ?? "", image) : prompt ?? undefined;
@@ -1497,8 +1516,8 @@ export function createAitermServer(options = {}) {
1497
1516
  launch_operation_id: z.string().regex(/^sha256:[0-9a-f]{64}$/).optional().describe("Claude Codeのpromptなしexact replay相関だけで使用"),
1498
1517
  remote: remoteInputField,
1499
1518
  terminal: terminalArgumentSchema.optional().describe(terminalArgumentDescription),
1500
- append_system_prompt: z.string().min(1).optional().describe("claude-code only. Launch instructions added to the system prompt; kept in Aiterm state, not in the project or home. Never put secrets here"),
1501
- mcp_config: z.object({ mcpServers: z.record(z.string(), z.unknown()) }).strict().optional().describe("claude-code only. Extra MCP servers for this seat. Secret header values: write ${NAME} and list NAME in env_vars"),
1519
+ append_system_prompt: z.string().min(1).optional().describe("claude-code and codex-cli only. Launch instructions added to the system prompt (Codex: appended to developer_instructions after Aiterm's marker, at most 64 KiB); kept in Aiterm state, not in the project or home. Never put secrets here"),
1520
+ mcp_config: z.object({ mcpServers: z.record(z.string(), z.unknown()) }).strict().optional().describe("claude-code and codex-cli only. Extra MCP servers for this seat. Secret header values: write ${NAME} and list NAME in env_vars. Codex takes only http servers {type?: \"http\", url, headers}: 'Authorization: Bearer ${NAME}' or a header whose whole value is ${NAME}; other shapes are refused before the seat starts"),
1502
1521
  fork_from: z.object({
1503
1522
  session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/).describe("The main Aiterm seat on the same machine (the terminal or remote when given)"),
1504
1523
  fork_id: z.string().min(1).max(200).optional().describe("Caller's fork ID, passed to the seat as THROUGHLINE_FORK_ID"),
@@ -1528,14 +1547,14 @@ export function createAitermServer(options = {}) {
1528
1547
  write_ban: z.object({ path: z.string(), method: z.enum(["landlock", "seatbelt"]) }) }).optional().describe("The seat this fork copies and the folder it cannot write"),
1529
1548
  },
1530
1549
  }, async ({ harness, remote, terminal, ...args }, extra) => {
1531
- if (harness !== "claude-code" && (args.append_system_prompt !== undefined || args.mcp_config !== undefined))
1532
- return fail(new AitermError("append_system_prompt and mcp_config are claude-code only", 2));
1550
+ if (harness !== "claude-code" && harness !== "codex-cli" && (args.append_system_prompt !== undefined || args.mcp_config !== undefined))
1551
+ return fail(launchInputRefusal(harness, `append_system_prompt and mcp_config are claude-code and codex-cli only; ${harness} cannot take them`));
1533
1552
  if (terminal)
1534
1553
  return launchTerminalAgent(harness, terminal, { ...args, ...(remote ? { remote } : {}) }, extra);
1535
1554
  if (remote && args.require_existing_resume)
1536
1555
  return fail(typeof args.session_name === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(args.session_name)
1537
1556
  ? new AgentResumeUnavailableError(args.session_name)
1538
- : new AitermError("require_existing_resume requires session_name", 2));
1557
+ : launchInputRefusal(harness, "require_existing_resume requires session_name"));
1539
1558
  if (!remote)
1540
1559
  return launchAgent(kindForHarness(harness), args, extra);
1541
1560
  try {
@@ -171,7 +171,7 @@ export function signalRuntimeProcess(target, signal, group) {
171
171
  "try {",
172
172
  "[void]$target.Handle",
173
173
  `if(([DateTimeOffset]$target.StartTime.ToUniversalTime()).ToUnixTimeMilliseconds() -ne ${Date.parse(target.started_identity)}) { exit 4 }`,
174
- signal === "SIGTERM" ? "[void]$target.CloseMainWindow()" : "$target.Kill()",
174
+ signal === "SIGKILL" ? "$target.Kill()" : "[void]$target.CloseMainWindow()",
175
175
  "} finally { $target.Dispose() }",
176
176
  ].join("\n");
177
177
  const result = spawnSync(resolveWindowsPowerShell7(), ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand",
@@ -5,7 +5,9 @@ const nativeRuntime = {
5
5
  read: () => readRuntimeProcesses(true), signal: signalRuntimeProcess,
6
6
  pause: ms => new Promise(resolve => setTimeout(resolve, ms)), now: () => performance.now(),
7
7
  };
8
- /** TERM, a five-second grace, then KILL; only the original pane tree and verified groups are selected. */
8
+ /** TERM, a five-second grace, then KILL; only the original pane tree and verified groups are selected.
9
+ * An interactive shell ignores TERM, so once its children are gone and only the pane root is left it is hung up,
10
+ * as a closing terminal would. A root that started alone keeps the full grace. */
9
11
  export async function stopProcessTree(root, verify, runtime = nativeRuntime) {
10
12
  if (!Number.isSafeInteger(root.pid) || root.pid <= 1 || root.pid === process.pid)
11
13
  throw new Error("invalid_process_tree_root");
@@ -67,7 +69,7 @@ export async function stopProcessTree(root, verify, runtime = nativeRuntime) {
67
69
  terminated.add(key(member));
68
70
  }
69
71
  });
70
- let until = null;
72
+ let until = null, hungUp = false;
71
73
  for (;;) {
72
74
  const alive = refresh();
73
75
  if (alive.length === 0)
@@ -77,6 +79,10 @@ export async function stopProcessTree(root, verify, runtime = nativeRuntime) {
77
79
  for (const row of childrenFirst(alive))
78
80
  if (!terminated.has(key(row)))
79
81
  signal(row, "SIGTERM");
82
+ if (until !== null && !hungUp && tree.length > 1 && alive.length === 1 && alive[0].pid === root.pid) {
83
+ signal(alive[0], "SIGHUP");
84
+ hungUp = true;
85
+ }
80
86
  until ??= runtime.now() + 5000;
81
87
  await runtime.pause(Math.min(100, Math.max(0, until - runtime.now())));
82
88
  }
@@ -27,6 +27,8 @@ export const credentialHandleSchema = z.object({
27
27
  handle: z.string().uuid("credential.handle must be the handle (UUID) the terminal registry gave, unchanged"),
28
28
  revision: z.number().int().positive("credential.revision must be the handle's positive integer revision, unchanged").max(Number.MAX_SAFE_INTEGER),
29
29
  }).strict();
30
+ /** The terminal's operating system as BellTeam registers it; Aiterm compares it with what the terminal really is (R20). */
31
+ export const terminalOsSchema = z.enum(["macos", "linux", "windows"]);
30
32
  /** The launch tools' terminal target (remote-terminal.md "One launch path"). Copied unchanged from BellTeam terminals. */
31
33
  export const terminalArgumentSchema = z.object({
32
34
  ref: z.string().uuid("terminal.ref must be the binding ref (UUID) the terminal registry gave for this terminal"),
@@ -35,6 +37,7 @@ export const terminalArgumentSchema = z.object({
35
37
  user: z.string().min(1, "terminal.target.user is required"),
36
38
  port: z.number().int().min(1).max(65535),
37
39
  }).strict(),
40
+ os: terminalOsSchema.optional(),
38
41
  trustRevision: revision("trustRevision"),
39
42
  credentialRevision: revision("credentialRevision").optional(),
40
43
  credential: credentialHandleSchema.optional(),
@@ -45,8 +48,8 @@ export const terminalArgumentSchema = z.object({
45
48
  message: "terminal needs exactly one key source: credential {handle, revision} from the registry, or credentialRevision for a native key" });
46
49
  });
47
50
  export const terminalArgumentDescription = "Run this seat on another computer (a registered terminal) over SSH. Value: exactly the terminal value your host system's terminal registry hands over, " +
48
- "{ref, target:{host,user,port}, trustRevision, and credentialRevision or credential {handle, revision}}; copy it unchanged, never invent or edit it, never use a host name or ssh command instead. " +
49
- "Omit it to launch on this computer. Give cwd in the same call: the absolute project folder on that terminal. Never launch locally and then cd or ssh. " +
51
+ "{ref, target:{host,user,port}, os?, trustRevision, and credentialRevision or credential {handle, revision}}; copy it unchanged, never invent or edit it, never use a host name or ssh command instead. " +
52
+ "Omit it to launch on this computer. Give cwd in the same call: the absolute project folder on that terminal (a POSIX path starting with /). Never launch locally and then cd or ssh. " +
50
53
  "Never put tokens, passwords or other secrets in any argument, prompt or typed text; pass secret values only by name in env_vars. " +
51
54
  "After launch, use session_id alone for pty_send, pty_observe, pty_read, pty_key, claude_turn, agent_stop and pty_close; Aiterm routes them to the terminal. " +
52
55
  "Errors and next step: TERMINAL_INVALID = malformed value, missing/relative cwd, or combined with remote: pass the registry's value unchanged with cwd. " +
@@ -56,4 +59,6 @@ export const terminalArgumentDescription = "Run this seat on another computer (a
56
59
  "CREDENTIAL_REQUIRED / CREDENTIAL_NOT_LOADED = this terminal's key comes from a credential handle that the registry must load first; never paste a key anywhere. " +
57
60
  "AUTH_FAILED = the terminal refused the key. UNREACHABLE = the terminal is offline; try later. CONNECTION_REFUSED = the terminal refused the SSH connection (SSH may be off there); try later. " +
58
61
  "REMOTE_AITERM_TOO_OLD = update Aiterm on the terminal. CWD_UNAVAILABLE = the folder does not exist there; do not pick another folder. " +
59
- "SEAT_FORWARD_UNAVAILABLE = the seat's MCP route back to this computer is not ready (launch again later), or the seat MCP URLs are not http://127.0.0.1:<one port>/api/seat-mcp. TERMINAL_HARNESS_UNSUPPORTED = use harness claude-code.";
62
+ "SEAT_FORWARD_UNAVAILABLE = the seat's MCP route back to this computer is not ready (launch again later), or the seat MCP URLs are not http://127.0.0.1:<one port>/api/seat-mcp. TERMINAL_HARNESS_UNSUPPORTED = use harness claude-code or codex-cli (codex-cli needs Aiterm 0.70.7 on the terminal). " +
63
+ "TERMINAL_OS_MISMATCH = the terminal is not the operating system os says: the registry's os is wrong or the binding points at another machine; ask the terminal registry, do not retry. " +
64
+ "TERMINAL_PLATFORM_UNSUPPORTED = Windows (and any system that is not macOS or Linux) cannot run seats yet.";
@@ -1,4 +1,4 @@
1
- // provision (remote-terminal.md R16): install this Aiterm version as a product-owned runtime on a macOS terminal,
1
+ // provision (remote-terminal.md R16): install this Aiterm version as a product-owned runtime on a macOS or Linux terminal,
2
2
  // before any terminal MCP exists. Runs over the binding's trusted key SSH; the terminal fetches the release assets.
3
3
  import { spawn, spawnSync } from "node:child_process";
4
4
  import { createRequire } from "node:module";
@@ -11,13 +11,28 @@ export const RUNTIME_RELEASE_BASE = "https://github.com/kitepon/aiterm-mcp/relea
11
11
  export const PROVISION_SCRIPT = String.raw `set -u
12
12
  V="$1"; BASE="$2"
13
13
  fail() { echo "AITERM_PROVISION_ERROR $1"; exit 3; }
14
- [ "$(uname -s)" = Darwin ] || fail PROVISION_PLATFORM_UNSUPPORTED
15
- case "$(uname -m)" in
16
- arm64) A=arm64 ;;
17
- x86_64) if [ "$(sysctl -in hw.optional.arm64 2>/dev/null)" = 1 ]; then A=arm64; else A=x64; fi ;;
14
+ case "$(uname -s)" in
15
+ Darwin)
16
+ OS=darwin
17
+ case "$(uname -m)" in
18
+ arm64) A=arm64 ;;
19
+ x86_64) if [ "$(sysctl -in hw.optional.arm64 2>/dev/null)" = 1 ]; then A=arm64; else A=x64; fi ;;
20
+ *) fail PROVISION_PLATFORM_UNSUPPORTED ;;
21
+ esac ;;
22
+ Linux)
23
+ OS=linux
24
+ case "$(uname -m)" in
25
+ x86_64) A=x64 ;;
26
+ aarch64|arm64) A=arm64 ;;
27
+ *) fail PROVISION_PLATFORM_UNSUPPORTED ;;
28
+ esac
29
+ # The Linux runtime has no tmux: seats use the user's own. Look on the login PATH, as the later remote commands do.
30
+ s=$(printenv SHELL); [ -x "$s" ] || s=/bin/sh
31
+ p=$("$s" -lc env </dev/null 2>/dev/null | sed -n 's/^PATH=//p' | tail -n 1); [ -n "$p" ] && PATH=$p; export PATH
32
+ command -v tmux >/dev/null 2>&1 || fail PROVISION_TMUX_MISSING ;;
18
33
  *) fail PROVISION_PLATFORM_UNSUPPORTED ;;
19
34
  esac
20
- NAME="aiterm-runtime-$V-darwin-$A"
35
+ NAME="aiterm-runtime-$V-$OS-$A"
21
36
  ROOT="$HOME/.aiterm/runtime"
22
37
  mkdir -p "$ROOT" 2>/dev/null && chmod 700 "$HOME/.aiterm" "$ROOT" 2>/dev/null || fail RUNTIME_DIR_UNAVAILABLE
23
38
  smoke() { "$1/bin/aiterm-remote-terminal" runtime-smoke --expect-version "$V" >/dev/null 2>&1 </dev/null; }
@@ -86,7 +101,7 @@ export async function provision(ref, version = pkg.version) {
86
101
  if (parsed && "result" in parsed && run.code === 0)
87
102
  return { schema: "aiterm.remote-provision.v1", ref, result: parsed.result, version: parsed.version };
88
103
  if (parsed && "code" in parsed)
89
- throw new RemoteTerminalError(parsed.code, `provisioning the terminal failed (${parsed.code})`);
104
+ throw new RemoteTerminalError(parsed.code, `provisioning the terminal failed (${parsed.code})`, parsed.code === "PROVISION_TMUX_MISSING" ? "install tmux with the terminal's package manager (for example apt install tmux), then provision again" : undefined);
90
105
  if (run.code === 255) {
91
106
  const f = classifySshFailure(run.stderr);
92
107
  throw new RemoteTerminalError(f.code, f.message, f.action);
@@ -98,6 +113,9 @@ export async function runtimeSmoke(expectVersion) {
98
113
  if (pkg.version !== expectVersion)
99
114
  throw new RemoteTerminalError("RUNTIME_SMOKE_FAILED", `runtime is ${pkg.version}, expected ${expectVersion}`);
100
115
  const tmux = spawnSync("tmux", ["-V"], { encoding: "utf8", timeout: 10_000 });
116
+ // The Linux runtime carries no tmux; its absence is the user's to fix.
117
+ if (process.platform === "linux" && tmux.error?.code === "ENOENT")
118
+ throw new RemoteTerminalError("PROVISION_TMUX_MISSING", "tmux is not installed on the terminal", "install tmux with the terminal's package manager, then provision again");
101
119
  if (tmux.status !== 0)
102
120
  throw new RemoteTerminalError("RUNTIME_SMOKE_FAILED", "tmux does not run");
103
121
  await verifySetupRuntime({ command: process.execPath, args: [fileURLToPath(new URL("./index.js", import.meta.url))] });
@@ -4,7 +4,7 @@
4
4
  // serve stdio MCP for one bound connection, spawned by BellTeam terminals
5
5
  // credential-load --ref R --terminal-id ID --handle UUID --revision N --purpose ssh-key (key bytes on stdin; one JSON receipt line)
6
6
  // transcript-read --session S [--cursor-session ID --offset N] [--max-bytes N] (runs on the terminal)
7
- // authorize-key --ref R (login password on stdin until EOF; R14) provision --ref R (macOS runtime; R16)
7
+ // authorize-key --ref R (login password on stdin until EOF; R14) provision --ref R (macOS/Linux runtime; R16)
8
8
  // path-status|make-dir --path P | --path-base64 B, list-dirs [--path P | --path-base64 B] (on the terminal; R15) runtime-smoke --expect-version V (on the terminal)
9
9
  import { realpathSync } from "node:fs";
10
10
  import { fileURLToPath } from "node:url";
@@ -14,7 +14,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
14
14
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
15
15
  import { REMOTE_COMMAND_OPS, RemoteTerminalConnection, RemoteTerminalError, bindingStatus, confirmHostKey, loadCredential, registerBinding } from "./remote-terminal.js";
16
16
  import { readCompletedTranscript } from "./transcript-read.js";
17
- import { credentialHandleSchema } from "./remote-contract.js";
17
+ import { credentialHandleSchema, terminalOsSchema } from "./remote-contract.js";
18
18
  import { inspectPath, listDirectories, makeDirectory } from "./remote-path.js";
19
19
  import { ASKPASS_SOCKET_ENV, askpass, authorizeKey, prepareAuthorization } from "./remote-authorize.js";
20
20
  import { provision, runtimeSmoke } from "./remote-provision.js";
@@ -67,7 +67,7 @@ function serve() {
67
67
  server.registerTool("remote_terminal_status", { description: "Public status of a terminal binding", inputSchema: { ref: z.string() } }, guarded(({ ref }) => bindingStatus(ref)));
68
68
  server.registerTool("remote_terminal_open", {
69
69
  description: "Open the bound connection for this process",
70
- inputSchema: { ref: z.string(), target: z.object({ host: z.string(), user: z.string(), port: z.number().int() }).strict(),
70
+ inputSchema: { ref: z.string(), target: z.object({ host: z.string(), user: z.string(), port: z.number().int() }).strict(), os: terminalOsSchema.optional(),
71
71
  trustRevision: z.string(), credentialRevision: z.string().optional(), credential: credentialHandleSchema.optional(),
72
72
  sudoCredential: credentialHandleSchema.optional(), privateEnv: z.record(z.string(), z.string()).optional() },
73
73
  }, guarded(async (args) => {
@@ -77,7 +77,7 @@ function serve() {
77
77
  connection.on("event", event => {
78
78
  server.server.notification({ method: "aiterm/remote-terminal-event", params: event }).catch(() => { });
79
79
  });
80
- return { opened: true, remoteVersion: connection.remoteVersion };
80
+ return { opened: true, remoteVersion: connection.remoteVersion, platform: connection.platform };
81
81
  }));
82
82
  server.registerTool("remote_terminal_call", {
83
83
  description: "Call a seat tool on the terminal's Aiterm",
@@ -10,7 +10,7 @@ import { createRequire } from "node:module";
10
10
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
11
11
  import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
12
12
  import { ensureStateRoot, writeJson0600 } from "./agent-shared.js";
13
- import { posixCommand } from "./remote.js";
13
+ import { posixCommand, remotePlatform } from "./remote.js";
14
14
  import { PRIVATE_ENV_SCHEMA } from "./private-env.js";
15
15
  import { checkRemotePath } from "./remote-path.js";
16
16
  const pkg = createRequire(import.meta.url)("../package.json");
@@ -305,8 +305,9 @@ export class RemoteTerminalConnection extends EventEmitter {
305
305
  identity;
306
306
  client;
307
307
  remoteVersion;
308
+ platform;
308
309
  closing = false;
309
- constructor(b, dir, agent, socket, identity, client, remoteVersion) {
310
+ constructor(b, dir, agent, socket, identity, client, remoteVersion, platform) {
310
311
  super();
311
312
  this.b = b;
312
313
  this.dir = dir;
@@ -315,6 +316,7 @@ export class RemoteTerminalConnection extends EventEmitter {
315
316
  this.identity = identity;
316
317
  this.client = client;
317
318
  this.remoteVersion = remoteVersion;
319
+ this.platform = platform;
318
320
  }
319
321
  static async open(input) {
320
322
  const target = validTarget(input.target);
@@ -330,6 +332,8 @@ export class RemoteTerminalConnection extends EventEmitter {
330
332
  for (const [name, value] of Object.entries(input.privateEnv ?? {}))
331
333
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || typeof value !== "string")
332
334
  throw new RemoteTerminalError("PRIVATE_ENV_INVALID", "invalid private env entry");
335
+ // R20: the connect command is shell-specific, so the platform is known (and the declared os checked) before any MCP connection.
336
+ const platform = await checkTerminalPlatform(trustedTarget(b), input.os);
333
337
  // Short path: the agent socket must fit macOS's 104-byte sun_path.
334
338
  const dir = fs.mkdtempSync(path.join(os.platform() === "win32" ? os.tmpdir() : "/tmp", "aiterm-rt-"));
335
339
  fs.chmodSync(dir, 0o700);
@@ -375,7 +379,7 @@ export class RemoteTerminalConnection extends EventEmitter {
375
379
  await client.close().catch(() => { });
376
380
  throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${remoteVersion}; ${REMOTE_MINIMUM_VERSION} or later is required`);
377
381
  }
378
- const connection = new RemoteTerminalConnection(b, dir, agent, agentSocket, identity, client, remoteVersion);
382
+ const connection = new RemoteTerminalConnection(b, dir, agent, agentSocket, identity, client, remoteVersion, platform);
379
383
  client.onclose = () => connection.ended();
380
384
  // After the caller has attached its listener to the returned connection.
381
385
  setImmediate(() => connection.emit("event", { type: "ready", at: new Date().toISOString(), remoteVersion }));
@@ -486,7 +490,8 @@ export class RemoteTerminalConnection extends EventEmitter {
486
490
  const f = classifySshFailure(run.stderr);
487
491
  throw new RemoteTerminalError(f.code, f.message, f.action);
488
492
  }
489
- const probe = op === "claude_version" ? run : await this.exec("claude --version 2>&1", 60_000);
493
+ // The official installer puts claude in ~/.local/bin, which a login shell may not have on PATH yet (Linux).
494
+ const probe = op === "claude_version" ? run : await this.exec('claude --version 2>&1 || "$HOME/.local/bin/claude" --version 2>&1', 60_000);
490
495
  const version = probe.code === 0 ? (/\d+\.\d+\.\d+\S*/.exec(probe.stdout)?.[0] ?? null) : null;
491
496
  return { op, exit_code: run.code, version, output_tail: run.stdout.slice(-2000) };
492
497
  }
@@ -565,6 +570,17 @@ function checkKeySource(ref, status, input) {
565
570
  throw new RemoteTerminalError("CREDENTIAL_REVISION_STALE", "the key changed; get the current value from the terminal registry and launch again");
566
571
  }
567
572
  const trustedTarget = (b) => ({ host: b.target.host, user: b.target.user, port: b.target.port, trusted_ref: b.ref });
573
+ /** R20/T4: the terminal's real platform; macOS and Linux pass. A declared os that differs is a wrong target, Windows comes in 0.70.8. */
574
+ export async function checkTerminalPlatform(target, declared) {
575
+ const actual = await remotePlatform(target);
576
+ if (actual === null)
577
+ throw new RemoteTerminalError("TERMINAL_PLATFORM_UNSUPPORTED", "the terminal is not a macOS, Linux or Windows system (the platform probe printed nothing recognisable)");
578
+ if (declared !== undefined && declared !== actual)
579
+ throw new RemoteTerminalError("TERMINAL_OS_MISMATCH", `the terminal is registered as ${declared} but runs ${actual}; correct the terminal's os or register the right machine`);
580
+ if (actual === "windows")
581
+ throw new RemoteTerminalError("TERMINAL_PLATFORM_UNSUPPORTED", "Windows terminals are not supported before Aiterm 0.70.8");
582
+ return actual;
583
+ }
568
584
  /** T1: the binding exists, the target is the binding's, both revisions are current. */
569
585
  export function terminalRemoteTarget(input) {
570
586
  const b = binding(input.ref);
package/dist/remote.js CHANGED
@@ -11,7 +11,7 @@ import { AitermError, observeAgentDone, readAgentTranscriptResult, windowsStartP
11
11
  import { ensureStateRoot, stateRoot } from "./agent-shared.js";
12
12
  import { currentUid } from "./state-root.js";
13
13
  import { PRIVATE_ENV_SCHEMA } from "./private-env.js";
14
- import { SshStdioTransport, classifySshFailure, trustedSshArguments } from "./remote-terminal.js";
14
+ import { RemoteTerminalError, SshStdioTransport, classifySshFailure, trustedSshArguments } from "./remote-terminal.js";
15
15
  const pkg = createRequire(import.meta.url)("../package.json");
16
16
  export { remoteTargetSchema, remoteInputSchema, remoteInputDescription } from "./remote-contract.js";
17
17
  // 平文で受け取ったパスフレーズは、このMCP processのメモリにだけ置く。ControlMasterが落ちた後の再接続に使う。
@@ -132,6 +132,43 @@ export function remoteShell(target) {
132
132
  }
133
133
  return shell;
134
134
  }
135
+ // 上のshell判定に続けて`uname -s`を流す。POSIX系は最後の行がDarwin/Linux。cmdは行全体が1つのechoになり、PowerShellでは`uname`が無く何も出ない。
136
+ export const REMOTE_PLATFORM_PROBE = `${REMOTE_SHELL_PROBE}; uname -s`;
137
+ /** probeの出力からOSを決める。Windows・macOS・Linuxのどれとも言えない出力はnull(推測しない)。 */
138
+ export function classifyRemotePlatform(output) {
139
+ const shell = classifyRemoteShell(output);
140
+ if (shell === "cmd")
141
+ return "windows";
142
+ const last = output.trim().split(/\r?\n/).pop()?.trim();
143
+ if (last === "Darwin")
144
+ return "macos";
145
+ if (last === "Linux")
146
+ return "linux";
147
+ // POSIX系のprobe行は`aiterm-probe %OS%`で1行目が終わる(unameの行が付くので、classifyRemoteShellはPowerShellと数える)。それ以外のDarwin/Linuxでない出力は未知のOS。
148
+ return shell === "powershell" && output.trim().split(/\r?\n/)[0].trim() !== "aiterm-probe %OS%" ? "windows" : null;
149
+ }
150
+ const platforms = new Map();
151
+ /** 端末のOSを1回だけ調べて、このprocessの間 接続先ごとに覚える。 */
152
+ export function remotePlatform(target) {
153
+ const key = remoteKey(target);
154
+ let platform = platforms.get(key);
155
+ if (!platform) {
156
+ platform = runSsh(target, REMOTE_PLATFORM_PROBE).then(({ code, stdout, stderr }) => {
157
+ if (code === 255) {
158
+ if (target.trusted_ref) {
159
+ const failure = classifySshFailure(stderr);
160
+ throw new RemoteTerminalError(failure.code, failure.message, failure.action);
161
+ }
162
+ const detail = stderr.trim().split("\n").slice(-3).join(" / ") || "exit 255";
163
+ throw new AitermError(`REMOTE_CONNECT_FAILED: ${remoteLabel(target)} へ接続できません(${detail})`, 2);
164
+ }
165
+ return classifyRemotePlatform(stdout);
166
+ });
167
+ platform.catch(() => platforms.delete(key));
168
+ platforms.set(key, platform);
169
+ }
170
+ return platform;
171
+ }
135
172
  // POSIX系の非ログイン実行では、~/.local/bin、Homebrew、nvmなどのPATHが入らない端末がある。
136
173
  // 利用者のログインshellからPATHだけを受け取り、処理は/bin/shで行う。profileの出力やfish等の文法差を
137
174
  // MCPのstdoutと処理へ持ち込まない。scriptは呼び出し側で検証済みの値だけで組み、単引用符を含めない。
@@ -3,7 +3,9 @@
3
3
  const ACTIONS = {
4
4
  TERMINAL_INVALID: "起動の指定(端末の情報か作業フォルダ)が正しくありません。BellTeamの不具合の恐れがあります。",
5
5
  TARGET_INVALID: "起動の指定(端末の情報)が正しくありません。BellTeamの不具合の恐れがあります。",
6
- TERMINAL_HARNESS_UNSUPPORTED: "この端末で起こせるAIは、今はClaude Codeだけです。メンバーのAIをClaude Codeにしてください。",
6
+ TERMINAL_OS_MISMATCH: "端末のOSが、登録されているOSと違います。別の機械を指している恐れがあり止めました。端末の登録(OS)を確かめてください。",
7
+ TERMINAL_PLATFORM_UNSUPPORTED: "この端末のOS(Windowsなど)では、まだ席を起こせません。MacかLinuxの端末を使ってください。",
8
+ TERMINAL_HARNESS_UNSUPPORTED: "この端末で起こせるAIは、今はClaude CodeとCodexだけです。メンバーのAIをClaude CodeかCodexにしてください。",
7
9
  REF_INVALID: "端末の登録が見つかりません。端末の登録を確かめてください。",
8
10
  BINDING_UNKNOWN: "端末の登録が見つかりません。端末の登録を確かめてください。",
9
11
  BINDING_STORE_UNREADABLE: "端末の登録を読めませんでした。端末の登録をやり直してください。",
@@ -17,7 +19,7 @@ const ACTIONS = {
17
19
  CREDENTIAL_REVISION_STALE: "端末へ入る鍵が新しくなりました。新しい鍵で起こし直します。",
18
20
  CREDENTIAL_UNAVAILABLE: "端末へ入る鍵を使えません。端末の登録で鍵を確かめてください。",
19
21
  AUTH_FAILED: "端末が鍵を受け付けませんでした。端末の登録から、パスワードで鍵を許可し直してください。",
20
- CONNECTION_REFUSED: "端末がSSHの接続を断りました。Macなら「リモートログイン」が入になっているか確かめてください。",
22
+ CONNECTION_REFUSED: "端末がSSHの接続を断りました。端末のSSHサーバーが入になっているか確かめてください(Macは「リモートログイン」、Linuxはsshdの起動)。",
21
23
  UNREACHABLE: "端末につながりません。電源とネットワークを確かめてください。つながれば起こし直します。",
22
24
  CONNECTION_FAILED: "端末へのSSH接続に失敗しました。端末の電源とSSHの設定を確かめてください。",
23
25
  REMOTE_AITERM_UNAVAILABLE: "端末にAitermが入っていません。端末の準備(Aitermの導入)をやり直してください。",
@@ -39,11 +41,13 @@ export function terminalLaunchAction(code) {
39
41
  export const LAUNCH_ERROR_META = "aiterm/launch_error";
40
42
  export const ERROR_CODE_META = "aiterm/error_code";
41
43
  /** R18 for a local launch: the fresh native creation left no seat (core.freshLaunchFailure). */
42
- export function launchNotStartedMeta(harness) {
44
+ export function launchNotStartedMeta(harness, phase = "native_create") {
43
45
  const code = "AGENT_LAUNCH_NOT_STARTED";
44
- return { [LAUNCH_ERROR_META]: { schema: "aiterm.agent-launch-error.v1", harness, code, phase: "native_create",
45
- effect: "not_started", session_created: false, action: ACTIONS[code] } };
46
+ return { [LAUNCH_ERROR_META]: { schema: "aiterm.agent-launch-error.v1", harness, code, phase,
47
+ effect: "not_started", session_created: false, action: phase === "input" ? INPUT_ACTION : ACTIONS[code] } };
46
48
  }
49
+ // phase "input": refused from the arguments alone; nothing was started, so launching again unchanged fails the same way.
50
+ const INPUT_ACTION = "起動の指定(追加の指示かMCPの設定)をこのAIでは使えません。席は作られていません。指定を見直してください。";
47
51
  /** R19: the leading symbolic code of a refused call, so the caller does not parse text. It claims no effect. */
48
52
  export function withErrorCode(result) {
49
53
  if (!result?.isError)
@@ -54,8 +58,8 @@ export function withErrorCode(result) {
54
58
  /** Adds R18's `_meta` to a failed terminal launch result; a result whose code is not listed is returned unchanged.
55
59
  * `_meta`, not structuredContent: SDK clients that listed the tools validate structuredContent against the
56
60
  * success outputSchema even on isError, and would turn this refusal into a protocol error. */
57
- export function withTerminalLaunchAction(result) {
58
- if (!result?.isError)
61
+ export function withTerminalLaunchAction(result, harness = "claude-code") {
62
+ if (!result?.isError || result._meta?.[LAUNCH_ERROR_META])
59
63
  return result;
60
64
  const structured = result.structuredContent;
61
65
  const preflight = structured?.schema === "aiterm.agent-launch-error.v1";
@@ -67,6 +71,6 @@ export function withTerminalLaunchAction(result) {
67
71
  return result;
68
72
  const failure = preflight
69
73
  ? { schema: structured.schema, harness: structured.harness, code, phase: structured.phase, effect: structured.effect, session_created: false, action }
70
- : { schema: "aiterm.agent-launch-error.v1", harness: "claude-code", code, phase: "terminal", effect: "not_started", session_created: false, action };
74
+ : { schema: "aiterm.agent-launch-error.v1", harness, code, phase: "terminal", effect: "not_started", session_created: false, action };
71
75
  return { ...result, _meta: { ...result._meta, [LAUNCH_ERROR_META]: failure } };
72
76
  }
package/dist/write-ban.js CHANGED
@@ -3,48 +3,24 @@
3
3
  import { spawnSync } from "node:child_process";
4
4
  import * as fs from "node:fs";
5
5
  import * as path from "node:path";
6
+ import { fileURLToPath } from "node:url";
6
7
  import { AitermError } from "./errors.js";
7
- // Linux: Landlock, unprivileged (works in standard Docker, where bwrap cannot create a namespace).
8
- // Handles only write-type rights and grants them on every sibling along / -> the folder, so only the folder
9
- // (and new entries directly in its ancestors) is unwritable. Fails closed: exit 126 before the CLI starts.
10
- const LANDLOCK_PY = `import ctypes,os,sys,struct
11
- a=sys.argv[1:];probe=a[0]=='--probe'
12
- if probe:a=a[1:]
13
- P=os.path.realpath(a[0]);L=ctypes.CDLL(None,use_errno=True)
14
- def c(r,w):
15
- if r<0:
16
- sys.stderr.write('aiterm write-ban: %s: %s\\n'%(w,os.strerror(ctypes.get_errno())));sys.exit(126)
17
- return r
18
- abi=c(L.syscall(444,None,0,1),'landlock unavailable')
19
- D=0
20
- for b in (1,4,5,6,7,8,9,10,11,12,13,14):D|=1<<b
21
- if abi<2:D&=~(1<<13)
22
- if abi<3:D&=~(1<<14)
23
- F=D&((1<<1)|(1<<14));A=struct.pack('QQQ',D,0,0)
24
- fd=c(L.syscall(444,ctypes.c_char_p(A),ctypes.c_size_t(len(A)),0),'create_ruleset')
25
- def g(p):
26
- try:q=os.open(p,os.O_PATH|os.O_CLOEXEC)
27
- except OSError:return
28
- try:c(L.syscall(445,fd,1,ctypes.c_char_p(struct.pack('=Qi',D if os.path.isdir(p) else F,q)),0),'add_rule '+p)
29
- finally:os.close(q)
30
- cur='/'
31
- for part in P.strip('/').split('/'):
32
- for e in os.listdir(cur):
33
- if e!=part:g(os.path.join(cur,e))
34
- cur=os.path.join(cur,part)
35
- c(L.prctl(38,1,0,0,0),'no_new_privs')
36
- c(L.syscall(446,fd,0),'restrict_self')
37
- if probe:print('landlock',abi);sys.exit(0)
38
- cmd=a[a.index('--')+1:];os.execvp(cmd[0],cmd)
39
- `;
40
- const LANDLOCK_LAUNCHER = `import base64;exec(base64.b64decode('${Buffer.from(LANDLOCK_PY).toString("base64")}'))`;
8
+ // Linux: Landlock via the bundled static helper (native/write-ban/aiterm-write-ban.c), so nothing has to be
9
+ // installed on the machine. Unprivileged (works in standard Docker, where bwrap cannot create a namespace).
10
+ // Fails closed: exit 126 before the CLI starts.
11
+ function landlockHelper() {
12
+ if (process.arch !== "x64" && process.arch !== "arm64")
13
+ throw unenforceable(`no write-ban helper for CPU ${process.arch}`);
14
+ return fileURLToPath(new URL(`../native/write-ban/linux-${process.arch}/aiterm-write-ban`, import.meta.url));
15
+ }
16
+ const unenforceable = (why) => new AitermError(`READONLY_UNENFORCEABLE: the project write-ban cannot be applied here: ${why}`, 2);
41
17
  function seatbeltProfile(folder) {
42
18
  return `(version 1)(allow default)(deny file-write* (subpath "${folder.replace(/[\\"]/g, "\\$&")}"))`;
43
19
  }
44
20
  /** argv placed before the CLI's own argv. The CLI is exec'd, so its PID and process name stay the seat's. */
45
21
  export function writeBanPrefix(ban) {
46
22
  return ban.method === "landlock"
47
- ? ["python3", "-c", LANDLOCK_LAUNCHER, ban.path, "--"]
23
+ ? [landlockHelper(), ban.path, "--"]
48
24
  : ["/usr/bin/sandbox-exec", "-p", seatbeltProfile(ban.path)];
49
25
  }
50
26
  /**
@@ -52,7 +28,6 @@ export function writeBanPrefix(ban) {
52
28
  * starting it would let it write the project (the one thing the Owner forbade).
53
29
  */
54
30
  export function probeWriteBan(folder, platform = process.platform) {
55
- const unenforceable = (why) => new AitermError(`READONLY_UNENFORCEABLE: the project write-ban cannot be applied here: ${why}`, 2);
56
31
  if (platform === "win32")
57
32
  throw unenforceable("Windows has no same-user folder write-ban yet");
58
33
  if (!path.isAbsolute(folder) || !fs.existsSync(folder))
@@ -62,7 +37,7 @@ export function probeWriteBan(folder, platform = process.platform) {
62
37
  throw unenforceable("the folder is the filesystem root");
63
38
  const ban = { path: real, method: platform === "darwin" ? "seatbelt" : "landlock" };
64
39
  const [bin, ...args] = writeBanPrefix(ban);
65
- const probe = ban.method === "landlock" ? [args[0], args[1], "--probe", real] : [...args, "/usr/bin/true"];
40
+ const probe = ban.method === "landlock" ? ["--probe", real] : [...args, "/usr/bin/true"];
66
41
  const r = spawnSync(bin, probe, { encoding: "utf8", timeout: 10_000 });
67
42
  if (r.status !== 0)
68
43
  throw unenforceable((r.stderr || r.error?.message || `exit ${r.status}`).trim().split("\n").pop() ?? "probe failed");
package/docs/RELEASE.md CHANGED
@@ -35,7 +35,7 @@ Steerの未公開release sourceは` scripts/fixtures/steer-release-source.json `
35
35
 
36
36
  ## Release手順
37
37
 
38
- 1. 変更に直結するfocused testを手元で通す。full regressionは手元で回さず、CIに任せる。
38
+ 1. 変更に直結するfocused testを手元で通す。`native/write-ban/aiterm-write-ban.c`を変えた時は`pip install ziglang==0.15.2`の上で`node scripts/build-write-ban.mjs`で組み直し、`--check`で同じbytesになることを確かめてから組んだ物をcommitする。full regressionは手元で回さず、CIに任せる。
39
39
  個別試験も`node scripts/run-seat-tests.mjs --test ...`で起動する。稼働中の席の保存場所を試験へ継承しない。
40
40
  2. `CHANGELOG.md`の`## [Unreleased]`へ内容を書き、mainへcommitしてpushする。
41
41
  3環境の全テストを先に通しておく時は、枝をpushして手動実行(`gh workflow run ci.yml --ref <枝> -f environment=all -f comparison_base=<前の公開commit>`)を
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.70.6",
3
+ "version": "0.70.7",
4
4
  "mcpName": "io.github.kitepon/aiterm-mcp",
5
5
  "description": "Persistent terminal MCP with one harness-based launcher for Claude Code, Codex CLI, Grok CLI, Cursor Agent CLI, and Antigravity CLI, plus durable PTYs for SSH, containers, and REPLs.",
6
6
  "keywords": [
@@ -55,6 +55,7 @@
55
55
  "files": [
56
56
  "dist/*.js",
57
57
  "dist/harnesses/*.js",
58
+ "native/write-ban/linux-*/aiterm-write-ban",
58
59
  "runtime-overlap.json",
59
60
  "state-compat.json",
60
61
  "README.md",