aiterm-mcp 0.68.1 → 0.70.0

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,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.70.0] - 2026-11-10
11
+
12
+ - `remote_terminal_command` takes `list_dirs` with an optional absolute `path` for a folder picker (BellTeam PR 887 S6; docs/architecture/remote-terminal.md R15). Without `path` it lists the SSH user's home. Result `{op, home, path, exists, directory, entries: [{name}] | null, truncated}`: subfolders only (a symlink to a folder counts), no names starting with `.`, ordered by name, at most 500 then `truncated: true`, read only. A missing folder or a file answers `exists`/`directory` false with `entries: null`, never an empty list; permission refusals (macOS privacy consent included) answer `FOLDER_NOT_PERMITTED` as for `path_status`. Needs this release on the terminal (`REMOTE_AITERM_TOO_OLD` otherwise).
13
+ - A terminal launch refused before any seat exists carries `_meta["aiterm/launch_error"]` (`aiterm.agent-launch-error.v1`, `phase: "terminal"`, `effect: "not_started"`) with its code and a fixed plain Japanese `action` for the Owner (BellTeam seatLaunch; remote-terminal.md R18). Server-side only; the terminal needs no update. A possibly started launch keeps the plain text. The terminal's Claude authentication refusal is now returned as an error with its structure instead of continuing as a launch result.
14
+
15
+ ## [0.69.0] - 2026-11-10
16
+
17
+ - Terminal self-service before a seat can open (docs/architecture/remote-terminal.md R14-R17; BellTeam PR 854 S2-S5).
18
+ - `aiterm-remote-terminal authorize-key --ref R`: the terminal's login password is the raw UTF-8 stdin until EOF (nothing stripped). After the binding's trust and held key are checked (before stdin is read), one password-only SSH login (no public key, no keyboard-interactive, one prompt) appends the held public key to `~/.ssh/authorized_keys` unless the same key type and blob is already there (`~/.ssh` 0700, file 0600, other entries kept). The password reaches ssh only through a one-shot askpass socket; never argv, env, files, logs or the PTY. Receipt `aiterm.remote-key-authorization.v1` `{ref, result: AUTHORIZED | ALREADY_AUTHORIZED}`; failures `PASSWORD_REJECTED`, `PASSWORD_AUTH_DISABLED`, `PASSWORD_INVALID`, `AUTHORIZED_KEYS_WRITE_FAILED` and the existing trust/key/network codes.
19
+ - `aiterm-remote-terminal provision --ref R` (macOS arm64/x86_64): over the binding's trusted key SSH and before any terminal MCP exists, the terminal downloads this version's runtime from the GitHub Release (official Node, the published aiterm-mcp, and a tmux with its libraries linked in), checks its sha256, stages and smokes it, then makes it `~/.aiterm/runtime/current` (the previous one stays as `previous`; running seats and tmux servers are untouched). No Homebrew, npm, Node, tmux, password or sudo on the terminal. Receipt `aiterm.remote-provision.v1` `{ref, result: PROVISIONED | ALREADY_CURRENT, version}`. Remote POSIX commands now put that runtime first on PATH. The release workflow `runtime.yml` builds and attaches the assets on the macOS runner.
20
+ - `remote_terminal_command` takes `path_status` and `make_dir` with an absolute `path` -> `{op, exists, directory, writable}`; `writable` is a real create-and-remove probe. Permission refusals (macOS privacy consent, ACL or POSIX, not told apart) answer `FOLDER_NOT_PERMITTED`, and a missing folder under an unreadable parent is not reported as missing. Needs this release on the terminal (`REMOTE_AITERM_TOO_OLD` otherwise).
21
+ - SSH "Connection refused" now answers `CONNECTION_REFUSED` instead of `UNREACHABLE` (evidence only: SSH may be off on the terminal). `trust-confirm` answers `UNREACHABLE` when the scan returns no host key at all (an asleep Mac is not another machine); keys without the confirmed fingerprint stay `HOST_KEY_FINGERPRINT_MISMATCH`.
22
+ - `agent_models` for claude-code returns the same list on every call. Claude Code keeps its served-catalog switch in the configuration root's shared global config, and seats or logins sharing that root rewrote it, so the list flipped between 5 and 14 models (Fable 5.2 missing at random). The catalog now runs in its own root per configuration root that only the catalog writes, holding only the root's access token (no refresh token, so the root's login is never rotated from there), and repeats until two runs agree while that root is cold (docs/architecture/harness-contracts.md C1-C4). Roots whose credentials are not a file (macOS Keychain), token/API-key environments and near-expiry tokens run on the root as before. New optional `configuration_root` (claude-code only, accepted like `agent_launch`; otherwise `AGENT_CONFIGURATION_ROOT_REJECTED`) reads the list of the account a seat is launched on.
23
+
10
24
  ## [0.68.1] - 2026-11-09
11
25
 
12
26
  - Seat activity (`readSeatTurns`): a fresh Claude seat that has never been busy and has no recorded turn or completion, such as a no-prompt launch after a harness switch, now reads `idle` after the usual 250 ms settle. Before, its ready composer had no completed-progress line ("✻ Cooked for 12s"), so the reading stayed unknown until the first input and after-turn work never started. Once the seat has a recorded turn or completion, the completed-progress line is still required.
@@ -3144,7 +3158,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3144
3158
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3145
3159
  provenance.
3146
3160
 
3147
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.68.1...HEAD
3161
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.0...HEAD
3162
+ [0.70.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.69.0...v0.70.0
3163
+ [0.69.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.68.1...v0.69.0
3148
3164
  [0.68.1]: https://github.com/kitepon/aiterm-mcp/compare/v0.68.0...v0.68.1
3149
3165
  [0.68.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.67.0...v0.68.0
3150
3166
  [0.67.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.66.0...v0.67.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.68.1** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.70.0** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
219
219
 
220
220
  ### 更新と巻き戻し
221
221
 
@@ -618,7 +618,7 @@ Claudeの相関済み承認は既存の`claude_approval`を使う。
618
618
  | `pty_observe` | pane/harnessの生存、native process identity、状態と活動 | `session_id`, `cursor?` |
619
619
  | `agent_launch` | harnessとmodelを別軸で選ぶ正規agent起動入口 | `harness`, `prompt?`, `model?`, `reasoning_effort?`, `fast?`, `cwd?`, `write_scope?`, `trust_project?`, `env_vars?`, `throughline_source_session?`, `throughline_supplement_file?` |
620
620
  | `agent_auth` | 公式CLIの認証を開始・確認・取消し、公式URL・device code・入力待ちを返す | `harness`, `action`, `session_id?`, `cwd?`, `env_vars?`, `relogin?`, `expected_binding?`, `response?` |
621
- | `agent_models` | harnessが今選べるmodelとreasoning effortを、そのharness自身の一覧からpromptを送らずに取得 | `harness`, `cwd?`, `include_hidden?` |
621
+ | `agent_models` | harnessが今選べるmodelとreasoning effortを、そのharness自身の一覧からpromptを送らずに取得 | `harness`, `cwd?`, `include_hidden?`, `configuration_root?`(claude-code) |
622
622
  | `agent_approval` | Codexの現在の承認を検査し、単発許可・拒否を送る | `action`, `session_id`, `approval_choice?`, `observed_prompt_digest?` |
623
623
  | `claude_agent` / `codex_agent` / `grok_agent` | deprecated互換alias(`composer_agent`は0.41.0で削除。Composerは`agent_launch`の`cursor-cli`で使う) | 旧launcher引数 |
624
624
  | `agent_configure` | 起動中のClaude/Codex/Grok/Cursor/Antigravityを再起動せずmodel/effort/fast変更 | `session_id`, `model?`, `reasoning_effort?`, `fast?` |
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.68.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.0** · 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
 
@@ -658,7 +658,7 @@ continue to use `claude_approval`.
658
658
  | `pty_observe` | Pane/harness liveness, native process identity, state, and activity | `session_id`, `cursor?` |
659
659
  | `agent_launch` | Canonical agent launch; harness and model are independent | `harness`, `prompt?`, `model?`, `reasoning_effort?`, `fast?`, `cwd?`, `write_scope?`, `trust_project?`, `env_vars?`, `throughline_source_session?`, `throughline_supplement_file?` |
660
660
  | `agent_auth` | 公式CLIの認証を開始・確認・取消し、公式URL・device code・入力待ちを返す | `harness`, `action`, `session_id?`, `cwd?`, `env_vars?`, `relogin?`, `expected_binding?`, `response?` |
661
- | `agent_models` | List the models and reasoning efforts a harness offers now, read from that harness's own catalog without sending a prompt | `harness`, `cwd?`, `include_hidden?` |
661
+ | `agent_models` | List the models and reasoning efforts a harness offers now, read from that harness's own catalog without sending a prompt | `harness`, `cwd?`, `include_hidden?`, `configuration_root?` (claude-code) |
662
662
  | `agent_approval` | Inspect a Codex approval and submit a one-time approval or denial | `action`, `session_id`, `approval_choice?`, `observed_prompt_digest?` |
663
663
  | `claude_agent` / `codex_agent` / `grok_agent` | Deprecated compatibility aliases (`composer_agent` was removed in 0.41.0; run Composer with `agent_launch` on `cursor-cli`) | legacy launcher arguments |
664
664
  | `agent_configure` | Change model/effort/fast in a running Claude, Codex, Grok, or Cursor session without restarting it | `session_id`, `model?`, `reasoning_effort?`, `fast?` |
@@ -0,0 +1,51 @@
1
+ // Catalog-only Claude config root per configuration root (harness-contracts.md C1-C4).
2
+ // Claude Code writes its served-catalog flag into the root's global config regardless of identity, so seats and logins
3
+ // sharing a root make the model list flap. The catalog runs in its own root that only the catalog writes.
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { ensureStateRoot } from "./agent-shared.js";
8
+ import { claudeDefaultConfigRoot } from "./claude-config-root.js";
9
+ const FRESH_MS = 10 * 60_000;
10
+ /**
11
+ * The catalog-only root for the root `env` selects, holding only the root's access token. null when the root has no
12
+ * file credential (macOS Keychain), the env authenticates by token/API key, or the access token is near expiry:
13
+ * the caller then runs on the root itself as before, which lets Claude Code refresh there.
14
+ */
15
+ export function claudeCatalogRoot(env, now = Date.now()) {
16
+ if (env.CLAUDE_CODE_OAUTH_TOKEN || env.ANTHROPIC_API_KEY || env.ANTHROPIC_AUTH_TOKEN)
17
+ return null;
18
+ const root = env.CLAUDE_CONFIG_DIR || claudeDefaultConfigRoot(env);
19
+ let oauth;
20
+ try {
21
+ oauth = JSON.parse(fs.readFileSync(path.join(root, ".credentials.json"), "utf8"))?.claudeAiOauth;
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ if (typeof oauth?.accessToken !== "string" || typeof oauth.expiresAt !== "number" || oauth.expiresAt - now < FRESH_MS)
27
+ return null;
28
+ let real = root;
29
+ try {
30
+ real = fs.realpathSync(root);
31
+ }
32
+ catch { }
33
+ const dir = path.join(ensureStateRoot(), "claude-catalog", createHash("sha256").update(real).digest("hex").slice(0, 16));
34
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
35
+ // The refresh token is single-use: a refresh here would sign the root out, so the copy cannot refresh.
36
+ const { refreshToken: _refresh, ...access } = oauth;
37
+ const tmp = path.join(dir, `.credentials.${randomUUID()}.tmp`);
38
+ fs.writeFileSync(tmp, JSON.stringify({ claudeAiOauth: access }), { mode: 0o600 });
39
+ fs.renameSync(tmp, path.join(dir, ".credentials.json"));
40
+ const digestFile = path.join(dir, "last-catalog.sha256");
41
+ return {
42
+ env: { ...env, CLAUDE_CONFIG_DIR: dir },
43
+ lastDigest: () => { try {
44
+ return fs.readFileSync(digestFile, "utf8");
45
+ }
46
+ catch {
47
+ return null;
48
+ } },
49
+ remember: digest => fs.writeFileSync(digestFile, digest, { mode: 0o600 }),
50
+ };
51
+ }
package/dist/core.js CHANGED
@@ -5228,6 +5228,10 @@ export async function authenticateAgent(kind, options) {
5228
5228
  * promptもturnも送らない。取得不能・形式異常はfallbackせずエラーにする。
5229
5229
  */
5230
5230
  export async function listAgentModels(kind, options = {}) {
5231
+ if (options.configuration_root !== undefined && kind !== "claude")
5232
+ throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: configuration_rootはclaude-code harnessだけで使えます。", 2);
5233
+ const claudeEnv = options.configuration_root === undefined ? process.env
5234
+ : withClaudeConfigRoot(process.env, resolveClaudeConfigurationRoot(options.configuration_root));
5231
5235
  const cwd = options.cwd ?? process.cwd();
5232
5236
  if (!path.isAbsolute(cwd))
5233
5237
  throw new AitermError("cwd は絶対パスで指定してください", 2);
@@ -5237,7 +5241,7 @@ export async function listAgentModels(kind, options = {}) {
5237
5241
  if (!bin)
5238
5242
  throw catalogUnavailable(agentLabel(kind), `${agentLabel(kind)} の CLI が見つかりません`);
5239
5243
  switch (kind) {
5240
- case "claude": return claudeModelChoices(bin, cwd);
5244
+ case "claude": return claudeModelChoices(bin, cwd, claudeEnv);
5241
5245
  case "codex": return codexModelChoices(bin, options.include_hidden === true);
5242
5246
  case "grok": return grokModelChoices(bin, cwd);
5243
5247
  case "cursor": return cursorModelChoices(bin, cwd);
@@ -10,6 +10,7 @@ import { fileURLToPath } from "node:url";
10
10
  import { AitermError, AgentAuthenticationPreflightError } from "../errors.js";
11
11
  import { modeBitsWorldAccessible } from "../tmux-runtime.js";
12
12
  import { runAgentProtocolCommand, spawnAgentControlCommand } from "../agent-resolver.js";
13
+ import { claudeCatalogRoot } from "../claude-catalog-root.js";
13
14
  import { catalogInvalid, catalogUnavailable, checkedCatalog, findJsonLine, processSummary } from "../model-catalog.js";
14
15
  import { currentUid, writeJson0600, shq, subagentInstruction, AGENT_DEFAULT_PREFACE, writeScopeLaunchNote, agentEventPath, createEmpty0600, writeAgentMetadata, agentLineageFields, assertSessionName, agentsDir, LAUNCH_ID_RE, AGENT_EVENT_TAIL_BYTES, readFileRange, } from "../agent-shared.js";
15
16
  export const OPERATION_ID_RE = /^sha256:[0-9a-f]{64}$/;
@@ -179,6 +180,27 @@ const CLAUDE_ULTRACODE_NOTE = "Claude Codeの--effortが受け付けるsession
179
180
  * promptは送らず、sessionを保存せず、利用者のhookとMCP serverを起動しない。
180
181
  */
181
182
  export async function claudeModelChoices(bin, cwd, env = process.env) {
183
+ // Run in the catalog-only root so other processes writing the shared config cannot flip the list
184
+ // (harness-contracts.md C1-C4). A cold root answers differently until its flag and catalog caches settle.
185
+ let own = claudeCatalogRoot(env);
186
+ if (!own) {
187
+ const shared = await claudeModelChoicesOnce(bin, cwd, env);
188
+ own = claudeCatalogRoot(env);
189
+ if (!own)
190
+ return shared;
191
+ }
192
+ let catalog;
193
+ for (let attempt = 0; attempt < CLAUDE_CATALOG_SETTLE_RUNS; attempt++) {
194
+ catalog = await claudeModelChoicesOnce(bin, cwd, own.env);
195
+ const digest = createHash("sha256").update(JSON.stringify(catalog)).digest("hex");
196
+ if (digest === own.lastDigest())
197
+ return catalog;
198
+ own.remember(digest);
199
+ }
200
+ return catalog;
201
+ }
202
+ const CLAUDE_CATALOG_SETTLE_RUNS = 4;
203
+ async function claudeModelChoicesOnce(bin, cwd, env) {
182
204
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "aiterm-claude-models-"));
183
205
  try {
184
206
  const settings = path.join(dir, "settings.json");
package/dist/index.js CHANGED
@@ -18,6 +18,7 @@ import { AitermError, AgentAuthenticationPreflightError, AgentResumeUnavailableE
18
18
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
19
19
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
20
20
  import { readPrivateEnvLine, setPrivateEnv } from "./private-env.js";
21
+ import { withTerminalLaunchAction } from "./terminal-launch-error.js";
21
22
  import { CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
22
23
  import { z } from "zod";
23
24
  import { agentModelsResult } from "./model-catalog.js";
@@ -1133,6 +1134,7 @@ export function createAitermServer(options = {}) {
1133
1134
  harness: z.enum(["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"]).describe("候補を取得するharness"),
1134
1135
  cwd: z.string().nullish().describe("CLIを実行する作業ディレクトリ(絶対パス・任意)。project設定で候補が変わるharness向け"),
1135
1136
  include_hidden: z.boolean().optional().describe("Codexが一覧で隠すmodelも返す(既定false)。他のharnessには隠すmodelが無い"),
1137
+ configuration_root: z.string().min(1).optional().describe("claude-code harnessだけ。一覧を読むアカウントの設定root(CLAUDE_CONFIG_DIR)。受ける範囲はagent_launchと同じ(既定のroot、またはAITERM_CLAUDE_CONFIG_ROOTSに並べた親の直下)。他はAGENT_CONFIGURATION_ROOT_REJECTED。省略は既定のroot"),
1136
1138
  },
1137
1139
  outputSchema: {
1138
1140
  schema: z.literal("aiterm.agent-models.v1"),
@@ -1145,9 +1147,9 @@ export function createAitermServer(options = {}) {
1145
1147
  fast_unavailable: fastModeFailureSchema.nullable().optional().describe("このアカウント・この端末では、どのmodelでもfastを使えない時の訳(harnessが先に答えられる時だけ。今はClaude Code)。使える・分からない時はnull"),
1146
1148
  models: z.array(agentModelChoiceSchema),
1147
1149
  },
1148
- }, async ({ harness, cwd, include_hidden }) => {
1150
+ }, async ({ harness, cwd, include_hidden, configuration_root }) => {
1149
1151
  try {
1150
- const catalog = await core.listAgentModels(kindForHarness(harness), { cwd, include_hidden });
1152
+ const catalog = await core.listAgentModels(kindForHarness(harness), { cwd, include_hidden, configuration_root });
1151
1153
  const result = agentModelsResult(harness, catalog);
1152
1154
  return {
1153
1155
  content: [{ type: "text", text: JSON.stringify(result) }],
@@ -1203,8 +1205,9 @@ export function createAitermServer(options = {}) {
1203
1205
  ? await callRemoteTool(target, "claude_agent", args, 600_000, privateEnv)
1204
1206
  : await callRemoteTool(target, "agent_launch", { harness, ...args }, 600_000, privateEnv);
1205
1207
  const structured = result.structuredContent;
1206
- if (!structured)
1207
- return { content: [...result.content, remoteNote(target, result)], isError: true };
1208
+ // The terminal's own launch refusal (e.g. Claude authentication preflight) keeps its structure and stays an error.
1209
+ if (!structured || result.isError && structured.schema === "aiterm.agent-launch-error.v1")
1210
+ return { content: [...result.content, remoteNote(target, result)], ...(structured ? { structuredContent: structured } : {}), isError: true };
1208
1211
  try {
1209
1212
  if (delivery && structured.event_cursor !== null)
1210
1213
  await registerRemoteDelivery(delivery, target, structured.session_id, structured.event_cursor, null, structured.input_id);
@@ -1267,10 +1270,10 @@ export function createAitermServer(options = {}) {
1267
1270
  const session = result?.structuredContent?.session_id;
1268
1271
  if (typeof session === "string")
1269
1272
  bindTerminalSession(session, target.trusted_ref);
1270
- return result;
1273
+ return withTerminalLaunchAction(result);
1271
1274
  }
1272
1275
  catch (e) {
1273
- return fail(e);
1276
+ return withTerminalLaunchAction(fail(e));
1274
1277
  }
1275
1278
  }
1276
1279
  async function launchAgent(kind, args, extra) {
@@ -0,0 +1,149 @@
1
+ // authorize-key (remote-terminal.md R14): one password-only SSH login that appends the terminal's held public key
2
+ // to ~/.ssh/authorized_keys. The password lives only in this process's memory and one askpass socket connection.
3
+ import { spawn } from "node:child_process";
4
+ import * as fs from "node:fs";
5
+ import * as net from "node:net";
6
+ import * as path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { RemoteTerminalError, agentAlive, binding, bindingStatus, classifySshFailure, credentialPublicKeyFile, publicKey, readCredential, sshEnvironment } from "./remote-terminal.js";
9
+ export const ASKPASS_SOCKET_ENV = "AITERM_ASKPASS_SOCKET";
10
+ const PUBLIC_KEY = /^[A-Za-z0-9@.-]+ [A-Za-z0-9+/]+={0,3}$/;
11
+ const MAX_PASSWORD_BYTES = 1023; // ssh reads at most 1024 bytes from askpass, cut at the first CR/LF
12
+ /** The key this binding authenticates with afterwards: native key file, or the one credential-load holds. */
13
+ function heldPublicKey(b) {
14
+ let line;
15
+ if (b.key_file) {
16
+ const key = publicKey(b.key_file);
17
+ if ("reason" in key)
18
+ throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", key.reason);
19
+ line = key.line;
20
+ }
21
+ else {
22
+ const loaded = readCredential(b.ref);
23
+ if (!loaded || !agentAlive(loaded.socket))
24
+ throw new RemoteTerminalError("CREDENTIAL_NOT_LOADED", "the terminal's credential is not loaded; resolve the handle and run credential-load first");
25
+ try {
26
+ line = fs.readFileSync(credentialPublicKeyFile(b.ref), "utf8").trim().split(/\s+/).slice(0, 2).join(" ");
27
+ }
28
+ catch {
29
+ throw new RemoteTerminalError("CREDENTIAL_NOT_LOADED", "the loaded credential has no public key; run credential-load again");
30
+ }
31
+ }
32
+ if (!PUBLIC_KEY.test(line))
33
+ throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", "the held public key is malformed");
34
+ return line;
35
+ }
36
+ /** Checks that need no password: done before the caller's stdin is read. */
37
+ export function prepareAuthorization(ref) {
38
+ const b = binding(ref);
39
+ const status = bindingStatus(ref);
40
+ if (!status.trust.available)
41
+ throw new RemoteTerminalError(status.trust.reason ?? "HOST_TRUST_MISSING", "the terminal's host key is not trusted", "confirm the new host key");
42
+ return { b, key: heldPublicKey(b) };
43
+ }
44
+ /** Raw stdin bytes, nothing removed. Values ssh's askpass cannot carry exactly are refused, never altered. */
45
+ export function checkPassword(password) {
46
+ let text = "";
47
+ try {
48
+ text = new TextDecoder("utf-8", { fatal: true }).decode(password);
49
+ }
50
+ catch { /* invalid below */ }
51
+ // eslint-disable-next-line no-control-regex
52
+ if (password.length === 0 || password.length > MAX_PASSWORD_BYTES || !text || /[\x00\r\n]/.test(text))
53
+ throw new RemoteTerminalError("PASSWORD_INVALID", "the password must be 1-1023 bytes of UTF-8 on stdin without NUL, CR or LF (no trailing newline)");
54
+ }
55
+ export function authorizedKeysScript(key) {
56
+ const [type, blob] = key.split(" ");
57
+ return [
58
+ "umask 077",
59
+ `k='${key}'; t='${type}'; b='${blob}'`,
60
+ 'd="$HOME/.ssh"; f="$d/authorized_keys"',
61
+ 'mkdir -p "$d" 2>/dev/null && chmod 700 "$d" 2>/dev/null || exit 21',
62
+ 'if [ ! -e "$f" ]; then : > "$f" 2>/dev/null || exit 22; fi',
63
+ 'chmod 600 "$f" 2>/dev/null || exit 22',
64
+ // Same key type and blob anywhere on a line: options and comments do not matter.
65
+ `if awk -v t="$t" -v b="$b" '{for(i=1;i<NF;i++) if($i==t && $(i+1)==b) f=1} END{exit f?0:1}' "$f" 2>/dev/null; then echo "AITERM_AUTHORIZE ALREADY_AUTHORIZED"; exit 0; fi`,
66
+ 'if [ -s "$f" ] && [ -n "$(tail -c 1 "$f")" ]; then printf \'\\n\' >> "$f" || exit 22; fi',
67
+ 'printf \'%s\\n\' "$k" >> "$f" || exit 22',
68
+ 'echo "AITERM_AUTHORIZE AUTHORIZED"',
69
+ "",
70
+ ].join("\n");
71
+ }
72
+ export function passwordSshArguments(b) {
73
+ return ["-F", "/dev/null", "-T", "-o", "BatchMode=no", "-o", "StrictHostKeyChecking=yes",
74
+ "-o", `UserKnownHostsFile=${b.known_hosts_file}`, "-o", "GlobalKnownHostsFile=/dev/null", "-o", "CheckHostIP=no",
75
+ ...(b.host_key_alias ? ["-o", `HostKeyAlias=${b.host_key_alias}`] : []),
76
+ "-o", "PubkeyAuthentication=no", "-o", "IdentityAgent=none", "-o", "IdentitiesOnly=yes", "-o", "IdentityFile=none",
77
+ "-o", "PreferredAuthentications=password", "-o", "PasswordAuthentication=yes", "-o", "KbdInteractiveAuthentication=no",
78
+ "-o", "GSSAPIAuthentication=no", "-o", "HostbasedAuthentication=no", "-o", "NumberOfPasswordPrompts=1",
79
+ "-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ConnectTimeout=15",
80
+ "-l", b.target.user, "-p", String(b.target.port), "--", b.target.host, "/bin/sh -s"];
81
+ }
82
+ const shq = (value) => `'${value.replace(/'/g, "'\\''")}'`;
83
+ export async function authorizeKey(prepared, password) {
84
+ const dir = fs.mkdtempSync(path.join("/tmp", "aiterm-ap-"));
85
+ let served = 0;
86
+ const server = net.createServer(connection => { served += 1; if (served === 1)
87
+ connection.end(password);
88
+ else
89
+ connection.end(); });
90
+ try {
91
+ checkPassword(password);
92
+ fs.chmodSync(dir, 0o700);
93
+ const socket = path.join(dir, "s");
94
+ await new Promise((resolve, reject) => { server.once("error", reject); server.listen(socket, resolve); });
95
+ const helper = path.join(dir, "askpass");
96
+ const cli = fileURLToPath(new URL("./remote-terminal-cli.js", import.meta.url));
97
+ fs.writeFileSync(helper, `#!/bin/sh\nexec ${shq(process.execPath)} ${shq(cli)} askpass "$@"\n`, { mode: 0o700 });
98
+ const env = { ...sshEnvironment(), SSH_ASKPASS: helper, SSH_ASKPASS_REQUIRE: "force", DISPLAY: process.env.DISPLAY ?? "aiterm:0", [ASKPASS_SOCKET_ENV]: socket };
99
+ const run = await new Promise((resolve, reject) => {
100
+ const child = spawn("ssh", passwordSshArguments(prepared.b), { env, stdio: ["pipe", "pipe", "pipe"] });
101
+ let stdout = "", stderr = "";
102
+ const timer = setTimeout(() => child.kill(), 120_000);
103
+ child.stdout.on("data", (chunk) => { stdout += chunk.toString("utf8"); });
104
+ child.stderr.on("data", (chunk) => { stderr = (stderr + chunk.toString("utf8")).slice(-4000); });
105
+ child.on("error", reject);
106
+ child.on("close", code => { clearTimeout(timer); resolve({ code, stdout, stderr }); });
107
+ child.stdin.on("error", () => { });
108
+ child.stdin.end(authorizedKeysScript(prepared.key));
109
+ });
110
+ const marker = /AITERM_AUTHORIZE (AUTHORIZED|ALREADY_AUTHORIZED)/.exec(run.stdout)?.[1];
111
+ if (run.code === 0 && marker)
112
+ return { schema: "aiterm.remote-key-authorization.v1", ref: prepared.b.ref, result: marker };
113
+ if (run.code === 21 || run.code === 22)
114
+ throw new RemoteTerminalError("AUTHORIZED_KEYS_WRITE_FAILED", "~/.ssh/authorized_keys could not be written on the terminal");
115
+ const denied = /Permission denied \(([^)]*)\)/.exec(run.stderr);
116
+ if (denied) {
117
+ if (served > 0)
118
+ throw new RemoteTerminalError("PASSWORD_REJECTED", "the terminal rejected the password");
119
+ if (!denied[1].split(",").includes("password"))
120
+ throw new RemoteTerminalError("PASSWORD_AUTH_DISABLED", "the terminal does not offer password login");
121
+ throw new RemoteTerminalError("AUTH_FAILED", "the password could not be offered to the terminal");
122
+ }
123
+ if (run.code === 255) {
124
+ const f = classifySshFailure(run.stderr);
125
+ throw new RemoteTerminalError(f.code, f.message, f.action);
126
+ }
127
+ throw new RemoteTerminalError("COMMAND_FAILED", "authorized_keys could not be updated on the terminal");
128
+ }
129
+ finally {
130
+ password.fill(0);
131
+ server.close();
132
+ fs.rmSync(dir, { recursive: true, force: true });
133
+ }
134
+ }
135
+ /** The SSH_ASKPASS helper: answer a password prompt once from the parent's socket, nothing else. */
136
+ export function askpass(prompt, socket) {
137
+ if (!socket || !/password/i.test(prompt) || /passphrase|yes\/no/i.test(prompt))
138
+ process.exit(1);
139
+ const chunks = [];
140
+ const connection = net.createConnection(socket);
141
+ connection.on("data", (chunk) => chunks.push(chunk));
142
+ connection.on("error", () => process.exit(1));
143
+ connection.on("end", () => {
144
+ const value = Buffer.concat(chunks);
145
+ if (value.length === 0)
146
+ process.exit(1);
147
+ process.stdout.write(Buffer.concat([value, Buffer.from("\n")]), () => { value.fill(0); process.exit(0); });
148
+ });
149
+ }
@@ -54,6 +54,6 @@ export const terminalArgumentDescription = "Run this seat on another computer (a
54
54
  "HOST_TRUST_STALE / CREDENTIAL_REVISION_STALE = the binding changed: get the current value from the terminal registry and launch again. " +
55
55
  "HOST_KEY_MISMATCH / HOST_TRUST_MISSING = the terminal's host key is not the trusted one: the Owner must confirm the new host key; do not retry. " +
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
- "AUTH_FAILED = the terminal refused the key. UNREACHABLE = the terminal is offline; try later. " +
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
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.";
@@ -0,0 +1,131 @@
1
+ // Terminal-side fixed path operations (remote-terminal.md R15). Runs on the terminal as the SSH user.
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import { RemoteTerminalError } from "./remote-terminal.js";
6
+ const MISSING = { schema: "aiterm.remote-path.v1", exists: false, directory: false, writable: false };
7
+ const denied = (code) => code === "EACCES" || code === "EPERM";
8
+ const notPermitted = () => new RemoteTerminalError("FOLDER_NOT_PERMITTED", "the folder cannot be used by the terminal's SSH user (privacy consent, ACL or permissions)");
9
+ export function checkRemotePath(value) {
10
+ // eslint-disable-next-line no-control-regex
11
+ if (typeof value !== "string" || !path.posix.isAbsolute(value) || /[\x00-\x1f\x7f]/.test(value) || Buffer.byteLength(value) > 4096)
12
+ throw new RemoteTerminalError("PATH_INVALID", "path must be an absolute path without control characters");
13
+ }
14
+ function errno(error) { return error?.code; }
15
+ /** Can this directory be listed? A privacy-protected folder (macOS TCC) refuses it with EPERM. */
16
+ function listable(dir) {
17
+ try {
18
+ fs.opendirSync(dir).closeSync();
19
+ return true;
20
+ }
21
+ catch (error) {
22
+ if (denied(errno(error)))
23
+ return false;
24
+ throw error;
25
+ }
26
+ }
27
+ /** writable = a probe directory could actually be created and removed now. */
28
+ function writable(dir) {
29
+ let probe;
30
+ try {
31
+ probe = fs.mkdtempSync(path.join(dir, ".aiterm-write-probe-"));
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ fs.rmdirSync(probe);
37
+ return true;
38
+ }
39
+ /** missing / file / a folder the SSH user can list; refusals throw FOLDER_NOT_PERMITTED, never read as missing. */
40
+ function folderState(target) {
41
+ let stat;
42
+ try {
43
+ stat = fs.statSync(target);
44
+ }
45
+ catch (error) {
46
+ const code = errno(error);
47
+ if (denied(code))
48
+ throw notPermitted();
49
+ if (code !== "ENOENT" && code !== "ENOTDIR")
50
+ throw new RemoteTerminalError("PATH_UNAVAILABLE", `the path cannot be inspected (${code ?? "unknown"})`);
51
+ // An inaccessible parent must not read as a missing folder.
52
+ for (let parent = path.dirname(target);; parent = path.dirname(parent)) {
53
+ let parentStat = null;
54
+ try {
55
+ parentStat = fs.statSync(parent);
56
+ }
57
+ catch (e) {
58
+ if (denied(errno(e)))
59
+ throw notPermitted();
60
+ }
61
+ if (parentStat) {
62
+ if (parentStat.isDirectory() && !listable(parent))
63
+ throw notPermitted();
64
+ break;
65
+ }
66
+ if (parent === path.dirname(parent))
67
+ break;
68
+ }
69
+ return "missing";
70
+ }
71
+ if (!stat.isDirectory())
72
+ return "file";
73
+ if (!listable(target))
74
+ throw notPermitted();
75
+ return "directory";
76
+ }
77
+ export function inspectPath(target) {
78
+ checkRemotePath(target);
79
+ const state = folderState(target);
80
+ if (state === "missing")
81
+ return MISSING;
82
+ if (state === "file")
83
+ return { schema: "aiterm.remote-path.v1", exists: true, directory: false, writable: false };
84
+ return { schema: "aiterm.remote-path.v1", exists: true, directory: true, writable: writable(target) };
85
+ }
86
+ export const LIST_DIRS_MAX = 500;
87
+ /** Read-only folder picker listing (R15): subfolders only, no dot names, sorted, at most LIST_DIRS_MAX. */
88
+ export function listDirectories(target, home = os.homedir()) {
89
+ const dir = target === undefined ? home : target;
90
+ checkRemotePath(dir);
91
+ const base = { schema: "aiterm.remote-dirs.v1", home, path: path.posix.resolve(dir) };
92
+ const state = folderState(base.path);
93
+ if (state !== "directory")
94
+ return { ...base, exists: state === "file", directory: false, entries: null, truncated: false };
95
+ let dirents;
96
+ try {
97
+ dirents = fs.readdirSync(base.path, { withFileTypes: true });
98
+ }
99
+ catch (error) {
100
+ if (denied(errno(error)))
101
+ throw notPermitted();
102
+ throw new RemoteTerminalError("PATH_UNAVAILABLE", `the folder cannot be listed (${errno(error) ?? "unknown"})`);
103
+ }
104
+ const names = [];
105
+ for (const entry of dirents) {
106
+ if (entry.name.startsWith("."))
107
+ continue;
108
+ let folder = entry.isDirectory();
109
+ if (!folder && entry.isSymbolicLink()) {
110
+ try {
111
+ folder = fs.statSync(path.join(base.path, entry.name)).isDirectory();
112
+ }
113
+ catch { /* broken or refused link: not a folder */ }
114
+ }
115
+ if (folder)
116
+ names.push(entry.name);
117
+ }
118
+ names.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
119
+ return { ...base, exists: true, directory: true, entries: names.slice(0, LIST_DIRS_MAX).map(name => ({ name })), truncated: names.length > LIST_DIRS_MAX };
120
+ }
121
+ export function makeDirectory(target) {
122
+ checkRemotePath(target);
123
+ try {
124
+ fs.mkdirSync(target, { recursive: true });
125
+ }
126
+ catch (error) {
127
+ if (denied(errno(error)))
128
+ throw notPermitted(); /* a file in the way shows in the inspection */
129
+ }
130
+ return inspectPath(target);
131
+ }
@@ -0,0 +1,105 @@
1
+ // provision (remote-terminal.md R16): install this Aiterm version as a product-owned runtime on a macOS terminal,
2
+ // before any terminal MCP exists. Runs over the binding's trusted key SSH; the terminal fetches the release assets.
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import { createRequire } from "node:module";
5
+ import { fileURLToPath } from "node:url";
6
+ import { RemoteTerminalError, bindingStatus, classifySshFailure, sshEnvironment, trustedSshArguments } from "./remote-terminal.js";
7
+ import { verifySetupRuntime } from "./setup.js";
8
+ const pkg = createRequire(import.meta.url)("../package.json");
9
+ export const RUNTIME_RELEASE_BASE = "https://github.com/kitepon/aiterm-mcp/releases/download";
10
+ /** The terminal-side bootstrap, run as `/bin/sh -s -- VERSION BASE`. Prints one result line. */
11
+ export const PROVISION_SCRIPT = String.raw `set -u
12
+ V="$1"; BASE="$2"
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 ;;
18
+ *) fail PROVISION_PLATFORM_UNSUPPORTED ;;
19
+ esac
20
+ NAME="aiterm-runtime-$V-darwin-$A"
21
+ ROOT="$HOME/.aiterm/runtime"
22
+ mkdir -p "$ROOT" 2>/dev/null && chmod 700 "$HOME/.aiterm" "$ROOT" 2>/dev/null || fail RUNTIME_DIR_UNAVAILABLE
23
+ smoke() { "$1/bin/aiterm-remote-terminal" runtime-smoke --expect-version "$V" >/dev/null 2>&1 </dev/null; }
24
+ LOCK="$ROOT/.lock"
25
+ if ! mkdir "$LOCK" 2>/dev/null; then
26
+ p=$(cat "$LOCK/pid" 2>/dev/null)
27
+ if [ -n "$p" ] && kill -0 "$p" 2>/dev/null; then fail PROVISION_BUSY; fi
28
+ rm -rf "$LOCK"; mkdir "$LOCK" 2>/dev/null || fail PROVISION_BUSY
29
+ fi
30
+ echo $$ > "$LOCK/pid"
31
+ STAGE="$ROOT/.stage-$$"
32
+ trap 'rm -rf "$STAGE" "$LOCK"' EXIT
33
+ if [ "$(cat "$ROOT/current/RUNTIME" 2>/dev/null)" = "$NAME" ] && smoke "$ROOT/current"; then
34
+ echo "AITERM_PROVISION ALREADY_CURRENT $V $A"; exit 0
35
+ fi
36
+ rm -rf "$ROOT"/.stage-*
37
+ mkdir -p "$STAGE/x" || fail RUNTIME_DIR_UNAVAILABLE
38
+ get() { curl -fsSL --retry 2 --connect-timeout 20 -o "$STAGE/$1" "$BASE/v$V/$1"; rc=$?; [ $rc = 0 ] && return 0; [ $rc = 22 ] && fail RUNTIME_ARTIFACT_UNAVAILABLE; fail RUNTIME_DOWNLOAD_FAILED; }
39
+ get "aiterm-runtime-$V-SHA256SUMS"
40
+ get "$NAME.tar.gz"
41
+ want=$(awk -v n="$NAME.tar.gz" '$2==n || $2=="*"n {print $1}' "$STAGE/aiterm-runtime-$V-SHA256SUMS")
42
+ if command -v shasum >/dev/null 2>&1; then got=$(shasum -a 256 "$STAGE/$NAME.tar.gz" | cut -d' ' -f1); else got=$(sha256sum "$STAGE/$NAME.tar.gz" | cut -d' ' -f1); fi
43
+ [ -n "$want" ] && [ "$want" = "$got" ] || fail RUNTIME_VERIFY_FAILED
44
+ tar -xzf "$STAGE/$NAME.tar.gz" -C "$STAGE/x" 2>/dev/null || fail RUNTIME_EXTRACT_FAILED
45
+ N="$STAGE/x/$NAME"
46
+ [ "$(cat "$N/RUNTIME" 2>/dev/null)" = "$NAME" ] || fail RUNTIME_VERIFY_FAILED
47
+ smoke "$N" || fail RUNTIME_SMOKE_FAILED
48
+ # Running seats and tmux servers are not touched; the previous runtime stays until the next provision.
49
+ rm -rf "$ROOT/previous"
50
+ if [ -d "$ROOT/current" ]; then mv "$ROOT/current" "$ROOT/previous" || fail RUNTIME_ACTIVATE_FAILED; fi
51
+ if ! mv "$N" "$ROOT/current"; then
52
+ [ -d "$ROOT/previous" ] && mv "$ROOT/previous" "$ROOT/current"
53
+ fail RUNTIME_ACTIVATE_FAILED
54
+ fi
55
+ echo "AITERM_PROVISION PROVISIONED $V $A"
56
+ `;
57
+ export function parseProvisionOutput(stdout) {
58
+ const ok = /^AITERM_PROVISION (PROVISIONED|ALREADY_CURRENT) (\S+) /m.exec(stdout);
59
+ if (ok)
60
+ return { result: ok[1], version: ok[2] };
61
+ const error = /^AITERM_PROVISION_ERROR ([A-Z_]+)$/m.exec(stdout);
62
+ return error ? { code: error[1] } : null;
63
+ }
64
+ export async function provision(ref, version = pkg.version) {
65
+ if (!/^\d+\.\d+\.\d+$/.test(version))
66
+ throw new RemoteTerminalError("VERSION_INVALID", "the runtime version must be x.y.z");
67
+ const status = bindingStatus(ref);
68
+ if (!status.trust.available)
69
+ throw new RemoteTerminalError(status.trust.reason ?? "HOST_TRUST_MISSING", "the terminal's host key is not trusted", "confirm the new host key");
70
+ if (status.credential.provider === "aiterm.native-ssh-key.v1" && !status.credential.available)
71
+ throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", status.credential.reason ?? "the key is unavailable");
72
+ // Throws CREDENTIAL_NOT_LOADED for a keyless binding whose key is not loaded.
73
+ const args = trustedSshArguments(ref, `/bin/sh -s -- ${version} ${RUNTIME_RELEASE_BASE}`, null);
74
+ const run = await new Promise((resolve, reject) => {
75
+ const child = spawn("ssh", args, { env: sshEnvironment(), stdio: ["pipe", "pipe", "pipe"] });
76
+ let stdout = "", stderr = "";
77
+ const timer = setTimeout(() => child.kill(), 1_200_000);
78
+ child.stdout.on("data", (chunk) => { stdout += chunk.toString("utf8"); });
79
+ child.stderr.on("data", (chunk) => { stderr = (stderr + chunk.toString("utf8")).slice(-4000); });
80
+ child.on("error", reject);
81
+ child.on("close", code => { clearTimeout(timer); resolve({ code, stdout, stderr }); });
82
+ child.stdin.on("error", () => { });
83
+ child.stdin.end(PROVISION_SCRIPT);
84
+ });
85
+ const parsed = parseProvisionOutput(run.stdout);
86
+ if (parsed && "result" in parsed && run.code === 0)
87
+ return { schema: "aiterm.remote-provision.v1", ref, result: parsed.result, version: parsed.version };
88
+ if (parsed && "code" in parsed)
89
+ throw new RemoteTerminalError(parsed.code, `provisioning the terminal failed (${parsed.code})`);
90
+ if (run.code === 255) {
91
+ const f = classifySshFailure(run.stderr);
92
+ throw new RemoteTerminalError(f.code, f.message, f.action);
93
+ }
94
+ throw new RemoteTerminalError("PROVISION_FAILED", "the terminal returned no provisioning result");
95
+ }
96
+ /** runtime-smoke on the terminal: this runtime's version, its tmux, and the setup probe through its own aiterm-mcp. */
97
+ export async function runtimeSmoke(expectVersion) {
98
+ if (pkg.version !== expectVersion)
99
+ throw new RemoteTerminalError("RUNTIME_SMOKE_FAILED", `runtime is ${pkg.version}, expected ${expectVersion}`);
100
+ const tmux = spawnSync("tmux", ["-V"], { encoding: "utf8", timeout: 10_000 });
101
+ if (tmux.status !== 0)
102
+ throw new RemoteTerminalError("RUNTIME_SMOKE_FAILED", "tmux does not run");
103
+ await verifySetupRuntime({ command: process.execPath, args: [fileURLToPath(new URL("./index.js", import.meta.url))] });
104
+ return { schema: "aiterm.runtime-smoke.v1", version: pkg.version, tmux: tmux.stdout.trim() };
105
+ }
@@ -4,15 +4,20 @@
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)
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)
7
9
  import { realpathSync } from "node:fs";
8
10
  import { fileURLToPath } from "node:url";
9
11
  import { createRequire } from "node:module";
10
12
  import { z } from "zod";
11
13
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
12
14
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
- import { RemoteTerminalConnection, RemoteTerminalError, bindingStatus, confirmHostKey, loadCredential, registerBinding } from "./remote-terminal.js";
15
+ import { REMOTE_COMMAND_OPS, RemoteTerminalConnection, RemoteTerminalError, bindingStatus, confirmHostKey, loadCredential, registerBinding } from "./remote-terminal.js";
14
16
  import { readCompletedTranscript } from "./transcript-read.js";
15
17
  import { credentialHandleSchema } from "./remote-contract.js";
18
+ import { inspectPath, listDirectories, makeDirectory } from "./remote-path.js";
19
+ import { ASKPASS_SOCKET_ENV, askpass, authorizeKey, prepareAuthorization } from "./remote-authorize.js";
20
+ import { provision, runtimeSmoke } from "./remote-provision.js";
16
21
  const pkg = createRequire(import.meta.url)("../package.json");
17
22
  function option(args, name) {
18
23
  const at = args.indexOf(name);
@@ -26,15 +31,26 @@ function errorDto(error, schema) {
26
31
  return { schema, code, message };
27
32
  }
28
33
  function oneShot(run, errorSchema) {
34
+ const fail = (error) => { process.stdout.write(`${JSON.stringify(errorDto(error, errorSchema))}\n`); process.exit(2); };
29
35
  try {
30
- process.stdout.write(`${JSON.stringify(run())}\n`);
31
- process.exit(0);
36
+ Promise.resolve(run()).then(value => { process.stdout.write(`${JSON.stringify(value)}\n`); process.exit(0); }, fail);
32
37
  }
33
38
  catch (error) {
34
- process.stdout.write(`${JSON.stringify(errorDto(error, errorSchema))}\n`);
35
- process.exit(2);
39
+ fail(error);
36
40
  }
37
41
  }
42
+ function readStdin() {
43
+ return new Promise(resolve => {
44
+ const chunks = [];
45
+ process.stdin.on("data", (chunk) => chunks.push(chunk));
46
+ process.stdin.on("end", () => { const all = Buffer.concat(chunks); for (const chunk of chunks)
47
+ chunk.fill(0); resolve(all); });
48
+ });
49
+ }
50
+ function pathArgument(rest) {
51
+ const encoded = option(rest, "--path-base64");
52
+ return encoded !== undefined ? Buffer.from(encoded, "base64").toString("utf8") : option(rest, "--path") ?? "";
53
+ }
38
54
  function serve() {
39
55
  const server = new McpServer({ name: "aiterm-remote-terminal", version: pkg.version });
40
56
  let connection = null;
@@ -92,9 +108,9 @@ function serve() {
92
108
  }
93
109
  });
94
110
  server.registerTool("remote_terminal_command", {
95
- description: "Fixed Claude Code setup operation on the terminal",
96
- inputSchema: { op: z.enum(["claude_version", "claude_install", "claude_update"]) },
97
- }, guarded(({ op }) => bound().command(op)));
111
+ description: "Fixed operation on the terminal: Claude Code setup, or a path check / mkdir / read-only folder listing",
112
+ inputSchema: { op: z.enum(REMOTE_COMMAND_OPS), path: z.string().optional() },
113
+ }, guarded(({ op, path }) => bound().command(op, path)));
98
114
  server.registerTool("remote_terminal_close", { description: "Close the bound connection and exit", inputSchema: {} }, guarded(async () => { const result = connection ? await connection.close() : { closed: true }; setTimeout(() => process.exit(0), 100); return result; }));
99
115
  server.connect(new StdioServerTransport()).catch(error => { console.error("aiterm-remote-terminal fatal:", error); process.exit(1); });
100
116
  }
@@ -124,6 +140,24 @@ export function main(args) {
124
140
  });
125
141
  return;
126
142
  }
143
+ if (command === "authorize-key")
144
+ return oneShot(() => {
145
+ // Trust and the held key are checked before stdin is read (R14).
146
+ const prepared = prepareAuthorization(option(rest, "--ref") ?? "");
147
+ return readStdin().then(password => authorizeKey(prepared, password));
148
+ }, "aiterm.remote-binding-error.v1");
149
+ if (command === "askpass")
150
+ return askpass(rest.join(" "), process.env[ASKPASS_SOCKET_ENV]);
151
+ if (command === "provision")
152
+ return oneShot(() => provision(option(rest, "--ref") ?? ""), "aiterm.remote-binding-error.v1");
153
+ if (command === "path-status")
154
+ return oneShot(() => inspectPath(pathArgument(rest)), "aiterm.remote-binding-error.v1");
155
+ if (command === "make-dir")
156
+ return oneShot(() => makeDirectory(pathArgument(rest)), "aiterm.remote-binding-error.v1");
157
+ if (command === "list-dirs")
158
+ return oneShot(() => listDirectories(rest.length ? pathArgument(rest) : undefined), "aiterm.remote-binding-error.v1");
159
+ if (command === "runtime-smoke")
160
+ return oneShot(() => runtimeSmoke(option(rest, "--expect-version") ?? ""), "aiterm.remote-binding-error.v1");
127
161
  if (command === "trust-confirm")
128
162
  return oneShot(() => confirmHostKey(option(rest, "--ref") ?? "", option(rest, "--fingerprint") ?? ""), "aiterm.remote-binding-error.v1");
129
163
  if (command === "transcript-read")
@@ -131,7 +165,7 @@ export function main(args) {
131
165
  const id = option(rest, "--cursor-session"), offset = option(rest, "--offset"), max = option(rest, "--max-bytes");
132
166
  return readCompletedTranscript(option(rest, "--session") ?? "", id ? { claudeSessionId: id, offset: Number(offset) } : null, max ? Number(max) : undefined);
133
167
  }, "aiterm.transcript-read-error.v1");
134
- process.stderr.write("usage: aiterm-remote-terminal serve|status|register|trust-confirm|transcript-read\n");
168
+ process.stderr.write("usage: aiterm-remote-terminal serve|status|register|trust-confirm|credential-load|authorize-key|provision|transcript-read|path-status|make-dir|list-dirs|runtime-smoke\n");
135
169
  process.exit(64);
136
170
  }
137
171
  let entry = false;
@@ -12,6 +12,7 @@ import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/s
12
12
  import { ensureStateRoot, writeJson0600 } from "./agent-shared.js";
13
13
  import { posixCommand } from "./remote.js";
14
14
  import { PRIVATE_ENV_SCHEMA } from "./private-env.js";
15
+ import { checkRemotePath } from "./remote-path.js";
15
16
  const pkg = createRequire(import.meta.url)("../package.json");
16
17
  export class RemoteTerminalError extends Error {
17
18
  code;
@@ -60,7 +61,7 @@ function readStore() {
60
61
  throw new RemoteTerminalError("BINDING_STORE_UNREADABLE", "the binding store is not valid");
61
62
  }
62
63
  }
63
- function binding(ref) {
64
+ export function binding(ref) {
64
65
  if (!REF.test(ref))
65
66
  throw new RemoteTerminalError("REF_INVALID", "ref must be a UUID");
66
67
  const found = readStore().find(item => item.ref === ref);
@@ -94,7 +95,7 @@ export function registerBinding(input) {
94
95
  function keyFingerprint(blob) {
95
96
  return `SHA256:${createHash("sha256").update(blob).digest("base64").replace(/=+$/, "")}`;
96
97
  }
97
- function publicKey(keyFile) {
98
+ export function publicKey(keyFile) {
98
99
  if (!fs.existsSync(keyFile))
99
100
  return { reason: "KEY_MISSING" };
100
101
  // Empty passphrase only: a passphrase-protected key cannot be used without a prompt.
@@ -150,8 +151,12 @@ export function confirmHostKey(ref, fingerprint) {
150
151
  throw new RemoteTerminalError("FINGERPRINT_INVALID", "fingerprint must be SHA256:<base64>");
151
152
  const b = binding(ref);
152
153
  const scan = spawnSync("ssh-keyscan", ["-T", "10", "-p", String(b.target.port), b.target.host], { encoding: "utf8", timeout: 20_000 });
153
- const matched = scan.stdout.split("\n").filter(line => line && !line.startsWith("#")).map(line => line.trim().split(/\s+/))
154
- .find(fields => fields.length >= 3 && keyFingerprint(Buffer.from(fields[2], "base64")) === fingerprint);
154
+ const keys = (scan.stdout ?? "").split("\n").filter(line => line && !line.startsWith("#")).map(line => line.trim().split(/\s+/))
155
+ .filter(fields => fields.length >= 3);
156
+ // No key at all is an asleep/offline terminal, not another machine.
157
+ if (keys.length === 0)
158
+ throw new RemoteTerminalError("UNREACHABLE", "the terminal presented no host key (asleep, offline or not accepting SSH)");
159
+ const matched = keys.find(fields => keyFingerprint(Buffer.from(fields[2], "base64")) === fingerprint);
155
160
  if (!matched)
156
161
  throw new RemoteTerminalError("HOST_KEY_FINGERPRINT_MISMATCH", "the terminal did not present the confirmed host key");
157
162
  const name = knownHostName(b);
@@ -171,7 +176,9 @@ export function classifySshFailure(stderr) {
171
176
  return { code: "AUTH_FAILED", message: "the terminal refused the key" };
172
177
  if (/aiterm-mcp: (command )?not found|aiterm-mcp: No such file/i.test(stderr))
173
178
  return { code: "REMOTE_AITERM_UNAVAILABLE", message: "Aiterm is not installed on the terminal" };
174
- if (/Connection refused|timed out|No route to host|Network is unreachable|Could not resolve|Connection closed|Connection reset/i.test(stderr))
179
+ if (/Connection refused/i.test(stderr))
180
+ return { code: "CONNECTION_REFUSED", message: "the terminal refused the SSH connection" };
181
+ if (/timed out|No route to host|Network is unreachable|Could not resolve|Connection closed|Connection reset/i.test(stderr))
175
182
  return { code: "UNREACHABLE", message: "the terminal cannot be reached" };
176
183
  return { code: "CONNECTION_FAILED", message: "the SSH connection failed" };
177
184
  }
@@ -216,7 +223,7 @@ export function sshArguments(b, agentSocket, identityFile, remoteCommand) {
216
223
  "-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ConnectTimeout=15", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=4",
217
224
  "-l", b.target.user, "-p", String(b.target.port), "--", b.target.host, remoteCommand];
218
225
  }
219
- function sshEnvironment() {
226
+ export function sshEnvironment() {
220
227
  const env = {};
221
228
  for (const key of ["PATH", "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "TMPDIR"])
222
229
  if (process.env[key] !== undefined)
@@ -259,6 +266,7 @@ export class SshStdioTransport {
259
266
  async close() { this.child?.kill(); }
260
267
  }
261
268
  export const REMOTE_SEAT_TOOLS = new Set(["agent_launch", "pty_send", "pty_observe", "pty_read", "pty_key", "claude_turn", "agent_stop", "pty_close"]);
269
+ export const REMOTE_COMMAND_OPS = ["claude_version", "claude_install", "claude_update", "path_status", "make_dir", "list_dirs"];
262
270
  const COMMANDS = {
263
271
  claude_version: "claude --version",
264
272
  claude_install: "curl -fsSL https://claude.ai/install.sh | bash",
@@ -289,6 +297,9 @@ export function versionAtLeast(actual, required) {
289
297
  }
290
298
  // The first release with --private-env-stdin and the transcript reader on the terminal.
291
299
  export const REMOTE_MINIMUM_VERSION = "0.65.0";
300
+ // The first release with the terminal's path-status / make-dir (R15).
301
+ export const REMOTE_PATH_OPS_VERSION = "0.69.0";
302
+ export const REMOTE_LIST_DIRS_VERSION = "0.70.0";
292
303
  export class RemoteTerminalConnection extends EventEmitter {
293
304
  b;
294
305
  dir;
@@ -464,7 +475,13 @@ export class RemoteTerminalConnection extends EventEmitter {
464
475
  throw new RemoteTerminalError("COMMAND_FAILED", "aiterm-wait returned no receipt");
465
476
  }
466
477
  }
467
- async command(op) {
478
+ async command(op, targetPath) {
479
+ if (op === "path_status" || op === "make_dir")
480
+ return this.pathCommand(op, targetPath);
481
+ if (op === "list_dirs")
482
+ return this.listDirs(targetPath);
483
+ if (targetPath !== undefined)
484
+ throw new RemoteTerminalError("COMMAND_INVALID", `${op} takes no path`);
468
485
  if (!Object.hasOwn(COMMANDS, op))
469
486
  throw new RemoteTerminalError("COMMAND_UNSUPPORTED", "unknown op");
470
487
  const run = await this.exec(`${COMMANDS[op]} 2>&1`, op === "claude_version" ? 60_000 : 900_000);
@@ -476,6 +493,53 @@ export class RemoteTerminalConnection extends EventEmitter {
476
493
  const version = probe.code === 0 ? (/\d+\.\d+\.\d+\S*/.exec(probe.stdout)?.[0] ?? null) : null;
477
494
  return { op, exit_code: run.code, version, output_tail: run.stdout.slice(-2000) };
478
495
  }
496
+ /** R15: the terminal's own fs answers; the path travels as base64 so no shell reads it. */
497
+ async pathCommand(op, targetPath) {
498
+ checkRemotePath(targetPath);
499
+ if (!versionAtLeast(this.remoteVersion, REMOTE_PATH_OPS_VERSION))
500
+ throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${this.remoteVersion}; ${REMOTE_PATH_OPS_VERSION} or later is required (provision the terminal)`);
501
+ const sub = op === "path_status" ? "path-status" : "make-dir";
502
+ const result = await this.exec(`exec aiterm-remote-terminal ${sub} --path-base64 ${Buffer.from(targetPath, "utf8").toString("base64")}`, 60_000);
503
+ if (result.code === 255) {
504
+ const f = classifySshFailure(result.stderr);
505
+ throw new RemoteTerminalError(f.code, f.message, f.action);
506
+ }
507
+ let parsed = null;
508
+ try {
509
+ parsed = JSON.parse(result.stdout.trim().split("\n").pop() ?? "");
510
+ }
511
+ catch { /* classified below */ }
512
+ if (result.code === 0 && parsed?.schema === "aiterm.remote-path.v1")
513
+ return { op, exists: parsed.exists === true, directory: parsed.directory === true, writable: parsed.writable === true };
514
+ if (parsed?.code)
515
+ throw new RemoteTerminalError(parsed.code, parsed.message ?? "path operation failed");
516
+ throw new RemoteTerminalError("COMMAND_FAILED", "the path operation failed on the terminal");
517
+ }
518
+ /** R15 list-dirs: read-only folder picker listing; no path lists the SSH user's home. */
519
+ async listDirs(targetPath) {
520
+ if (targetPath !== undefined)
521
+ checkRemotePath(targetPath);
522
+ if (!versionAtLeast(this.remoteVersion, REMOTE_LIST_DIRS_VERSION))
523
+ throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${this.remoteVersion}; ${REMOTE_LIST_DIRS_VERSION} or later is required (update or provision the terminal)`);
524
+ const flag = targetPath === undefined ? "" : ` --path-base64 ${Buffer.from(targetPath, "utf8").toString("base64")}`;
525
+ const result = await this.exec(`exec aiterm-remote-terminal list-dirs${flag}`, 60_000);
526
+ if (result.code === 255) {
527
+ const f = classifySshFailure(result.stderr);
528
+ throw new RemoteTerminalError(f.code, f.message, f.action);
529
+ }
530
+ let parsed = null;
531
+ try {
532
+ parsed = JSON.parse(result.stdout.trim().split("\n").pop() ?? "");
533
+ }
534
+ catch { /* classified below */ }
535
+ if (result.code === 0 && parsed?.schema === "aiterm.remote-dirs.v1") {
536
+ const { home, path: listed, exists, directory, entries, truncated } = parsed;
537
+ return { op: "list_dirs", home, path: listed, exists, directory, entries, truncated };
538
+ }
539
+ if (parsed?.code)
540
+ throw new RemoteTerminalError(parsed.code, parsed.message ?? "folder listing failed");
541
+ throw new RemoteTerminalError("COMMAND_FAILED", "the folder listing failed on the terminal");
542
+ }
479
543
  async close() {
480
544
  this.closing = true;
481
545
  await this.client.close().catch(() => { });
@@ -756,7 +820,7 @@ function agentSocketPath(ref) {
756
820
  return path.join(dir, `${ref.slice(0, 8)}.sock`);
757
821
  }
758
822
  function agentEnv(socket) { return { ...sshEnvironment(), SSH_AUTH_SOCK: socket }; }
759
- function agentAlive(socket) {
823
+ export function agentAlive(socket) {
760
824
  if (!fs.existsSync(socket))
761
825
  return false;
762
826
  const listed = spawnSync("ssh-add", ["-l"], { env: agentEnv(socket), stdio: ["ignore", "ignore", "ignore"], timeout: 10_000 });
package/dist/remote.js CHANGED
@@ -135,8 +135,10 @@ export function remoteShell(target) {
135
135
  // POSIX系の非ログイン実行では、~/.local/bin、Homebrew、nvmなどのPATHが入らない端末がある。
136
136
  // 利用者のログインshellからPATHだけを受け取り、処理は/bin/shで行う。profileの出力やfish等の文法差を
137
137
  // MCPのstdoutと処理へ持ち込まない。scriptは呼び出し側で検証済みの値だけで組み、単引用符を含めない。
138
+ // provisionで入れた製品のruntime(remote-terminal.md R16)があれば、利用者のPATH上の別のaiterm-mcp・tmuxより先に使う。
138
139
  export function posixCommand(script) {
139
- const importPath = 'p=$("${SHELL:-/bin/sh}" -lc env </dev/null 2>/dev/null | sed -n "s/^PATH=//p" | tail -n 1); [ -n "$p" ] && PATH=$p; export PATH';
140
+ const importPath = 'p=$("${SHELL:-/bin/sh}" -lc env </dev/null 2>/dev/null | sed -n "s/^PATH=//p" | tail -n 1); [ -n "$p" ] && PATH=$p; ' +
141
+ 'r="$HOME/.aiterm/runtime/current/bin"; [ -x "$r/aiterm-mcp" ] && PATH="$r:$PATH"; export PATH';
140
142
  return `/bin/sh -c '${importPath}; ${script}'`;
141
143
  }
142
144
  /** 現地のaiterm-mcpを起動するコマンド。Windowsはユーザー環境からPATHが入るので、そのまま呼ぶ。 */
@@ -0,0 +1,57 @@
1
+ // remote-terminal.md R18: a terminal launch refused before any seat exists, as a code plus a fixed plain Japanese
2
+ // sentence the Owner reads. Only codes raised before the seat exists are listed; anything else may have started.
3
+ const ACTIONS = {
4
+ TERMINAL_INVALID: "起動の指定(端末の情報か作業フォルダ)が正しくありません。BellTeamの不具合の恐れがあります。",
5
+ TARGET_INVALID: "起動の指定(端末の情報)が正しくありません。BellTeamの不具合の恐れがあります。",
6
+ TERMINAL_HARNESS_UNSUPPORTED: "この端末で起こせるAIは、今はClaude Codeだけです。メンバーのAIをClaude Codeにしてください。",
7
+ REF_INVALID: "端末の登録が見つかりません。端末の登録を確かめてください。",
8
+ BINDING_UNKNOWN: "端末の登録が見つかりません。端末の登録を確かめてください。",
9
+ BINDING_STORE_UNREADABLE: "端末の登録を読めませんでした。端末の登録をやり直してください。",
10
+ TARGET_MISMATCH: "端末の登録内容(宛先)が変わったため止めました。端末の登録を確かめてください。",
11
+ HOST_TRUST_MISSING: "端末の本人確認(ホスト鍵の確認)が済んでいません。端末の画面でホスト鍵を確かめてください。",
12
+ KNOWN_HOSTS_UNREADABLE: "端末の本人確認の記録を読めませんでした。端末の画面でホスト鍵を確かめ直してください。",
13
+ HOST_KEY_MISMATCH: "端末が前と違うホスト鍵を示したため、別の機械の恐れがあり止めました。端末の画面でホスト鍵を確かめ直してください。",
14
+ HOST_TRUST_STALE: "端末のホスト鍵の確認が新しくなりました。新しい登録内容で起こし直すまでお待ちください。",
15
+ CREDENTIAL_REQUIRED: "端末へ入る鍵が登録されていません。端末の登録で鍵を設定してください。",
16
+ CREDENTIAL_NOT_LOADED: "端末へ入る鍵がまだ読み込まれていません。読み込み直してから起こし直します。",
17
+ CREDENTIAL_REVISION_STALE: "端末へ入る鍵が新しくなりました。新しい鍵で起こし直します。",
18
+ CREDENTIAL_UNAVAILABLE: "端末へ入る鍵を使えません。端末の登録で鍵を確かめてください。",
19
+ AUTH_FAILED: "端末が鍵を受け付けませんでした。端末の登録から、パスワードで鍵を許可し直してください。",
20
+ CONNECTION_REFUSED: "端末がSSHの接続を断りました。Macなら「リモートログイン」が入になっているか確かめてください。",
21
+ UNREACHABLE: "端末につながりません。電源とネットワークを確かめてください。つながれば起こし直します。",
22
+ CONNECTION_FAILED: "端末へのSSH接続に失敗しました。端末の電源とSSHの設定を確かめてください。",
23
+ REMOTE_AITERM_UNAVAILABLE: "端末にAitermが入っていません。端末の準備(Aitermの導入)をやり直してください。",
24
+ REMOTE_AITERM_TOO_OLD: "端末のAitermが古いため起こせません。端末のAitermを更新してください。",
25
+ SEAT_FORWARD_UNAVAILABLE: "端末からBellTeamへ戻る通り道がまだ用意できていません。少し待ってから起こし直してください。",
26
+ CWD_UNAVAILABLE: "端末に作業フォルダがありません。メンバーの作業フォルダを選び直すか、そのフォルダを作ってください。",
27
+ CLAUDE_AUTH_NOT_AUTHENTICATED: "端末のClaude Codeにログインしていません。端末でClaude Codeにログインしてください。",
28
+ CLAUDE_AUTH_STATUS_UNCONFIRMED: "端末のClaude Codeのログイン状態を確かめられませんでした。少し待ってから起こし直してください。",
29
+ CLAUDE_AUTH_STATUS_TIMEOUT: "端末のClaude Codeのログイン状態を時間内に確かめられませんでした。少し待ってから起こし直してください。",
30
+ };
31
+ /** The code of an Aiterm error text ("CODE: ..." or the terminal's "aiterm: CODE: ..."), or null. */
32
+ export function errorCode(text) {
33
+ return /^(?:aiterm: )?([A-Z][A-Z0-9_]{2,63}):/.exec(text)?.[1] ?? null;
34
+ }
35
+ export function terminalLaunchAction(code) {
36
+ return typeof code === "string" && Object.hasOwn(ACTIONS, code) ? ACTIONS[code] : null;
37
+ }
38
+ export const LAUNCH_ERROR_META = "aiterm/launch_error";
39
+ /** Adds R18's `_meta` to a failed terminal launch result; a result whose code is not listed is returned unchanged.
40
+ * `_meta`, not structuredContent: SDK clients that listed the tools validate structuredContent against the
41
+ * success outputSchema even on isError, and would turn this refusal into a protocol error. */
42
+ export function withTerminalLaunchAction(result) {
43
+ if (!result?.isError)
44
+ return result;
45
+ const structured = result.structuredContent;
46
+ const preflight = structured?.schema === "aiterm.agent-launch-error.v1";
47
+ if (structured && !preflight)
48
+ return result;
49
+ const code = preflight ? structured.code : errorCode(result.content?.find((item) => item.type === "text")?.text ?? "");
50
+ const action = terminalLaunchAction(code);
51
+ if (!action)
52
+ return result;
53
+ const failure = preflight
54
+ ? { schema: structured.schema, harness: structured.harness, code, phase: structured.phase, effect: structured.effect, session_created: false, action }
55
+ : { schema: "aiterm.agent-launch-error.v1", harness: "claude-code", code, phase: "terminal", effect: "not_started", session_created: false, action };
56
+ return { ...result, _meta: { ...result._meta, [LAUNCH_ERROR_META]: failure } };
57
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.68.1",
3
+ "version": "0.70.0",
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": [