aiterm-mcp 0.70.9 → 0.70.11

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,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.70.11] - 2026-11-10
11
+
12
+ - macOS: a Codex seat with `mcp_config` no longer stops at `reason=unrecognized_screen` with Codex's "unexpected argument '<cwd>'". The pane's bash 3.2 brace-expanded the typed launch line when it held a `"` (the `-c mcp_servers.<name>={...}` value). The one-line launch now sends every quote and expanding character (single and double quotes, backquote, `$`, `!`, `{`, `}`) as a `printf %b` octal escape. Linux, zsh and dash read the same line.
13
+ - `pty_list` seat turns (caller opt-in): terminal relays start before the local read, and their 4 s budget counts only time the event loop was free. Before, a synchronous local read in another overlapping `pty_list` used up the budget while the terminal's answer waited, so most overlapping calls listed every terminal seat in `unread`. Measured with three overlapping calls against the macbook terminal: 0.70.9 left 2 of 3 unread and dropped a row from the third; 0.70.11 returned both rows in all three.
14
+
15
+ ## [0.70.10] - 2026-11-10
16
+
17
+ - Claude seats that compacted while idle no longer read as `turn: null` until their next turn. Claude's idle compaction shows a busy spinner and sends no Stop; the `⏺ Compacted while idle` notice above the composer now ends the span that spinner opened, and the row settles to `{state: "idle"}`.
18
+ - `pty_list` seat turns (caller opt-in): a seat whose span another live reader holds at that instant is listed in `unread` (the caller keeps its last state) instead of a row with `turn: null`. A terminal's own `unread` is relayed for its bound sessions, and overlapping callers share one in-flight relay per terminal instead of starting one reader on the terminal each.
19
+ - Codex seats whose `~/.codex/config.toml` already has a stdio MCP server with the same name as an `mcp_config` server (for example `call-bridge`) now start instead of `AGENT_LAUNCH_NOT_STARTED: CODEX_MCP_SERVER_CONFLICT`. For that seat only, Aiterm takes over the user's entry with its own stdio relay (`dist/mcp-http-bridge.js`), which forwards every MCP message to the seat's http server with the seat's headers; the tool names keep the server name and the user's config.toml is not written. `CODEX_MCP_SERVER_CONFLICT` is gone.
20
+
10
21
  ## [0.70.9] - 2026-11-10
11
22
 
12
23
  - All five harnesses can run on a terminal. `agent_launch` (and the per-harness launchers) with `terminal` now accepts `grok-cli`, `cursor-cli` and `antigravity-cli` beside `claude-code` and `codex-cli`, routed to the terminal's `agent_launch` the same way, with the seat-forward URL rewrite and header extraction unchanged. These three need Aiterm 0.70.9 on the terminal (`REMOTE_AITERM_TOO_OLD` before any private value is sent). `TERMINAL_HARNESS_UNSUPPORTED` stays only as a guard for a name outside the five.
@@ -3228,7 +3239,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3228
3239
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3229
3240
  provenance.
3230
3241
 
3231
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.9...HEAD
3242
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.11...HEAD
3243
+ [0.70.11]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.10...v0.70.11
3244
+ [0.70.10]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.9...v0.70.10
3232
3245
  [0.70.9]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.8...v0.70.9
3233
3246
  [0.70.8]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.7...v0.70.8
3234
3247
  [0.70.7]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.6...v0.70.7
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.9** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.70.11** · 動作対象は 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.9** · 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.11** · 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
 
