aiterm-mcp 0.70.1 → 0.70.3

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,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.70.3] - 2026-11-10
11
+
12
+ - A terminal seat's BellTeam MCP forward now goes to the container port named in the launch's own seat MCP URLs (`http://127.0.0.1:<D>/api/seat-mcp...`), stored in the terminal binding as `seat_ingress_port`; the forward keeper builds `-R 127.0.0.1:P:127.0.0.1:<D>` from the binding whichever Aiterm process holds it. Before, the keeper read `BELLTEAM_REMOTE_SEAT_PORT` from its own environment with default 4182, so a keeper started by a process without that variable forwarded the seats to BellTeam's admin port (401). The variable and the default are gone. Seat URLs that are not `http`, not `127.0.0.1`, or name different ports refuse the launch with `SEAT_FORWARD_UNAVAILABLE` (`not_started`) before any session. A binding written before this release has no `seat_ingress_port` and builds no forward until its next seat launch writes it, so seats launched earlier lose BellTeam MCP until relaunched. A launch with a different port clears the old forward port and the keeper replaces its ssh. Server side only (the terminal needs no update). Older Aiterm ignores the new binding field.
13
+ - Every active Aiterm process now runs the 60 s forward check, so when the process holding a terminal's forward exits, another one takes it over within a minute. Before, only processes that saw terminal seats when they initialized ran it, and a forward could stay down until another Aiterm started.
14
+
15
+ ## [0.70.2] - 2026-11-10
16
+
17
+ - A managed Claude or Codex launch (fresh or resumed) that fails after its terminal session was created, while Aiterm still sets it up (the process birth identity cannot be read, the session environment cannot be registered, the `.log` or offset file cannot be written, or the output pipe fails), now closes that session before returning the error. Before, the plain named session stayed, and every later launch of the same name was refused with "session '<name>' は既に存在します" until someone closed it by hand. Only the session this launch created is closed: creation marks it with a one-time token (first as the window name, then as the session option `@aiterm_create_token`), and the close is conditional on the native identity and that token, so a session of the same name that replaced it, and its files, are kept. The original error text is kept; `creation_rollback_unconfirmed` is appended only when the close fails while the session is still there. Failures after the setup (startup screens, the initial prompt, a lost transport) keep their existing behavior, and plain `pty_open` is unchanged. The session is created by the terminal's Aiterm, so a remote terminal needs this release; updating only the server side does not change it (docs/architecture/lifecycle-state-ownership.md).
18
+
10
19
  ## [0.70.1] - 2026-11-10
11
20
 
12
21
  - Claude Code's "Updates to Consumer Terms and Policies" screen (2.1.318, grove) is classified as `blocked` / `vendor_onboarding_required` instead of `unrecognized_screen`, so a launch stops with the plain hint instead of waiting it out. Aiterm never answers it: the terms and the model-training choice belong to the account holder.
@@ -3163,7 +3172,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3163
3172
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3164
3173
  provenance.
3165
3174
 
3166
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.1...HEAD
3175
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.3...HEAD
3176
+ [0.70.3]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.2...v0.70.3
3177
+ [0.70.2]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.1...v0.70.2
3167
3178
  [0.70.1]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.0...v0.70.1
