aiterm-mcp 0.70.6 → 0.70.8

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.
@@ -4,7 +4,7 @@
4
4
  // serve stdio MCP for one bound connection, spawned by BellTeam terminals
5
5
  // credential-load --ref R --terminal-id ID --handle UUID --revision N --purpose ssh-key (key bytes on stdin; one JSON receipt line)
6
6
  // transcript-read --session S [--cursor-session ID --offset N] [--max-bytes N] (runs on the terminal)
7
- // authorize-key --ref R (login password on stdin until EOF; R14) provision --ref R (macOS runtime; R16)
7
+ // authorize-key --ref R [--os macos|linux|windows] (login password on stdin until EOF; R14) provision --ref R (macOS/Linux runtime; R16)
8
8
  // path-status|make-dir --path P | --path-base64 B, list-dirs [--path P | --path-base64 B] (on the terminal; R15) runtime-smoke --expect-version V (on the terminal)
9
9
  import { realpathSync } from "node:fs";
10
10
  import { fileURLToPath } from "node:url";
@@ -14,7 +14,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
14
14
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
15
15
  import { REMOTE_COMMAND_OPS, RemoteTerminalConnection, RemoteTerminalError, bindingStatus, confirmHostKey, loadCredential, registerBinding } from "./remote-terminal.js";
16
16
  import { readCompletedTranscript } from "./transcript-read.js";
17
- import { credentialHandleSchema } from "./remote-contract.js";
17
+ import { credentialHandleSchema, terminalOsSchema } from "./remote-contract.js";
18
18
  import { inspectPath, listDirectories, makeDirectory } from "./remote-path.js";
19
19
  import { ASKPASS_SOCKET_ENV, askpass, authorizeKey, prepareAuthorization } from "./remote-authorize.js";
20
20
  import { provision, runtimeSmoke } from "./remote-provision.js";