@@ -349,6 +349,8 @@ export function parentPaneEvidence(kind, screen) {
349
349
  const observed = agentPaneObservation(kind, current);
350
350
  if (observed.state === "blocked" || observed.state === "unknown")
351
351
  return "unknown";
352
+ if (kind === "claude" && observed.state === "idle" && /^⏺ Compacted while idle\b/u.test(current))
353
+ return "ready_compacted";
352
354
  if (kind === "claude" && observed.state === "idle"
353
355
  && !/^[·✢✳✶✻✽*∗] [^…\n]+ for \d[^…\n]*$/mu.test(current))
354
356
  return "ready_no_completion";
package/dist/core.js CHANGED
@@ -11,7 +11,7 @@ import { inspectIdleSettings, inspectCodexResumeSettings, codexRecoveryComposer
11
11
  import { AGENT_TUI_READY_TIMEOUT_MS, AGENT_TUI_FIRST_DRAW_TIMEOUT_MS, AGENT_TUI_READY_POLL_MS, isAgentTuiReady, isAgentTuiBusy, isAgentTuiIdleReady, agentPaneObservation, parentPaneEvidence, waitAgentTuiReadyImpl, detectAgentSubmitResidueImpl, waitCursorPromptVisibleImpl, settleAgentDoneScreenImpl } from "./agent-screen-observation.js";
12
12
  export { launchEchoIsLastOnScreen, __testSetAgentTuiReadyStableSamples } from "./agent-screen-observation.js";
13
13
  import { parseClaudeOperationMarker } from "./claude-operation-marker.js";
14
- import { withManagedSpan, observeManagedSpan } from "./managed-seat-turn.js";
14
+ import { withManagedSpan, observeManagedSpan, SPAN_HELD } from "./managed-seat-turn.js";
15
15
  /**
16
16
  * core — CLI/MCP が共有する端末操作とharness進行(Node/TS 版)。
17
17
  *
@@ -3751,7 +3751,7 @@ export function readSessionInterimWords(name, after, from = null) {
3751
3751
  * read current original-pane activity, with observation identity and no waiter.
3752
3752
  */
3753
3753
  export function readSeatTurns(sessionIds) {
3754
- const seats = [];
3754
+ const seats = [], unread = [];
3755
3755
  const observedAt = new Map();
3756
3756
  for (const name of sessionIds) {
3757
3757
  const meta = tryLoadAgentMetadata(name);
@@ -3764,6 +3764,10 @@ export function readSeatTurns(sessionIds) {
3764
3764
  : meta.kind === "codex" ? codexSeatTurn(meta) : readManagedSeatTurn(meta);
3765
3765
  }
3766
3766
  catch { /* 読めない席は、分からないまま返す */ }
3767
+ if (turn === SPAN_HELD) {
3768
+ unread.push(name);
3769
+ continue;
3770
+ }
3767
3771
  if (meta.kind !== "codex")
3768
3772
  observedAt.set(name, performance.now());
3769
3773
  seats.push({ session_id: name, launch_id: meta.launch_id, harness: agentHarness(meta.kind),
@@ -3774,7 +3778,7 @@ export function readSeatTurns(sessionIds) {
3774
3778
  if (seat.harness !== "codex-cli"
3775
3779
  && performance.now() - observedAt.get(seat.session_id) >= 15_000)
3776
3780
  seat.turn = null;
3777
- return { schema: "aiterm.seat-turns.v1", seats };
3781
+ return { schema: "aiterm.seat-turns.v1", seats, unread };
3778
3782
  }
3779
3783
  function managedSeatConversation(meta) {
3780
3784
  if (meta.kind === "antigravity") {
@@ -5,12 +5,14 @@ import { authUrl, authUserCode } from "../agent-auth.js";
5
5
  import * as fs from "node:fs";
6
6
  import * as os from "node:os";
7
7
  import * as path from "node:path";
8
+ import { fileURLToPath } from "node:url";
8
9
  import { randomBytes, createHash } from "node:crypto";
9
10
  import { z } from "zod";
10
11
  import { AitermError, launchInputRefusal } from "../errors.js";
11
12
  import { spawnAgentControlCommand } from "../agent-resolver.js";
12
13
  import * as steer from "aiterm-steer-delivery";
13
14
  import { AITERM_PROFILE } from "../steer-profile.js";
15
+ import { setupNodeExecutable } from "../setup-node.js";
14
16
  import { catalogInvalid, catalogUnavailable, checkedCatalog } from "../model-catalog.js";
15
17
  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
18
  import { confirmedAgentResumeRecoveryOrigin, readAgentLifecycle, readAgentResumeRecipe, agentResumeRecipeDigest } from "../agent-lifecycle.js";
@@ -911,8 +913,11 @@ const MCP_SERVER_NAME = /^[A-Za-z0-9_-]{1,64}$/;
911
913
  const HEADER_NAME = /^[A-Za-z0-9-]{1,128}$/;
912
914
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
913
915
  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
+ /** `mcp_config` -> one `-c` value per server. Refuses (CODEX_MCP_CONFIG_UNSUPPORTED) what Codex's http server table cannot say.
917
+ * `userStdio`: names the user's config.toml already defines as stdio servers. `-c` merges key by key into that table and
918
+ * Codex refuses `command` + `url`, so such a server is taken over as stdio running Aiterm's relay to the same url and headers
919
+ * (mcp-http-bridge.ts); the user's other keys of that table (env, cwd, timeouts, enabled_tools) still apply. */
920
+ export function codexMcpOverrides(mcp, userStdio = new Set()) {
916
921
  const refuse = (message) => { throw new AitermError(`CODEX_MCP_CONFIG_UNSUPPORTED: ${message}`, 2); };
917
922
  const servers = mcp?.mcpServers;
918
923
  if (!mcp || typeof mcp !== "object" || Object.keys(mcp).some(key => key !== "mcpServers") || !servers || typeof servers !== "object" || Array.isArray(servers))
@@ -935,7 +940,7 @@ export function codexMcpOverrides(mcp) {
935
940
  if (!url || (url.protocol !== "http:" && url.protocol !== "https:"))
936
941
  return refuse(`server '${name}': url must be an http(s) URL`);
937
942
  const fields = [`url=${toml(spec.url)}`];
938
- const envHeaders = [], literalHeaders = [], seen = new Set();
943
+ const envHeaders = [], literalHeaders = [], seen = new Set(), bridgeArgs = [], envNames = [];
939
944
  let bearer = null;
940
945
  if (spec.headers !== undefined && (!spec.headers || typeof spec.headers !== "object" || Array.isArray(spec.headers)))
941
946
  return refuse(`server '${name}': headers must be an object`);
@@ -955,11 +960,19 @@ export function codexMcpOverrides(mcp) {
955
960
  bearer = envName;
956
961
  else
957
962
  envHeaders.push(`${toml(header)}=${toml(envName)}`);
963
+ bridgeArgs.push(...(bearerName !== undefined ? ["--bearer-env", envName] : ["--env-header", `${header}=${envName}`]));
964
+ envNames.push(envName);
958
965
  }
959
966
  else if (value.includes("${"))
960
967
  return refuse(`server '${name}': header '${header}' mixes text with \${NAME}; only the whole value or 'Bearer \${NAME}' can be given`);
961
- else
968
+ else {
962
969
  literalHeaders.push(`${toml(header)}=${toml(value)}`);
970
+ bridgeArgs.push("--header", `${header}=${value}`);
971
+ }
972
+ }
973
+ if (userStdio.has(name)) {
974
+ const args = [fileURLToPath(new URL("../mcp-http-bridge.js", import.meta.url)), spec.url, ...bridgeArgs];
975
+ return `mcp_servers.${name}={command=${toml(setupNodeExecutable(process.execPath))},args=[${args.map(toml).join(",")}],env_vars=[${envNames.map(toml).join(",")}],enabled=true,disabled_tools=[]}`;
963
976
  }
964
977
  if (bearer !== null)
965
978
  fields.push(`bearer_token_env_var=${toml(bearer)}`);
@@ -970,16 +983,9 @@ export function codexMcpOverrides(mcp) {
970
983
  return `mcp_servers.${name}={${fields.join(",")}}`;
971
984
  });
972
985
  }
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);
986
+ /** Names of the stdio MCP servers in the user's config.toml (codexMcpOverrides takes those over with the relay).
987
+ * shortcut: reads only `[mcp_servers.NAME]` section headers, an inline or dotted-key definition is not seen (Codex then refuses that seat's config at start); upgrade with a TOML parser. */
988
+ export function codexUserStdioServers(codexHome) {
983
989
  let body = "";
984
990
  try {
985
991
  body = fs.readFileSync(path.join(codexHome, "config.toml"), "utf8");
@@ -1000,15 +1006,18 @@ export function checkCodexCallerInput(prompt, mcp, codexHome) {
1000
1006
  if (inside && /^\s*command\s*=/.test(line))
1001
1007
  stdio.add(inside);
1002
1008
  }
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
- }
1009
+ return stdio;
1010
+ }
1011
+ /** Pre-start check of the caller fields for a Codex launch: the text size and the server shapes. */
1012
+ export function checkCodexCallerInput(prompt, mcp) {
1013
+ if (prompt != null && (!prompt.trim() || Buffer.byteLength(prompt, "utf8") > CODEX_CALLER_PROMPT_MAX))
1014
+ throw new AitermError("append_system_prompt must be non-empty and at most 64 KiB for codex-cli (it travels in argv)", 2);
1015
+ if (mcp != null)
1016
+ codexMcpOverrides(mcp);
1008
1017
  }
1009
1018
  /** Both caller files, as Claude's writeClaudeCallerFiles: Aiterm state, 0600, never the project or the Codex home. */
1010
1019
  export function writeCodexCallerFiles(meta, prompt, mcp) {
1011
- checkCodexCallerInput(prompt, mcp, meta.codex_home ?? realCodexHome());
1020
+ checkCodexCallerInput(prompt, mcp);
1012
1021
  if (prompt !== null) {
1013
1022
  const file = agentCodexCallerPromptPath(meta.aiterm_session);
1014
1023
  fs.writeFileSync(file, prompt, { mode: 0o600 });
@@ -1024,7 +1033,7 @@ export function writeCodexCallerFiles(meta, prompt, mcp) {
1024
1033
  /** The caller launch fields of a Codex input, refused as a not-started input refusal (phase "input"). */
1025
1034
  export function refuseCodexCallerInput(prompt, mcp) {
1026
1035
  try {
1027
- checkCodexCallerInput(prompt, mcp, realCodexHome());
1036
+ checkCodexCallerInput(prompt, mcp);
1028
1037
  }
1029
1038
  catch (e) {
1030
1039
  throw e instanceof AitermError ? launchInputRefusal("codex-cli", e.message) : e;
@@ -1053,7 +1062,7 @@ export function codexAgentArgv(bin, model, effort, prompt, meta) {
1053
1062
  parts.push("-c", `developer_instructions=${subagentInstruction(meta)}${meta.codex_caller_prompt_file ? `\n\n${fs.readFileSync(meta.codex_caller_prompt_file, "utf8")}` : ""}`);
1054
1063
  }
1055
1064
  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"))))
1065
+ for (const override of codexMcpOverrides(JSON.parse(fs.readFileSync(meta.codex_caller_mcp_file, "utf8")), codexUserStdioServers(meta.codex_home ?? realCodexHome())))
1057
1066
  parts.push("-c", override);
1058
1067
  if (prompt)
1059
1068
  parts.push(prompt); // 初手プロンプト(任意)
package/dist/index.js CHANGED
@@ -37,7 +37,7 @@ import { ExecutionError, executionErrorResult } from "./execution-wire.js";
37
37
  import { attachExecutionControlRegistrar } from "./execution-tools.js";
38
38
  import { ParentDeliveryManager, deliveryKey } from "./parent-delivery.js";
39
39
  import { failureObservationSchema } from "./parent-delivery-record.js";
40
- import { acceptRemote, callRemoteTool, observeRemoteAgentDone, remoteLabel, remoteWaitProcess } from "./remote.js";
40
+ import { acceptRemote, callRemoteTool, loopDeadline, observeRemoteAgentDone, remoteLabel, remoteWaitProcess } from "./remote.js";
41
41
  import { codexParentFromRequest } from "./codex-parent-receiver.js";
42
42
  import { claudeParentFromRequest, discardClaudeHookRequest } from "./claude-parent-receiver.js";
43
43
  import { parentDeliveryDiagnostic } from "./parent-hook-diagnostic.js";
@@ -835,24 +835,41 @@ export function createAitermServer(options = {}) {
835
835
  return fail(e);
836
836
  }
837
837
  });
838
+ const remoteSeatTurnsInFlight = new Map();
838
839
  // Declared controller caller markers opt into current-turn metadata (ADR 0122).
839
840
  // 説明と引数には出さない(steer-follow.ts の冒頭)。それ以外の呼び手には何も足さない。
840
841
  async function seatTurnsMeta(sessions, requestMeta) {
841
842
  if (!interimCallerFromMeta(requestMeta, server.server.getClientVersion()?.name, server.server.getClientCapabilities()))
842
843
  return {};
843
844
  try {
844
- const local = core.readSeatTurns(sessions.filter(session => session.harness !== null).map(session => session.session_id));
845
845
  // Terminal seats: the same call relayed with the same _meta; each terminal answers only for its own bound sessions.
846
846
  // Inside the caller's 5 s pty_list budget (tool catalog timeout_ms): a terminal that fails or is slow contributes
847
847
  // no rows, and its sessions are listed in `unread` so the caller keeps their last state instead of reading them as gone.
848
- const remote = await Promise.all(terminalSeatGroups().map(({ target, sessions: bound }) => Promise.race([
849
- callRemoteTool(target, "pty_list", {}, 4_000, undefined, requestMeta).then(result => {
850
- const seats = result._meta?.[SEAT_TURNS_RESULT_META_KEY]?.seats;
851
- return Array.isArray(seats) ? { seats: seats.filter((seat) => bound.includes(seat?.session_id)), unread: [] } : { seats: [], unread: bound };
852
- }, () => ({ seats: [], unread: bound })),
853
- new Promise(resolve => setTimeout(resolve, 4_000, { seats: [], unread: bound }).unref()),
854
- ])));
855
- return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { ...local, seats: [...local.seats, ...remote.flatMap(r => r.seats)], unread: remote.flatMap(r => r.unread) } } };
848
+ // Overlapping callers share one in-flight relay per terminal: each relay starts its own reader on the terminal, and
849
+ // two readers of one seat at once leave one of them without the span lock (that seat comes back in its `unread`).
850
+ // Relays start before the synchronous local read so the terminal works meanwhile; their 4 s counts only time this
851
+ // process's event loop was free (loopDeadline), since a blocked loop cannot take the answer however soon it came.
852
+ const relays = Promise.all(terminalSeatGroups().map(({ target, sessions: bound }) => {
853
+ const key = JSON.stringify([target, requestMeta]);
854
+ let call = remoteSeatTurnsInFlight.get(key);
855
+ if (!call) {
856
+ // The request's own timeout is wall-clock: keep it well above the loop-time budget below.
857
+ call = callRemoteTool(target, "pty_list", {}, 15_000, undefined, requestMeta)
858
+ .then(result => result._meta?.[SEAT_TURNS_RESULT_META_KEY] ?? null, () => null)
859
+ .finally(() => remoteSeatTurnsInFlight.delete(key));
860
+ remoteSeatTurnsInFlight.set(key, call);
861
+ }
862
+ return Promise.race([
863
+ call.then(answer => Array.isArray(answer?.seats)
864
+ ? { seats: answer.seats.filter((seat) => bound.includes(seat?.session_id)),
865
+ unread: Array.isArray(answer.unread) ? answer.unread.filter((name) => bound.includes(name)) : [] }
866
+ : { seats: [], unread: bound }),
867
+ loopDeadline(4_000, { seats: [], unread: bound }),
868
+ ]);
869
+ }));
870
+ const local = core.readSeatTurns(sessions.filter(session => session.harness !== null).map(session => session.session_id));
871
+ const remote = await relays;
872
+ return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { ...local, seats: [...local.seats, ...remote.flatMap(r => r.seats)], unread: [...local.unread, ...remote.flatMap(r => r.unread)] } } };
856
873
  }
857
874
  catch (e) {
858
875
  return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { schema: "aiterm.seat-turns.v1", error: e instanceof Error ? e.message : String(e) } } };
@@ -1527,7 +1544,7 @@ export function createAitermServer(options = {}) {
1527
1544
  remote: remoteInputField,
1528
1545
  terminal: terminalArgumentSchema.optional().describe(terminalArgumentDescription),
1529
1546
  append_system_prompt: z.string().min(1).optional().describe("Launch instructions added to the system prompt; kept in Aiterm state, not in the project or home. Never put secrets here. Codex: appended to developer_instructions after Aiterm's marker; Grok: appended to --rules; at most 64 KiB for both. Cursor and Antigravity have no system-prompt channel: the text goes in front of the first prompt (Antigravity needs a prompt; at most 64 KiB)"),
1530
- mcp_config: z.object({ mcpServers: z.record(z.string(), z.unknown()) }).strict().optional().describe("Extra MCP servers for this seat. Secret header values: write ${NAME} and list NAME in env_vars. Codex, Grok, Cursor and Antigravity take only http servers {type?: \"http\", url, headers}: a literal header, 'Authorization: Bearer ${NAME}' or a header whose whole value is ${NAME}; other shapes, and a ${NAME} with no value at launch, are refused before the seat starts. Cursor runs a server as plugin-aiterm-caller-<name> beside a same-name user server; Grok and Antigravity replace a same-name user server for this seat"),
1547
+ mcp_config: z.object({ mcpServers: z.record(z.string(), z.unknown()) }).strict().optional().describe("Extra MCP servers for this seat. Secret header values: write ${NAME} and list NAME in env_vars. Codex, Grok, Cursor and Antigravity take only http servers {type?: \"http\", url, headers}: a literal header, 'Authorization: Bearer ${NAME}' or a header whose whole value is ${NAME}; other shapes, and a ${NAME} with no value at launch, are refused before the seat starts. Cursor runs a server as plugin-aiterm-caller-<name> beside a same-name user server; Codex, Grok and Antigravity replace a same-name user server for this seat (Codex: a user stdio server of that name runs Aiterm's relay to the given url instead)"),
1531
1548
  fork_from: z.object({
1532
1549
  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)"),
1533
1550
  fork_id: z.string().min(1).max(200).optional().describe("Caller's fork ID, passed to the seat as THROUGHLINE_FORK_ID"),
@@ -12,6 +12,8 @@ const recordSchema = z.object({ binding: z.string().min(1), span: spanSchema.nul
12
12
  settled_from: z.string().nullable().optional() }).strict();
13
13
  const ownerSchema = z.object({ pid: z.number().int().positive(), started_identity: stamp, token: z.string() }).strict();
14
14
  export const managedSpanDirectory = (meta) => agentMetadataPath(meta.aiterm_session, meta.launch_id).replace(/\.agent\.json$/, ".seat-span.d");
15
+ /** Another live reader holds the span this instant: no observation this tick (seat-turns `unread`), not an unknown turn. */
16
+ export const SPAN_HELD = Symbol("span-held");
15
17
  /** Same callback owns live capture and the short identity transaction. Never waits or sends input. */
16
18
  export function withManagedSpan(meta, capture) {
17
19
  const directory = managedSpanDirectory(meta);
@@ -39,10 +41,10 @@ export function withManagedSpan(meta, capture) {
39
41
  return observed.state === "absent" || observed.state === "present" && observed.actor.started_identity !== prior.started_identity;
40
42
  };
41
43
  if (!dead())
42
- return null;
44
+ return SPAN_HELD;
43
45
  const after = fs.lstatSync(lock, { bigint: true });
44
46
  if (before.dev !== after.dev || before.ino !== after.ino || !dead())
45
- return null;
47
+ return SPAN_HELD;
46
48
  // Retain this nonempty destination: a competing reap cannot move a later owner's lock over it.
47
49
  fs.renameSync(lock, path.join(directory, `retired-${before.dev}-${before.ino}`));
48
50
  fs.renameSync(candidate, lock);
@@ -95,7 +97,8 @@ export function observeManagedSpan(file, binding, evidence, terminal, at, positi
95
97
  return { state: "running", turn_id, started_at, event_cursor: null, interim_from, wait_process: null };
96
98
  }
97
99
  // A launch that never showed busy nor any terminal has no turn to hide: its settled ready is idle.
98
- if (!terminal && (record?.span || record?.terminal) || record?.span && terminal === record.terminal)
100
+ // An idle compaction has no Stop of its own; its notice settles the span its spinner opened.
101
+ if (evidence !== "ready_compacted" && (!terminal && (record?.span || record?.terminal) || record?.span && terminal === record.terminal))
99
102
  return null;
100
103
  if (!record)
101
104
  record = { binding, span: null, terminal, ready: null };
@@ -0,0 +1,47 @@
1
+ // A stdio MCP server that relays every message to one streamable-HTTP MCP server.
2
+ // Codex merges `-c mcp_servers.NAME={...}` key by key into the user's table of that name, so a seat's http server
3
+ // cannot replace a user stdio server (`command` + `url` is refused). The seat instead takes over that stdio entry
4
+ // with this relay (codex.ts codexMcpOverrides), leaving ~/.codex/config.toml untouched.
5
+ // argv: <url> then pairs: --header NAME=VALUE (literal) | --env-header NAME=ENV | --bearer-env ENV
6
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
8
+ import { isJSONRPCRequest } from "@modelcontextprotocol/sdk/types.js";
9
+ const fail = (message) => { process.stderr.write(`aiterm mcp bridge: ${message}\n`); process.exit(1); };
10
+ function bridgeHeaders(args, env) {
11
+ const headers = {};
12
+ for (let i = 0; i < args.length; i += 2) {
13
+ const [flag, value] = [args[i], args[i + 1] ?? ""];
14
+ const eq = value.indexOf("=");
15
+ const envValue = (name) => env[name] ?? fail(`${name} has no value`);
16
+ if (flag === "--bearer-env")
17
+ headers.Authorization = `Bearer ${envValue(value)}`;
18
+ else if (flag === "--header" && eq > 0)
19
+ headers[value.slice(0, eq)] = value.slice(eq + 1);
20
+ else if (flag === "--env-header" && eq > 0)
21
+ headers[value.slice(0, eq)] = envValue(value.slice(eq + 1));
22
+ else
23
+ fail(`unknown argument ${flag}`);
24
+ }
25
+ return headers;
26
+ }
27
+ const [url, ...rest] = process.argv.slice(2);
28
+ const remote = new StreamableHTTPClientTransport(new URL(url ?? fail("no url")), { requestInit: { headers: bridgeHeaders(rest, process.env) } });
29
+ const local = new StdioServerTransport();
30
+ local.onmessage = message => void remote.send(message).catch((error) => {
31
+ // A request the server never answered would hang the Codex tool call; answer it with the transport error.
32
+ if (isJSONRPCRequest(message))
33
+ void local.send({ jsonrpc: "2.0", id: message.id, error: { code: -32603, message: `aiterm mcp bridge: ${error.message}` } });
34
+ });
35
+ remote.onmessage = message => {
36
+ const version = message.result?.protocolVersion;
37
+ if (typeof version === "string")
38
+ remote.setProtocolVersion(version);
39
+ void local.send(message);
40
+ };
41
+ remote.onerror = error => process.stderr.write(`aiterm mcp bridge: ${error.message}\n`);
42
+ // Codex closing our stdin ends the seat's use of the server; an open SSE stream must not keep this process alive.
43
+ const stop = () => void remote.close().finally(() => process.exit(0));
44
+ local.onclose = stop;
45
+ process.stdin.on("end", stop);
46
+ await remote.start();
47
+ await local.start();
package/dist/remote.js CHANGED
@@ -373,3 +373,19 @@ export async function answerAnywhere(session, options) {
373
373
  const { remote, ...rest } = options ?? {};
374
374
  return remote ? readRemoteAgentAnswer(remote, session, rest) : readAgentTranscriptResult(session, rest);
375
375
  }
376
+ /** Resolves with `value` after `ms` of event-loop time: a stretch the loop spent blocked counts at most 150 ms. */
377
+ export function loopDeadline(ms, value) {
378
+ return new Promise(resolve => {
379
+ let left = ms, last = performance.now();
380
+ const step = () => {
381
+ const now = performance.now();
382
+ left -= Math.min(now - last, 150);
383
+ last = now;
384
+ if (left <= 0)
385
+ resolve(value);
386
+ else
387
+ setTimeout(step, 100).unref();
388
+ };
389
+ setTimeout(step, 100).unref();
390
+ });
391
+ }
@@ -894,8 +894,10 @@ export function atomicShellMultiline(text, foreground) {
894
894
  return text;
895
895
  if (!POSIX_ATOMIC_SHELLS.has(foreground))
896
896
  return text;
897
+ // Quote-like and expanding bytes travel as %b octal: bash 3.2 (macOS) brace-expands a `{a,b}` in this word when the
898
+ // payload holds a `"` (the old `'"'"'` quote included), and an interactive shell would history-expand a `!`.
897
899
  const quoted = text.replace(/\\/g, "\\\\").replace(/\n/g, "\\n")
898
- .replace(/\r/g, "\\r").replace(/\t/g, "\\t").replace(/'/g, `'"'"'`);
900
+ .replace(/\r/g, "\\r").replace(/\t/g, "\\t").replace(/['"`$!{}]/g, c => `\\0${c.charCodeAt(0).toString(8).padStart(3, "0")}`);
899
901
  // printf %bで本文を復元する。末尾LFの除去はpty_sendのsubmit Enterと同値。
900
902
  return `eval "$(command printf '%b' '${quoted}')"`;
901
903
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.70.9",
3
+ "version": "0.70.11",
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": [