3168
3179
  [0.70.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.69.0...v0.70.0
3169
3180
  [0.69.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.68.1...v0.69.0
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.1** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.70.3** · 動作対象は 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.1** · 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.3** · 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
 
package/dist/core.js CHANGED
@@ -54,7 +54,7 @@ import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcess
54
54
  import { liveNodeExecutable } from "./live-node.js";
55
55
  import { resolveClaudeConfigurationRoot, withClaudeConfigRoot } from "./claude-config-root.js";
56
56
  import { AitermError, AgentResumeUnavailableError, AgentResumeError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
57
- import { isWin, SOCKDIR, SOCK, tmuxCommand, readOnlyTmuxList, PtyDiagnosticError, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, } from "./tmux-runtime.js";
57
+ import { isWin, SOCKDIR, SOCK, tmuxCommand, readOnlyTmuxList, PtyDiagnosticError, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, withNativeSessionSetupRollback, hasNativeSessionSetupRollback, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, } from "./tmux-runtime.js";
58
58
  import { AGENT_DEFAULT_PREFACE, sleep, currentUid, runtimeStateBase, safeStatSize, readFileRange, writeJson0600, createEmpty0600, shq, LAUNCH_ID_RE, AGENT_LINEAGE_RE, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, publishAgentGeneration, agentMetadataPath, writeAgentMetadata, AGENT_EVENT_TAIL_BYTES, agentLabel, agentHarness, subagentInstruction, } from "./agent-shared.js";
59
59
  import { AuthResponseError, authUi, authPromptDigest, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
60
60
  import { processStartIdentity } from "./runtime-error-os.js";
@@ -663,106 +663,111 @@ export function openSession(name, shell = "bash", envVars = []) {
663
663
  function openSessionInternal(name, shell, envVars, preserveAgentState) {
664
664
  assertExecutionContext(name);
665
665
  shell = resolveWinPaneShell(shell);
666
- for (const key of envVars) {
667
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
668
- throw new AitermError("env_varsの環境変数名が不正です", 2);
669
- }
670
- try {
671
- fs.mkdirSync(SOCKDIR, { recursive: true });
672
- }
673
- catch (error) {
674
- ownTelemetryFailure("AITERM.PERSISTENCE_WRITE_FAILED", error);
675
- }
676
- // macOS標準bashの移行bannerを抑止する。環境変数の注入方法はterminal runtimeが所有する。
677
- const banner = process.platform === "darwin" && path.basename(shell) === "bash"
678
- ? ["BASH_SILENCE_DEPRECATION_WARNING=1"]
679
- : [];
680
- // 並行性対策: 複数エージェントが同時に名前なし open すると autoName が同じ t{i} を返し得る(TOCTOU)。
681
- // 自動採番は初回のみ読みやすい t{i}、衝突したら乱数 nonce 名でリトライする(線形リトライは高並行で
682
- // 全員が同じ空き番号に殺到してスケールしない)。明示名は既存ならエラー(呼び手責任=意図的共有と区別)。
683
- const explicit = !!name;
684
- let nm = name || autoName();
685
- assertSessionName(nm);
686
- for (let attempt = 0;; attempt++) {
687
- if (attempt >= 20)
688
- throw new AitermError("openSession: 自動採番のリトライ上限(tmux new-session が重複以外で失敗し続けている可能性)", 2);
689
- if (sessionExists(nm)) {
690
- if (explicit)
691
- throw new AitermError(`session '${nm}' は既に存在します(list で確認)`, 2);
666
+ return withNativeSessionSetupRollback(shell, () => {
667
+ for (const key of envVars) {
668
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
669
+ throw new AitermError("env_varsの環境変数名が不正です", 2);
692
670
  }
693
- else {
694
- const environment = [...banner, ...envVars.filter(key => key !== "AITERM_SESSION_ID" && launchEnvValue(key) !== undefined)
695
- .map(key => `${key}=${launchEnvValue(key)}`), `AITERM_SESSION_ID=${nm}`];
696
- const launch = sessionEnvironmentLaunch(shell, environment);
697
- const r = tmuxNewSession(true, nm, launch, environment.map(entry => entry.slice(0, entry.indexOf("="))));
698
- if (r.code === 0) {
699
- if (launch.register_after_start)
700
- for (const entry of environment) {
701
- const at = entry.indexOf("=");
702
- const registered = tmux("set-environment", "-t", nm, entry.slice(0, at), entry.slice(at + 1));
703
- if (registered.code !== 0) {
704
- tmux("kill-session", "-t", nm);
705
- throw new AitermError("session環境変数を登録できません", 2);
671
+ try {
672
+ fs.mkdirSync(SOCKDIR, { recursive: true });
673
+ }
674
+ catch (error) {
675
+ ownTelemetryFailure("AITERM.PERSISTENCE_WRITE_FAILED", error);
676
+ }
677
+ // macOS標準bashの移行bannerを抑止する。環境変数の注入方法はterminal runtimeが所有する。
678
+ const banner = process.platform === "darwin" && path.basename(shell) === "bash"
679
+ ? ["BASH_SILENCE_DEPRECATION_WARNING=1"]
680
+ : [];
681
+ // 並行性対策: 複数エージェントが同時に名前なし open すると autoName が同じ t{i} を返し得る(TOCTOU)。
682
+ // 自動採番は初回のみ読みやすい t{i}、衝突したら乱数 nonce 名でリトライする(線形リトライは高並行で
683
+ // 全員が同じ空き番号に殺到してスケールしない)。明示名は既存ならエラー(呼び手責任=意図的共有と区別)。
684
+ const explicit = !!name;
685
+ let nm = name || autoName();
686
+ assertSessionName(nm);
687
+ for (let attempt = 0;; attempt++) {
688
+ if (attempt >= 20)
689
+ throw new AitermError("openSession: 自動採番のリトライ上限(tmux new-session が重複以外で失敗し続けている可能性)", 2);
690
+ if (sessionExists(nm)) {
691
+ if (explicit)
692
+ throw new AitermError(`session '${nm}' は既に存在します(list で確認)`, 2);
693
+ }
694
+ else {
695
+ const environment = [...banner, ...envVars.filter(key => key !== "AITERM_SESSION_ID" && launchEnvValue(key) !== undefined)
696
+ .map(key => `${key}=${launchEnvValue(key)}`), `AITERM_SESSION_ID=${nm}`];
697
+ const launch = sessionEnvironmentLaunch(shell, environment);
698
+ const r = tmuxNewSession(true, nm, launch, environment.map(entry => entry.slice(0, entry.indexOf("="))));
699
+ if (r.code === 0) {
700
+ if (launch.register_after_start)
701
+ for (const entry of environment) {
702
+ const at = entry.indexOf("=");
703
+ const registered = tmux("set-environment", "-t", nm, entry.slice(0, at), entry.slice(at + 1));
704
+ if (registered.code !== 0) {
705
+ if (!hasNativeSessionSetupRollback())
706
+ tmux("kill-session", "-t", nm);
707
+ throw new AitermError("session環境変数を登録できません", 2);
708
+ }
706
709
  }
707
- }
708
- break;
710
+ break;
711
+ }
712
+ // 自動採番かつ「重複名」由来の失敗(他エージェントが同名を先に取った)なら次名でリトライ。
713
+ const dup = /duplicate|already exists/i.test(r.stderr);
714
+ if (explicit || !dup)
715
+ throw new AitermError("tmux new-session 失敗: " + r.stderr.trim(), 2);
709
716
  }
710
- // 自動採番かつ「重複名」由来の失敗(他エージェントが同名を先に取った)なら次名でリトライ。
711
- const dup = /duplicate|already exists/i.test(r.stderr);
712
- if (explicit || !dup)
713
- throw new AitermError("tmux new-session 失敗: " + r.stderr.trim(), 2);
717
+ nm = nonceName();
718
+ assertSessionName(nm);
714
719
  }
715
- nm = nonceName();
716
- assertSessionName(nm);
717
- }
718
- // 新規セッションの .log は必ず truncate する。"a"(追記)だと外部 kill / killAll / クラッシュで
719
- // 同名 session だけ消えて .log が残った場合、offset=0 と相まって旧出力を新規として返す(B5)。
720
- // break は new-session 成功後にのみ到達=作りたての空 session ゆえ切り詰めは安全。lastcmd/mark 残骸も掃除。
721
- try {
722
- fs.writeFileSync(logpath(nm), "");
723
- }
724
- catch (error) {
725
- ownTelemetryFailure("AITERM.PERSISTENCE_WRITE_FAILED", error);
726
- }
727
- for (const p of [lastcmdpath(nm), markpath(nm)]) {
720
+ // 新規セッションの .log は必ず truncate する。"a"(追記)だと外部 kill / killAll / クラッシュで
721
+ // 同名 session だけ消えて .log が残った場合、offset=0 と相まって旧出力を新規として返す(B5)。
722
+ // break は new-session 成功後にのみ到達=作りたての空 session ゆえ切り詰めは安全。lastcmd/mark 残骸も掃除。
728
723
  try {
729
- fs.unlinkSync(p);
724
+ fs.writeFileSync(logpath(nm), "");
730
725
  }
731
- catch {
732
- /* noop */
726
+ catch (error) {
727
+ ownTelemetryFailure("AITERM.PERSISTENCE_WRITE_FAILED", error);
733
728
  }
734
- }
735
- if (!preserveAgentState)
736
- cleanupAgentState(nm);
737
- // pipe-pane の引数は tmux 内部の /bin/sh -c で再解釈される(argv ではない)。パスは単一引用符で包み、
738
- // パス自身の ' は '\'' イディオムでエスケープする(名前は検証済みだが、Windows ユーザー名 O'Brien 等が
739
- // 一時パスに ' を持ち込み redirect を壊すのを防ぐ。空白対策も兼ねる)。
740
- // Windows の psmux は `cat > <path>` を in-process の直接ファイルsinkとして処理する
741
- // (psmux e3e4b71 以降)。パスは Windows 形のまま渡す。
742
- const pipeTarget = logpath(nm);
743
- const quoted = `'${pipeTarget.replace(/'/g, "'\\''")}'`;
744
- const pr = tmux("pipe-pane", "-t", nm, "-o", `cat >> ${quoted}`);
745
- if (pr.code !== 0) {
746
- // 配管に失敗した session は pty_read が永遠に空を返す=成功を装わない。作った session を片付けて明示エラー。
747
- try {
748
- tmuxCleanup("kill-session", "-t", nm);
729
+ for (const p of [lastcmdpath(nm), markpath(nm)]) {
730
+ try {
731
+ fs.unlinkSync(p);
732
+ }
733
+ catch {
734
+ /* noop */
735
+ }
736
+ }
737
+ if (!preserveAgentState)
738
+ cleanupAgentState(nm);
739
+ // pipe-pane の引数は tmux 内部の /bin/sh -c で再解釈される(argv ではない)。パスは単一引用符で包み、
740
+ // パス自身の ' は '\'' イディオムでエスケープする(名前は検証済みだが、Windows ユーザー名 O'Brien 等が
741
+ // 一時パスに ' を持ち込み redirect を壊すのを防ぐ。空白対策も兼ねる)。
742
+ // Windows の psmux は `cat > <path>` を in-process の直接ファイルsinkとして処理する
743
+ // (psmux e3e4b71 以降)。パスは Windows 形のまま渡す。
744
+ const pipeTarget = logpath(nm);
745
+ const quoted = `'${pipeTarget.replace(/'/g, "'\\''")}'`;
746
+ const pr = tmux("pipe-pane", "-t", nm, "-o", `cat >> ${quoted}`);
747
+ if (pr.code !== 0) {
748
+ // 配管に失敗した session は pty_read が永遠に空を返す=成功を装わない。作った session を片付けて明示エラー。
749
+ if (!hasNativeSessionSetupRollback()) {
750
+ try {
751
+ tmuxCleanup("kill-session", "-t", nm);
752
+ }
753
+ catch { /* cleanup failure is not a second observation */ }
754
+ try {
755
+ fs.unlinkSync(logpath(nm)); // B14: 直前に作った空 .log も残さない
756
+ }
757
+ catch {
758
+ /* noop */
759
+ }
760
+ }
761
+ ownTelemetryFailure("AITERM.PERSISTENCE_WRITE_FAILED", new AitermError("tmux pipe-pane 失敗(出力ログを配管できないため session を破棄): " + pr.stderr.trim(), 2), 2);
749
762
  }
750
- catch { /* cleanup failure is not a second observation */ }
751
763
  try {
752
- fs.unlinkSync(logpath(nm)); // B14: 直前に作った空 .log も残さない
764
+ writeOffset(nm, 0);
753
765
  }
754
- catch {
755
- /* noop */
766
+ catch (error) {
767
+ ownTelemetryFailure("AITERM.PERSISTENCE_WRITE_FAILED", error);
756
768
  }
757
- ownTelemetryFailure("AITERM.PERSISTENCE_WRITE_FAILED", new AitermError("tmux pipe-pane 失敗(出力ログを配管できないため session を破棄): " + pr.stderr.trim(), 2), 2);
758
- }
759
- try {
760
- writeOffset(nm, 0);
761
- }
762
- catch (error) {
763
- ownTelemetryFailure("AITERM.PERSISTENCE_WRITE_FAILED", error);
764
- }
765
- return [nm, attachHint(nm)];
769
+ return [nm, attachHint(nm)];
770
+ });
766
771
  }
767
772
  export const AGENT_PREFACE_MAX_CHARS = 200;
768
773
  // 行頭のASCII記号と空白は、入力欄が命令として読む(Claude Codeの`/`・`!`・`#`・`?`など)。`@`は文中でも候補の枠を開く。
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { remoteInputDescription, remoteInputSchema, terminalArgumentDescription, terminalArgumentSchema } from "./remote-contract.js";
3
- import { boundTerminalTarget, bindTerminalSession, ensureSeatForward, extractMcpHeaders, hasSeatMcpUrl, maintainSeatForwards, REMOTE_MINIMUM_VERSION, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
3
+ import { boundTerminalTarget, bindTerminalSession, ensureSeatForward, extractMcpHeaders, maintainSeatForwards, REMOTE_MINIMUM_VERSION, seatIngressPort, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
4
4
  import { launchEnvValue } from "./private-env.js";
5
5
  import { AuthResponseError, authUiSchema, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
6
6
  import { configurationRequestSchema, configurationToolOutputSchema, applyConfigurationRequest, reconcileConfigurationRequest } from "./configure-request.js";
@@ -1262,8 +1262,9 @@ export function createAitermServer(options = {}) {
1262
1262
  const extracted = extractMcpHeaders(mcpConfig);
1263
1263
  Object.assign(privateEnv, extracted.env);
1264
1264
  mcpConfig = extracted.config;
1265
- if (hasSeatMcpUrl(mcpConfig))
1266
- mcpConfig = rewriteSeatMcpConfig(mcpConfig, await ensureSeatForward(target.trusted_ref));
1265
+ const ingress = seatIngressPort(mcpConfig);
1266
+ if (ingress)
1267
+ mcpConfig = rewriteSeatMcpConfig(mcpConfig, await ensureSeatForward(target.trusted_ref, ingress));
1267
1268
  }
1268
1269
  const envVars = [...new Set([...(args.env_vars ?? []), ...Object.keys(privateEnv)])];
1269
1270
  const result = await launchRemoteAgent(target, harness, { ...args, ...(envVars.length ? { env_vars: envVars } : {}), ...(mcpConfig ? { mcp_config: mcpConfig } : {}) }, extra, privateEnv);
@@ -56,4 +56,4 @@ export const terminalArgumentDescription = "Run this seat on another computer (a
56
56
  "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
57
  "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
58
  "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. TERMINAL_HARNESS_UNSUPPORTED = use harness claude-code.";
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.";
@@ -182,12 +182,9 @@ export function classifySshFailure(stderr) {
182
182
  return { code: "UNREACHABLE", message: "the terminal cannot be reached" };
183
183
  return { code: "CONNECTION_FAILED", message: "the SSH connection failed" };
184
184
  }
185
- /** -R spec for the seats' BellTeam MCP (remote-terminal.md R12). P=0 lets the terminal's sshd pick the port. */
186
- export function seatForwardSpec(terminalPort, env = process.env) {
187
- const port = Number(env.BELLTEAM_REMOTE_SEAT_PORT ?? 4182);
188
- if (!Number.isInteger(port) || port < 1 || port > 65535)
189
- throw new RemoteTerminalError("SEAT_FORWARD_UNAVAILABLE", "BELLTEAM_REMOTE_SEAT_PORT is not a port");
190
- return `127.0.0.1:${terminalPort}:127.0.0.1:${port}`;
185
+ /** -R spec for the seats' BellTeam MCP (remote-terminal.md R12). P=0 lets the terminal's sshd pick the port; D comes from the binding. */
186
+ export function seatForwardSpec(terminalPort, ingressPort) {
187
+ return `127.0.0.1:${terminalPort}:127.0.0.1:${ingressPort}`;
191
188
  }
192
189
  /** ssh stderr -> the allocated terminal port, "refused", or null while unknown. */
193
190
  export function parseSeatForward(stderr) {
@@ -631,15 +628,28 @@ export function boundTerminalTarget(session) {
631
628
  return ref ? trustedTarget(binding(ref)) : null;
632
629
  }
633
630
  const SEAT_PATH = /^\/api\/seat-mcp(\/|$)/;
634
- export function hasSeatMcpUrl(config) {
635
- return Object.values((config.mcpServers ?? {})).some(server => {
631
+ /** The one container port D of the seat URLs (R12), or null without seat URLs. */
632
+ export function seatIngressPort(config) {
633
+ const ports = new Set();
634
+ for (const server of Object.values((config.mcpServers ?? {}))) {
635
+ let url;
636
636
  try {
637
- return typeof server?.url === "string" && SEAT_PATH.test(new URL(server.url).pathname);
637
+ if (typeof server?.url !== "string")
638
+ continue;
639
+ url = new URL(server.url);
638
640
  }
639
641
  catch {
640
- return false;
642
+ continue;
641
643
  }
642
- });
644
+ if (!SEAT_PATH.test(url.pathname))
645
+ continue;
646
+ if (url.protocol !== "http:" || url.hostname !== "127.0.0.1")
647
+ throw new RemoteTerminalError("SEAT_FORWARD_UNAVAILABLE", "seat MCP URLs must be http://127.0.0.1:<port>/api/seat-mcp");
648
+ ports.add(Number(url.port || 80));
649
+ }
650
+ if (ports.size > 1)
651
+ throw new RemoteTerminalError("SEAT_FORWARD_UNAVAILABLE", "seat MCP URLs name different ports");
652
+ return ports.size ? [...ports][0] : null;
643
653
  }
644
654
  /** Header values leave the config file: each becomes ${AITERM_MCP_HEADER_n}, its value goes to the private env line. */
645
655
  export function extractMcpHeaders(config) {
@@ -716,11 +726,19 @@ function releaseLock(ref) {
716
726
  function forwardNeeded(ref) {
717
727
  return (keepers.get(ref)?.launchUntil ?? 0) > Date.now() || Object.values(readSeats()).includes(ref);
718
728
  }
729
+ function storedIngress(ref) {
730
+ try {
731
+ return binding(ref).seat_ingress_port;
732
+ }
733
+ catch {
734
+ return undefined;
735
+ }
736
+ }
719
737
  function keep(ref) {
720
- const keeper = keepers.get(ref) ?? { child: null, refusals: 0, timer: null, launchUntil: 0 };
738
+ const keeper = keepers.get(ref) ?? { child: null, ingress: 0, refusals: 0, timer: null, launchUntil: 0 };
721
739
  keepers.set(ref, keeper);
722
740
  if (keeper.child) {
723
- if (!forwardNeeded(ref))
741
+ if (!forwardNeeded(ref) || storedIngress(ref) !== keeper.ingress)
724
742
  keeper.child.kill();
725
743
  return;
726
744
  }
@@ -742,11 +760,17 @@ function keep(ref) {
742
760
  releaseLock(ref);
743
761
  return;
744
762
  }
763
+ // No D in the binding (written before 0.70.3): no forward until a launch writes D; never a default port.
764
+ if (!b.seat_ingress_port) {
765
+ releaseLock(ref);
766
+ return;
767
+ }
745
768
  const requested = b.seat_forward_port ?? 0;
769
+ keeper.ingress = b.seat_ingress_port;
746
770
  let args;
747
771
  try {
748
772
  // The remote command ends when our stdin closes, so the forward dies with this process even on SIGKILL.
749
- args = trustedSshArguments(ref, "cat >/dev/null", null, ["-o", "ExitOnForwardFailure=yes", "-R", seatForwardSpec(requested)]);
773
+ args = trustedSshArguments(ref, "cat >/dev/null", null, ["-o", "ExitOnForwardFailure=yes", "-R", seatForwardSpec(requested, b.seat_ingress_port)]);
750
774
  }
751
775
  catch {
752
776
  releaseLock(ref);
@@ -775,19 +799,22 @@ function keep(ref) {
775
799
  keeper.timer.unref();
776
800
  });
777
801
  }
778
- /** Every 60 s: keep (or take over) the forwards this process's state root needs. */
802
+ /** Every 60 s in every active process: keep (or take over from an exited holder) the forwards this state root needs. */
779
803
  export function maintainSeatForwards() {
780
804
  const refs = new Set([...Object.values(readSeats()), ...keepers.keys(), ...loadedCredentialRefs()]);
781
805
  for (const ref of refs)
782
806
  keep(ref);
783
- if (refs.size && !maintainTimer) {
807
+ if (!maintainTimer) {
784
808
  maintainTimer = setInterval(maintainSeatForwards, 60_000);
785
809
  maintainTimer.unref();
786
810
  }
787
811
  }
788
- /** The terminal-local port for seat URLs; starts the keeper if no process holds it yet. */
789
- export async function ensureSeatForward(ref, timeoutMs = 30_000) {
790
- const keeper = keepers.get(ref) ?? { child: null, refusals: 0, timer: null, launchUntil: 0 };
812
+ /** The terminal-local port for seat URLs reaching container port `ingress`; starts the keeper if no process holds it yet. */
813
+ export async function ensureSeatForward(ref, ingress, timeoutMs = 30_000) {
814
+ // A new D makes the old P (forwarding to the old D) useless: clear it so the wait below sees only a forward to D.
815
+ if (binding(ref).seat_ingress_port !== ingress)
816
+ writeBinding(ref, { seat_ingress_port: ingress, seat_forward_port: undefined });
817
+ const keeper = keepers.get(ref) ?? { child: null, ingress: 0, refusals: 0, timer: null, launchUntil: 0 };
791
818
  keeper.launchUntil = Date.now() + LAUNCH_GRACE_MS;
792
819
  keepers.set(ref, keeper);
793
820
  maintainSeatForwards();
@@ -5,7 +5,7 @@ import { spawnSync } from "node:child_process";
5
5
  import * as fs from "node:fs";
6
6
  import * as path from "node:path";
7
7
  import * as os from "node:os";
8
- import { createHash } from "node:crypto";
8
+ import { createHash, randomBytes } from "node:crypto";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { AsyncLocalStorage } from "node:async_hooks";
11
11
  import stringWidth from 'string-width';
@@ -15,7 +15,7 @@ import { ExecutionError } from "./execution-wire.js";
15
15
  import { parseNativeSessionReceipt, nativePaneTarget, nativeSessionTarget, nativeSessionCondition } from "./native-session.js";
16
16
  const nativeTargets = new AsyncLocalStorage();
17
17
  const nativeReads = new Set(["list-sessions", "list-commands", "list-panes", "list-windows", "has-session", "display-message", "capture-pane", "show-environment", "show-options"]);
18
- const nativePanes = new Set(["send-keys", "paste-buffer", "pipe-pane", "capture-pane", "display-message", "list-panes"]);
18
+ const nativePanes = new Set(["send-keys", "paste-buffer", "pipe-pane", "capture-pane", "display-message", "list-panes", "rename-window", "set-window-option"]);
19
19
  const nativeTargetUnavailable = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 復帰したnative端末の本人性を確認できません。", 2);
20
20
  function verifyNativeTarget(frame) {
21
21
  if (frame.checking)
@@ -48,6 +48,44 @@ export function withNativeSessionCreation(session, created, verify, body) {
48
48
  throw nativeTargetUnavailable();
49
49
  return nativeTargets.run({ session, target: null, created, verify }, body);
50
50
  }
51
+ const CREATION_TOKEN_OPTION = "@aiterm_create_token";
52
+ export function hasNativeSessionSetupRollback() { return !!nativeTargets.getStore()?.setup; }
53
+ /** Only the native setup is transactional; later readiness may intentionally retain a live agent. */
54
+ export function withNativeSessionSetupRollback(shell, body) {
55
+ const frame = nativeTargets.getStore();
56
+ if (!frame?.created || frame.setup)
57
+ return body();
58
+ const token = randomBytes(16).toString("hex");
59
+ const setup = { token, window: `aiterm-create-${token}`, shell: path.basename(shell), target: null };
60
+ frame.setup = setup;
61
+ try {
62
+ return body();
63
+ }
64
+ catch (error) {
65
+ if (setup.target) {
66
+ try {
67
+ const closed = creationCommand(setup, ["kill-session", "-t", setup.target.session_id], true);
68
+ // An already absent native is a finished rollback: the created callback may have closed it.
69
+ if (closed.code !== 0 && creationCommand(setup, ["has-session", "-t", setup.target.session_id]).code === 0)
70
+ throw nativeTargetUnavailable();
71
+ }
72
+ catch {
73
+ if (error instanceof Error)
74
+ error.message += "\ncreation_rollback_unconfirmed: 作成した端末の片付けを確認できません。";
75
+ }
76
+ }
77
+ throw error;
78
+ }
79
+ finally {
80
+ delete frame.setup;
81
+ }
82
+ }
83
+ // This scope is private to marker transfer and rollback; ordinary effects still require OS birth identity.
84
+ function creationCommand(setup, args, allowRefusal = false) {
85
+ const target = setup.target;
86
+ const creationCondition = `#{||:#{==:#{window_name},${setup.window}},#{==:#{${CREATION_TOKEN_OPTION}},${setup.token}}}`;
87
+ return nativeTargets.run({ session: target.session_id, target, verify: () => { }, creationCondition, allowRefusal }, () => runTmux(false, undefined, args));
88
+ }
51
89
  function captureNativeSessionReceipt(receipt) {
52
90
  const frame = nativeTargets.getStore();
53
91
  if (!frame?.created || frame.target)
@@ -63,6 +101,23 @@ function captureNativeSessionReceipt(receipt) {
63
101
  throw nativeTargetUnavailable();
64
102
  frame.session = target.session_id;
65
103
  frame.target = target;
104
+ if (frame.setup) {
105
+ const setup = frame.setup;
106
+ setup.target = { ...target };
107
+ const commands = [["set-option", "-t", target.session_id, CREATION_TOKEN_OPTION, setup.token],
108
+ ["rename-window", "-t", target.session_id, setup.shell]];
109
+ if (isWin) {
110
+ const inherited = creationCommand(setup, ["show-options", "-t", target.session_id, "-v", "automatic-rename"]);
111
+ if (inherited.code !== 0 || !["on", "off"].includes(inherited.stdout.trim()))
112
+ throw nativeTargetUnavailable();
113
+ commands.push(["set-window-option", "-t", target.session_id, "automatic-rename", inherited.stdout.trim()]);
114
+ }
115
+ else
116
+ commands.push(["set-window-option", "-t", target.session_id, "-u", "automatic-rename"]);
117
+ for (const command of commands)
118
+ if (creationCommand(setup, command).code !== 0)
119
+ throw nativeTargetUnavailable();
120
+ }
66
121
  frame.created({ ...frame.target });
67
122
  verifyNativeTarget(frame);
68
123
  }
@@ -114,7 +169,9 @@ function nativeConditionalArgs(args) {
114
169
  const target = nativeTargets.getStore()?.target;
115
170
  if (!target || nativeReads.has(args[0]) || args[0] === "delete-buffer")
116
171
  return args;
117
- const condition = nativeSessionCondition(target, nativeTargets.getStore()?.allowExitedPane);
172
+ const frame = nativeTargets.getStore();
173
+ const nativeCondition = nativeSessionCondition(target, frame.allowExitedPane);
174
+ const condition = frame.creationCondition ? `#{&&:${nativeCondition},${frame.creationCondition}}` : nativeCondition;
118
175
  const quote = (value) => isWin
119
176
  ? `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`
120
177
  : `'${value.replace(/'/g, "'\\''")}'`;
@@ -431,7 +488,7 @@ function runTmux(observe, input, args, session, deadline) {
431
488
  ptyDependencyError(tmuxMissingMessage(), observe);
432
489
  }
433
490
  const native = nativeTargets.getStore();
434
- if (native?.target && args[0] === "if-shell" && (r.stdout ?? "").trim() === NATIVE_REFUSED)
491
+ if (native?.target && !native.allowRefusal && args[0] === "if-shell" && (r.stdout ?? "").trim() === NATIVE_REFUSED)
435
492
  throw nativeTargetUnavailable();
436
493
  if (native?.target && r.status !== 0)
437
494
  verifyNativeTarget(native);
@@ -697,13 +754,19 @@ export function tmuxNewSession(observe, name, launch, registered = []) {
697
754
  }
698
755
  const printNative = pinned ? ["-P", "-F", "#{session_id}\t#{session_name}\t#{pid}\t#{pane_id}\t#{pane_pid}"]
699
756
  : guarded ? ["-P", "-F", "#{session_id}\t#{session_name}\t#{pid}"] : [];
757
+ const witness = nativeTargets.getStore()?.setup;
758
+ if (witness)
759
+ printNative.push("-n", witness.window);
700
760
  if (isWin) {
701
761
  const result = runTmux(observe, undefined, ["new-session", "-d", "-s", name, ...printNative, ...launch.args, "-f", TMUX_EMPTY_CONFIG, launch.shell]);
702
762
  if (result.code === 0) {
703
763
  if (pinned) {
704
764
  try {
705
- if (parseNativeSessionReceipt(result.stdout).session_id !== name)
765
+ const receipt = parseNativeSessionReceipt(result.stdout);
766
+ if (receipt.session_id !== name)
706
767
  throw nativeTargetUnavailable();
768
+ if (witness)
769
+ witness.target = receipt;
707
770
  }
708
771
  catch {
709
772
  throw nativeTargetUnavailable();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.70.1",
3
+ "version": "0.70.3",
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": [