aiterm-mcp 0.66.0 → 0.67.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,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.67.0] - 2026-11-09
11
+
12
+ - Terminals without a native key (docs/architecture/remote-terminal.md R13). `aiterm-remote-terminal register --host H --user U --port P` creates a keyless binding with Aiterm's own empty known_hosts (`~/.config/aiterm/known_hosts.d/<ref>`; trust via `trust-confirm`). `aiterm-remote-terminal credential-load --ref R --terminal-id ID --handle UUID --revision N --purpose ssh-key` takes the resolved OpenSSH private key only on stdin and holds it in a private per-terminal ssh-agent (memory only); the receipt carries metadata only. The terminal value then carries `credential: {handle, revision}` instead of `credentialRevision`; Aiterm checks the loaded handle and revision (`CREDENTIAL_NOT_LOADED`, `CREDENTIAL_REVISION_STALE`, `CREDENTIAL_REQUIRED`). `sudoCredential` is accepted and kept as a handle only. The agent is removed when no seat of that terminal remains.
13
+
10
14
  ## [0.66.0] - 2026-11-09
11
15
 
12
16
  - One launch path for seats on another computer (Owner ruling; docs/architecture/remote-terminal.md). `agent_launch`, `claude_agent`, `codex_agent` and `grok_agent` take `terminal: {ref, target:{host,user,port}, trustRevision, credentialRevision}` (the value BellTeam terminals hands over, unchanged) and `cwd` (the project folder on that terminal, required). Omitted = local, as before. The value is checked against the Aiterm-held binding and its revisions; a malformed value, a missing or relative `cwd`, or `terminal` together with `remote` answers `TERMINAL_INVALID` with a plain message. First scope `claude-code`; other harnesses answer `TERMINAL_HARNESS_UNSUPPORTED`.
@@ -3132,7 +3136,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3132
3136
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3133
3137
  provenance.
3134
3138
 
3135
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.66.0...HEAD
3139
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.67.0...HEAD
3140
+ [0.67.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.66.0...v0.67.0
3136
3141
  [0.66.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.65.1...v0.66.0
3137
3142
  [0.65.1]: https://github.com/kitepon/aiterm-mcp/compare/v0.65.0...v0.65.1
3138
3143
  [0.65.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.64.2...v0.65.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.66.0** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.67.0** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
219
219
 
220
220
  ### 更新と巻き戻し
221
221
 
package/README.md CHANGED
@@ -227,7 +227,7 @@ collection is off by default and performs no network I/O. It ships via
227
227
  tag-triggered CI with npm provenance (OIDC Trusted Publishing); the GitHub
228
228
  Release re-registers the Official MCP Registry entry.
229
229
 
230
- **Status:** actively maintained · current public release **v0.66.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).
230
+ **Status:** actively maintained · current public release **v0.67.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
 
@@ -22,6 +22,11 @@ export const remoteInputSchema = remoteTargetSchema.omit({ trusted_ref: true }).
22
22
  export const remoteInputDescription = "別端末のAitermで実行する時のSSH接続情報。hostだけならssh_configの接続名として使う。" +
23
23
  "Aitermは接続情報を保存・管理しない。passphraseは会話記録に残るため、ssh-agentかpassphrase_env(環境変数名)を推奨する。";
24
24
  const revision = (field) => z.string().regex(/^sha256:[0-9a-f]{64}$/, `terminal.${field} must be the sha256:<hex> revision the terminal registry returned with this binding; pass it unchanged`);
25
+ /** A credential owner's handle for a key; the value itself never travels in an argument. */
26
+ export const credentialHandleSchema = z.object({
27
+ handle: z.string().uuid("credential.handle must be the handle (UUID) the terminal registry gave, unchanged"),
28
+ revision: z.number().int().positive("credential.revision must be the handle's positive integer revision, unchanged").max(Number.MAX_SAFE_INTEGER),
29
+ }).strict();
25
30
  /** The launch tools' terminal target (remote-terminal.md "One launch path"). Copied unchanged from BellTeam terminals. */
26
31
  export const terminalArgumentSchema = z.object({
27
32
  ref: z.string().uuid("terminal.ref must be the binding ref (UUID) the terminal registry gave for this terminal"),
@@ -31,10 +36,16 @@ export const terminalArgumentSchema = z.object({
31
36
  port: z.number().int().min(1).max(65535),
32
37
  }).strict(),
33
38
  trustRevision: revision("trustRevision"),
34
- credentialRevision: revision("credentialRevision"),
35
- }).strict();
39
+ credentialRevision: revision("credentialRevision").optional(),
40
+ credential: credentialHandleSchema.optional(),
41
+ sudoCredential: credentialHandleSchema.optional(),
42
+ }).strict().superRefine((value, context) => {
43
+ if ((value.credential === undefined) === (value.credentialRevision === undefined))
44
+ context.addIssue({ code: "custom",
45
+ message: "terminal needs exactly one key source: credential {handle, revision} from the registry, or credentialRevision for a native key" });
46
+ });
36
47
  export const terminalArgumentDescription = "Run this seat on another computer (a registered terminal) over SSH. Value: exactly the terminal value your host system's terminal registry hands over, " +