@@ -67,7 +67,7 @@ function serve() {
67
67
  server.registerTool("remote_terminal_status", { description: "Public status of a terminal binding", inputSchema: { ref: z.string() } }, guarded(({ ref }) => bindingStatus(ref)));
68
68
  server.registerTool("remote_terminal_open", {
69
69
  description: "Open the bound connection for this process",
70
- inputSchema: { ref: z.string(), target: z.object({ host: z.string(), user: z.string(), port: z.number().int() }).strict(),
70
+ inputSchema: { ref: z.string(), target: z.object({ host: z.string(), user: z.string(), port: z.number().int() }).strict(), os: terminalOsSchema.optional(),
71
71
  trustRevision: z.string(), credentialRevision: z.string().optional(), credential: credentialHandleSchema.optional(),
72
72
  sudoCredential: credentialHandleSchema.optional(), privateEnv: z.record(z.string(), z.string()).optional() },
73
73
  }, guarded(async (args) => {
@@ -77,7 +77,7 @@ function serve() {
77
77
  connection.on("event", event => {
78
78
  server.server.notification({ method: "aiterm/remote-terminal-event", params: event }).catch(() => { });
79
79
  });
80
- return { opened: true, remoteVersion: connection.remoteVersion };
80
+ return { opened: true, remoteVersion: connection.remoteVersion, platform: connection.platform };
81
81
  }));
82
82
  server.registerTool("remote_terminal_call", {
83
83
  description: "Call a seat tool on the terminal's Aiterm",
@@ -144,7 +144,10 @@ export function main(args) {
144
144
  return oneShot(() => {
145
145
  // Trust and the held key are checked before stdin is read (R14).
146
146
  const prepared = prepareAuthorization(option(rest, "--ref") ?? "");
147
- return readStdin().then(password => authorizeKey(prepared, password));
147
+ const system = option(rest, "--os");
148
+ if (system !== undefined && !terminalOsSchema.safeParse(system).success)
149
+ throw new RemoteTerminalError("OS_INVALID", "--os must be macos, linux or windows");
150
+ return readStdin().then(password => authorizeKey(prepared, password, system === "windows" ? "windows" : "posix"));
148
151
  }, "aiterm.remote-binding-error.v1");
149
152
  if (command === "askpass")
150
153
  return askpass(rest.join(" "), process.env[ASKPASS_SOCKET_ENV]);
@@ -10,7 +10,7 @@ import { createRequire } from "node:module";
10
10
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
11
11
  import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
12
12
  import { ensureStateRoot, writeJson0600 } from "./agent-shared.js";
13
- import { posixCommand } from "./remote.js";
13
+ import { WAIT_RESOLVE, powershellForShell, remotePlatform, remoteShell, terminalCommand, terminalProgram } from "./remote.js";
14
14
  import { PRIVATE_ENV_SCHEMA } from "./private-env.js";
15
15
  import { checkRemotePath } from "./remote-path.js";
16
16
  const pkg = createRequire(import.meta.url)("../package.json");
@@ -174,7 +174,8 @@ export function classifySshFailure(stderr) {
174
174
  return { code: "HOST_TRUST_MISSING", message: "the terminal's host key is not trusted", action: "confirm the new host key" };
175
175
  if (/Permission denied|Too many authentication failures/i.test(stderr))
176
176
  return { code: "AUTH_FAILED", message: "the terminal refused the key" };
177
- if (/aiterm-mcp: (command )?not found|aiterm-mcp: No such file/i.test(stderr))
177
+ // POSIX, our own Windows guard (any language), and the English cmd / PowerShell wording when it names an Aiterm program.
178
+ if (/aiterm-[\w-]+: (command )?not found|aiterm-[\w-]+: No such file|aiterm-[\w-]+['"]? is not recognized as (an internal or external command|(the|a) name of a cmdlet)/i.test(stderr))
178
179
  return { code: "REMOTE_AITERM_UNAVAILABLE", message: "Aiterm is not installed on the terminal" };
179
180
  if (/Connection refused/i.test(stderr))
180
181
  return { code: "CONNECTION_REFUSED", message: "the terminal refused the SSH connection" };
@@ -264,11 +265,22 @@ export class SshStdioTransport {
264
265
  }
265
266
  export const REMOTE_SEAT_TOOLS = new Set(["agent_launch", "pty_send", "pty_observe", "pty_read", "pty_key", "claude_turn", "agent_stop", "pty_close"]);
266
267
  export const REMOTE_COMMAND_OPS = ["claude_version", "claude_install", "claude_update", "path_status", "make_dir", "list_dirs"];
268
+ // Fixed operations per terminal shell (R21). Windows: the official PowerShell installer; a failure stops with exit 1 and its message.
267
269
  const COMMANDS = {
268
- claude_version: "claude --version",
269
- claude_install: "curl -fsSL https://claude.ai/install.sh | bash",
270
- claude_update: "claude update",
270
+ claude_version: { posix: "claude --version 2>&1", windows: "claude --version 2>&1" },
271
+ claude_install: { posix: "curl -fsSL https://claude.ai/install.sh | bash 2>&1",
272
+ windows: "& { $ErrorActionPreference = 'Stop'; try { irm https://claude.ai/install.ps1 | iex } catch { $_.Exception.Message; exit 1 } } *>&1; exit 0" },
273
+ claude_update: { posix: "claude update 2>&1", windows: "claude update 2>&1" },
271
274
  };
275
+ // The official installers' place, which a login shell may not have on PATH yet.
276
+ const CLAUDE_VERSION_AFTER_INSTALL = {
277
+ posix: 'claude --version 2>&1 || "$HOME/.local/bin/claude" --version 2>&1',
278
+ windows: "$p = (Get-Command claude -ErrorAction SilentlyContinue).Source; if (-not $p) { $p = Join-Path $env:USERPROFILE '.local\\bin\\claude.exe' }; & $p --version 2>&1",
279
+ };
280
+ /** The remote command the forward keeper holds: it ends exactly when ssh's stdin closes. */
281
+ export function keeperCommand(shell) {
282
+ return shell === "posix" ? "cat >/dev/null" : powershellForShell(shell, "[Console]::In.ReadToEnd() | Out-Null");
283
+ }
272
284
  const WAIT_FLAGS = new Set(["--session", "--operation", "--timeout", "--cursor", "--steer", "--launch", "--input"]);
273
285
  const WAIT_VALUE = /^[A-Za-z0-9_.:-]{1,128}$/;
274
286
  /** wait_process.args minus the CLI path: only aiterm-wait's own flag/value pairs, each value a plain token. */
@@ -297,6 +309,8 @@ export const REMOTE_MINIMUM_VERSION = "0.65.0";
297
309
  // The first release with the terminal's path-status / make-dir (R15).
298
310
  export const REMOTE_PATH_OPS_VERSION = "0.69.0";
299
311
  export const REMOTE_LIST_DIRS_VERSION = "0.70.0";
312
+ // The first release whose terminal-side path operations know drive paths.
313
+ export const REMOTE_WINDOWS_PATH_VERSION = "0.70.8";
300
314
  export class RemoteTerminalConnection extends EventEmitter {
301
315
  b;
302
316
  dir;
@@ -305,8 +319,10 @@ export class RemoteTerminalConnection extends EventEmitter {
305
319
  identity;
306
320
  client;
307
321
  remoteVersion;
322
+ platform;
323
+ shell;
308
324
  closing = false;
309
- constructor(b, dir, agent, socket, identity, client, remoteVersion) {
325
+ constructor(b, dir, agent, socket, identity, client, remoteVersion, platform, shell) {
310
326
  super();
311
327
  this.b = b;
312
328
  this.dir = dir;
@@ -315,6 +331,8 @@ export class RemoteTerminalConnection extends EventEmitter {
315
331
  this.identity = identity;
316
332
  this.client = client;
317
333
  this.remoteVersion = remoteVersion;
334
+ this.platform = platform;
335
+ this.shell = shell;
318
336
  }
319
337
  static async open(input) {
320
338
  const target = validTarget(input.target);
@@ -330,6 +348,9 @@ export class RemoteTerminalConnection extends EventEmitter {
330
348
  for (const [name, value] of Object.entries(input.privateEnv ?? {}))
331
349
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || typeof value !== "string")
332
350
  throw new RemoteTerminalError("PRIVATE_ENV_INVALID", "invalid private env entry");
351
+ // R20: the connect command is shell-specific, so the platform is known (and the declared os checked) before any MCP connection.
352
+ const platform = await checkTerminalPlatform(trustedTarget(b), input.os);
353
+ const shell = await remoteShell(trustedTarget(b));
333
354
  // Short path: the agent socket must fit macOS's 104-byte sun_path.
334
355
  const dir = fs.mkdtempSync(path.join(os.platform() === "win32" ? os.tmpdir() : "/tmp", "aiterm-rt-"));
335
356
  fs.chmodSync(dir, 0o700);
@@ -360,7 +381,7 @@ export class RemoteTerminalConnection extends EventEmitter {
360
381
  throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", key.reason);
361
382
  fs.writeFileSync(identity, `${key.line}\n`, { mode: 0o600 });
362
383
  }
363
- const transport = new SshStdioTransport(sshArguments(b, agentSocket, identity, posixCommand("exec aiterm-mcp --private-env-stdin")), `${JSON.stringify({ schema: PRIVATE_ENV_SCHEMA, env: input.privateEnv ?? {} })}\n`);
384
+ const transport = new SshStdioTransport(sshArguments(b, agentSocket, identity, terminalCommand(shell, terminalProgram(["aiterm-mcp", "--private-env-stdin"]))), `${JSON.stringify({ schema: PRIVATE_ENV_SCHEMA, env: input.privateEnv ?? {} })}\n`);
364
385
  const client = new Client({ name: "aiterm-remote-terminal", version: pkg.version });
365
386
  try {
366
387
  await client.connect(transport, { timeout: 60_000 });
@@ -375,7 +396,7 @@ export class RemoteTerminalConnection extends EventEmitter {
375
396
  await client.close().catch(() => { });
376
397
  throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${remoteVersion}; ${REMOTE_MINIMUM_VERSION} or later is required`);
377
398
  }
378
- const connection = new RemoteTerminalConnection(b, dir, agent, agentSocket, identity, client, remoteVersion);
399
+ const connection = new RemoteTerminalConnection(b, dir, agent, agentSocket, identity, client, remoteVersion, platform, shell);
379
400
  client.onclose = () => connection.ended();
380
401
  // After the caller has attached its listener to the returned connection.
381
402
  setImmediate(() => connection.emit("event", { type: "ready", at: new Date().toISOString(), remoteVersion }));
@@ -411,7 +432,7 @@ export class RemoteTerminalConnection extends EventEmitter {
411
432
  }
412
433
  exec(script, timeoutMs, signal) {
413
434
  return new Promise((resolve, reject) => {
414
- const child = spawn("ssh", sshArguments(this.b, this.socket, this.identity, posixCommand(script)), { env: sshEnvironment(), stdio: ["ignore", "pipe", "pipe"] });
435
+ const child = spawn("ssh", sshArguments(this.b, this.socket, this.identity, terminalCommand(this.shell, script)), { env: sshEnvironment(), stdio: ["ignore", "pipe", "pipe"] });
415
436
  let stdout = "", stderr = "";
416
437
  const timer = setTimeout(() => child.kill(), timeoutMs);
417
438
  signal?.addEventListener("abort", () => child.kill(), { once: true });
@@ -435,7 +456,7 @@ export class RemoteTerminalConnection extends EventEmitter {
435
456
  throw new RemoteTerminalError("TRANSCRIPT_MAX_INVALID", "invalid maxBytes");
436
457
  parts.push("--max-bytes", String(input.maxBytes));
437
458
  }
438
- const result = await this.exec(`exec aiterm-remote-terminal ${parts.join(" ")}`, 120_000);
459
+ const result = await this.exec(terminalProgram(["aiterm-remote-terminal", ...parts]), 120_000);
439
460
  const line = result.stdout.trim().split("\n").pop() ?? "";
440
461
  let parsed = null;
441
462
  try {
@@ -456,8 +477,7 @@ export class RemoteTerminalConnection extends EventEmitter {
456
477
  async wait(waitProcess, signal) {
457
478
  const flags = waitArguments(waitProcess?.args);
458
479
  // Same resolution as remoteWaitCommand: npm may link only aiterm-mcp.
459
- const resolve = 'w=$(command -v aiterm-wait) || w="$(dirname "$(readlink -f "$(command -v aiterm-mcp)")")/aiterm-wait-cli.js"';
460
- const result = await this.exec(`${resolve}; exec "$w" ${flags.join(" ")}`, 90_000_000, signal);
480
+ const result = await this.exec({ posix: `${WAIT_RESOLVE}; exec "$w" ${flags.join(" ")}`, windows: terminalProgram(["aiterm-wait", ...flags]).windows }, 90_000_000, signal);
461
481
  if (signal?.aborted)
462
482
  throw new RemoteTerminalError("WAIT_CANCELLED", "the wait was cancelled");
463
483
  const line = result.stdout.trim().split("\n").pop() ?? "";
@@ -481,22 +501,23 @@ export class RemoteTerminalConnection extends EventEmitter {
481
501
  throw new RemoteTerminalError("COMMAND_INVALID", `${op} takes no path`);
482
502
  if (!Object.hasOwn(COMMANDS, op))
483
503
  throw new RemoteTerminalError("COMMAND_UNSUPPORTED", "unknown op");
484
- const run = await this.exec(`${COMMANDS[op]} 2>&1`, op === "claude_version" ? 60_000 : 900_000);
504
+ const run = await this.exec(COMMANDS[op], op === "claude_version" ? 60_000 : 900_000);
485
505
  if (run.code === 255) {
486
506
  const f = classifySshFailure(run.stderr);
487
507
  throw new RemoteTerminalError(f.code, f.message, f.action);
488
508
  }
489
- const probe = op === "claude_version" ? run : await this.exec("claude --version 2>&1", 60_000);
509
+ const probe = op === "claude_version" ? run : await this.exec(CLAUDE_VERSION_AFTER_INSTALL, 60_000);
490
510
  const version = probe.code === 0 ? (/\d+\.\d+\.\d+\S*/.exec(probe.stdout)?.[0] ?? null) : null;
491
511
  return { op, exit_code: run.code, version, output_tail: run.stdout.slice(-2000) };
492
512
  }
493
513
  /** R15: the terminal's own fs answers; the path travels as base64 so no shell reads it. */
494
514
  async pathCommand(op, targetPath) {
495
- checkRemotePath(targetPath);
496
- if (!versionAtLeast(this.remoteVersion, REMOTE_PATH_OPS_VERSION))
497
- throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${this.remoteVersion}; ${REMOTE_PATH_OPS_VERSION} or later is required (provision the terminal)`);
515
+ checkRemotePath(targetPath, this.platform === "windows" ? "windows" : "posix");
516
+ const minimum = this.platform === "windows" ? REMOTE_WINDOWS_PATH_VERSION : REMOTE_PATH_OPS_VERSION;
517
+ if (!versionAtLeast(this.remoteVersion, minimum))
518
+ throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${this.remoteVersion}; ${minimum} or later is required (provision the terminal)`);
498
519
  const sub = op === "path_status" ? "path-status" : "make-dir";
499
- const result = await this.exec(`exec aiterm-remote-terminal ${sub} --path-base64 ${Buffer.from(targetPath, "utf8").toString("base64")}`, 60_000);
520
+ const result = await this.exec(terminalProgram(["aiterm-remote-terminal", sub, "--path-base64", Buffer.from(targetPath, "utf8").toString("base64")]), 60_000);
500
521
  if (result.code === 255) {
501
522
  const f = classifySshFailure(result.stderr);
502
523
  throw new RemoteTerminalError(f.code, f.message, f.action);
@@ -515,11 +536,12 @@ export class RemoteTerminalConnection extends EventEmitter {
515
536
  /** R15 list-dirs: read-only folder picker listing; no path lists the SSH user's home. */
516
537
  async listDirs(targetPath) {
517
538
  if (targetPath !== undefined)
518
- checkRemotePath(targetPath);
519
- if (!versionAtLeast(this.remoteVersion, REMOTE_LIST_DIRS_VERSION))
520
- 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)`);
521
- const flag = targetPath === undefined ? "" : ` --path-base64 ${Buffer.from(targetPath, "utf8").toString("base64")}`;
522
- const result = await this.exec(`exec aiterm-remote-terminal list-dirs${flag}`, 60_000);
539
+ checkRemotePath(targetPath, this.platform === "windows" ? "windows" : "posix");
540
+ const minimum = this.platform === "windows" ? REMOTE_WINDOWS_PATH_VERSION : REMOTE_LIST_DIRS_VERSION;
541
+ if (!versionAtLeast(this.remoteVersion, minimum))
542
+ throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${this.remoteVersion}; ${minimum} or later is required (update or provision the terminal)`);
543
+ const flag = targetPath === undefined ? [] : ["--path-base64", Buffer.from(targetPath, "utf8").toString("base64")];
544
+ const result = await this.exec(terminalProgram(["aiterm-remote-terminal", "list-dirs", ...flag]), 60_000);
523
545
  if (result.code === 255) {
524
546
  const f = classifySshFailure(result.stderr);
525
547
  throw new RemoteTerminalError(f.code, f.message, f.action);
@@ -564,7 +586,16 @@ function checkKeySource(ref, status, input) {
564
586
  if (status.credential.revision !== input.credentialRevision)
565
587
  throw new RemoteTerminalError("CREDENTIAL_REVISION_STALE", "the key changed; get the current value from the terminal registry and launch again");
566
588
  }
567
- const trustedTarget = (b) => ({ host: b.target.host, user: b.target.user, port: b.target.port, trusted_ref: b.ref });
589
+ export const trustedTarget = (b) => ({ host: b.target.host, user: b.target.user, port: b.target.port, trusted_ref: b.ref });
590
+ /** R20/T4: the terminal's real platform (macOS, Linux or Windows). A declared os that differs is a wrong target; any other system is refused. */
591
+ export async function checkTerminalPlatform(target, declared) {
592
+ const actual = await remotePlatform(target);
593
+ if (actual === null)
594
+ throw new RemoteTerminalError("TERMINAL_PLATFORM_UNSUPPORTED", "the terminal is not a macOS, Linux or Windows system (the platform probe printed nothing recognisable)");
595
+ if (declared !== undefined && declared !== actual)
596
+ throw new RemoteTerminalError("TERMINAL_OS_MISMATCH", `the terminal is registered as ${declared} but runs ${actual}; correct the terminal's os or register the right machine`);
597
+ return actual;
598
+ }
568
599
  /** T1: the binding exists, the target is the binding's, both revisions are current. */
569
600
  export function terminalRemoteTarget(input) {
570
601
  const b = binding(input.ref);
@@ -754,7 +785,7 @@ function keep(ref) {
754
785
  keeper.child.kill();
755
786
  return;
756
787
  }
757
- if (keeper.timer)
788
+ if (keeper.timer || keeper.starting)
758
789
  return;
759
790
  if (!forwardNeeded(ref)) {
760
791
  releaseLock(ref);
@@ -779,37 +810,45 @@ function keep(ref) {
779
810
  }
780
811
  const requested = b.seat_forward_port ?? 0;
781
812
  keeper.ingress = b.seat_ingress_port;
782
- let args;
783
- try {
784
- // The remote command ends when our stdin closes, so the forward dies with this process even on SIGKILL.
785
- args = trustedSshArguments(ref, "cat >/dev/null", null, ["-o", "ExitOnForwardFailure=yes", "-R", seatForwardSpec(requested, b.seat_ingress_port)]);
786
- }
787
- catch {
788
- releaseLock(ref);
789
- return;
790
- }
791
- const child = spawn("ssh", args, { env: sshEnvironment(), stdio: ["pipe", "ignore", "pipe"] });
792
- keeper.child = child;
793
- let stderr = "";
794
- child.stderr.on("data", (chunk) => {
795
- stderr = (stderr + chunk.toString("utf8")).slice(-4000);
796
- const forward = parseSeatForward(stderr);
797
- if (typeof forward === "number" && forward !== requested) {
798
- writeBinding(ref, { seat_forward_port: forward });
799
- keeper.refusals = 0;
800
- }
801
- });
802
- child.on("error", () => { });
803
- child.on("close", () => {
804
- keeper.child = null;
805
- if (parseSeatForward(stderr) === "refused" && requested !== 0 && ++keeper.refusals >= FORWARD_REFUSALS_BEFORE_NEW_PORT) {
806
- // The old P stays taken on the terminal: let sshd pick a new one (seats launched with the old P need a relaunch).
807
- writeBinding(ref, { seat_forward_port: undefined });
808
- keeper.refusals = 0;
809
- }
813
+ const again = () => {
810
814
  keeper.timer = setTimeout(() => { keeper.timer = null; keep(ref); }, FORWARD_RESTART_MS);
811
815
  keeper.timer.unref();
812
- });
816
+ };
817
+ // The remote command depends on the terminal's shell (T4): known from the cache, or probed once by this process.
818
+ keeper.starting = true;
819
+ remoteShell(trustedTarget(b)).then(shell => {
820
+ keeper.starting = false;
821
+ let args;
822
+ try {
823
+ // The remote command ends when our stdin closes, so the forward dies with this process even on SIGKILL.
824
+ args = trustedSshArguments(ref, keeperCommand(shell), null, ["-o", "ExitOnForwardFailure=yes", "-R", seatForwardSpec(requested, b.seat_ingress_port)]);
825
+ }
826
+ catch {
827
+ releaseLock(ref);
828
+ return;
829
+ }
830
+ const child = spawn("ssh", args, { env: sshEnvironment(), stdio: ["pipe", "ignore", "pipe"] });
831
+ keeper.child = child;
832
+ let stderr = "";
833
+ child.stderr.on("data", (chunk) => {
834
+ stderr = (stderr + chunk.toString("utf8")).slice(-4000);
835
+ const forward = parseSeatForward(stderr);
836
+ if (typeof forward === "number" && forward !== requested) {
837
+ writeBinding(ref, { seat_forward_port: forward });
838
+ keeper.refusals = 0;
839
+ }
840
+ });
841
+ child.on("error", () => { });
842
+ child.on("close", () => {
843
+ keeper.child = null;
844
+ if (parseSeatForward(stderr) === "refused" && requested !== 0 && ++keeper.refusals >= FORWARD_REFUSALS_BEFORE_NEW_PORT) {
845
+ // The old P stays taken on the terminal: let sshd pick a new one (seats launched with the old P need a relaunch).
846
+ writeBinding(ref, { seat_forward_port: undefined });
847
+ keeper.refusals = 0;
848
+ }
849
+ again();
850
+ });
851
+ }, () => { keeper.starting = false; again(); });
813
852
  }
814
853
  /** Every 60 s in every active process: keep (or take over from an exited holder) the forwards this state root needs. */
815
854
  export function maintainSeatForwards() {
package/dist/remote.js CHANGED
@@ -11,7 +11,7 @@ import { AitermError, observeAgentDone, readAgentTranscriptResult, windowsStartP
11
11
  import { ensureStateRoot, stateRoot } from "./agent-shared.js";
12
12
  import { currentUid } from "./state-root.js";
13
13
  import { PRIVATE_ENV_SCHEMA } from "./private-env.js";
14
- import { SshStdioTransport, classifySshFailure, trustedSshArguments } from "./remote-terminal.js";
14
+ import { RemoteTerminalError, SshStdioTransport, classifySshFailure, trustedSshArguments } from "./remote-terminal.js";
15
15
  const pkg = createRequire(import.meta.url)("../package.json");
16
16
  export { remoteTargetSchema, remoteInputSchema, remoteInputDescription } from "./remote-contract.js";
17
17
  // 平文で受け取ったパスフレーズは、このMCP processのメモリにだけ置く。ControlMasterが落ちた後の再接続に使う。
@@ -122,6 +122,10 @@ export function remoteShell(target) {
122
122
  if (!shell) {
123
123
  shell = runSsh(target, REMOTE_SHELL_PROBE).then(({ code, stdout, stderr }) => {
124
124
  if (code === 255) {
125
+ if (target.trusted_ref) {
126
+ const failure = classifySshFailure(stderr);
127
+ throw new RemoteTerminalError(failure.code, failure.message, failure.action);
128
+ }
125
129
  const detail = stderr.trim().split("\n").slice(-3).join(" / ") || "exit 255";
126
130
  throw new AitermError(`REMOTE_CONNECT_FAILED: ${remoteLabel(target)} へ接続できません(${detail})`, 2);
127
131
  }
@@ -132,6 +136,47 @@ export function remoteShell(target) {
132
136
  }
133
137
  return shell;
134
138
  }
139
+ // 上のshell判定に続けて`uname -s`を流す。POSIX系は最後の行がDarwin/Linux。cmdは行全体が1つのechoになり、PowerShellでは`uname`が無く何も出ない。
140
+ export const REMOTE_PLATFORM_PROBE = `${REMOTE_SHELL_PROBE}; uname -s`;
141
+ /** probeの出力からOSを決める。Windows・macOS・Linuxのどれとも言えない出力はnull(推測しない)。 */
142
+ export function classifyRemotePlatform(output) {
143
+ const shell = classifyRemoteShell(output);
144
+ if (shell === "cmd")
145
+ return "windows";
146
+ const last = output.trim().split(/\r?\n/).pop()?.trim();
147
+ if (last === "Darwin")
148
+ return "macos";
149
+ if (last === "Linux")
150
+ return "linux";
151
+ // POSIX系のprobe行は`aiterm-probe %OS%`で1行目が終わる(unameの行が付くので、classifyRemoteShellはPowerShellと数える)。それ以外のDarwin/Linuxでない出力は未知のOS。
152
+ return shell === "powershell" && output.trim().split(/\r?\n/)[0].trim() !== "aiterm-probe %OS%" ? "windows" : null;
153
+ }
154
+ const platforms = new Map();
155
+ /** 端末のOSを1回だけ調べて、このprocessの間 接続先ごとに覚える。 */
156
+ export function remotePlatform(target) {
157
+ const key = remoteKey(target);
158
+ let platform = platforms.get(key);
159
+ if (!platform) {
160
+ platform = runSsh(target, REMOTE_PLATFORM_PROBE).then(({ code, stdout, stderr }) => {
161
+ if (code === 255) {
162
+ if (target.trusted_ref) {
163
+ const failure = classifySshFailure(stderr);
164
+ throw new RemoteTerminalError(failure.code, failure.message, failure.action);
165
+ }
166
+ const detail = stderr.trim().split("\n").slice(-3).join(" / ") || "exit 255";
167
+ throw new AitermError(`REMOTE_CONNECT_FAILED: ${remoteLabel(target)} へ接続できません(${detail})`, 2);
168
+ }
169
+ const found = classifyRemotePlatform(stdout);
170
+ // The same run tells which shell sshd starts, so a command build needs no second probe (T4).
171
+ if (found && !shells.has(key))
172
+ shells.set(key, Promise.resolve(found !== "windows" ? "posix" : classifyRemoteShell(stdout) === "cmd" ? "cmd" : "powershell"));
173
+ return found;
174
+ });
175
+ platform.catch(() => platforms.delete(key));
176
+ platforms.set(key, platform);
177
+ }
178
+ return platform;
179
+ }
135
180
  // POSIX系の非ログイン実行では、~/.local/bin、Homebrew、nvmなどのPATHが入らない端末がある。
136
181
  // 利用者のログインshellからPATHだけを受け取り、処理は/bin/shで行う。profileの出力やfish等の文法差を
137
182
  // MCPのstdoutと処理へ持ち込まない。scriptは呼び出し側で検証済みの値だけで組み、単引用符を含めない。
@@ -141,6 +186,34 @@ export function posixCommand(script) {
141
186
  'r="$HOME/.aiterm/runtime/current/bin"; [ -x "$r/aiterm-mcp" ] && PATH="$r:$PATH"; export PATH';
142
187
  return `/bin/sh -c '${importPath}; ${script}'`;
143
188
  }
189
+ /** PowerShellの単引用符literal。`'`だけが特別で、`$`・空白・二重引用符・非ASCIIはそのまま文字になる。 */
190
+ export const powershellQuote = (value) => `'${value.replace(/'/g, "''")}'`;
191
+ /** `& 'prog' 'arg'...`。引数は全て単引用符で包む。 */
192
+ export const powershellInvoke = (argv) => `& ${argv.map(powershellQuote).join(" ")}`;
193
+ /** 固定のプログラム呼び出し。windowsのaiterm-*は、無い時に言語によらず読める`command not found`を出す。 */
194
+ export function terminalProgram(argv) {
195
+ const [program] = argv;
196
+ return {
197
+ posix: `exec ${argv.join(" ")}`,
198
+ windows: `${program.startsWith("aiterm-") ? `if (-not (Get-Command ${powershellQuote(program)} -ErrorAction SilentlyContinue)) { [Console]::Error.WriteLine(${powershellQuote(`${program}: command not found`)}); exit 127 }; ` : ""}${powershellInvoke(argv)}`,
199
+ };
200
+ }
201
+ // 製品のruntime(remote-terminal.md R16)があれば、利用者のPATH上の別のaiterm-mcpより先に使う。
202
+ // npm's .ps1 shims win over .cmd in PowerShell, and Windows PowerShell 5.1 is Restricted by default: allow scripts for this process only.
203
+ const WINDOWS_PREAMBLE = "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force -ErrorAction SilentlyContinue; $r = Join-Path $env:USERPROFILE '.aiterm\\runtime\\current\\bin'; if (Test-Path -LiteralPath (Join-Path $r 'aiterm-mcp.cmd')) { $env:PATH = $r + ';' + $env:PATH }; ";
204
+ // `pwsh -c`は最後のnative commandの失敗を全て1にする。ここで本物の終了codeを返す。
205
+ const WINDOWS_EPILOGUE = "; $ok = $?; $code = $LASTEXITCODE; if ($code) { exit $code }; if ($ok) { exit 0 }; exit 1";
206
+ /** PowerShell本文を、shellが`cmd`の時だけ`powershell -EncodedCommand`で包む(引用符の書式がcmdとPowerShellで違うため)。 */
207
+ export function powershellForShell(shell, body) {
208
+ return shell === "powershell" ? body
209
+ : `powershell -NoProfile -NonInteractive -OutputFormat Text -EncodedCommand ${Buffer.from(body, "utf16le").toString("base64")}`;
210
+ }
211
+ /** 端末のshellに合う1つのコマンド文字列。userの文字列はここへ入れない(固定文・検証済みtoken・base64だけ)。 */
212
+ export function terminalCommand(shell, script) {
213
+ return shell === "posix" ? posixCommand(script.posix) : powershellForShell(shell, `${WINDOWS_PREAMBLE}${script.windows}${WINDOWS_EPILOGUE}`);
214
+ }
215
+ /** stdinに載せたPowerShell scriptを丸ごと実行する入口(authorize-key・Windows provision)。scriptは多行・ASCIIだけ。 */
216
+ export const WINDOWS_STDIN_SCRIPT_COMMAND = powershellForShell("cmd", "Invoke-Expression ([Console]::In.ReadToEnd())");
144
217
  /** 現地のaiterm-mcpを起動するコマンド。Windowsはユーザー環境からPATHが入るので、そのまま呼ぶ。 */
145
218
  export function remoteServerCommand(shell) {
146
219
  return shell === "posix" ? posixCommand("exec aiterm-mcp") : "aiterm-mcp";
@@ -150,7 +223,9 @@ export async function callRemoteTool(target, name, args, timeoutMs = 600_000, pr
150
223
  if (privateEnv && !target.trusted_ref)
151
224
  throw new AitermError("REMOTE_PRIVATE_ENV_UNSUPPORTED: private values travel only to a terminal binding", 2);
152
225
  const shell = await remoteShell(target);
153
- const command = privateEnv ? posixCommand("exec aiterm-mcp --private-env-stdin") : remoteServerCommand(shell);
226
+ // 信頼済み端末はshellごとの正規のコマンド(runtimeの優先と終了codeを含む)。個別指定のremoteは従来のまま。
227
+ const command = target.trusted_ref ? terminalCommand(shell, terminalProgram(privateEnv ? ["aiterm-mcp", "--private-env-stdin"] : ["aiterm-mcp"]))
228
+ : privateEnv ? posixCommand("exec aiterm-mcp --private-env-stdin") : remoteServerCommand(shell);
154
229
  const { args: sshArgs, env } = sshInvocation(target, command);
155
230
  const transport = privateEnv
156
231
  ? new SshStdioTransport(sshArgs, `${JSON.stringify({ schema: PRIVATE_ENV_SCHEMA, env: privateEnv })}\n`)
@@ -189,9 +264,11 @@ export async function callRemoteTool(target, name, args, timeoutMs = 600_000, pr
189
264
  await client.close().catch(() => { });
190
265
  }
191
266
  }
267
+ // npmのbinをPATHへ通さず aiterm-mcp だけリンクしている端末がある。見つからなければ同じpackageのCLIを使う。
268
+ export const WAIT_RESOLVE = 'w=$(command -v aiterm-wait) || w="$(dirname "$(readlink -f "$(command -v aiterm-mcp)")")/aiterm-wait-cli.js"';
192
269
  const SESSION_RE = /^[A-Za-z0-9_-]{1,64}$/;
193
270
  const OPERATION_RE = /^sha256:[0-9a-f]{64}$/;
194
- export function remoteWaitCommand(shell, session, cursor, operationId, timeout, inputId) {
271
+ export function remoteWaitCommand(shell, session, cursor, operationId, timeout, inputId, trusted = false) {
195
272
  if (!SESSION_RE.test(session))
196
273
  throw new AitermError("REMOTE_SESSION_INVALID: session名が不正です", 2);
197
274
  if (operationId !== null && !OPERATION_RE.test(operationId))
@@ -205,16 +282,16 @@ export function remoteWaitCommand(shell, session, cursor, operationId, timeout,
205
282
  parts.push("--operation", operationId);
206
283
  if (inputId !== undefined)
207
284
  parts.push("--input", inputId);
285
+ if (trusted)
286
+ return terminalCommand(shell, { posix: `${WAIT_RESOLVE}; exec "$w" ${parts.join(" ")}`, windows: terminalProgram(["aiterm-wait", ...parts]).windows });
208
287
  if (shell !== "posix")
209
288
  return `aiterm-wait ${parts.join(" ")}`;
210
- // npmのbinをPATHへ通さず aiterm-mcp だけリンクしている端末がある。見つからなければ同じpackageのCLIを使う。
211
- const resolve = 'w=$(command -v aiterm-wait) || w="$(dirname "$(readlink -f "$(command -v aiterm-mcp)")")/aiterm-wait-cli.js"';
212
- return posixCommand(`${resolve}; exec "$w" ${parts.join(" ")}`);
289
+ return posixCommand(`${WAIT_RESOLVE}; exec "$w" ${parts.join(" ")}`);
213
290
  }
214
291
  /** 親が別processで起動する完了待ち。ssh越しのaiterm-waitで、exit codeは現地のaiterm-waitをそのまま返す。 */
215
292
  export async function remoteWaitProcess(target, session, cursor, inputId) {
216
293
  // 別processには鍵のパスフレーズを渡せない。ssh-agentか、張ってあるControlMasterの接続に相乗りする。
217
- const { args } = sshInvocation(target, remoteWaitCommand(await remoteShell(target), session, cursor, null, 600, inputId), { passphrase: false });
294
+ const { args } = sshInvocation(target, remoteWaitCommand(await remoteShell(target), session, cursor, null, 600, inputId, !!target.trusted_ref), { passphrase: false });
218
295
  return { executable: "ssh", args, windows_start_process_argument_list: process.platform === "win32" ? windowsStartProcessArgumentList(args) : null };
219
296
  }
220
297
  function runSsh(target, command, signal) {
@@ -240,7 +317,7 @@ export async function observeRemoteAgentDone(target, session, options) {
240
317
  if (options.signal?.aborted)
241
318
  throw new AitermError("REMOTE_OBSERVE_ABORTED: 観測を停止しました", 2);
242
319
  const remaining = infinite ? 86_400 : Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
243
- const command = remoteWaitCommand(await remoteShell(target), session, options.cursor ?? null, options.operation_id ?? null, Math.min(remaining, 86_400), options.input_id);
320
+ const command = remoteWaitCommand(await remoteShell(target), session, options.cursor ?? null, options.operation_id ?? null, Math.min(remaining, 86_400), options.input_id, !!target.trusted_ref);
244
321
  const { code, stdout, stderr } = await runSsh(target, command, options.signal);
245
322
  if (options.signal?.aborted)
246
323
  throw new AitermError("REMOTE_OBSERVE_ABORTED: 観測を停止しました", 2);
@@ -3,7 +3,9 @@
3
3
  const ACTIONS = {
4
4
  TERMINAL_INVALID: "起動の指定(端末の情報か作業フォルダ)が正しくありません。BellTeamの不具合の恐れがあります。",
5
5
  TARGET_INVALID: "起動の指定(端末の情報)が正しくありません。BellTeamの不具合の恐れがあります。",
6
- TERMINAL_HARNESS_UNSUPPORTED: "この端末で起こせるAIは、今はClaude Codeだけです。メンバーのAIをClaude Codeにしてください。",
6
+ TERMINAL_OS_MISMATCH: "端末のOSが、登録されているOSと違います。別の機械を指している恐れがあり止めました。端末の登録(OS)を確かめてください。",
7
+ TERMINAL_PLATFORM_UNSUPPORTED: "この端末のOSは、Mac・Linux・Windowsのどれとも確かめられず、席を起こせません。Mac、Linux、Windowsのどれかの端末を使ってください。",
8
+ TERMINAL_HARNESS_UNSUPPORTED: "この端末で起こせるAIは、今はClaude CodeとCodexだけです。メンバーのAIをClaude CodeかCodexにしてください。",
7
9
  REF_INVALID: "端末の登録が見つかりません。端末の登録を確かめてください。",
8
10
  BINDING_UNKNOWN: "端末の登録が見つかりません。端末の登録を確かめてください。",
9
11
  BINDING_STORE_UNREADABLE: "端末の登録を読めませんでした。端末の登録をやり直してください。",
@@ -17,10 +19,10 @@ const ACTIONS = {
17
19
  CREDENTIAL_REVISION_STALE: "端末へ入る鍵が新しくなりました。新しい鍵で起こし直します。",
18
20
  CREDENTIAL_UNAVAILABLE: "端末へ入る鍵を使えません。端末の登録で鍵を確かめてください。",
19
21
  AUTH_FAILED: "端末が鍵を受け付けませんでした。端末の登録から、パスワードで鍵を許可し直してください。",
20
- CONNECTION_REFUSED: "端末がSSHの接続を断りました。Macなら「リモートログイン」が入になっているか確かめてください。",
22
+ CONNECTION_REFUSED: "端末がSSHの接続を断りました。端末のSSHサーバーが入になっているか確かめてください(Macは「リモートログイン」、Linuxはsshdの起動、WindowsはオプションのOpenSSHサーバーの追加とsshdサービスの起動)。",
21
23
  UNREACHABLE: "端末につながりません。電源とネットワークを確かめてください。つながれば起こし直します。",
22
24
  CONNECTION_FAILED: "端末へのSSH接続に失敗しました。端末の電源とSSHの設定を確かめてください。",
23
- REMOTE_AITERM_UNAVAILABLE: "端末にAitermが入っていません。端末の準備(Aitermの導入)をやり直してください。",
25
+ REMOTE_AITERM_UNAVAILABLE: "端末にAitermが入っていません(またはsshで入った時のPATHにありません)。端末の準備(Aitermの導入)をやり直してください。",
24
26
  REMOTE_AITERM_TOO_OLD: "端末のAitermが古いため起こせません。端末のAitermを更新してください。",
25
27
  SEAT_FORWARD_UNAVAILABLE: "端末からBellTeamへ戻る通り道がまだ用意できていません。少し待ってから起こし直してください。",
26
28
  CWD_UNAVAILABLE: "端末に作業フォルダがありません。メンバーの作業フォルダを選び直すか、そのフォルダを作ってください。",
@@ -39,11 +41,13 @@ export function terminalLaunchAction(code) {
39
41
  export const LAUNCH_ERROR_META = "aiterm/launch_error";
40
42
  export const ERROR_CODE_META = "aiterm/error_code";
41
43
  /** R18 for a local launch: the fresh native creation left no seat (core.freshLaunchFailure). */
42
- export function launchNotStartedMeta(harness) {
44
+ export function launchNotStartedMeta(harness, phase = "native_create") {
43
45
  const code = "AGENT_LAUNCH_NOT_STARTED";
44
- return { [LAUNCH_ERROR_META]: { schema: "aiterm.agent-launch-error.v1", harness, code, phase: "native_create",
45
- effect: "not_started", session_created: false, action: ACTIONS[code] } };
46
+ return { [LAUNCH_ERROR_META]: { schema: "aiterm.agent-launch-error.v1", harness, code, phase,
47
+ effect: "not_started", session_created: false, action: phase === "input" ? INPUT_ACTION : ACTIONS[code] } };
46
48
  }
49
+ // phase "input": refused from the arguments alone; nothing was started, so launching again unchanged fails the same way.
50
+ const INPUT_ACTION = "起動の指定(追加の指示かMCPの設定)をこのAIでは使えません。席は作られていません。指定を見直してください。";
47
51
  /** R19: the leading symbolic code of a refused call, so the caller does not parse text. It claims no effect. */
48
52
  export function withErrorCode(result) {
49
53
  if (!result?.isError)
@@ -54,8 +58,8 @@ export function withErrorCode(result) {
54
58
  /** Adds R18's `_meta` to a failed terminal launch result; a result whose code is not listed is returned unchanged.
55
59
  * `_meta`, not structuredContent: SDK clients that listed the tools validate structuredContent against the
56
60
  * success outputSchema even on isError, and would turn this refusal into a protocol error. */
57
- export function withTerminalLaunchAction(result) {
58
- if (!result?.isError)
61
+ export function withTerminalLaunchAction(result, harness = "claude-code") {
62
+ if (!result?.isError || result._meta?.[LAUNCH_ERROR_META])
59
63
  return result;
60
64
  const structured = result.structuredContent;
61
65
  const preflight = structured?.schema === "aiterm.agent-launch-error.v1";
@@ -67,6 +71,6 @@ export function withTerminalLaunchAction(result) {
67
71
  return result;
68
72
  const failure = preflight
69
73
  ? { schema: structured.schema, harness: structured.harness, code, phase: structured.phase, effect: structured.effect, session_created: false, action }
70
- : { schema: "aiterm.agent-launch-error.v1", harness: "claude-code", code, phase: "terminal", effect: "not_started", session_created: false, action };
74
+ : { schema: "aiterm.agent-launch-error.v1", harness, code, phase: "terminal", effect: "not_started", session_created: false, action };
71
75
  return { ...result, _meta: { ...result._meta, [LAUNCH_ERROR_META]: failure } };
72
76
  }
@@ -6,7 +6,7 @@ import { spawnSync } from "node:child_process";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { readCompletedTranscript } from "./transcript-read.js";
8
8
  import { boundTerminalTarget, classifySshFailure, trustedSshArguments } from "./remote-terminal.js";
9
- import { posixCommand } from "./remote.js";
9
+ import { remoteShell, terminalCommand, terminalProgram } from "./remote.js";
10
10
  const ERROR = "aiterm.transcript-read-error.v1";
11
11
  function option(args, name) {
12
12
  const at = args.indexOf(name);
@@ -30,14 +30,14 @@ export function transcriptFlags(args) {
30
30
  }
31
31
  return flags;
32
32
  }
33
- function run(args) {
33
+ async function run(args) {
34
34
  const flags = transcriptFlags(args);
35
35
  const target = boundTerminalTarget(flags[1]);
36
36
  if (!target) {
37
37
  const id = option(flags, "--cursor-session"), max = option(flags, "--max-bytes");
38
38
  return { line: JSON.stringify(readCompletedTranscript(flags[1], id ? { claudeSessionId: id, offset: Number(option(flags, "--offset")) } : null, max ? Number(max) : undefined)), code: 0 };
39
39
  }
40
- const ssh = spawnSync("ssh", trustedSshArguments(target.trusted_ref, posixCommand(`exec aiterm-remote-terminal transcript-read ${flags.join(" ")}`), null), { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 120_000, maxBuffer: 64 * 1024 * 1024 });
40
+ const ssh = spawnSync("ssh", trustedSshArguments(target.trusted_ref, terminalCommand(await remoteShell(target), terminalProgram(["aiterm-remote-terminal", "transcript-read", ...flags])), null), { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 120_000, maxBuffer: 64 * 1024 * 1024 });
41
41
  const line = (ssh.stdout ?? "").trim().split("\n").pop() ?? "";
42
42
  let parsed = null;
43
43
  try {
@@ -57,14 +57,9 @@ try {
57
57
  }
58
58
  catch { /* imported */ }
59
59
  if (entry) {
60
- try {
61
- const { line, code } = run(process.argv.slice(2));
62
- process.stdout.write(`${line}\n`);
63
- process.exit(code);
64
- }
65
- catch (error) {
60
+ run(process.argv.slice(2)).then(({ line, code }) => { process.stdout.write(`${line}\n`); process.exit(code); }, (error) => {
66
61
  const message = error instanceof Error ? error.message : String(error);
67
62
  process.stdout.write(`${JSON.stringify({ schema: ERROR, code: /^([A-Z][A-Z0-9_]+):/.exec(message)?.[1] ?? "AITERM_FAILED", message })}\n`);
68
63
  process.exit(2);
69
- }
64
+ });
70
65
  }