aiterm-mcp 0.64.2 → 0.65.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,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.65.0] - 2026-11-09
11
+
12
+ - Bound remote terminal (`aiterm-remote-terminal`, docs/architecture/remote-terminal.md), first for macOS + Claude Code. One UID-private process per connection holds an Aiterm-held binding (`register`: target, existing key, known_hosts, host-key alias) and returns only public revisions (`status --ref`). `remote_terminal_open` checks the target and both revisions, loads the key into a per-connection private ssh-agent, connects with `ssh -F /dev/null`, strict host checking against the bound known_hosts, and sends private env values on the encrypted stdin. Then `remote_terminal_call` (seat tools, results unchanged), `remote_terminal_wait` (the terminal's `aiterm-wait`), `remote_terminal_transcript_read` (Claude JSONL lines only through the latest completed turn), `remote_terminal_command` (`claude --version`, official install, `claude update`), events `aiterm/remote-terminal-event` (`ready`/`lost`/`closed`). Host-key changes answer `HOST_KEY_MISMATCH` with "confirm the new host key"; `trust-confirm` writes a scanned key only when it equals the confirmed fingerprint.
13
+ - `aiterm-mcp --private-env-stdin` reads one private env line before MCP; those values reach a launch through `env_vars` and never enter `process.env`.
14
+ - POSIX launches no longer type inherited env values into the pane: they are written to a 0600 file that the launch line sources and deletes, so the pane log and screen keep only its path. Windows launches are unchanged.
15
+ - Claude `agent_launch` accepts `append_system_prompt` and `mcp_config`; both are kept in Aiterm's own state and passed as `--append-system-prompt-file` / `--mcp-config`, never written to the project or home config. Write secrets in `mcp_config` as `${ENV}` names.
16
+ - A missing or non-directory `cwd` is refused as `CWD_UNAVAILABLE:` before a session is created.
17
+ - A `tmux -V` start that fails for lack of memory or processes, or is killed by a signal, now answers `PTY_START_FAILED:` and is no longer recorded or reported as `AITERM.PTY_DEPENDENCY_UNAVAILABLE` (seen when the host ran out of memory on 2026-11-09).
18
+ - The Claude Stop hook records `transcript_path` and `transcript_offset` (end of the last complete line) in its `agent_done` event.
19
+
10
20
  ## [0.64.2] - 2026-11-08
11
21
 
12
22
  - Claude wait (`observeAgentDone` / `aiterm-wait`): a transcript API-error record whose CLI `error` field is `rate_limit` (for example the Fable limit record with no `apiErrorStatus`) is now `failure.category: "rate_limited"`, whatever its text. When Stop still fires, the wait looks at the turn's last assistant record up to the Stop time and returns that error instead of `done`. The hibernate exception for a rate-limited turn reads the same category.
@@ -3110,7 +3120,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3110
3120
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3111
3121
  provenance.
3112
3122
 
3113
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.64.2...HEAD
3123
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.65.0...HEAD
3124
+ [0.65.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.64.2...v0.65.0
3114
3125
  [0.64.2]: https://github.com/kitepon/aiterm-mcp/compare/v0.64.1...v0.64.2
3115
3126
  [0.64.1]: https://github.com/kitepon/aiterm-mcp/compare/v0.64.0...v0.64.1
3116
3127
  [0.64.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.18...v0.64.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.64.2** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.65.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.64.2** · 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.65.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
 
@@ -1,4 +1,5 @@
1
1
  import fs from "node:fs";
2
+ import { launchEnvValue } from "./private-env.js";
2
3
  import path from "node:path";
3
4
  import { createHash } from "node:crypto";
4
5
  import { z } from "zod";
@@ -155,7 +156,7 @@ export function captureAgentResumeTemplate(meta, effort, envNames, configuration
155
156
  return;
156
157
  writeAgentResumeTemplate(meta, { schema: "aiterm.agent-resume-template.v1", launch_id: meta.launch_id, kind: meta.kind,
157
158
  executable: meta.agent_executable, cwd: meta.cwd, configuration_root: configurationRoot, model: meta.model ?? null, reasoning_effort: effort,
158
- environment: Object.fromEntries([...new Set([...envNames, ...(meta.kind === "claude" ? ["CLAUDE_CONFIG_DIR"] : [])])].map(name => [name, env[name] ?? null])), state: "confirmed" });
159
+ environment: Object.fromEntries([...new Set([...envNames, ...(meta.kind === "claude" ? ["CLAUDE_CONFIG_DIR"] : [])])].map(name => [name, launchEnvValue(name, env) ?? null])), state: "confirmed" });
159
160
  }
160
161
  export function finishAgentResumeConfiguration(meta, before, model, effort) {
161
162
  const complete = !!model && !!effort;
@@ -3,7 +3,7 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import { AitermError } from "./errors.js";
5
5
  import { executionNativeBindingSchema } from "./execution-close.js";
6
- import { OPERATION_ID_RE, agentManagedClaudeSettingsPath, agentClaudeResultPath } from "./harnesses/claude.js";
6
+ import { OPERATION_ID_RE, agentManagedClaudeSettingsPath, agentClaudeResultPath, agentClaudeCallerPromptPath, agentClaudeCallerMcpPath } from "./harnesses/claude.js";
7
7
  import { resolveAndValidateGrokAuth } from "./harnesses/grok.js";
8
8
  import { assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, agentEventPath, agentLineageFields, LAUNCH_ID_RE, AGENT_LINEAGE_RE } from "./agent-shared.js";
9
9
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -159,6 +159,8 @@ export function loadAgentMetadata(name) {
159
159
  ...loadAgentLineageFields(m, true),
160
160
  node_platform: process.platform,
161
161
  claude_settings: expectedSettings,
162
+ ...(m.claude_caller_prompt_file === agentClaudeCallerPromptPath(name) ? { claude_caller_prompt_file: m.claude_caller_prompt_file } : {}),
163
+ ...(m.claude_caller_mcp_file === agentClaudeCallerMcpPath(name) ? { claude_caller_mcp_file: m.claude_caller_mcp_file } : {}),
162
164
  ...(m.claude_home === undefined ? {} : { claude_home: m.claude_home }),
163
165
  result_file: expectedResult,
164
166
  };
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import * as fs from "node:fs";
3
+ import { completedTranscriptOffset } from "./transcript-offset.js";
3
4
  import * as path from "node:path";
4
5
  import { currentUid as uid, runtimeStateBase } from "./state-root.js";
5
6
  import { createHash, randomBytes } from "node:crypto";
@@ -183,6 +184,9 @@ async function main() {
183
184
  const seatConversation = seatVendorSessionId(agents, session, launchId);
184
185
  if (seatConversation !== null && seatConversation !== payload.session_id)
185
186
  noop();
187
+ // The completed prefix of the native transcript (remote-terminal.md, Kiro C7): readers never pass this offset.
188
+ const transcript = typeof payload.transcript_path === "string" && path.isAbsolute(payload.transcript_path)
189
+ ? completedTranscriptOffset(payload.transcript_path) : null;
186
190
  const text = payload.last_assistant_message;
187
191
  const resultBytes = Buffer.byteLength(text, "utf8");
188
192
  if (resultBytes > MAX_RESULT_BYTES)
@@ -216,6 +220,7 @@ async function main() {
216
220
  stop_hook_active: !!payload.stop_hook_active,
217
221
  result_digest: resultDigest,
218
222
  result_bytes: resultBytes,
223
+ ...(transcript ? { transcript_path: transcript.path, transcript_offset: transcript.offset } : {}),
219
224
  at: endedAt,
220
225
  });
221
226
  try {
package/dist/core.js CHANGED
@@ -25,6 +25,7 @@ import { spawnSync } from "node:child_process";
25
25
  import * as fs from "node:fs";
26
26
  import * as path from "node:path";
27
27
  import { createHash, randomBytes } from "node:crypto";
28
+ import { launchEnvValue } from "./private-env.js";
28
29
  import { fileURLToPath } from "node:url";
29
30
  import * as rtk from "./rtk.js";
30
31
  import { manageClaudeAgentGoal, manageGrokAgentGoal } from "./agent-goal-native-result.js";
@@ -64,7 +65,7 @@ import { readFileOrNull, restoreJsonSetting, withUserConfigLock, restoreUserDefa
64
65
  import { isDeepStrictEqual } from "node:util";
65
66
  import { grokAuthPlan, grokAuthStatus, grokAuthPane, GROK_MODEL_DEFAULTS, realGrokHome, resolveAndValidateGrokAuth, assertGrokModelAvailable, grokModelChoices, grokModelFromFooter, grokFooterModelName, grokModelDefaultsFromBody, restoreGrokModelDefaults, grokEventsTranscript, grokSessionDirectory, latestGrokCompletion, grokTurnSettled, observeGrokDone, buildGrokAgentCmd, grokAgentArgv, grokLaunchNote, grokEnvTokens, grokEnvEntries, grokTuiReady, grokPaneObservation, GROK_INTERRUPT_KEY, grokRateLimitDialog, grokPromptAwaitingAccept, grokUnacceptedPromptRestored, grokStartupAction, grokFooterHasConfiguration, grokTranscriptText, createGrokAgentMetadata, } from "./harnesses/grok.js";
66
67
  import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexCompletedTurnId, codexWorkingResumeConfiguration, captureCodexRecoveryProof, captureCodexResumeProof, readCodexResumeProof, codexResumeProofDigest, codexRootTranscript, codexRunningTurn, codexInterruptionRecord, observeCodexDone, buildCodexAgentCmd, codexAgentArgv, codexResumeArgv, codexLaunchNote, codexPaneObservation, CODEX_INTERRUPT_KEY, codexHelperProcess, codexRateLimitModelSwitchDialog, codexApprovalDialog, codexStartupAction, codexModelChoice, codexEffortChoice, codexMoreReasoningChoice, codexTranscriptText, createCodexAgentMetadata, codexModelChoices, codexFastCommandOffered, codexFooterShowsFast, codexServiceTierNotices, restoreCodexDefaults, restoreCodexDefaultInFile, } from "./harnesses/codex.js";
67
- import { claudeAuthPlan, claudeAuthStatus, claudeAuthPane, OPERATION_ID_RE, CLAUDE_RESULT_MAX_BYTES, CLAUDE_EFFORTS, agentClaudeOperationPath, agentClaudeApprovalReceiptPath, agentClaudeDispatchReceiptPath, validateOperationId, readClaudeResultText, assertClaudeAuthenticationReady, claudeModelChoices, claudeConfigDir, claudeProjectSlug, claudeFastIndicatorShown, claudeFastResult, buildClaudeAgentCmd, claudeAgentArgv, claudeResumeArgv, claudeLaunchNote, claudePaneObservation, CLAUDE_INTERRUPT_KEY, claudeUsageLimit, claudeLiveSelectMenu, claudeStartupAction, createClaudeAgentMetadata, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, claudeApiErrorEndingTurn, claudeFailureCategory, } from "./harnesses/claude.js";
68
+ import { claudeAuthPlan, claudeAuthStatus, claudeAuthPane, OPERATION_ID_RE, CLAUDE_RESULT_MAX_BYTES, CLAUDE_EFFORTS, agentClaudeOperationPath, agentClaudeApprovalReceiptPath, agentClaudeDispatchReceiptPath, validateOperationId, readClaudeResultText, assertClaudeAuthenticationReady, claudeModelChoices, claudeConfigDir, claudeProjectSlug, claudeFastIndicatorShown, claudeFastResult, buildClaudeAgentCmd, claudeAgentArgv, claudeResumeArgv, claudeLaunchNote, claudePaneObservation, CLAUDE_INTERRUPT_KEY, claudeUsageLimit, claudeLiveSelectMenu, claudeStartupAction, createClaudeAgentMetadata, writeClaudeCallerFiles, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, claudeApiErrorEndingTurn, claudeFailureCategory, } from "./harnesses/claude.js";
68
69
  import { cursorAuthPlan, cursorAuthStatus, cursorAuthPane, bindCursorTranscriptSession, cursorTurnBoundary, latestCursorCompletion, cursorTranscript, cursorTranscriptSessionId, observeCursorDone, cursorTranscriptText, assertCursorAuthenticationReady, assertCursorModelAvailable, cursorModelChoices, cursorModelIsFastVariant, cursorFastParameter, cursorHeaderShowsFast, cursorPickerView, cursorEffortSelected, cursorParameterRows, cursorUserConfigPath, CURSOR_DEFAULT_MODEL_KEYS, realCursorHome, buildCursorAgentCmd, cursorAgentArgv, cursorPromptWithLineage, createCursorAgentMetadata, cursorLaunchNote, cursorEffortNavigation, cursorTuiReady, cursorPaneObservation, CURSOR_INTERRUPT_KEY, cursorPromptHooksRunning, cursorUsageLimit, CURSOR_SUBMIT_SEQUENCE, validateCursorModelEffort, } from "./harnesses/cursor.js";
69
70
  import { interimFromNow, readInterimWords, recordInterimBoundary } from "./interim-words.js";
70
71
  import { codexSeatTurn, grokSteerAcceptance, observeSteerDone, readSteerEntry, recordSteer } from "./steer-follow.js";
@@ -381,6 +382,9 @@ function cleanupAgentState(name) {
381
382
  f.endsWith(".wait.lock") ||
382
383
  f.endsWith(".claude-settings.json") ||
383
384
  f.endsWith(".claude-mcp.json") ||
385
+ f.endsWith(".claude-caller-prompt.md") ||
386
+ f.endsWith(".claude-caller-mcp.json") ||
387
+ f.endsWith(".launch-env") ||
384
388
  f.endsWith(".claude-result.json") ||
385
389
  f.endsWith(".cursor-result.json") ||
386
390
  f.endsWith(".antigravity-session.json") ||
@@ -687,8 +691,8 @@ function openSessionInternal(name, shell, envVars, preserveAgentState) {
687
691
  throw new AitermError(`session '${nm}' は既に存在します(list で確認)`, 2);
688
692
  }
689
693
  else {
690
- const environment = [...banner, ...envVars.filter(key => key !== "AITERM_SESSION_ID" && process.env[key] !== undefined)
691
- .map(key => `${key}=${process.env[key]}`), `AITERM_SESSION_ID=${nm}`];
694
+ const environment = [...banner, ...envVars.filter(key => key !== "AITERM_SESSION_ID" && launchEnvValue(key) !== undefined)
695
+ .map(key => `${key}=${launchEnvValue(key)}`), `AITERM_SESSION_ID=${nm}`];
692
696
  const launch = sessionEnvironmentLaunch(shell, environment);
693
697
  const r = tmuxNewSession(true, nm, launch, environment.map(entry => entry.slice(0, entry.indexOf("="))));
694
698
  if (r.code === 0) {
@@ -6834,6 +6838,10 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot) {
6834
6838
  next.model = recipe.model;
6835
6839
  next.fast = false;
6836
6840
  next.agent_executable = recipe.executable;
6841
+ if (previous.claude_caller_prompt_file)
6842
+ next.claude_caller_prompt_file = previous.claude_caller_prompt_file;
6843
+ if (previous.claude_caller_mcp_file)
6844
+ next.claude_caller_mcp_file = previous.claude_caller_mcp_file;
6837
6845
  if (isWin)
6838
6846
  next.windows_launch_exit_tracked = true;
6839
6847
  if (next.kind === "claude")
@@ -7466,7 +7474,7 @@ function agentVendorSessionEnv(meta) {
7466
7474
  */
7467
7475
  function agentEnvEntries(meta, sid, envVars = []) {
7468
7476
  const inherited = envVars.flatMap((name) => {
7469
- const value = process.env[name];
7477
+ const value = launchEnvValue(name);
7470
7478
  return value === undefined ? [] : [[name, value]];
7471
7479
  });
7472
7480
  if (!meta)
@@ -7494,6 +7502,15 @@ function agentEnvPrefix(meta, sid, envVars = []) {
7494
7502
  ];
7495
7503
  return tokens.length ? tokens.join(" ") + " " : "";
7496
7504
  }
7505
+ /** Inherited values are written to a 0600 file the launch line sources and deletes, so the typed
7506
+ * line and the pane log carry only its path (remote-terminal.md R7). Identity names stay inline. */
7507
+ function launchEnvSource(sid, entries) {
7508
+ if (entries.length === 0)
7509
+ return "";
7510
+ const file = path.join(agentsDir(), `${sid}.${randomBytes(8).toString("hex")}.launch-env`);
7511
+ fs.writeFileSync(file, entries.map(([name, value]) => `export ${name}=${shq(value)}\n`).join(""), { mode: 0o600, flag: "wx" });
7512
+ return `. ${shq(file)} && rm -f ${shq(file)} && `;
7513
+ }
7497
7514
  function buildAgentLaunchNote(kind, model, effort, meta) {
7498
7515
  if (kind === "claude")
7499
7516
  return claudeLaunchNote(model, effort, meta);
@@ -7622,7 +7639,7 @@ function prepareAgentLaunch(kind, opts = {}) {
7622
7639
  st = null;
7623
7640
  }
7624
7641
  if (!st || !st.isDirectory()) {
7625
- throw new AitermError(`cwd '${opts.cwd}' がディレクトリとして存在しません`, 2);
7642
+ throw new AitermError(`CWD_UNAVAILABLE: cwd '${opts.cwd}' がディレクトリとして存在しません`, 2);
7626
7643
  }
7627
7644
  cwd = opts.cwd;
7628
7645
  }
@@ -7728,6 +7745,8 @@ function prepareAgentLaunch(kind, opts = {}) {
7728
7745
  if (hasExecutionCreationScope())
7729
7746
  meta.execution_native = executionCreatedNativeBinding(sid);
7730
7747
  meta.agent_executable = bin;
7748
+ if (meta.kind === "claude")
7749
+ writeClaudeCallerFiles(meta, opts.append_system_prompt ?? null, opts.mcp_config ?? null);
7731
7750
  if (isWin && ["claude", "codex", "grok", "antigravity"].includes(kind))
7732
7751
  meta.windows_launch_exit_tracked = true;
7733
7752
  if (kind === "claude" || kind === "codex")
@@ -7774,7 +7793,7 @@ function prepareAgentLaunch(kind, opts = {}) {
7774
7793
  else {
7775
7794
  const cmd = buildAgentCmd(kind, binForCmd, model, effort, opts.prompt ?? null, meta, cursorFast);
7776
7795
  const envPrefix = (!claudeRoot ? "" : claudeRoot.selector === null ? "unset CLAUDE_CONFIG_DIR && "
7777
- : `CLAUDE_CONFIG_DIR=${shq(claudeRoot.selector)} `) + agentEnvPrefix(meta, sid, envVars);
7796
+ : `CLAUDE_CONFIG_DIR=${shq(claudeRoot.selector)} `) + launchEnvSource(sid, agentEnvEntries(null, sid, envVars)) + agentEnvPrefix(meta, sid);
7778
7797
  const command = cwdForCmd ? `cd ${shq(cwdForCmd)} && ${envPrefix}${cmd}` : `${envPrefix}${cmd}`;
7779
7798
  // このpaneのbashはAitermが自分で選んだ。sub-agent instructionのLFを含む起動commandは、
7780
7799
  // 利用者のshell送信と同じknown-shell適合で1物理行にしてから打つ(sanitizeはしない)。
@@ -7994,6 +8013,8 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
7994
8013
  fast_state: fastPlan.state,
7995
8014
  base_model: requestedModel,
7996
8015
  claude_root: claudeRoot,
8016
+ append_system_prompt: opts.append_system_prompt ?? null,
8017
+ mcp_config: opts.mcp_config ?? null,
7997
8018
  };
7998
8019
  // GrokとCursorは、起動の --model の値を利用者の既定へ書く(Cursorは版による)。起動の前後で、直前の値へ戻す。
7999
8020
  const launch = () => {
@@ -21,6 +21,34 @@ export function agentManagedClaudeSettingsPath(name, launchId) {
21
21
  throw new AitermError(`launch_id が不正です: ${launchId}`, 2);
22
22
  return path.join(agentsDir(), `${name}.${launchId}.claude-settings.json`);
23
23
  }
24
+ export function agentClaudeCallerPromptPath(name) {
25
+ assertSessionName(name);
26
+ return path.join(agentsDir(), `${name}.claude-caller-prompt.md`);
27
+ }
28
+ export function agentClaudeCallerMcpPath(name) {
29
+ assertSessionName(name);
30
+ return path.join(agentsDir(), `${name}.claude-caller-mcp.json`);
31
+ }
32
+ const CALLER_PROMPT_MAX = 512 * 1024;
33
+ /** Keep the caller's launch instructions and MCP servers beside the seat's own state; argv carries only the paths. */
34
+ export function writeClaudeCallerFiles(meta, prompt, mcp) {
35
+ if (prompt !== null) {
36
+ if (!prompt.trim() || Buffer.byteLength(prompt, "utf8") > CALLER_PROMPT_MAX)
37
+ throw new AitermError("append_system_prompt must be non-empty and at most 512 KiB", 2);
38
+ const file = agentClaudeCallerPromptPath(meta.aiterm_session);
39
+ fs.writeFileSync(file, prompt, { mode: 0o600 });
40
+ fs.chmodSync(file, 0o600);
41
+ meta.claude_caller_prompt_file = file;
42
+ }
43
+ if (mcp !== null) {
44
+ const servers = mcp.mcpServers;
45
+ if (Object.keys(mcp).some(key => key !== "mcpServers") || !servers || typeof servers !== "object" || Array.isArray(servers))
46
+ throw new AitermError("mcp_config must be {mcpServers: {...}}", 2);
47
+ const file = agentClaudeCallerMcpPath(meta.aiterm_session);
48
+ writeJson0600(file, mcp);
49
+ meta.claude_caller_mcp_file = file;
50
+ }
51
+ }
24
52
  export function agentClaudeResultPath(name, launchId) {
25
53
  assertSessionName(name);
26
54
  if (!LAUNCH_ID_RE.test(launchId))
@@ -311,6 +339,10 @@ export function claudeAgentArgv(bin, model, effort, prompt, meta) {
311
339
  const parts = [bin];
312
340
  if (meta?.kind === "claude") {
313
341
  parts.push("--dangerously-skip-permissions", "--setting-sources", "user,project,local", "--settings", meta.claude_settings ?? "", "--session-id", meta.vendor_session_id ?? "", "--append-system-prompt", subagentInstruction(meta, CLAUDE_DELIVERY_NOTES));
342
+ if (meta.claude_caller_prompt_file)
343
+ parts.push("--append-system-prompt-file", meta.claude_caller_prompt_file);
344
+ if (meta.claude_caller_mcp_file)
345
+ parts.push("--mcp-config", meta.claude_caller_mcp_file);
314
346
  }
315
347
  if (model)
316
348
  parts.push("--model", model);
@@ -330,7 +362,7 @@ export function claudeResumeArgv(bin, model, effort, meta) {
330
362
  }
331
363
  export function buildClaudeAgentCmd(bin, model, effort, prompt, meta) {
332
364
  const argv = claudeAgentArgv(bin, model, effort, prompt, meta);
333
- const values = new Set(["--setting-sources", "--settings", "--session-id", "--append-system-prompt", "--model", "--effort"]);
365
+ const values = new Set(["--setting-sources", "--settings", "--session-id", "--append-system-prompt", "--append-system-prompt-file", "--mcp-config", "--model", "--effort"]);
334
366
  return argv.map((arg, index) => index === 0 || values.has(argv[index - 1]) || (prompt && index === argv.length - 1)
335
367
  ? shq(arg) : arg).join(" ");
336
368
  }
package/dist/index.js CHANGED
@@ -15,6 +15,7 @@ import { AitermError, AgentAuthenticationPreflightError, AgentResumeUnavailableE
15
15
  */
16
16
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
17
17
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
18
+ import { readPrivateEnvLine, setPrivateEnv } from "./private-env.js";
18
19
  import { CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
19
20
  import { z } from "zod";
20
21
  import { agentModelsResult } from "./model-catalog.js";
@@ -1216,7 +1217,7 @@ export function createAitermServer(options = {}) {
1216
1217
  }
1217
1218
  async function launchAgent(kind, args, extra) {
1218
1219
  const supportsWriteScope = kind !== "claude";
1219
- const { prompt, image, throughline_source_session, throughline_supplement_file, model, reasoning_effort, fast, env_vars, cwd, session_name, launch_operation_id, write_scope, trust_project, require_existing_resume, configuration_root } = args;
1220
+ const { prompt, image, throughline_source_session, throughline_supplement_file, model, reasoning_effort, fast, env_vars, cwd, session_name, launch_operation_id, write_scope, trust_project, require_existing_resume, configuration_root, append_system_prompt, mcp_config } = args;
1220
1221
  let delivery = null;
1221
1222
  try {
1222
1223
  if (!supportsWriteScope && write_scope !== undefined) {
@@ -1244,6 +1245,8 @@ export function createAitermServer(options = {}) {
1244
1245
  session_name: session_name ?? undefined,
1245
1246
  require_existing_resume,
1246
1247
  configuration_root,
1248
+ append_system_prompt,
1249
+ mcp_config,
1247
1250
  launch_operation_id: launch_operation_id ?? undefined,
1248
1251
  ...(supportsWriteScope ? { write_scope } : {}),
1249
1252
  });
@@ -1343,6 +1346,10 @@ export function createAitermServer(options = {}) {
1343
1346
  trust_project: z.boolean().optional().describe("対象projectを信頼し、既知のworkspace・project hooks・MCP初期同意を起動中に進める"),
1344
1347
  cwd: z.string().nullish().describe("作業ディレクトリ(対象リポのルート等・任意)"),
1345
1348
  session_name: z.string().nullish().describe("セッション名(省略で自動採番)"),
1349
+ ...(kind === "claude" ? {
1350
+ append_system_prompt: z.string().min(1).optional().describe("Launch instructions added to the system prompt; kept in Aiterm state, not in the project or home"),
1351
+ mcp_config: z.object({ mcpServers: z.record(z.string(), z.unknown()) }).strict().optional().describe("Extra MCP servers for this seat; write secrets as ${ENV} names given in env_vars"),
1352
+ } : {}),
1346
1353
  ...writeScopeInputSchema,
1347
1354
  ...correlatedLaunchSchema,
1348
1355
  },
@@ -1487,9 +1494,16 @@ export function createAitermServer(options = {}) {
1487
1494
  return server;
1488
1495
  }
1489
1496
  async function main() {
1497
+ // A bound remote terminal sends its private values first (remote-terminal.md R5); never through argv or env.
1498
+ const privateLine = process.argv.includes("--private-env-stdin");
1499
+ if (privateLine)
1500
+ setPrivateEnv(await readPrivateEnvLine(process.stdin));
1490
1501
  const server = createAitermServer();
1491
1502
  const transport = new StdioServerTransport();
1492
1503
  await server.connect(transport);
1504
+ // The private line reader paused stdin; the transport's listener is attached now, so nothing is lost.
1505
+ if (privateLine)
1506
+ process.stdin.resume();
1493
1507
  // 受け口がまだ受け取っていない実行時エラーがあれば、別processで送る(明示して有効にした端末だけ。既定では何も起動しない)。
1494
1508
  triggerRuntimeErrorReport();
1495
1509
  }
@@ -0,0 +1,75 @@
1
+ import { AitermError } from "./errors.js";
2
+ export const PRIVATE_ENV_SCHEMA = "aiterm.private-env.v1";
3
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
4
+ const MAX_LINE = 256 * 1024;
5
+ const values = new Map();
6
+ export function parsePrivateEnvLine(line) {
7
+ let parsed;
8
+ try {
9
+ parsed = JSON.parse(line);
10
+ }
11
+ catch {
12
+ throw new AitermError("PRIVATE_ENV_INVALID: the private env line is not JSON", 2);
13
+ }
14
+ const env = parsed;
15
+ if (!env || env.schema !== PRIVATE_ENV_SCHEMA || typeof env.env !== "object" || env.env === null || Array.isArray(env.env))
16
+ throw new AitermError("PRIVATE_ENV_INVALID: unexpected private env schema", 2);
17
+ const out = {};
18
+ for (const [name, value] of Object.entries(env.env)) {
19
+ if (!NAME.test(name) || typeof value !== "string" || value.includes("\0"))
20
+ throw new AitermError("PRIVATE_ENV_INVALID: invalid private env entry", 2);
21
+ out[name] = value;
22
+ }
23
+ return out;
24
+ }
25
+ export function setPrivateEnv(env) {
26
+ for (const [name, value] of Object.entries(env))
27
+ values.set(name, value);
28
+ }
29
+ /** The value a launch uses for an env_vars name: the private value first, then this process's env. */
30
+ export function launchEnvValue(name, env = process.env) {
31
+ return values.get(name) ?? env[name];
32
+ }
33
+ /** Read exactly one line before the MCP stream starts and give the rest back to the stream. */
34
+ export function readPrivateEnvLine(stream) {
35
+ return new Promise((resolve, reject) => {
36
+ let buffered = Buffer.alloc(0);
37
+ const finish = (error, env) => {
38
+ stream.off("data", onData);
39
+ stream.off("end", onEnd);
40
+ stream.off("error", onError);
41
+ stream.pause();
42
+ if (error)
43
+ reject(error);
44
+ else
45
+ resolve(env);
46
+ };
47
+ const onData = (chunk) => {
48
+ buffered = Buffer.concat([buffered, chunk]);
49
+ const at = buffered.indexOf(0x0a);
50
+ if (at < 0) {
51
+ if (buffered.length > MAX_LINE)
52
+ finish(new AitermError("PRIVATE_ENV_INVALID: the private env line is too long", 2));
53
+ return;
54
+ }
55
+ const rest = buffered.subarray(at + 1);
56
+ let env;
57
+ try {
58
+ env = parsePrivateEnvLine(buffered.subarray(0, at).toString("utf8"));
59
+ }
60
+ catch (error) {
61
+ finish(error);
62
+ return;
63
+ }
64
+ // Detach first: unshift on a flowing stream emits synchronously and would re-enter this handler.
65
+ finish(null, env);
66
+ if (rest.length)
67
+ stream.unshift(rest);
68
+ };
69
+ const onEnd = () => finish(new AitermError("PRIVATE_ENV_INVALID: stdin ended before the private env line", 2));
70
+ const onError = (error) => finish(error);
71
+ stream.on("data", onData);
72
+ stream.on("end", onEnd);
73
+ stream.on("error", onError);
74
+ });
75
+ }
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env node
2
+ // aiterm-remote-terminal (remote-terminal.md). Run as the UID that can read the terminal key.
3
+ // status --ref R | register ... | trust-confirm --ref R --fingerprint F (one JSON line; exit 0 result, 2 error)
4
+ // serve stdio MCP for one bound connection, spawned by BellTeam terminals
5
+ // transcript-read --session S [--cursor-session ID --offset N] [--max-bytes N] (runs on the terminal)
6
+ import { realpathSync } from "node:fs";
7
+ import { fileURLToPath } from "node:url";
8
+ import { createRequire } from "node:module";
9
+ import { z } from "zod";
10
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
11
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
12
+ import { RemoteTerminalConnection, RemoteTerminalError, bindingStatus, confirmHostKey, registerBinding } from "./remote-terminal.js";
13
+ import { readCompletedTranscript } from "./transcript-read.js";
14
+ const pkg = createRequire(import.meta.url)("../package.json");
15
+ function option(args, name) {
16
+ const at = args.indexOf(name);
17
+ return at >= 0 ? args[at + 1] : undefined;
18
+ }
19
+ function errorDto(error, schema) {
20
+ if (error instanceof RemoteTerminalError)
21
+ return { schema, code: error.code, message: error.message, ...(error.action ? { action: error.action } : {}) };
22
+ const message = error instanceof Error ? error.message : String(error);
23
+ const code = /^([A-Z][A-Z0-9_]+):/.exec(message)?.[1] ?? "AITERM_FAILED";
24
+ return { schema, code, message };
25
+ }
26
+ function oneShot(run, errorSchema) {
27
+ try {
28
+ process.stdout.write(`${JSON.stringify(run())}\n`);
29
+ process.exit(0);
30
+ }
31
+ catch (error) {
32
+ process.stdout.write(`${JSON.stringify(errorDto(error, errorSchema))}\n`);
33
+ process.exit(2);
34
+ }
35
+ }
36
+ function serve() {
37
+ const server = new McpServer({ name: "aiterm-remote-terminal", version: pkg.version });
38
+ let connection = null;
39
+ const ok = (value) => ({ content: [{ type: "text", text: JSON.stringify(value) }], structuredContent: value });
40
+ const fail = (error) => ({ content: [{ type: "text", text: JSON.stringify(errorDto(error, "aiterm.remote-terminal-error.v1")) }], isError: true });
41
+ const bound = () => { if (!connection)
42
+ throw new RemoteTerminalError("NOT_OPEN", "remote_terminal_open first"); return connection; };
43
+ const guarded = (fn) => async (args) => { try {
44
+ return ok(await fn(args));
45
+ }
46
+ catch (error) {
47
+ return fail(error);
48
+ } };
49
+ server.registerTool("remote_terminal_status", { description: "Public status of a terminal binding", inputSchema: { ref: z.string() } }, guarded(({ ref }) => bindingStatus(ref)));
50
+ server.registerTool("remote_terminal_open", {
51
+ description: "Open the bound connection for this process",
52
+ 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() },
54
+ }, guarded(async (args) => {
55
+ if (connection)
56
+ throw new RemoteTerminalError("ALREADY_OPEN", "this process already holds a connection");
57
+ connection = await RemoteTerminalConnection.open(args);
58
+ connection.on("event", event => {
59
+ server.server.notification({ method: "aiterm/remote-terminal-event", params: event }).catch(() => { });
60
+ });
61
+ return { opened: true, remoteVersion: connection.remoteVersion };
62
+ }));
63
+ server.registerTool("remote_terminal_call", {
64
+ description: "Call a seat tool on the terminal's Aiterm",
65
+ inputSchema: { name: z.string(), args: z.record(z.string(), z.unknown()), timeoutMs: z.number().int().positive().optional(),
66
+ private: z.object({ appendSystemPrompt: z.string().optional(), mcpConfig: z.record(z.string(), z.unknown()).optional() }).strict().optional() },
67
+ }, async ({ name, args, timeoutMs, private: priv }) => {
68
+ // The terminal's tool result passes through unchanged.
69
+ try {
70
+ return await bound().call(name, args, { private: priv, timeoutMs });
71
+ }
72
+ catch (error) {
73
+ return fail(error);
74
+ }
75
+ });
76
+ server.registerTool("remote_terminal_transcript_read", {
77
+ description: "Completed native transcript lines from a cursor",
78
+ inputSchema: { sessionName: z.string(), cursor: z.object({ claudeSessionId: z.string(), offset: z.number().int() }).strict().nullable(), maxBytes: z.number().int().positive().optional() },
79
+ }, guarded(args => bound().transcriptRead(args)));
80
+ server.registerTool("remote_terminal_wait", {
81
+ description: "Run the terminal's aiterm-wait for a receipt's wait_process; cancel the request to stop",
82
+ inputSchema: { waitProcess: z.object({ executable: z.string().optional(), args: z.array(z.string()) }).passthrough() },
83
+ }, async ({ waitProcess }, extra) => {
84
+ try {
85
+ return ok(await bound().wait(waitProcess, extra.signal));
86
+ }
87
+ catch (error) {
88
+ return fail(error);
89
+ }
90
+ });
91
+ server.registerTool("remote_terminal_command", {
92
+ description: "Fixed Claude Code setup operation on the terminal",
93
+ inputSchema: { op: z.enum(["claude_version", "claude_install", "claude_update"]) },
94
+ }, guarded(({ op }) => bound().command(op)));
95
+ 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; }));
96
+ server.connect(new StdioServerTransport()).catch(error => { console.error("aiterm-remote-terminal fatal:", error); process.exit(1); });
97
+ }
98
+ export function main(args) {
99
+ const [command, ...rest] = args;
100
+ if (command === "serve")
101
+ return serve();
102
+ if (command === "status")
103
+ return oneShot(() => bindingStatus(option(rest, "--ref") ?? ""), "aiterm.remote-binding-error.v1");
104
+ if (command === "register")
105
+ return oneShot(() => registerBinding({
106
+ 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,
108
+ }), "aiterm.remote-binding-error.v1");
109
+ if (command === "trust-confirm")
110
+ return oneShot(() => confirmHostKey(option(rest, "--ref") ?? "", option(rest, "--fingerprint") ?? ""), "aiterm.remote-binding-error.v1");
111
+ if (command === "transcript-read")
112
+ return oneShot(() => {
113
+ const id = option(rest, "--cursor-session"), offset = option(rest, "--offset"), max = option(rest, "--max-bytes");
114
+ return readCompletedTranscript(option(rest, "--session") ?? "", id ? { claudeSessionId: id, offset: Number(offset) } : null, max ? Number(max) : undefined);
115
+ }, "aiterm.transcript-read-error.v1");
116
+ process.stderr.write("usage: aiterm-remote-terminal serve|status|register|trust-confirm|transcript-read\n");
117
+ process.exit(64);
118
+ }
119
+ let entry = false;
120
+ try {
121
+ entry = !!process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
122
+ }
123
+ catch { /* imported */ }
124
+ if (entry)
125
+ main(process.argv.slice(2));
@@ -0,0 +1,433 @@
1
+ // Bound remote terminal (remote-terminal.md). Runs only as the UID that can read the terminal key:
2
+ // the key is loaded into a per-connection private ssh-agent and never leaves this process.
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import { EventEmitter } from "node:events";
5
+ import * as fs from "node:fs";
6
+ import * as os from "node:os";
7
+ import * as path from "node:path";
8
+ import { createHash, randomUUID } from "node:crypto";
9
+ import { createRequire } from "node:module";
10
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
11
+ import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
12
+ import { writeJson0600 } from "./agent-shared.js";
13
+ import { posixCommand } from "./remote.js";
14
+ import { PRIVATE_ENV_SCHEMA } from "./private-env.js";
15
+ const pkg = createRequire(import.meta.url)("../package.json");
16
+ export class RemoteTerminalError extends Error {
17
+ code;
18
+ action;
19
+ constructor(code, message, action) {
20
+ super(`${code}: ${message}`);
21
+ this.code = code;
22
+ this.action = action;
23
+ }
24
+ }
25
+ const REF = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
26
+ const HOST = /^(?!-)[A-Za-z0-9._:\[\]-]{1,255}$/;
27
+ const USER = /^(?!-)[A-Za-z0-9._-]{1,64}$/;
28
+ const FINGERPRINT = /^SHA256:[A-Za-z0-9+/]{43}$/;
29
+ export function validTarget(value) {
30
+ const t = value;
31
+ if (!t || typeof t !== "object" || !HOST.test(String(t.host)) || !USER.test(String(t.user))
32
+ || !Number.isInteger(t.port) || t.port < 1 || t.port > 65535 || Object.keys(t).some(key => !["host", "user", "port"].includes(key)))
33
+ throw new RemoteTerminalError("TARGET_INVALID", "target must be {host, user, port}");
34
+ return { host: t.host, user: t.user, port: t.port };
35
+ }
36
+ // ---- binding store (UID-private) ----
37
+ // Durable and independent of the caller's env (the state root follows AITERM_STATE_BASE/TMPDIR, a binding must not).
38
+ export function storePath() {
39
+ const dir = path.join(os.homedir(), ".config", "aiterm");
40
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
41
+ return path.join(dir, "remote-bindings.json");
42
+ }
43
+ function readStore() {
44
+ let text;
45
+ try {
46
+ text = fs.readFileSync(storePath(), "utf8");
47
+ }
48
+ catch (error) {
49
+ if (error.code === "ENOENT")
50
+ return [];
51
+ throw new RemoteTerminalError("BINDING_STORE_UNREADABLE", "the binding store cannot be read");
52
+ }
53
+ try {
54
+ const parsed = JSON.parse(text);
55
+ if (parsed?.schema !== "aiterm.remote-bindings.v1" || !Array.isArray(parsed.bindings))
56
+ throw new Error("schema");
57
+ return parsed.bindings;
58
+ }
59
+ catch {
60
+ throw new RemoteTerminalError("BINDING_STORE_UNREADABLE", "the binding store is not valid");
61
+ }
62
+ }
63
+ function binding(ref) {
64
+ if (!REF.test(ref))
65
+ throw new RemoteTerminalError("REF_INVALID", "ref must be a UUID");
66
+ const found = readStore().find(item => item.ref === ref);
67
+ if (!found)
68
+ throw new RemoteTerminalError("BINDING_UNKNOWN", "no binding has this ref");
69
+ return found;
70
+ }
71
+ export function registerBinding(input) {
72
+ const target = validTarget(input.target);
73
+ for (const file of [input.keyFile, input.knownHostsFile]) {
74
+ if (!path.isAbsolute(file))
75
+ throw new RemoteTerminalError("PATH_INVALID", "key and known_hosts paths must be absolute");
76
+ }
77
+ if (input.hostKeyAlias != null && !HOST.test(input.hostKeyAlias))
78
+ throw new RemoteTerminalError("ALIAS_INVALID", "host key alias is not a host name");
79
+ const bindings = readStore();
80
+ const next = { ref: randomUUID(), target, key_file: input.keyFile, known_hosts_file: input.knownHostsFile,
81
+ host_key_alias: input.hostKeyAlias ?? null, created_at: new Date().toISOString() };
82
+ writeJson0600(storePath(), { schema: "aiterm.remote-bindings.v1", bindings: [...bindings, next] });
83
+ return bindingStatus(next.ref);
84
+ }
85
+ function keyFingerprint(blob) {
86
+ return `SHA256:${createHash("sha256").update(blob).digest("base64").replace(/=+$/, "")}`;
87
+ }
88
+ function publicKey(keyFile) {
89
+ if (!fs.existsSync(keyFile))
90
+ return { reason: "KEY_MISSING" };
91
+ // Empty passphrase only: a passphrase-protected key cannot be used without a prompt.
92
+ const result = spawnSync("ssh-keygen", ["-y", "-P", "", "-f", keyFile], { encoding: "utf8", timeout: 10_000 });
93
+ if (result.status !== 0)
94
+ return { reason: /passphrase|incorrect/i.test(result.stderr ?? "") ? "KEY_PASSPHRASE_REQUIRED" : "KEY_UNREADABLE" };
95
+ const fields = result.stdout.trim().split(/\s+/);
96
+ return { line: `${fields[0]} ${fields[1]}`, blob: Buffer.from(fields[1] ?? "", "base64") };
97
+ }
98
+ function knownHostName(b) {
99
+ return b.host_key_alias ?? (b.target.port === 22 ? b.target.host : `[${b.target.host}]:${b.target.port}`);
100
+ }
101
+ /** Matching known_hosts entries, normalized to "keytype blob" (marker kept), sorted. */
102
+ export function parseKnownHostsMatches(output) {
103
+ return output.split("\n").filter(line => line && !line.startsWith("#")).map(line => {
104
+ const fields = line.trim().split(/\s+/);
105
+ const marker = fields[0].startsWith("@") ? `${fields.shift()} ` : "";
106
+ return `${marker}${fields[1]} ${fields[2]}`;
107
+ }).sort();
108
+ }
109
+ function trustEntries(b) {
110
+ if (!fs.existsSync(b.known_hosts_file))
111
+ return { reason: "KNOWN_HOSTS_UNREADABLE" };
112
+ const result = spawnSync("ssh-keygen", ["-F", knownHostName(b), "-f", b.known_hosts_file], { encoding: "utf8", timeout: 10_000 });
113
+ if (result.status === 1)
114
+ return { reason: "HOST_TRUST_MISSING" };
115
+ if (result.status !== 0)
116
+ return { reason: "KNOWN_HOSTS_UNREADABLE" };
117
+ const entries = parseKnownHostsMatches(result.stdout);
118
+ return entries.length ? entries : { reason: "HOST_TRUST_MISSING" };
119
+ }
120
+ const digest = (text) => `sha256:${createHash("sha256").update(text).digest("hex")}`;
121
+ export function bindingStatus(ref) {
122
+ const b = binding(ref);
123
+ const key = publicKey(b.key_file);
124
+ const trust = trustEntries(b);
125
+ return {
126
+ 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 },
130
+ trust: Array.isArray(trust)
131
+ ? { provider: "aiterm.known-hosts.v1", revision: digest(trust.join("\n")), available: true, reason: null,
132
+ fingerprints: trust.map(entry => keyFingerprint(Buffer.from(entry.split(" ").at(-1), "base64"))) }
133
+ : { provider: "aiterm.known-hosts.v1", revision: null, fingerprints: [], available: false, reason: trust.reason },
134
+ };
135
+ }
136
+ /** Scan once; write the key only when it equals the fingerprint the Owner confirmed. A scan alone is never trust. */
137
+ export function confirmHostKey(ref, fingerprint) {
138
+ if (!FINGERPRINT.test(fingerprint))
139
+ throw new RemoteTerminalError("FINGERPRINT_INVALID", "fingerprint must be SHA256:<base64>");
140
+ const b = binding(ref);
141
+ const scan = spawnSync("ssh-keyscan", ["-T", "10", "-p", String(b.target.port), b.target.host], { encoding: "utf8", timeout: 20_000 });
142
+ const matched = scan.stdout.split("\n").filter(line => line && !line.startsWith("#")).map(line => line.trim().split(/\s+/))
143
+ .find(fields => fields.length >= 3 && keyFingerprint(Buffer.from(fields[2], "base64")) === fingerprint);
144
+ if (!matched)
145
+ throw new RemoteTerminalError("HOST_KEY_FINGERPRINT_MISMATCH", "the terminal did not present the confirmed host key");
146
+ const name = knownHostName(b);
147
+ if (fs.existsSync(b.known_hosts_file))
148
+ spawnSync("ssh-keygen", ["-R", name, "-f", b.known_hosts_file], { timeout: 10_000 });
149
+ fs.appendFileSync(b.known_hosts_file, `${name} ${matched[1]} ${matched[2]}\n`, { mode: 0o600 });
150
+ fs.rmSync(`${b.known_hosts_file}.old`, { force: true });
151
+ return bindingStatus(ref);
152
+ }
153
+ // ---- connection ----
154
+ export function classifySshFailure(stderr) {
155
+ if (/REMOTE HOST IDENTIFICATION HAS CHANGED|Host key for .* has changed/i.test(stderr))
156
+ return { code: "HOST_KEY_MISMATCH", message: "the terminal presented a different host key", action: "confirm the new host key" };
157
+ if (/Host key verification failed|No .* host key is known/i.test(stderr))
158
+ return { code: "HOST_TRUST_MISSING", message: "the terminal's host key is not trusted", action: "confirm the new host key" };
159
+ if (/Permission denied|Too many authentication failures/i.test(stderr))
160
+ return { code: "AUTH_FAILED", message: "the terminal refused the key" };
161
+ if (/aiterm-mcp: (command )?not found|aiterm-mcp: No such file/i.test(stderr))
162
+ return { code: "REMOTE_AITERM_UNAVAILABLE", message: "Aiterm is not installed on the terminal" };
163
+ if (/Connection refused|timed out|No route to host|Network is unreachable|Could not resolve|Connection closed|Connection reset/i.test(stderr))
164
+ return { code: "UNREACHABLE", message: "the terminal cannot be reached" };
165
+ return { code: "CONNECTION_FAILED", message: "the SSH connection failed" };
166
+ }
167
+ export function sshArguments(b, agentSocket, identityFile, remoteCommand) {
168
+ return ["-F", "/dev/null", "-T", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes",
169
+ "-o", `UserKnownHostsFile=${b.known_hosts_file}`, "-o", "GlobalKnownHostsFile=/dev/null", "-o", "CheckHostIP=no",
170
+ ...(b.host_key_alias ? ["-o", `HostKeyAlias=${b.host_key_alias}`] : []),
171
+ "-o", `IdentityAgent=${agentSocket}`, "-o", "IdentitiesOnly=yes", "-o", `IdentityFile=${identityFile}`,
172
+ "-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ConnectTimeout=15", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=4",
173
+ "-l", b.target.user, "-p", String(b.target.port), "--", b.target.host, remoteCommand];
174
+ }
175
+ function sshEnvironment() {
176
+ const env = {};
177
+ for (const key of ["PATH", "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "TMPDIR"])
178
+ if (process.env[key] !== undefined)
179
+ env[key] = process.env[key];
180
+ return env;
181
+ }
182
+ /** MCP over an ssh child whose stdin first carries the private env line (remote-terminal.md R5). */
183
+ class SshStdioTransport {
184
+ args;
185
+ privateLine;
186
+ onclose;
187
+ onerror;
188
+ onmessage;
189
+ stderr = "";
190
+ buffer = new ReadBuffer();
191
+ child = null;
192
+ constructor(args, privateLine) {
193
+ this.args = args;
194
+ this.privateLine = privateLine;
195
+ }
196
+ async start() {
197
+ const child = spawn("ssh", this.args, { env: sshEnvironment(), stdio: ["pipe", "pipe", "pipe"] });
198
+ this.child = child;
199
+ child.stderr.on("data", (chunk) => { this.stderr = (this.stderr + chunk.toString("utf8")).slice(-4000); });
200
+ child.stdout.on("data", (chunk) => {
201
+ this.buffer.append(chunk);
202
+ for (let message = this.buffer.readMessage(); message; message = this.buffer.readMessage())
203
+ this.onmessage?.(message);
204
+ });
205
+ child.on("error", error => this.onerror?.(error));
206
+ child.on("close", () => { this.child = null; this.onclose?.(); });
207
+ child.stdin.on("error", error => this.onerror?.(error));
208
+ child.stdin.write(this.privateLine);
209
+ }
210
+ async send(message) {
211
+ if (!this.child?.stdin)
212
+ throw new RemoteTerminalError("CONNECTION_LOST", "the terminal connection is closed");
213
+ this.child.stdin.write(serializeMessage(message));
214
+ }
215
+ async close() { this.child?.kill(); }
216
+ }
217
+ export const REMOTE_SEAT_TOOLS = new Set(["agent_launch", "pty_send", "pty_observe", "pty_read", "pty_key", "claude_turn", "agent_stop", "pty_close"]);
218
+ const COMMANDS = {
219
+ claude_version: "claude --version",
220
+ claude_install: "curl -fsSL https://claude.ai/install.sh | bash",
221
+ claude_update: "claude update",
222
+ };
223
+ const WAIT_FLAGS = new Set(["--session", "--operation", "--timeout", "--cursor", "--steer", "--launch", "--input"]);
224
+ const WAIT_VALUE = /^[A-Za-z0-9_.:-]{1,128}$/;
225
+ /** wait_process.args minus the CLI path: only aiterm-wait's own flag/value pairs, each value a plain token. */
226
+ export function waitArguments(args) {
227
+ if (!Array.isArray(args) || args.some(arg => typeof arg !== "string"))
228
+ throw new RemoteTerminalError("WAIT_INVALID", "wait_process.args must be strings");
229
+ const rest = args[0]?.startsWith("--") ? args : args.slice(1);
230
+ if (rest.length === 0 || rest.length % 2 !== 0)
231
+ throw new RemoteTerminalError("WAIT_INVALID", "wait_process has no flags");
232
+ for (let i = 0; i < rest.length; i += 2)
233
+ if (!WAIT_FLAGS.has(rest[i]) || !WAIT_VALUE.test(rest[i + 1]))
234
+ throw new RemoteTerminalError("WAIT_INVALID", `unsupported wait argument ${rest[i]}`);
235
+ if (!rest.includes("--session"))
236
+ throw new RemoteTerminalError("WAIT_INVALID", "wait_process needs --session");
237
+ return rest;
238
+ }
239
+ function versionAtLeast(actual, required) {
240
+ const a = actual.split(/[.-]/).slice(0, 3).map(Number), r = required.split(/[.-]/).slice(0, 3).map(Number);
241
+ for (let i = 0; i < 3; i++)
242
+ if ((a[i] ?? 0) !== (r[i] ?? 0))
243
+ return (a[i] ?? 0) > (r[i] ?? 0);
244
+ return true;
245
+ }
246
+ // The first release with --private-env-stdin and the transcript reader on the terminal.
247
+ export const REMOTE_MINIMUM_VERSION = "0.65.0";
248
+ export class RemoteTerminalConnection extends EventEmitter {
249
+ b;
250
+ dir;
251
+ agent;
252
+ socket;
253
+ identity;
254
+ client;
255
+ remoteVersion;
256
+ closing = false;
257
+ constructor(b, dir, agent, socket, identity, client, remoteVersion) {
258
+ super();
259
+ this.b = b;
260
+ this.dir = dir;
261
+ this.agent = agent;
262
+ this.socket = socket;
263
+ this.identity = identity;
264
+ this.client = client;
265
+ this.remoteVersion = remoteVersion;
266
+ }
267
+ static async open(input) {
268
+ const target = validTarget(input.target);
269
+ const b = binding(input.ref);
270
+ if (b.target.host !== target.host || b.target.user !== target.user || b.target.port !== target.port)
271
+ throw new RemoteTerminalError("TARGET_MISMATCH", "the target differs from the registered binding");
272
+ const status = bindingStatus(input.ref);
273
+ if (!status.trust.available)
274
+ throw new RemoteTerminalError(status.trust.reason ?? "HOST_TRUST_MISSING", "host trust is unavailable", "confirm the new host key");
275
+ if (status.trust.revision !== input.trustRevision)
276
+ throw new RemoteTerminalError("HOST_TRUST_STALE", "the host trust revision changed; re-read status");
277
+ if (!status.credential.available)
278
+ throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", status.credential.reason ?? "the key is unavailable");
279
+ if (status.credential.revision !== input.credentialRevision)
280
+ throw new RemoteTerminalError("CREDENTIAL_REVISION_STALE", "the key revision changed; re-read status");
281
+ for (const [name, value] of Object.entries(input.privateEnv ?? {}))
282
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || typeof value !== "string")
283
+ throw new RemoteTerminalError("PRIVATE_ENV_INVALID", "invalid private env entry");
284
+ // Short path: the agent socket must fit macOS's 104-byte sun_path.
285
+ const dir = fs.mkdtempSync(path.join(os.platform() === "win32" ? os.tmpdir() : "/tmp", "aiterm-rt-"));
286
+ fs.chmodSync(dir, 0o700);
287
+ const socket = path.join(dir, "a.sock");
288
+ const agent = spawn("ssh-agent", ["-D", "-a", socket], { env: sshEnvironment(), stdio: ["ignore", "ignore", "ignore"] });
289
+ const cleanup = () => { agent.kill(); fs.rmSync(dir, { recursive: true, force: true }); };
290
+ try {
291
+ const deadline = Date.now() + 5000;
292
+ while (!fs.existsSync(socket)) {
293
+ if (Date.now() > deadline || agent.exitCode !== null)
294
+ throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", "the private agent did not start");
295
+ await new Promise(resolve => setTimeout(resolve, 50));
296
+ }
297
+ const added = spawnSync("ssh-add", ["-q", b.key_file], { env: { ...sshEnvironment(), SSH_AUTH_SOCK: socket }, stdio: ["ignore", "ignore", "pipe"], timeout: 10_000 });
298
+ if (added.status !== 0)
299
+ throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", "the key could not be loaded");
300
+ const identity = path.join(dir, "id.pub");
301
+ const key = publicKey(b.key_file);
302
+ if ("reason" in key)
303
+ throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", key.reason);
304
+ fs.writeFileSync(identity, `${key.line}\n`, { mode: 0o600 });
305
+ 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`);
306
+ const client = new Client({ name: "aiterm-remote-terminal", version: pkg.version });
307
+ try {
308
+ await client.connect(transport, { timeout: 60_000 });
309
+ }
310
+ catch {
311
+ const failure = classifySshFailure(transport.stderr);
312
+ throw new RemoteTerminalError(failure.code, failure.message, failure.action);
313
+ }
314
+ const remoteVersion = client.getServerVersion()?.version ?? "0.0.0";
315
+ // An older terminal would ignore the private env line and launch without the private values.
316
+ if (!versionAtLeast(remoteVersion, REMOTE_MINIMUM_VERSION)) {
317
+ await client.close().catch(() => { });
318
+ throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${remoteVersion}; ${REMOTE_MINIMUM_VERSION} or later is required`);
319
+ }
320
+ const connection = new RemoteTerminalConnection(b, dir, agent, socket, identity, client, remoteVersion);
321
+ client.onclose = () => connection.ended();
322
+ queueMicrotask(() => connection.emit("event", { type: "ready", at: new Date().toISOString(), remoteVersion }));
323
+ return connection;
324
+ }
325
+ catch (error) {
326
+ cleanup();
327
+ throw error;
328
+ }
329
+ }
330
+ ended() {
331
+ const at = new Date().toISOString();
332
+ this.agent.kill();
333
+ fs.rmSync(this.dir, { recursive: true, force: true });
334
+ this.emit("event", (this.closing ? { type: "closed", at } : { type: "lost", at, code: "CONNECTION_LOST" }));
335
+ }
336
+ async call(name, args, options = {}) {
337
+ if (!REMOTE_SEAT_TOOLS.has(name))
338
+ throw new RemoteTerminalError("TOOL_UNSUPPORTED", `${name} is not a bound seat tool`);
339
+ if (options.private && name !== "agent_launch")
340
+ throw new RemoteTerminalError("PRIVATE_OPTIONS_UNSUPPORTED", "private options apply to agent_launch only");
341
+ const full = { ...args,
342
+ ...(options.private?.appendSystemPrompt !== undefined ? { append_system_prompt: options.private.appendSystemPrompt } : {}),
343
+ ...(options.private?.mcpConfig !== undefined ? { mcp_config: options.private.mcpConfig } : {}) };
344
+ try {
345
+ return await this.client.callTool({ name, arguments: full }, undefined, { timeout: options.timeoutMs ?? 600_000, resetTimeoutOnProgress: true });
346
+ }
347
+ catch (error) {
348
+ if (this.client.transport === undefined)
349
+ throw new RemoteTerminalError("CONNECTION_LOST", "the terminal connection was lost");
350
+ throw error;
351
+ }
352
+ }
353
+ exec(script, timeoutMs, signal) {
354
+ return new Promise((resolve, reject) => {
355
+ const child = spawn("ssh", sshArguments(this.b, this.socket, this.identity, posixCommand(script)), { env: sshEnvironment(), stdio: ["ignore", "pipe", "pipe"] });
356
+ let stdout = "", stderr = "";
357
+ const timer = setTimeout(() => child.kill(), timeoutMs);
358
+ signal?.addEventListener("abort", () => child.kill(), { once: true });
359
+ child.stdout.on("data", (chunk) => { stdout += chunk.toString("utf8"); });
360
+ child.stderr.on("data", (chunk) => { stderr = (stderr + chunk.toString("utf8")).slice(-4000); });
361
+ child.on("error", reject);
362
+ child.on("close", code => { clearTimeout(timer); resolve({ code, stdout, stderr }); });
363
+ });
364
+ }
365
+ async transcriptRead(input) {
366
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(input.sessionName))
367
+ throw new RemoteTerminalError("SESSION_INVALID", "invalid session name");
368
+ const parts = ["transcript-read", "--session", input.sessionName];
369
+ if (input.cursor) {
370
+ if (!/^[0-9a-f-]{36}$/i.test(input.cursor.claudeSessionId) || !Number.isSafeInteger(input.cursor.offset) || input.cursor.offset < 0)
371
+ throw new RemoteTerminalError("TRANSCRIPT_CURSOR_INVALID", "invalid cursor");
372
+ parts.push("--cursor-session", input.cursor.claudeSessionId, "--offset", String(input.cursor.offset));
373
+ }
374
+ if (input.maxBytes !== undefined) {
375
+ if (!Number.isSafeInteger(input.maxBytes) || input.maxBytes < 1)
376
+ throw new RemoteTerminalError("TRANSCRIPT_MAX_INVALID", "invalid maxBytes");
377
+ parts.push("--max-bytes", String(input.maxBytes));
378
+ }
379
+ const result = await this.exec(`exec aiterm-remote-terminal ${parts.join(" ")}`, 120_000);
380
+ const line = result.stdout.trim().split("\n").pop() ?? "";
381
+ let parsed = null;
382
+ try {
383
+ parsed = JSON.parse(line);
384
+ }
385
+ catch { /* classified below */ }
386
+ if (result.code === 0 && parsed?.schema === "aiterm.transcript-read.v1")
387
+ return parsed;
388
+ if (parsed?.code)
389
+ throw new RemoteTerminalError(parsed.code, parsed.message ?? "transcript read failed");
390
+ if (result.code === 255) {
391
+ const f = classifySshFailure(result.stderr);
392
+ throw new RemoteTerminalError(f.code, f.message, f.action);
393
+ }
394
+ throw new RemoteTerminalError("COMMAND_FAILED", "the transcript reader failed on the terminal");
395
+ }
396
+ /** Run the terminal's aiterm-wait with the flags of a receipt's wait_process; its one-line JSON comes back unchanged. */
397
+ async wait(waitProcess, signal) {
398
+ const flags = waitArguments(waitProcess?.args);
399
+ // Same resolution as remoteWaitCommand: npm may link only aiterm-mcp.
400
+ const resolve = 'w=$(command -v aiterm-wait) || w="$(dirname "$(readlink -f "$(command -v aiterm-mcp)")")/aiterm-wait-cli.js"';
401
+ const result = await this.exec(`${resolve}; exec "$w" ${flags.join(" ")}`, 90_000_000, signal);
402
+ if (signal?.aborted)
403
+ throw new RemoteTerminalError("WAIT_CANCELLED", "the wait was cancelled");
404
+ const line = result.stdout.trim().split("\n").pop() ?? "";
405
+ try {
406
+ return JSON.parse(line);
407
+ }
408
+ catch {
409
+ if (result.code === 255) {
410
+ const f = classifySshFailure(result.stderr);
411
+ throw new RemoteTerminalError(f.code, f.message, f.action);
412
+ }
413
+ throw new RemoteTerminalError("COMMAND_FAILED", "aiterm-wait returned no receipt");
414
+ }
415
+ }
416
+ async command(op) {
417
+ if (!Object.hasOwn(COMMANDS, op))
418
+ throw new RemoteTerminalError("COMMAND_UNSUPPORTED", "unknown op");
419
+ const run = await this.exec(`${COMMANDS[op]} 2>&1`, op === "claude_version" ? 60_000 : 900_000);
420
+ if (run.code === 255) {
421
+ const f = classifySshFailure(run.stderr);
422
+ throw new RemoteTerminalError(f.code, f.message, f.action);
423
+ }
424
+ const probe = op === "claude_version" ? run : await this.exec("claude --version 2>&1", 60_000);
425
+ const version = probe.code === 0 ? (/\d+\.\d+\.\d+\S*/.exec(probe.stdout)?.[0] ?? null) : null;
426
+ return { op, exit_code: run.code, version, output_tail: run.stdout.slice(-2000) };
427
+ }
428
+ async close() {
429
+ this.closing = true;
430
+ await this.client.close().catch(() => { });
431
+ return { closed: true };
432
+ }
433
+ }
package/dist/remote.js CHANGED
@@ -130,7 +130,7 @@ export function remoteShell(target) {
130
130
  // POSIX系の非ログイン実行では、~/.local/bin、Homebrew、nvmなどのPATHが入らない端末がある。
131
131
  // 利用者のログインshellからPATHだけを受け取り、処理は/bin/shで行う。profileの出力やfish等の文法差を
132
132
  // MCPのstdoutと処理へ持ち込まない。scriptは呼び出し側で検証済みの値だけで組み、単引用符を含めない。
133
- function posixCommand(script) {
133
+ export function posixCommand(script) {
134
134
  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';
135
135
  return `/bin/sh -c '${importPath}; ${script}'`;
136
136
  }
@@ -330,6 +330,11 @@ function tmuxMissingMessage() {
330
330
  const override = "別の場所にある tmux を使うには AITERM_TMUX=/path/to/tmux を指定してください。";
331
331
  return `${head}${hint}${override}`;
332
332
  }
333
+ /** A spawn that failed for lack of resources or by a signal says nothing about tmux being installed. */
334
+ export function tmuxStartTransient(result) {
335
+ const code = result.error?.code;
336
+ return result.signal != null || ["ENOMEM", "EAGAIN", "EMFILE", "ENFILE"].includes(code ?? "");
337
+ }
333
338
  // POSIX(Linux/WSL2/macOS) 用の tmux バイナリ解決。Windows の ensureWinBridge() に対応する事前確認。
334
339
  // 解決順: AITERM_TMUX(明示指定)→ PATH 上の tmux → Homebrew 既定パス。一度だけ実行しキャッシュする。
335
340
  // 見つからなければ tmuxMissingMessage で投げる(黙ってフォールバックせず、原因が見えるようにする)。
@@ -343,6 +348,8 @@ export function resolveTmux(observe = true, deadline) {
343
348
  diagnosticSpawnFailure(r, deadline, true);
344
349
  if (!r.error && r.status === 0)
345
350
  return (tmuxBin = override);
351
+ if (tmuxStartTransient(r))
352
+ throw new AitermError(`PTY_START_FAILED: tmux could not be started now (${r.error?.code ?? r.signal}). Retry later.`, 2);
346
353
  ptyDependencyError(`AITERM_TMUX に指定された tmux を起動できません: ${override}(\`${override} -V\` が通りません)`, observe);
347
354
  }
348
355
  // CLI/開発時は PATH 上の tmux をそのまま使う(最優先)。
@@ -351,6 +358,9 @@ export function resolveTmux(observe = true, deadline) {
351
358
  diagnosticSpawnFailure(onPath, deadline);
352
359
  if (!onPath.error && onPath.status === 0)
353
360
  return (tmuxBin = "tmux");
361
+ // Out of memory or processes, or killed: tmux exists but could not run now. That is not a missing dependency.
362
+ if (tmuxStartTransient(onPath))
363
+ throw new AitermError(`PTY_START_FAILED: tmux could not be started now (${onPath.error?.code ?? onPath.signal}). Retry later.`, 2);
354
364
  // GUI 起動などで PATH に Homebrew の bin が無い場合、既定の場所を探す。
355
365
  // 使う場合は黙らず stderr へ告知する(stdout は JSON-RPC 専用=index.ts の制約)。
356
366
  for (const cand of ["/opt/homebrew/bin/tmux", "/usr/local/bin/tmux"]) {
@@ -0,0 +1,27 @@
1
+ // Kept dependency-free: the Claude Stop hook imports it on every turn end.
2
+ import * as fs from "node:fs";
3
+ /** End of the last complete line (exclusive byte offset); a partly written last line is left for the next turn. */
4
+ export function completedTranscriptOffset(file) {
5
+ let fd = null;
6
+ try {
7
+ fd = fs.openSync(file, "r");
8
+ let end = fs.fstatSync(fd).size;
9
+ const chunk = Buffer.alloc(64 * 1024);
10
+ while (end > 0) {
11
+ const start = Math.max(0, end - chunk.length);
12
+ const read = fs.readSync(fd, chunk, 0, end - start, start);
13
+ const at = chunk.subarray(0, read).lastIndexOf(0x0a);
14
+ if (at >= 0)
15
+ return { path: file, offset: start + at + 1 };
16
+ end = start;
17
+ }
18
+ return { path: file, offset: 0 };
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ finally {
24
+ if (fd !== null)
25
+ fs.closeSync(fd);
26
+ }
27
+ }
@@ -0,0 +1,74 @@
1
+ // C7 native transcript read on the terminal (remote-terminal.md R9). Lines are returned only up to the
2
+ // offset the Claude Stop hook recorded for the latest completed turn, never the unfinished tail.
3
+ import * as fs from "node:fs";
4
+ import { AitermError } from "./errors.js";
5
+ import { loadAgentMetadata } from "./agent-metadata-reader.js";
6
+ const DEFAULT_MAX = 4 * 1024 * 1024;
7
+ function latestCompletion(eventFile, vendorSessionId) {
8
+ let text;
9
+ try {
10
+ text = fs.readFileSync(eventFile, "utf8");
11
+ }
12
+ catch {
13
+ return null;
14
+ }
15
+ let found = null;
16
+ for (const line of text.split("\n")) {
17
+ if (!line)
18
+ continue;
19
+ let event;
20
+ try {
21
+ event = JSON.parse(line);
22
+ }
23
+ catch {
24
+ continue;
25
+ }
26
+ if (event?.type === "agent_done" && event.vendor_session_id === vendorSessionId
27
+ && typeof event.transcript_path === "string" && Number.isSafeInteger(event.transcript_offset) && event.transcript_offset >= 0)
28
+ found = { path: event.transcript_path, offset: event.transcript_offset };
29
+ }
30
+ return found;
31
+ }
32
+ export function readCompletedTranscript(sessionName, cursor, maxBytes = DEFAULT_MAX) {
33
+ const meta = loadAgentMetadata(sessionName);
34
+ if (meta.kind !== "claude" || !meta.vendor_session_id)
35
+ throw new AitermError("TRANSCRIPT_UNSUPPORTED: only Claude Code seats have a native transcript cursor", 2);
36
+ return readTranscriptRange(meta.event_file, meta.vendor_session_id, cursor, maxBytes);
37
+ }
38
+ export function readTranscriptRange(eventFile, id, cursor, maxBytes = DEFAULT_MAX) {
39
+ // A fresh conversation (new seat or account switch) starts from its beginning.
40
+ const start = cursor && cursor.claudeSessionId === id ? cursor.offset : 0;
41
+ if (!Number.isSafeInteger(start) || start < 0)
42
+ throw new AitermError("TRANSCRIPT_CURSOR_INVALID: offset must be a non-negative integer", 2);
43
+ const done = latestCompletion(eventFile, id);
44
+ const unchanged = { schema: "aiterm.transcript-read.v1", entries: [], cursor: { claudeSessionId: id, offset: start }, complete_through: done?.offset ?? null, more: false };
45
+ if (!done || done.offset === start)
46
+ return unchanged;
47
+ if (start > done.offset)
48
+ throw new AitermError("TRANSCRIPT_CURSOR_AHEAD: the cursor is past the latest completed turn", 2);
49
+ const length = Math.min(done.offset - start, Math.max(1, maxBytes));
50
+ const buffer = Buffer.alloc(length);
51
+ const fd = fs.openSync(done.path, "r");
52
+ let read;
53
+ try {
54
+ read = fs.readSync(fd, buffer, 0, length, start);
55
+ }
56
+ finally {
57
+ fs.closeSync(fd);
58
+ }
59
+ const end = buffer.subarray(0, read).lastIndexOf(0x0a) + 1;
60
+ if (end === 0) {
61
+ if (read < done.offset - start)
62
+ throw new AitermError("TRANSCRIPT_LINE_TOO_LONG: one line exceeds max_bytes", 2);
63
+ return unchanged;
64
+ }
65
+ const entries = [];
66
+ let at = 0;
67
+ while (at < end) {
68
+ const next = buffer.indexOf(0x0a, at) + 1;
69
+ entries.push(buffer.subarray(at, next).toString("utf8"));
70
+ at = next;
71
+ }
72
+ return { schema: "aiterm.transcript-read.v1", entries, cursor: { claudeSessionId: id, offset: start + end },
73
+ complete_through: done.offset, more: start + end < done.offset };
74
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.64.2",
3
+ "version": "0.65.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": [
@@ -48,7 +48,8 @@
48
48
  "aiterm-parent-delivery": "dist/parent-delivery-cli.js",
49
49
  "aiterm-update": "dist/update-cli.js",
50
50
  "aiterm-idle-check": "dist/agent-idle-cli.js",
51
- "aiterm-resume-state": "dist/resume-state-cli.js"
51
+ "aiterm-resume-state": "dist/resume-state-cli.js",
52
+ "aiterm-remote-terminal": "dist/remote-terminal-cli.js"
52
53
  },
53
54
  "files": [
54
55
  "dist/*.js",