37
- "{ref, target:{host,user,port}, trustRevision, credentialRevision}; copy it unchanged, never invent or edit it, never use a host name or ssh command instead. " +
48
+ "{ref, target:{host,user,port}, trustRevision, and credentialRevision or credential {handle, revision}}; copy it unchanged, never invent or edit it, never use a host name or ssh command instead. " +
38
49
  "Omit it to launch on this computer. Give cwd in the same call: the absolute project folder on that terminal. Never launch locally and then cd or ssh. " +
39
50
  "Never put tokens, passwords or other secrets in any argument, prompt or typed text; pass secret values only by name in env_vars. " +
40
51
  "After launch, use session_id alone for pty_send, pty_observe, pty_read, pty_key, claude_turn, agent_stop and pty_close; Aiterm routes them to the terminal. " +
@@ -42,6 +53,7 @@ export const terminalArgumentDescription = "Run this seat on another computer (a
42
53
  "TARGET_MISMATCH / BINDING_UNKNOWN = the value is not this terminal's binding: ask the terminal registry again. " +
43
54
  "HOST_TRUST_STALE / CREDENTIAL_REVISION_STALE = the binding changed: get the current value from the terminal registry and launch again. " +
44
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
+ "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. " +
45
57
  "AUTH_FAILED = the terminal refused the key. UNREACHABLE = the terminal is offline; try later. " +
46
58
  "REMOTE_AITERM_TOO_OLD = update Aiterm on the terminal. CWD_UNAVAILABLE = the folder does not exist there; do not pick another folder. " +
47
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.";
@@ -2,6 +2,7 @@
2
2
  // aiterm-remote-terminal (remote-terminal.md). Run as the UID that can read the terminal key.
3
3
  // status --ref R | register ... | trust-confirm --ref R --fingerprint F (one JSON line; exit 0 result, 2 error)
4
4
  // serve stdio MCP for one bound connection, spawned by BellTeam terminals
5
+ // credential-load --ref R --terminal-id ID --handle UUID --revision N --purpose ssh-key (key bytes on stdin; one JSON receipt line)
5
6
  // transcript-read --session S [--cursor-session ID --offset N] [--max-bytes N] (runs on the terminal)
6
7
  import { realpathSync } from "node:fs";
7
8
  import { fileURLToPath } from "node:url";
@@ -9,8 +10,9 @@ import { createRequire } from "node:module";
9
10
  import { z } from "zod";
10
11
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
11
12
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
12
- import { RemoteTerminalConnection, RemoteTerminalError, bindingStatus, confirmHostKey, registerBinding } from "./remote-terminal.js";
13
+ import { RemoteTerminalConnection, RemoteTerminalError, bindingStatus, confirmHostKey, loadCredential, registerBinding } from "./remote-terminal.js";
13
14
  import { readCompletedTranscript } from "./transcript-read.js";
15
+ import { credentialHandleSchema } from "./remote-contract.js";
14
16
  const pkg = createRequire(import.meta.url)("../package.json");
15
17
  function option(args, name) {
16
18
  const at = args.indexOf(name);
@@ -50,7 +52,8 @@ function serve() {
50
52
  server.registerTool("remote_terminal_open", {
51
53
  description: "Open the bound connection for this process",
52
54
  inputSchema: { ref: z.string(), target: z.object({ host: z.string(), user: z.string(), port: z.number().int() }).strict(),
53
- trustRevision: z.string(), credentialRevision: z.string(), privateEnv: z.record(z.string(), z.string()).optional() },
55
+ trustRevision: z.string(), credentialRevision: z.string().optional(), credential: credentialHandleSchema.optional(),
56
+ sudoCredential: credentialHandleSchema.optional(), privateEnv: z.record(z.string(), z.string()).optional() },
54
57
  }, guarded(async (args) => {
55
58
  if (connection)
56
59
  throw new RemoteTerminalError("ALREADY_OPEN", "this process already holds a connection");
@@ -104,8 +107,23 @@ export function main(args) {
104
107
  if (command === "register")
105
108
  return oneShot(() => registerBinding({
106
109
  target: { host: option(rest, "--host") ?? "", user: option(rest, "--user") ?? "", port: Number(option(rest, "--port") ?? "22") },
107
- keyFile: option(rest, "--key-file") ?? "", knownHostsFile: option(rest, "--known-hosts") ?? "", hostKeyAlias: option(rest, "--host-key-alias") ?? null,
110
+ keyFile: option(rest, "--key-file") ?? null, knownHostsFile: option(rest, "--known-hosts") ?? null, hostKeyAlias: option(rest, "--host-key-alias") ?? null,
108
111
  }), "aiterm.remote-binding-error.v1");
112
+ if (command === "credential-load") {
113
+ // Key bytes only on stdin until EOF (remote-terminal.md R13); flags carry metadata only.
114
+ const chunks = [];
115
+ process.stdin.on("data", (chunk) => chunks.push(chunk));
116
+ process.stdin.on("end", () => {
117
+ const key = Buffer.concat(chunks);
118
+ for (const chunk of chunks)
119
+ chunk.fill(0);
120
+ loadCredential({ ref: option(rest, "--ref") ?? "", terminalId: option(rest, "--terminal-id") ?? "", handle: option(rest, "--handle") ?? "",
121
+ revision: option(rest, "--revision") ?? "", purpose: option(rest, "--purpose") ?? "" }, key)
122
+ .then(receipt => { process.stdout.write(`${JSON.stringify(receipt)}\n`); process.exit(0); })
123
+ .catch(error => { process.stdout.write(`${JSON.stringify(errorDto(error, "aiterm.remote-binding-error.v1"))}\n`); process.exit(2); });
124
+ });
125
+ return;
126
+ }
109
127
  if (command === "trust-confirm")
110
128
  return oneShot(() => confirmHostKey(option(rest, "--ref") ?? "", option(rest, "--fingerprint") ?? ""), "aiterm.remote-binding-error.v1");
111
129
  if (command === "transcript-read")
@@ -68,16 +68,25 @@ function binding(ref) {
68
68
  throw new RemoteTerminalError("BINDING_UNKNOWN", "no binding has this ref");
69
69
  return found;
70
70
  }
71
+ /** Without keyFile the key comes from a credential handle at open/launch; without knownHostsFile Aiterm keeps an empty one per binding. */
71
72
  export function registerBinding(input) {
72
73
  const target = validTarget(input.target);
73
74
  for (const file of [input.keyFile, input.knownHostsFile]) {
74
- if (!path.isAbsolute(file))
75
+ if (file && !path.isAbsolute(file))
75
76
  throw new RemoteTerminalError("PATH_INVALID", "key and known_hosts paths must be absolute");
76
77
  }
77
78
  if (input.hostKeyAlias != null && !HOST.test(input.hostKeyAlias))
78
79
  throw new RemoteTerminalError("ALIAS_INVALID", "host key alias is not a host name");
79
80
  const bindings = readStore();
80
- const next = { ref: randomUUID(), target, key_file: input.keyFile, known_hosts_file: input.knownHostsFile,
81
+ const ref = randomUUID();
82
+ let knownHostsFile = input.knownHostsFile || null;
83
+ if (!knownHostsFile) {
84
+ const dir = path.join(path.dirname(storePath()), "known_hosts.d");
85
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
86
+ knownHostsFile = path.join(dir, ref);
87
+ fs.writeFileSync(knownHostsFile, "", { mode: 0o600, flag: "wx" });
88
+ }
89
+ const next = { ref, target, key_file: input.keyFile || null, known_hosts_file: knownHostsFile,
81
90
  host_key_alias: input.hostKeyAlias ?? null, created_at: new Date().toISOString() };
82
91
  writeJson0600(storePath(), { schema: "aiterm.remote-bindings.v1", bindings: [...bindings, next] });
83
92
  return bindingStatus(next.ref);
@@ -120,13 +129,15 @@ function trustEntries(b) {
120
129
  const digest = (text) => `sha256:${createHash("sha256").update(text).digest("hex")}`;
121
130
  export function bindingStatus(ref) {
122
131
  const b = binding(ref);
123
- const key = publicKey(b.key_file);
132
+ const key = b.key_file ? publicKey(b.key_file) : null;
124
133
  const trust = trustEntries(b);
125
134
  return {
126
135
  schema: "aiterm.remote-binding-status.v1", ref, target: b.target,
127
- credential: "reason" in key
128
- ? { provider: "aiterm.native-ssh-key.v1", revision: null, fingerprint: null, available: false, reason: key.reason }
129
- : { provider: "aiterm.native-ssh-key.v1", revision: digest(key.line), fingerprint: keyFingerprint(key.blob), available: true, reason: null },
136
+ credential: key === null
137
+ ? { provider: "aiterm.credential-handle.v1", revision: null, fingerprint: null, available: false, reason: "KEY_FROM_CREDENTIAL" }
138
+ : "reason" in key
139
+ ? { provider: "aiterm.native-ssh-key.v1", revision: null, fingerprint: null, available: false, reason: key.reason }
140
+ : { provider: "aiterm.native-ssh-key.v1", revision: digest(key.line), fingerprint: keyFingerprint(key.blob), available: true, reason: null },
130
141
  trust: Array.isArray(trust)
131
142
  ? { provider: "aiterm.known-hosts.v1", revision: digest(trust.join("\n")), available: true, reason: null,
132
143
  fingerprints: trust.map(entry => keyFingerprint(Buffer.from(entry.split(" ").at(-1), "base64"))) }
@@ -307,10 +318,7 @@ export class RemoteTerminalConnection extends EventEmitter {
307
318
  throw new RemoteTerminalError(status.trust.reason ?? "HOST_TRUST_MISSING", "host trust is unavailable", "confirm the new host key");
308
319
  if (status.trust.revision !== input.trustRevision)
309
320
  throw new RemoteTerminalError("HOST_TRUST_STALE", "the host trust revision changed; re-read status");
310
- if (!status.credential.available)
311
- throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", status.credential.reason ?? "the key is unavailable");
312
- if (status.credential.revision !== input.credentialRevision)
313
- throw new RemoteTerminalError("CREDENTIAL_REVISION_STALE", "the key revision changed; re-read status");
321
+ checkKeySource(input.ref, status, input);
314
322
  for (const [name, value] of Object.entries(input.privateEnv ?? {}))
315
323
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || typeof value !== "string")
316
324
  throw new RemoteTerminalError("PRIVATE_ENV_INVALID", "invalid private env entry");
@@ -327,15 +335,24 @@ export class RemoteTerminalConnection extends EventEmitter {
327
335
  throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", "the private agent did not start");
328
336
  await new Promise(resolve => setTimeout(resolve, 50));
329
337
  }
330
- const added = spawnSync("ssh-add", ["-q", b.key_file], { env: { ...sshEnvironment(), SSH_AUTH_SOCK: socket }, stdio: ["ignore", "ignore", "pipe"], timeout: 10_000 });
331
- if (added.status !== 0)
332
- throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", "the key could not be loaded");
333
- const identity = path.join(dir, "id.pub");
334
- const key = publicKey(b.key_file);
335
- if ("reason" in key)
336
- throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", key.reason);
337
- fs.writeFileSync(identity, `${key.line}\n`, { mode: 0o600 });
338
- const transport = new SshStdioTransport(sshArguments(b, socket, identity, posixCommand("exec aiterm-mcp --private-env-stdin")), `${JSON.stringify({ schema: PRIVATE_ENV_SCHEMA, env: input.privateEnv ?? {} })}\n`);
338
+ // A keyless binding authenticates with the credential agent loaded by credential-load (R13); checkKeySource checked it.
339
+ const loaded = b.key_file ? null : readCredential(b.ref);
340
+ let agentSocket = socket, identity = path.join(dir, "id.pub");
341
+ if (loaded) {
342
+ agentSocket = loaded.socket;
343
+ identity = credentialPublicKeyFile(b.ref);
344
+ }
345
+ else {
346
+ const keyFile = b.key_file;
347
+ const added = spawnSync("ssh-add", ["-q", keyFile], { env: { ...sshEnvironment(), SSH_AUTH_SOCK: socket }, stdio: ["ignore", "ignore", "pipe"], timeout: 10_000 });
348
+ if (added.status !== 0)
349
+ throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", "the key could not be loaded");
350
+ const key = publicKey(keyFile);
351
+ if ("reason" in key)
352
+ throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", key.reason);
353
+ fs.writeFileSync(identity, `${key.line}\n`, { mode: 0o600 });
354
+ }
355
+ 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`);
339
356
  const client = new Client({ name: "aiterm-remote-terminal", version: pkg.version });
340
357
  try {
341
358
  await client.connect(transport, { timeout: 60_000 });
@@ -350,7 +367,7 @@ export class RemoteTerminalConnection extends EventEmitter {
350
367
  await client.close().catch(() => { });
351
368
  throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${remoteVersion}; ${REMOTE_MINIMUM_VERSION} or later is required`);
352
369
  }
353
- const connection = new RemoteTerminalConnection(b, dir, agent, socket, identity, client, remoteVersion);
370
+ const connection = new RemoteTerminalConnection(b, dir, agent, agentSocket, identity, client, remoteVersion);
354
371
  client.onclose = () => connection.ended();
355
372
  // After the caller has attached its listener to the returned connection.
356
373
  setImmediate(() => connection.emit("event", { type: "ready", at: new Date().toISOString(), remoteVersion }));
@@ -465,6 +482,27 @@ export class RemoteTerminalConnection extends EventEmitter {
465
482
  return { closed: true };
466
483
  }
467
484
  }
485
+ /** T1 key source: a credential handle (its revision checked by the resolver) or the binding's native key revision, never both. */
486
+ function checkKeySource(ref, status, input) {
487
+ if (input.credential) {
488
+ if (input.credentialRevision !== undefined)
489
+ throw new RemoteTerminalError("TERMINAL_INVALID", "give credential or credentialRevision, not both: with a credential handle the registry omits credentialRevision");
490
+ if (status.credential.provider !== "aiterm.credential-handle.v1")
491
+ throw new RemoteTerminalError("TERMINAL_INVALID", "this terminal has a native key; pass credentialRevision instead of credential");
492
+ const loaded = readCredential(ref);
493
+ if (!loaded || loaded.handle !== input.credential.handle || !agentAlive(loaded.socket))
494
+ throw new RemoteTerminalError("CREDENTIAL_NOT_LOADED", "the terminal's credential is not loaded; resolve the handle and run credential-load, then launch again");
495
+ if (loaded.revision !== input.credential.revision)
496
+ throw new RemoteTerminalError("CREDENTIAL_REVISION_STALE", "the loaded credential has another revision; run credential-load with the current one, then launch again");
497
+ return;
498
+ }
499
+ if (status.credential.provider === "aiterm.credential-handle.v1")
500
+ throw new RemoteTerminalError("CREDENTIAL_REQUIRED", "this terminal has no native key; pass the terminal's credential handle from the registry");
501
+ if (!status.credential.available)
502
+ throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", status.credential.reason ?? "the key is unavailable");
503
+ if (status.credential.revision !== input.credentialRevision)
504
+ throw new RemoteTerminalError("CREDENTIAL_REVISION_STALE", "the key changed; get the current value from the terminal registry and launch again");
505
+ }
468
506
  const trustedTarget = (b) => ({ host: b.target.host, user: b.target.user, port: b.target.port, trusted_ref: b.ref });
469
507
  /** T1: the binding exists, the target is the binding's, both revisions are current. */
470
508
  export function terminalRemoteTarget(input) {
@@ -477,19 +515,26 @@ export function terminalRemoteTarget(input) {
477
515
  throw new RemoteTerminalError(status.trust.reason ?? "HOST_TRUST_MISSING", "the terminal's host key is not trusted (confirm the new host key)");
478
516
  if (status.trust.revision !== input.trustRevision)
479
517
  throw new RemoteTerminalError("HOST_TRUST_STALE", "the host trust changed; get the current value from the terminal registry and launch again");
480
- if (!status.credential.available)
481
- throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", status.credential.reason ?? "the key is unavailable");
482
- if (status.credential.revision !== input.credentialRevision)
483
- throw new RemoteTerminalError("CREDENTIAL_REVISION_STALE", "the key changed; get the current value from the terminal registry and launch again");
518
+ checkKeySource(input.ref, status, input);
484
519
  return trustedTarget(b);
485
520
  }
486
521
  /** ssh argv for a trusted target: no user config, the binding's known_hosts only, its key file only. */
487
522
  export function trustedSshArguments(ref, remoteCommand, controlPath, extra = []) {
488
523
  const b = binding(ref);
524
+ let identity;
525
+ if (b.key_file)
526
+ identity = ["-o", "IdentityAgent=none", "-o", "IdentitiesOnly=yes", "-o", `IdentityFile=${b.key_file}`];
527
+ else {
528
+ // R13: only the key credential-load put into this terminal's private agent (its public half selects it).
529
+ const loaded = readCredential(ref);
530
+ if (!loaded || !fs.existsSync(loaded.socket))
531
+ throw new RemoteTerminalError("CREDENTIAL_NOT_LOADED", "the terminal's credential is not loaded; resolve the handle and run credential-load");
532
+ identity = ["-o", `IdentityAgent=${loaded.socket}`, "-o", "IdentitiesOnly=yes", "-o", `IdentityFile=${credentialPublicKeyFile(ref)}`];
533
+ }
489
534
  return ["-F", "/dev/null", "-T", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes",
490
535
  "-o", `UserKnownHostsFile=${b.known_hosts_file}`, "-o", "GlobalKnownHostsFile=/dev/null", "-o", "CheckHostIP=no",
491
536
  ...(b.host_key_alias ? ["-o", `HostKeyAlias=${b.host_key_alias}`] : []),
492
- "-o", "IdentityAgent=none", "-o", "IdentitiesOnly=yes", "-o", `IdentityFile=${b.key_file}`,
537
+ ...identity,
493
538
  ...(controlPath ? ["-o", "ControlMaster=auto", "-o", `ControlPath=${controlPath}`, "-o", "ControlPersist=600"] : ["-o", "ControlMaster=no", "-o", "ControlPath=none"]),
494
539
  "-o", "ConnectTimeout=15", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=4", ...extra,
495
540
  "-l", b.target.user, "-p", String(b.target.port), "--", b.target.host, ...(remoteCommand === null ? [] : [remoteCommand])];
@@ -620,6 +665,7 @@ function keep(ref) {
620
665
  if (!forwardNeeded(ref)) {
621
666
  releaseLock(ref);
622
667
  keepers.delete(ref);
668
+ releaseIdleCredential(ref);
623
669
  return;
624
670
  }
625
671
  if (!holdLock(ref))
@@ -667,7 +713,7 @@ function keep(ref) {
667
713
  }
668
714
  /** Every 60 s: keep (or take over) the forwards this process's state root needs. */
669
715
  export function maintainSeatForwards() {
670
- const refs = new Set([...Object.values(readSeats()), ...keepers.keys()]);
716
+ const refs = new Set([...Object.values(readSeats()), ...keepers.keys(), ...loadedCredentialRefs()]);
671
717
  for (const ref of refs)
672
718
  keep(ref);
673
719
  if (refs.size && !maintainTimer) {
@@ -691,3 +737,116 @@ export async function ensureSeatForward(ref, timeoutMs = 30_000) {
691
737
  await new Promise(resolve => setTimeout(resolve, 250));
692
738
  }
693
739
  }
740
+ // ---- R13 credential agent: a keyless terminal's key, loaded by execution over stdin, held only in a private ssh-agent ----
741
+ const LOAD_GRACE_MS = 120_000, MAX_KEY_BYTES = 64 * 1024;
742
+ function credentialDir() {
743
+ const dir = path.join(path.dirname(storePath()), "credentials");
744
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
745
+ return dir;
746
+ }
747
+ const credentialMetaFile = (ref) => path.join(credentialDir(), `${ref}.json`);
748
+ export const credentialPublicKeyFile = (ref) => path.join(credentialDir(), `${ref}.pub`);
749
+ function agentSocketPath(ref) {
750
+ // Short and stable across processes: macOS-style 104-byte sun_path limits also apply here.
751
+ const dir = path.join("/tmp", `aiterm-ka-${process.getuid?.() ?? 0}`);
752
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
753
+ const stat = fs.lstatSync(dir);
754
+ if (!stat.isDirectory() || stat.uid !== (process.getuid?.() ?? 0) || (stat.mode & 0o777) !== 0o700)
755
+ throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", "the credential agent directory is not a private directory of this user");
756
+ return path.join(dir, `${ref.slice(0, 8)}.sock`);
757
+ }
758
+ function agentEnv(socket) { return { ...sshEnvironment(), SSH_AUTH_SOCK: socket }; }
759
+ function agentAlive(socket) {
760
+ if (!fs.existsSync(socket))
761
+ return false;
762
+ const listed = spawnSync("ssh-add", ["-l"], { env: agentEnv(socket), stdio: ["ignore", "ignore", "ignore"], timeout: 10_000 });
763
+ return listed.status === 0; // 1 = alive but empty, which cannot authenticate either
764
+ }
765
+ export function readCredential(ref) {
766
+ try {
767
+ const meta = JSON.parse(fs.readFileSync(credentialMetaFile(ref), "utf8"));
768
+ return meta?.schema === "aiterm.credential-agent.v1" && meta.ref === ref ? meta : null;
769
+ }
770
+ catch {
771
+ return null;
772
+ }
773
+ }
774
+ function loadedCredentialRefs() {
775
+ try {
776
+ return fs.readdirSync(credentialDir()).filter(name => name.endsWith(".json")).map(name => name.slice(0, -5)).filter(ref => REF.test(ref));
777
+ }
778
+ catch {
779
+ return [];
780
+ }
781
+ }
782
+ export function releaseCredential(ref) {
783
+ const meta = readCredential(ref);
784
+ if (meta?.agent_pid)
785
+ try {
786
+ process.kill(meta.agent_pid);
787
+ }
788
+ catch { /* already gone */ }
789
+ for (const file of [credentialMetaFile(ref), credentialPublicKeyFile(ref), meta?.socket].filter((f) => !!f))
790
+ fs.rmSync(file, { force: true });
791
+ }
792
+ /** No terminal seat of this ref and no launch pending: the key leaves memory. */
793
+ function releaseIdleCredential(ref) {
794
+ const meta = readCredential(ref);
795
+ if (!meta || Object.values(readSeats()).includes(ref) || Date.now() - Date.parse(meta.loaded_at) < LOAD_GRACE_MS)
796
+ return;
797
+ releaseCredential(ref);
798
+ }
799
+ /** credential-load (R13): key bytes only from the caller's stdin; the receipt carries metadata only. */
800
+ export async function loadCredential(input, key) {
801
+ try {
802
+ if (input.purpose !== "ssh-key")
803
+ throw new RemoteTerminalError("CREDENTIAL_PURPOSE_UNSUPPORTED", "only --purpose ssh-key is loaded; a sudo secret is never loaded here");
804
+ if (!/^[A-Za-z0-9._-]{1,128}$/.test(input.terminalId))
805
+ throw new RemoteTerminalError("TERMINAL_ID_INVALID", "--terminal-id is required");
806
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(input.handle))
807
+ throw new RemoteTerminalError("CREDENTIAL_HANDLE_INVALID", "--handle must be a UUID");
808
+ const revision = Number(input.revision);
809
+ if (!/^[1-9]\d{0,15}$/.test(input.revision) || !Number.isSafeInteger(revision))
810
+ throw new RemoteTerminalError("CREDENTIAL_REVISION_INVALID", "--revision must be a positive integer");
811
+ const b = binding(input.ref);
812
+ if (b.key_file)
813
+ throw new RemoteTerminalError("TERMINAL_INVALID", "this terminal has a native key; a credential is loaded only for keyless terminals");
814
+ if (key.length === 0 || key.length > MAX_KEY_BYTES || !key.includes("PRIVATE KEY-----"))
815
+ throw new RemoteTerminalError("CREDENTIAL_INVALID", "stdin is not an OpenSSH private key");
816
+ const socket = agentSocketPath(b.ref);
817
+ let pid = readCredential(b.ref)?.agent_pid ?? null;
818
+ if (!agentAliveOrEmpty(socket)) {
819
+ fs.rmSync(socket, { force: true });
820
+ // Detached: the agent outlives this one-shot and holds the key in memory only.
821
+ const agent = spawn("ssh-agent", ["-D", "-a", socket], { env: sshEnvironment(), stdio: "ignore", detached: true });
822
+ agent.unref();
823
+ pid = agent.pid ?? null;
824
+ const deadline = Date.now() + 5000;
825
+ while (!fs.existsSync(socket)) {
826
+ if (Date.now() > deadline)
827
+ throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", "the credential agent did not start");
828
+ await new Promise(resolve => setTimeout(resolve, 50));
829
+ }
830
+ }
831
+ spawnSync("ssh-add", ["-D"], { env: agentEnv(socket), stdio: ["ignore", "ignore", "ignore"], timeout: 10_000 });
832
+ const added = spawnSync("ssh-add", ["-q", "-"], { env: agentEnv(socket), input: key, stdio: ["pipe", "ignore", "ignore"], timeout: 10_000 });
833
+ if (added.status !== 0)
834
+ throw new RemoteTerminalError("CREDENTIAL_INVALID", "the agent did not accept the key (passphrase-protected or malformed)");
835
+ const listed = spawnSync("ssh-add", ["-L"], { env: agentEnv(socket), encoding: "utf8", timeout: 10_000 });
836
+ const line = listed.stdout.trim().split("\n")[0]?.split(/\s+/).slice(0, 2).join(" ") ?? "";
837
+ const fingerprint = keyFingerprint(Buffer.from(line.split(" ")[1] ?? "", "base64"));
838
+ fs.writeFileSync(credentialPublicKeyFile(b.ref), `${line}\n`, { mode: 0o600 });
839
+ writeJson0600(credentialMetaFile(b.ref), { schema: "aiterm.credential-agent.v1", ref: b.ref, terminal_id: input.terminalId, handle: input.handle,
840
+ revision, fingerprint, agent_pid: pid, socket, loaded_at: new Date().toISOString() });
841
+ return { schema: "aiterm.credential-load.v1", accepted: true, ref: b.ref, terminal_id: input.terminalId, handle: input.handle, revision, fingerprint };
842
+ }
843
+ finally {
844
+ key.fill(0);
845
+ }
846
+ }
847
+ function agentAliveOrEmpty(socket) {
848
+ if (!fs.existsSync(socket))
849
+ return false;
850
+ const listed = spawnSync("ssh-add", ["-l"], { env: agentEnv(socket), stdio: ["ignore", "ignore", "ignore"], timeout: 10_000 });
851
+ return listed.status === 0 || listed.status === 1;
852
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.66.0",
3
+ "version": "0.67.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": [