aiterm-mcp 0.70.7 → 0.70.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.70.8] - 2026-11-10
11
+
12
+ - Windows forks (x64): `agent_launch.fork_from` now starts the fork with every write inside the project folder refused instead of answering `READONLY_UNENFORCEABLE`. A bundled helper (`native/write-ban/win32-x64/aiterm-write-ban.exe`, about 24 KB, built reproducibly with the Linux ones) runs the CLI under a restricted copy of the user's token with no privileges and an Aiterm marker SID. The project folder carries, once, an inheritable Deny ACE for that marker SID (plus OWNER RIGHTS = READ_CONTROL and WRITE_DAC, so the DACL cannot be rewritten). The ACEs affect no other process, so the main seat writes as before and nothing is cleaned up later. npm shims run through `pwsh -File`. Measured on fox: new file, append, delete, rename, attributes, Set-Acl, icacls, takeown, git and cmd redirects inside were refused; writes outside succeeded. `fork_of.write_ban.method` is `restricted-token`.
13
+ - The Linux terminal runtime now carries its own tmux, so a Linux terminal needs no tmux installed. `aiterm-runtime-<version>-linux-<x64|arm64>.tar.gz` holds `bin/tmux` 3.8, a fully static musl binary (libevent 2.1.13, utf8proc 2.12.0 and ncurses 6.5 linked in, no libc of the terminal), cross-built on the runner with `zig cc` (`ziglang` 0.15.2 from PyPI, as the write-ban helper) from source tarballs pinned by sha256 in `scripts/build-linux-runtime.mjs`. ncurses keeps compiled-in entries for `screen-256color`, `tmux-256color`, `xterm-256color`, `xterm`, `screen`, `tmux`, `linux`, `vt100`, `dumb` and `ansi`, so tmux also starts on a machine without a terminfo database; it still reads the terminal's own database first. `default-terminal` stays `screen-256color`. The runtime `bin` is first on PATH, so seats use it.
14
+ - `provision` no longer checks for tmux on a Linux terminal, and `PROVISION_TMUX_MISSING` is gone (the bootstrap and `runtime-smoke` never answer it). `runtime-smoke` runs the runtime's own `bin/tmux -V` on both systems. The runtime build checks both tmux binaries are static ELF files of the right machine and, for the host architecture, starts a session with no terminfo database in reach. `runtime.yml` installs `ziglang` in the Linux job and no longer installs a system tmux there.
15
+ - Windows: a local Claude Code / Codex launch no longer types the whole PowerShell launch command (several KB with the sub-agent instruction) into the pane. The psmux send worker drains 300 ms per 256 bytes, so that one call took about 6.4 s of a 9.9 s launch (fox, 0.70.7). Aiterm now writes the command to a private 0600 file in its launch state and types one short line that reads it, deletes it and runs it in the pane's scope. The command, its exit tracking and the drains are unchanged. Environment values no longer appear in the pane's scrollback. POSIX launches are unchanged.
16
+ - Windows terminals (x64) can host Claude Code and Codex seats. A terminal whose OpenSSH Server default shell is PowerShell 7, Windows PowerShell 5.1 or `cmd` is no longer refused with `TERMINAL_PLATFORM_UNSUPPORTED` (that code stays for a system that is none of macOS, Linux and Windows). Every command Aiterm sends to a trusted terminal now comes from one builder, `terminalCommand(shell, {posix, windows})`: POSIX terminals get the same `/bin/sh -c` line as before; on Windows the line puts `%USERPROFILE%\.aiterm\runtime\current\bin` first on PATH when it holds `aiterm-mcp.cmd`, allows scripts for that process only (npm's `.ps1` shims), runs `& 'prog' 'arg'...` with every argument single-quoted, and ends with the real exit code (`pwsh -c` alone turns every native failure into 1). A missing `aiterm-*` program prints `<prog>: command not found` and exits 127, so `REMOTE_AITERM_UNAVAILABLE` does not depend on the language of Windows' own error (fox's is Japanese and CP932); the English cmd and PowerShell "is not recognized as ..." texts that name an `aiterm-*` program are classified the same way. `cmd` is not a PowerShell: its body goes through `powershell -EncodedCommand`. This covers the MCP connection (open, private env line, per-call tools), `aiterm-wait`, `aiterm-transcript-read` and `remote_terminal_command`. The platform probe now also fixes the shell kind in the per-ref cache, so no second probe is made.
17
+ - A terminal launch's `cwd` is checked in the terminal's own form: `/...` on macOS and Linux, a drive-absolute `X:\...` on Windows (UNC, device, relative, drive-relative, `/` separators and forbidden characters are `TERMINAL_INVALID`). Without `os` the form is checked against the probed system, still before any session. `path_status`, `make_dir` and `list_dirs` take the same native paths on both sides and need Aiterm 0.70.8 on a Windows terminal (`REMOTE_AITERM_TOO_OLD` otherwise); `list_dirs` on Windows leaves out `$Recycle.Bin` and `System Volume Information` besides dot names.
18
+ - The seat MCP forward keeper holds its reverse forward with a remote command that ends when its stdin closes on every shell: `cat >/dev/null` on POSIX, `[Console]::In.ReadToEnd() | Out-Null` on Windows. It reads the shell from the per-ref cache and probes once when this process has not. A SIGKILLed holder ended the Windows forward within seconds.
19
+ - `remote_terminal_command` `claude_install` on Windows is the official `irm https://claude.ai/install.ps1 | iex` (a failure stops with exit 1 and its message); `claude_version` and `claude_update` are unchanged, and after an install the version is also read from `%USERPROFILE%\.local\bin\claude.exe`.
20
+ - `aiterm-remote-terminal authorize-key --ref R --os windows` appends the held public key on a Windows terminal: to `%ProgramData%\ssh\administrators_authorized_keys` when the user is in Administrators and `sshd_config` still has the default `Match Group administrators` block (the file's ACL is reset to Administrators and SYSTEM only, as sshd requires), else to `%USERPROFILE%\.ssh\authorized_keys`; same duplicate check by key type and blob, UTF-8 without BOM, the file's own line ending. The password login cannot be probed first (no key works yet), so the caller names the system with `--os`; without it, or with `macos` / `linux`, the POSIX script runs as before.
21
+ - `aiterm-remote-terminal provision` installs the runtime on Windows x64 from `aiterm-runtime-<version>-win32-x64.zip` in the same `SHA256SUMS` (now five files), through a PowerShell 5.1 bootstrap that verifies the checksum, extracts with `tar.exe`, runs `runtime-smoke` and repoints a `current` junction (previous kept as `previous`, an old folder in use stays). `runtime-smoke` on Windows checks `psmux -V` by Aiterm's own lookup. `scripts/build-windows-runtime.mjs` builds the zip (official Node win-x64 zip checked against its pinned sha256, the npm package, CRLF `bin\*.cmd` wrappers) and `.github/workflows/runtime.yml` runs it on `windows-latest`; `scripts/upload-runtime-assets.mjs` lists the five assets. The zip carries its own psmux 3.3.8 (`bin\psmux.exe`, the official MIT release, sha256-pinned; the wrappers set `AITERM_PSMUX` to it), so the terminal needs no psmux installed, as Linux needs no tmux.
22
+ - The `CONNECTION_REFUSED` and `TERMINAL_PLATFORM_UNSUPPORTED` sentences for the Owner name the Windows steps (the optional OpenSSH Server feature and the sshd service).
23
+
10
24
  ## [0.70.7] - 2026-11-10
11
25
 
12
26
  - `pty_list` seat turns (`aiterm.seat-turns.v1`, BellTeam caller only) add `unread: [session_id]`. It names the terminal-bound sessions whose terminal failed or did not answer within 4 s, so the caller can keep their last state instead of reading them as gone. A session missing from a terminal that did answer is absent, as before.
@@ -3207,7 +3221,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3207
3221
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3208
3222
  provenance.
3209
3223
 
3210
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.7...HEAD
3224
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.8...HEAD
3225
+ [0.70.8]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.7...v0.70.8
3211
3226
  [0.70.7]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.6...v0.70.7
3212
3227
  [0.70.6]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.5...v0.70.6
3213
3228
  [0.70.5]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.4...v0.70.5
package/README.ja.md CHANGED
@@ -215,7 +215,7 @@ runtime-error store は canonical dotagents config の `collection.enabled: true
215
215
  場合だけ収集し、既定OFF、network送信は行いません。tag起点CIのnpm provenance(OIDC Trusted
216
216
  Publishing)で公開し、GitHub Release が Official MCP Registry を再登録します。
217
217
 
218
- **状態:** 開発継続中 · 現行公開版 **v0.70.7** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.70.8** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
219
219
 
220
220
  ### 更新と巻き戻し
221
221
 
package/README.md CHANGED
@@ -227,7 +227,7 @@ collection is off by default and performs no network I/O. It ships via
227
227
  tag-triggered CI with npm provenance (OIDC Trusted Publishing); the GitHub
228
228
  Release re-registers the Official MCP Registry entry.
229
229
 
230
- **Status:** actively maintained · current public release **v0.70.7** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
230
+ **Status:** actively maintained · current public release **v0.70.8** · 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
 
@@ -58,7 +58,7 @@ function forkOfField(v) {
58
58
  || typeof v.vendor_session_id !== "string" || !UUID_RE.test(v.vendor_session_id)
59
59
  || (v.fork_id !== undefined && typeof v.fork_id !== "string") || (v.first_input !== undefined && typeof v.first_input !== "string")
60
60
  || !v.write_ban || typeof v.write_ban.path !== "string" || !path.isAbsolute(v.write_ban.path)
61
- || (v.write_ban.method !== "landlock" && v.write_ban.method !== "seatbelt"))
61
+ || !["landlock", "seatbelt", "restricted-token"].includes(v.write_ban.method))
62
62
  throw new AitermError("agent metadata fork_of が不正です", 2);
63
63
  return { fork_of: { session_id: v.session_id, vendor_session_id: v.vendor_session_id, ...(v.fork_id === undefined ? {} : { fork_id: v.fork_id }),
64
64
  write_ban: { path: v.write_ban.path, method: v.write_ban.method }, ...(v.first_input === undefined ? {} : { first_input: v.first_input }) } };
@@ -277,6 +277,16 @@ export function windowsAgentLaunchLine(cwd, env, argv, exited) {
277
277
  const command = parts.join("; ");
278
278
  return exited ? `try { ${command} } finally { [IO.File]::WriteAllText(${psq(exited.file)}, ${psq(exited.launch_id)}) }` : command;
279
279
  }
280
+ /**
281
+ * The one short line typed into a Windows pane instead of the long launch command, which is read
282
+ * from `file` (0600, Aiterm launch state), deleted, and run in the pane's own scope. The psmux
283
+ * worker drains 300 ms per 256 bytes, so a multi-KB line cost 6 s (fox, 0.70.7). Invoke-Expression
284
+ * is not subject to ExecutionPolicy, unlike running a .ps1.
285
+ */
286
+ export function windowsLaunchIndirection(file) {
287
+ const f = `'${file.replace(/'/g, "''")}'`;
288
+ return `$aitermLaunch=[IO.File]::ReadAllText(${f}); Remove-Item -LiteralPath ${f}; Invoke-Expression $aitermLaunch`;
289
+ }
280
290
  /**
281
291
  * Keep accepted shebang wrappers in the same pane, as for control commands.
282
292
  * Invoking .sh directly in PowerShell uses its file association and can open a
package/dist/core.js CHANGED
@@ -53,10 +53,10 @@ import { unfinishedDeliveriesOwnedBy } from "./parent-delivery-owners.js";
53
53
  import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, signalRuntimeProcess, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, macKeepAwakeProcess, processElapsedSeconds } from "./process-runtime.js";
54
54
  import { liveNodeExecutable } from "./live-node.js";
55
55
  import { resolveClaudeConfigurationRoot, withClaudeConfigRoot } from "./claude-config-root.js";
56
- import { probeWriteBan, writeBanPrefix } from "./write-ban.js";
56
+ import { probeWriteBan, writeBanPrefix, windowsWriteBanArgv } from "./write-ban.js";
57
57
  import { AitermError, AgentResumeUnavailableError, AgentResumeError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
58
58
  import { isWin, SOCKDIR, SOCK, tmuxCommand, readOnlyTmuxList, PtyDiagnosticError, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, withNativeSessionSetupRollback, hasNativeSessionSetupRollback, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, rememberPaneShell, } from "./tmux-runtime.js";
59
- import { AGENT_DEFAULT_PREFACE, sleep, currentUid, runtimeStateBase, safeStatSize, readFileRange, writeJson0600, createEmpty0600, shq, LAUNCH_ID_RE, AGENT_LINEAGE_RE, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, publishAgentGeneration, agentMetadataPath, writeAgentMetadata, AGENT_EVENT_TAIL_BYTES, agentLabel, agentHarness, subagentInstruction, } from "./agent-shared.js";
59
+ import { AGENT_DEFAULT_PREFACE, sleep, currentUid, runtimeStateBase, safeStatSize, readFileRange, writeJson0600, writeText0600, createEmpty0600, shq, LAUNCH_ID_RE, AGENT_LINEAGE_RE, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, publishAgentGeneration, agentMetadataPath, writeAgentMetadata, AGENT_EVENT_TAIL_BYTES, agentLabel, agentHarness, subagentInstruction, } from "./agent-shared.js";
60
60
  import { AuthResponseError, authUi, authPromptDigest, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
61
61
  import { processStartIdentity } from "./runtime-error-os.js";
62
62
  import { processStartIdentities } from "./process-start.js";
@@ -70,7 +70,7 @@ import { claudeAuthPlan, claudeAuthStatus, claudeAuthPane, OPERATION_ID_RE, CLAU
70
70
  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";
71
71
  import { interimFromNow, interimFromToken, readInterimWords, recordInterimBoundary } from "./interim-words.js";
72
72
  import { codexSeatTurn, grokSteerAcceptance, observeSteerDone, readSteerEntry, recordSteer } from "./steer-follow.js";
73
- import { resolveAgentBin, resolveThroughlineBin, runThroughlineHandoffContext, isWindowsNativeExecutable, isUsableAgentExecutableFile, agentBinForPaneShell, resolveWinPaneShell, windowsAgentArgv, windowsAgentLaunchLine } from "./agent-resolver.js";
73
+ import { resolveAgentBin, resolveThroughlineBin, runThroughlineHandoffContext, isWindowsNativeExecutable, isUsableAgentExecutableFile, agentBinForPaneShell, resolveWinPaneShell, windowsAgentArgv, windowsAgentLaunchLine, windowsLaunchIndirection } from "./agent-resolver.js";
74
74
  export { AitermError } from "./errors.js";
75
75
  export { tmuxSpawnEnv } from "./tmux-runtime.js";
76
76
  export { agentHarness } from "./agent-shared.js";
@@ -350,6 +350,12 @@ function savedAgentSessionNames() {
350
350
  return match ? [match[1]] : [];
351
351
  }))] : [];
352
352
  }
353
+ /** Windows: the full PowerShell launch command goes to a private file; only the short reader line is typed (and shown). */
354
+ export function windowsLaunchTyped(name, launchId, full) {
355
+ const file = agentMetadataPath(name, launchId) + ".launch.ps1";
356
+ writeText0600(file, full);
357
+ return windowsLaunchIndirection(file);
358
+ }
353
359
  function cleanupAgentState(name) {
354
360
  assertSessionName(name);
355
361
  agentMetadataNegativeCache.delete(name);
@@ -366,6 +372,7 @@ function cleanupAgentState(name) {
366
372
  if (f.endsWith(".agent.json") ||
367
373
  f.endsWith(".active-launch.json") ||
368
374
  f.endsWith(".launch-exited") ||
375
+ f.endsWith(".launch.ps1") ||
369
376
  f.endsWith(".events.jsonl") ||
370
377
  f.endsWith(".activity.jsonl") ||
371
378
  f.endsWith(".resume.json") ||
@@ -6914,10 +6921,12 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot) {
6914
6921
  if (registerSessionEnvironment(true, name, [...(registeredSessionEnvironment(name) ?? []), ...Object.keys(recipe.environment)]).code !== 0)
6915
6922
  throw uncertain();
6916
6923
  phase = "vendor_start";
6917
- const argv = [...(next.fork_of ? writeBanPrefix(next.fork_of.write_ban) : []),
6918
- ...(next.kind === "claude" ? claudeResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next)
6919
- : codexResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next, recipe.cwd))];
6920
- const full = isWin ? windowsAgentLaunchLine(recipe.cwd, environment, windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), { file: agentMetadataPath(name, next.launch_id) + ".launch-exited", launch_id: next.launch_id })
6924
+ const cliArgv = next.kind === "claude" ? claudeResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next)
6925
+ : codexResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next, recipe.cwd);
6926
+ const argv = [...(next.fork_of && !isWin ? writeBanPrefix(next.fork_of.write_ban) : []), ...cliArgv];
6927
+ const forkBan = next.fork_of?.write_ban;
6928
+ const winArgv = () => (cli => forkBan ? windowsWriteBanArgv(forkBan, cli) : cli)(windowsAgentArgv(cliArgv, () => resolveWinPaneShell("bash")));
6929
+ const full = isWin ? windowsLaunchTyped(name, next.launch_id, windowsAgentLaunchLine(recipe.cwd, environment, winArgv(), { file: agentMetadataPath(name, next.launch_id) + ".launch-exited", launch_id: next.launch_id }))
6921
6930
  : `cd ${shq(recipe.cwd)} && /usr/bin/env ${environment.filter(([, value]) => value === null).map(([key]) => `-u ${shq(key)}`).join(" ")} `
6922
6931
  + `${environment.filter(([, value]) => value !== null).map(([key, value]) => shq(`${key}=${value}`)).join(" ")} ${argv.map(shq).join(" ")}`;
6923
6932
  agentLaunchLines.set(name, atomicShellMultiline(full, shell));
@@ -7837,7 +7846,9 @@ function prepareAgentLaunch(kind, opts = {}) {
7837
7846
  : grokAgentArgv(kind, bin, model, effort, prompt, meta);
7838
7847
  full = windowsAgentLaunchLine(cwd, [
7839
7848
  ...claudeRootEntries, ...(meta?.kind === "grok" ? grokEnvEntries(meta) : []), ...agentEnvEntries(meta, sid, envVars),
7840
- ], windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), meta?.windows_launch_exit_tracked ? { file: agentMetadataPath(sid, meta.launch_id) + ".launch-exited", launch_id: meta.launch_id } : undefined);
7849
+ ], (cli => meta?.fork_of ? windowsWriteBanArgv(meta.fork_of.write_ban, cli) : cli)(windowsAgentArgv(argv, () => resolveWinPaneShell("bash"))), meta?.windows_launch_exit_tracked ? { file: agentMetadataPath(sid, meta.launch_id) + ".launch-exited", launch_id: meta.launch_id } : undefined);
7850
+ if (meta)
7851
+ full = windowsLaunchTyped(sid, meta.launch_id, full);
7841
7852
  }
7842
7853
  else {
7843
7854
  const cmd = (meta?.fork_of ? writeBanPrefix(meta.fork_of.write_ban).map(shq).join(" ") + " " : "")
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { loadAgentMetadata } from "./agent-metadata-reader.js";
3
3
  import { remoteInputDescription, remoteInputSchema, terminalArgumentDescription, terminalArgumentSchema } from "./remote-contract.js";
4
4
  import { boundTerminalTarget, bindTerminalSession, terminalSeatGroups, ensureSeatForward, extractMcpHeaders, maintainSeatForwards, REMOTE_MINIMUM_VERSION, seatIngressPort, checkTerminalPlatform, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
5
+ import { terminalCwdFits } from "./remote-path.js";
5
6
  import { launchEnvValue } from "./private-env.js";
6
7
  import { AuthResponseError, authUiSchema, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
7
8
  import { configurationRequestSchema, configurationToolOutputSchema, applyConfigurationRequest, reconcileConfigurationRequest } from "./configure-request.js";
@@ -1275,13 +1276,15 @@ export function createAitermServer(options = {}) {
1275
1276
  throw new AitermError("TERMINAL_INVALID: use terminal or remote, not both; for a registered terminal pass only terminal", 2);
1276
1277
  if (harness !== "claude-code" && harness !== "codex-cli")
1277
1278
  throw new AitermError(`TERMINAL_HARNESS_UNSUPPORTED: terminal seats support harnesses claude-code and codex-cli; ${harness} is not available on a terminal yet`, 2);
1278
- // A declared Windows terminal is refused by the platform check below (0.70.8 brings its path form).
1279
- if (typeof args.cwd !== "string" || (terminal.os !== "windows" && !args.cwd.startsWith("/")))
1280
- throw new AitermError("TERMINAL_INVALID: cwd is required with terminal: the absolute POSIX project folder on that terminal, starting with / (never launch locally and cd)", 2);
1279
+ const cwdForm = "TERMINAL_INVALID: cwd is required with terminal: the absolute project folder on that terminal in its own form (a POSIX path starting with / on macOS and Linux, X:\\folder with backslashes on Windows; never launch locally and cd)";
1280
+ if (!terminalCwdFits(args.cwd, terminal.os))
1281
+ throw new AitermError(cwdForm, 2);
1281
1282
  if (args.require_existing_resume)
1282
1283
  throw new AitermError("TERMINAL_INVALID: require_existing_resume is local-only", 2);
1283
1284
  const target = terminalRemoteTarget(terminal);
1284
- await checkTerminalPlatform(target, terminal.os);
1285
+ // Without a declared os the cwd form is checked against the probed system, still before any session.
1286
+ if (!terminalCwdFits(args.cwd, await checkTerminalPlatform(target, terminal.os)))
1287
+ throw new AitermError(cwdForm, 2);
1285
1288
  // The private line is sent before the server answers; check its version first so an old one never sees it.
1286
1289
  let version = terminalVersions.get(target.trusted_ref);
1287
1290
  if (!version) {
@@ -1521,7 +1524,7 @@ export function createAitermServer(options = {}) {
1521
1524
  fork_from: z.object({
1522
1525
  session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/).describe("The main Aiterm seat on the same machine (the terminal or remote when given)"),
1523
1526
  fork_id: z.string().min(1).max(200).optional().describe("Caller's fork ID, passed to the seat as THROUGHLINE_FORK_ID"),
1524
- }).strict().optional().describe("claude-code and codex-cli. Start a disposable fork of that seat's latest saved conversation, in its cwd, with the main's tools and MCP. Every write inside that cwd (the project folder) is refused below the tools for the whole process tree (Linux Landlock, macOS sandbox-exec); everything else is allowed. Windows answers READONLY_UNENFORCEABLE. Requires a prompt; no write_scope. Close it after its answer"),
1527
+ }).strict().optional().describe("claude-code and codex-cli. Start a disposable fork of that seat's latest saved conversation, in its cwd, with the main's tools and MCP. Every write inside that cwd (the project folder) is refused below the tools for the whole process tree (Linux Landlock, macOS sandbox-exec, Windows restricted token + folder deny ACE); everything else is allowed. Requires a prompt; no write_scope. Close it after its answer"),
1525
1528
  },
1526
1529
  outputSchema: {
1527
1530
  schema: z.literal("aiterm.agent-launch-result.v1"),
@@ -1544,7 +1547,7 @@ export function createAitermServer(options = {}) {
1544
1547
  write_scope: z.string().optional(),
1545
1548
  write_scope_enforcement: z.enum(["enforced_read_only", "declaration_only_unsupported"]).optional(),
1546
1549
  fork_of: z.object({ session_id: z.string(), vendor_session_id: z.string(),
1547
- write_ban: z.object({ path: z.string(), method: z.enum(["landlock", "seatbelt"]) }) }).optional().describe("The seat this fork copies and the folder it cannot write"),
1550
+ write_ban: z.object({ path: z.string(), method: z.enum(["landlock", "seatbelt", "restricted-token"]) }) }).optional().describe("The seat this fork copies and the folder it cannot write"),
1548
1551
  },
1549
1552
  }, async ({ harness, remote, terminal, ...args }, extra) => {
1550
1553
  if (harness !== "claude-code" && harness !== "codex-cli" && (args.append_system_prompt !== undefined || args.mcp_config !== undefined))
@@ -5,6 +5,7 @@ import * as fs from "node:fs";
5
5
  import * as net from "node:net";
6
6
  import * as path from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
+ import { WINDOWS_STDIN_SCRIPT_COMMAND } from "./remote.js";
8
9
  import { RemoteTerminalError, agentAlive, binding, bindingStatus, classifySshFailure, credentialPublicKeyFile, publicKey, readCredential, sshEnvironment } from "./remote-terminal.js";
9
10
  export const ASKPASS_SOCKET_ENV = "AITERM_ASKPASS_SOCKET";
10
11
  const PUBLIC_KEY = /^[A-Za-z0-9@.-]+ [A-Za-z0-9+/]+={0,3}$/;
@@ -69,7 +70,50 @@ export function authorizedKeysScript(key) {
69
70
  "",
70
71
  ].join("\n");
71
72
  }
72
- export function passwordSshArguments(b) {
73
+ /** PowerShell variant (5.1 and 7, ASCII only, run from stdin). Decides the file from the user's group and sshd_config, then the same protocol:
74
+ * markers on stdout (the nested exit code is not reliable under `pwsh -c`), ERROR 21 = the folder, 22 = the file or its ACL. */
75
+ export function windowsAuthorizedKeysScript(key) {
76
+ const [type, blob] = key.split(" ");
77
+ return [
78
+ "$ErrorActionPreference = 'Stop'",
79
+ `$key = '${key}'; $type = '${type}'; $blob = '${blob}'`,
80
+ "function Done($text) { Write-Output ('AITERM_AUTHORIZE ' + $text); exit 0 }",
81
+ "function Fail($n) { Write-Output ('AITERM_AUTHORIZE_ERROR ' + $n); exit $n }",
82
+ // sshd reads administrators_authorized_keys instead of the user's file only for Administrators and only with the default Match block.
83
+ "$shared = $false",
84
+ "try {",
85
+ " $admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",
86
+ " $cfg = Join-Path $env:ProgramData 'ssh\\sshd_config'",
87
+ " if ($admin -and (Test-Path -LiteralPath $cfg)) {",
88
+ " $in = $false",
89
+ " foreach ($line in [IO.File]::ReadAllLines($cfg)) {",
90
+ " $t = $line.Trim()",
91
+ " if ($t -match '^Match\\s') { $in = ($t -match '^Match\\s+Group\\s+administrators\\s*$') }",
92
+ " elseif ($in -and $t -match '^AuthorizedKeysFile\\s+__PROGRAMDATA__/ssh/administrators_authorized_keys\\s*$') { $shared = $true }",
93
+ " }",
94
+ " }",
95
+ "} catch { $shared = $false }",
96
+ "$dir = Join-Path $env:USERPROFILE '.ssh'",
97
+ "if ($shared) { $file = Join-Path $env:ProgramData 'ssh\\administrators_authorized_keys' } else { $file = Join-Path $dir 'authorized_keys' }",
98
+ "try { if (-not $shared) { New-Item -ItemType Directory -Force -Path $dir | Out-Null } } catch { Fail 21 }",
99
+ "try {",
100
+ " $text = ''",
101
+ " if (Test-Path -LiteralPath $file) { $text = [IO.File]::ReadAllText($file) }",
102
+ " foreach ($line in ($text -split '\\r?\\n')) {",
103
+ " $f = $line.Trim() -split '\\s+'",
104
+ " for ($i = 0; $i -lt $f.Length - 1; $i++) { if ($f[$i] -eq $type -and $f[$i + 1] -eq $blob) { Done 'ALREADY_AUTHORIZED' } }",
105
+ " }",
106
+ ' $nl = "`n"; if ($text.Contains("`r`n")) { $nl = "`r`n" }',
107
+ " $prefix = ''; if ($text.Length -gt 0 -and -not $text.EndsWith(\"`n\")) { $prefix = $nl }",
108
+ " [IO.File]::AppendAllText($file, $prefix + $key + $nl, (New-Object System.Text.UTF8Encoding($false)))",
109
+ // sshd ignores the shared file unless only Administrators and SYSTEM may use it (well-known SIDs: names are localized).
110
+ " if ($shared) { & icacls.exe $file /inheritance:r /grant '*S-1-5-32-544:F' /grant '*S-1-5-18:F' | Out-Null; if ($LASTEXITCODE -ne 0) { throw 'acl' } }",
111
+ "} catch { Fail 22 }",
112
+ "Done 'AUTHORIZED'",
113
+ "",
114
+ ].join("\n");
115
+ }
116
+ export function passwordSshArguments(b, system = "posix") {
73
117
  return ["-F", "/dev/null", "-T", "-o", "BatchMode=no", "-o", "StrictHostKeyChecking=yes",
74
118
  "-o", `UserKnownHostsFile=${b.known_hosts_file}`, "-o", "GlobalKnownHostsFile=/dev/null", "-o", "CheckHostIP=no",
75
119
  ...(b.host_key_alias ? ["-o", `HostKeyAlias=${b.host_key_alias}`] : []),
@@ -77,10 +121,10 @@ export function passwordSshArguments(b) {
77
121
  "-o", "PreferredAuthentications=password", "-o", "PasswordAuthentication=yes", "-o", "KbdInteractiveAuthentication=no",
78
122
  "-o", "GSSAPIAuthentication=no", "-o", "HostbasedAuthentication=no", "-o", "NumberOfPasswordPrompts=1",
79
123
  "-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ConnectTimeout=15",
80
- "-l", b.target.user, "-p", String(b.target.port), "--", b.target.host, "/bin/sh -s"];
124
+ "-l", b.target.user, "-p", String(b.target.port), "--", b.target.host, system === "windows" ? WINDOWS_STDIN_SCRIPT_COMMAND : "/bin/sh -s"];
81
125
  }
82
126
  const shq = (value) => `'${value.replace(/'/g, "'\\''")}'`;
83
- export async function authorizeKey(prepared, password) {
127
+ export async function authorizeKey(prepared, password, system = "posix") {
84
128
  const dir = fs.mkdtempSync(path.join("/tmp", "aiterm-ap-"));
85
129
  let served = 0;
86
130
  const server = net.createServer(connection => { served += 1; if (served === 1)
@@ -97,7 +141,7 @@ export async function authorizeKey(prepared, password) {
97
141
  fs.writeFileSync(helper, `#!/bin/sh\nexec ${shq(process.execPath)} ${shq(cli)} askpass "$@"\n`, { mode: 0o700 });
98
142
  const env = { ...sshEnvironment(), SSH_ASKPASS: helper, SSH_ASKPASS_REQUIRE: "force", DISPLAY: process.env.DISPLAY ?? "aiterm:0", [ASKPASS_SOCKET_ENV]: socket };
99
143
  const run = await new Promise((resolve, reject) => {
100
- const child = spawn("ssh", passwordSshArguments(prepared.b), { env, stdio: ["pipe", "pipe", "pipe"] });
144
+ const child = spawn("ssh", passwordSshArguments(prepared.b, system), { env, stdio: ["pipe", "pipe", "pipe"] });
101
145
  let stdout = "", stderr = "";
102
146
  const timer = setTimeout(() => child.kill(), 120_000);
103
147
  child.stdout.on("data", (chunk) => { stdout += chunk.toString("utf8"); });
@@ -105,12 +149,13 @@ export async function authorizeKey(prepared, password) {
105
149
  child.on("error", reject);
106
150
  child.on("close", code => { clearTimeout(timer); resolve({ code, stdout, stderr }); });
107
151
  child.stdin.on("error", () => { });
108
- child.stdin.end(authorizedKeysScript(prepared.key));
152
+ child.stdin.end(system === "windows" ? windowsAuthorizedKeysScript(prepared.key) : authorizedKeysScript(prepared.key));
109
153
  });
110
154
  const marker = /AITERM_AUTHORIZE (AUTHORIZED|ALREADY_AUTHORIZED)/.exec(run.stdout)?.[1];
111
155
  if (run.code === 0 && marker)
112
156
  return { schema: "aiterm.remote-key-authorization.v1", ref: prepared.b.ref, result: marker };
113
- if (run.code === 21 || run.code === 22)
157
+ const failed = Number(/AITERM_AUTHORIZE_ERROR (21|22)/.exec(run.stdout)?.[1] ?? run.code);
158
+ if (failed === 21 || failed === 22)
114
159
  throw new RemoteTerminalError("AUTHORIZED_KEYS_WRITE_FAILED", "~/.ssh/authorized_keys could not be written on the terminal");
115
160
  const denied = /Permission denied \(([^)]*)\)/.exec(run.stderr);
116
161
  if (denied) {
@@ -49,10 +49,10 @@ export const terminalArgumentSchema = z.object({
49
49
  });
50
50
  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, " +
51
51
  "{ref, target:{host,user,port}, os?, trustRevision, and credentialRevision or credential {handle, revision}}; copy it unchanged, never invent or edit it, never use a host name or ssh command instead. " +
52
- "Omit it to launch on this computer. Give cwd in the same call: the absolute project folder on that terminal (a POSIX path starting with /). Never launch locally and then cd or ssh. " +
52
+ "Omit it to launch on this computer. Give cwd in the same call: the absolute project folder on that terminal in its own form (a POSIX path starting with / on macOS and Linux, a drive path like C:\\folder with backslashes on Windows). Never launch locally and then cd or ssh. " +
53
53
  "Never put tokens, passwords or other secrets in any argument, prompt or typed text; pass secret values only by name in env_vars. " +
54
54
  "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. " +
55
- "Errors and next step: TERMINAL_INVALID = malformed value, missing/relative cwd, or combined with remote: pass the registry's value unchanged with cwd. " +
55
+ "Errors and next step: TERMINAL_INVALID = malformed value, missing/relative cwd (or one in the other system's form), or combined with remote: pass the registry's value unchanged with cwd. " +
56
56
  "TARGET_MISMATCH / BINDING_UNKNOWN = the value is not this terminal's binding: ask the terminal registry again. " +
57
57
  "HOST_TRUST_STALE / CREDENTIAL_REVISION_STALE = the binding changed: get the current value from the terminal registry and launch again. " +
58
58
  "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. " +
@@ -61,4 +61,4 @@ export const terminalArgumentDescription = "Run this seat on another computer (a
61
61
  "REMOTE_AITERM_TOO_OLD = update Aiterm on the terminal. CWD_UNAVAILABLE = the folder does not exist there; do not pick another folder. " +
62
62
  "SEAT_FORWARD_UNAVAILABLE = the seat's MCP route back to this computer is not ready (launch again later), or the seat MCP URLs are not http://127.0.0.1:<one port>/api/seat-mcp. TERMINAL_HARNESS_UNSUPPORTED = use harness claude-code or codex-cli (codex-cli needs Aiterm 0.70.7 on the terminal). " +
63
63
  "TERMINAL_OS_MISMATCH = the terminal is not the operating system os says: the registry's os is wrong or the binding points at another machine; ask the terminal registry, do not retry. " +
64
- "TERMINAL_PLATFORM_UNSUPPORTED = Windows (and any system that is not macOS or Linux) cannot run seats yet.";
64
+ "TERMINAL_PLATFORM_UNSUPPORTED = the terminal is not a macOS, Linux or Windows system, so it cannot run seats.";
@@ -6,10 +6,32 @@ import { RemoteTerminalError } from "./remote-terminal.js";
6
6
  const MISSING = { schema: "aiterm.remote-path.v1", exists: false, directory: false, writable: false };
7
7
  const denied = (code) => code === "EACCES" || code === "EPERM";
8
8
  const notPermitted = () => new RemoteTerminalError("FOLDER_NOT_PERMITTED", "the folder cannot be used by the terminal's SSH user (privacy consent, ACL or permissions)");
9
- export function checkRemotePath(value) {
9
+ // Drive-absolute with backslashes: UNC (\\server), device (\\?\), drive-relative (C:x), `/` separators and the characters
10
+ // Windows forbids in a name (a second `:` would be an alternate data stream) are refused.
11
+ // eslint-disable-next-line no-control-regex
12
+ const WINDOWS_ABSOLUTE = /^[A-Za-z]:\\[^<>:"/|?*\x00-\x1f\x7f]*$/;
13
+ /** The native absolute form of a terminal's system: `/...` on macOS and Linux, `X:\...` on Windows. */
14
+ export function isNativeAbsolute(value, system) {
15
+ if (typeof value !== "string")
16
+ return false;
10
17
  // eslint-disable-next-line no-control-regex
11
- if (typeof value !== "string" || !path.posix.isAbsolute(value) || /[\x00-\x1f\x7f]/.test(value) || Buffer.byteLength(value) > 4096)
12
- throw new RemoteTerminalError("PATH_INVALID", "path must be an absolute path without control characters");
18
+ if (/[\x00-\x1f\x7f]/.test(value))
19
+ return false;
20
+ return system === "windows" ? WINDOWS_ABSOLUTE.test(value) : path.posix.isAbsolute(value);
21
+ }
22
+ /** A launch `cwd` in the form of the terminal's system; without a known system either native form passes (the probed one is checked later). */
23
+ export function terminalCwdFits(cwd, platform) {
24
+ if (typeof cwd !== "string")
25
+ return false;
26
+ if (platform === "windows")
27
+ return isNativeAbsolute(cwd, "windows");
28
+ return cwd.startsWith("/") || (platform === undefined && isNativeAbsolute(cwd, "windows"));
29
+ }
30
+ /** The terminal's own system by default (this code runs on the terminal); the container side names the terminal's system. */
31
+ export function checkRemotePath(value, system = process.platform === "win32" ? "windows" : "posix") {
32
+ if (typeof value !== "string" || !isNativeAbsolute(value, system) || Buffer.byteLength(value) > 4096)
33
+ throw new RemoteTerminalError("PATH_INVALID", system === "windows"
34
+ ? "path must be a drive-absolute path like C:\\folder (backslashes, no UNC, no control characters)" : "path must be an absolute path without control characters");
13
35
  }
14
36
  function errno(error) { return error?.code; }
15
37
  /** Can this directory be listed? A privacy-protected folder (macOS TCC) refuses it with EPERM. */
@@ -84,11 +106,13 @@ export function inspectPath(target) {
84
106
  return { schema: "aiterm.remote-path.v1", exists: true, directory: true, writable: writable(target) };
85
107
  }
86
108
  export const LIST_DIRS_MAX = 500;
109
+ // Folders every drive root has: listing them raises access errors or shows system internals, never a project.
110
+ const WINDOWS_SYSTEM_FOLDERS = new Set(["$recycle.bin", "system volume information"]);
87
111
  /** Read-only folder picker listing (R15): subfolders only, no dot names, sorted, at most LIST_DIRS_MAX. */
88
112
  export function listDirectories(target, home = os.homedir()) {
89
113
  const dir = target === undefined ? home : target;
90
114
  checkRemotePath(dir);
91
- const base = { schema: "aiterm.remote-dirs.v1", home, path: path.posix.resolve(dir) };
115
+ const base = { schema: "aiterm.remote-dirs.v1", home, path: path.resolve(dir) };
92
116
  const state = folderState(base.path);
93
117
  if (state !== "directory")
94
118
  return { ...base, exists: state === "file", directory: false, entries: null, truncated: false };
@@ -103,7 +127,7 @@ export function listDirectories(target, home = os.homedir()) {
103
127
  }
104
128
  const names = [];
105
129
  for (const entry of dirents) {
106
- if (entry.name.startsWith("."))
130
+ if (entry.name.startsWith(".") || (process.platform === "win32" && WINDOWS_SYSTEM_FOLDERS.has(entry.name.toLowerCase())))
107
131
  continue;
108
132
  let folder = entry.isDirectory();
109
133
  if (!folder && entry.isSymbolicLink()) {
@@ -1,10 +1,14 @@
1
- // provision (remote-terminal.md R16): install this Aiterm version as a product-owned runtime on a macOS or Linux terminal,
1
+ // provision (remote-terminal.md R16): install this Aiterm version as a product-owned runtime on a macOS, Linux or Windows terminal,
2
2
  // before any terminal MCP exists. Runs over the binding's trusted key SSH; the terminal fetches the release assets.
3
3
  import { spawn, spawnSync } from "node:child_process";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
4
6
  import { createRequire } from "node:module";
5
7
  import { fileURLToPath } from "node:url";
6
- import { RemoteTerminalError, bindingStatus, classifySshFailure, sshEnvironment, trustedSshArguments } from "./remote-terminal.js";
8
+ import { RemoteTerminalError, binding, bindingStatus, classifySshFailure, sshEnvironment, trustedSshArguments, trustedTarget } from "./remote-terminal.js";
9
+ import { WINDOWS_STDIN_SCRIPT_COMMAND, remotePlatform } from "./remote.js";
7
10
  import { verifySetupRuntime } from "./setup.js";
11
+ import { psmuxBin, psmuxVersionSupported } from "./tmux-runtime.js";
8
12
  const pkg = createRequire(import.meta.url)("../package.json");
9
13
  export const RUNTIME_RELEASE_BASE = "https://github.com/kitepon/aiterm-mcp/releases/download";
10
14
  /** The terminal-side bootstrap, run as `/bin/sh -s -- VERSION BASE`. Prints one result line. */
@@ -25,11 +29,7 @@ case "$(uname -s)" in
25
29
  x86_64) A=x64 ;;
26
30
  aarch64|arm64) A=arm64 ;;
27
31
  *) fail PROVISION_PLATFORM_UNSUPPORTED ;;
28
- esac
29
- # The Linux runtime has no tmux: seats use the user's own. Look on the login PATH, as the later remote commands do.
30
- s=$(printenv SHELL); [ -x "$s" ] || s=/bin/sh
31
- p=$("$s" -lc env </dev/null 2>/dev/null | sed -n 's/^PATH=//p' | tail -n 1); [ -n "$p" ] && PATH=$p; export PATH
32
- command -v tmux >/dev/null 2>&1 || fail PROVISION_TMUX_MISSING ;;
32
+ esac ;;
33
33
  *) fail PROVISION_PLATFORM_UNSUPPORTED ;;
34
34
  esac
35
35
  NAME="aiterm-runtime-$V-$OS-$A"
@@ -69,6 +69,77 @@ if ! mv "$N" "$ROOT/current"; then
69
69
  fi
70
70
  echo "AITERM_PROVISION PROVISIONED $V $A"
71
71
  `;
72
+ /** The Windows bootstrap (PowerShell 5.1 and 7, ASCII only), run from stdin with V and BASE written in (both are validated before). Same result lines as PROVISION_SCRIPT.
73
+ * `current` is a junction to `runtime\<name>`: a running aiterm-mcp keeps its files open, and repointing a junction does not touch them. */
74
+ export function windowsProvisionScript(version, base) {
75
+ return [
76
+ "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'",
77
+ `$V = '${version}'; $BASE = '${base}'`,
78
+ "function Fail($c) { Write-Output ('AITERM_PROVISION_ERROR ' + $c); exit 3 }",
79
+ "if ($env:PROCESSOR_ARCHITECTURE -ne 'AMD64' -and $env:PROCESSOR_ARCHITEW6432 -ne 'AMD64') { Fail 'PROVISION_PLATFORM_UNSUPPORTED' }",
80
+ "$NAME = 'aiterm-runtime-' + $V + '-win32-x64'",
81
+ "$ROOT = Join-Path $env:USERPROFILE '.aiterm\\runtime'",
82
+ "try { New-Item -ItemType Directory -Force -Path $ROOT | Out-Null } catch { Fail 'RUNTIME_DIR_UNAVAILABLE' }",
83
+ // Windows PowerShell 5.1 turns native stderr into a terminating error under 'Stop'. The runtime carries its own psmux.
84
+ "function Native($exe, $arguments) { $ErrorActionPreference = 'Continue'; $o = & $exe @arguments 2>&1 | Out-String; return @{ ok = ($LASTEXITCODE -eq 0); out = $o } }",
85
+ "function Smoke($dir) { $r = Native (Join-Path $dir 'bin\\aiterm-remote-terminal.cmd') @('runtime-smoke', '--expect-version', $V); return $r.ok }",
86
+ "function Target($link) { $i = Get-Item -LiteralPath $link -Force -ErrorAction SilentlyContinue; if ($i -and $i.LinkType -eq 'Junction') { return [string]$i.Target }; return $null }",
87
+ "function Unlink($link) { if (Test-Path -LiteralPath $link) { [IO.Directory]::Delete($link) } }",
88
+ "$lock = Join-Path $ROOT '.lock'",
89
+ "try { New-Item -ItemType Directory -Path $lock | Out-Null } catch {",
90
+ " $p = 0; try { $p = [int](Get-Content -LiteralPath (Join-Path $lock 'pid') -ErrorAction Stop) } catch { }",
91
+ " if ($p -gt 0 -and (Get-Process -Id $p -ErrorAction SilentlyContinue)) { Fail 'PROVISION_BUSY' }",
92
+ " Remove-Item -LiteralPath $lock -Recurse -Force -ErrorAction SilentlyContinue",
93
+ " try { New-Item -ItemType Directory -Path $lock | Out-Null } catch { Fail 'PROVISION_BUSY' }",
94
+ "}",
95
+ "Set-Content -LiteralPath (Join-Path $lock 'pid') -Value $PID",
96
+ "$stage = Join-Path $ROOT ('.stage-' + $PID)",
97
+ "try {",
98
+ " $current = Join-Path $ROOT 'current'",
99
+ " $runtimeFile = Join-Path $current 'RUNTIME'",
100
+ " if ((Test-Path -LiteralPath $runtimeFile) -and ((Get-Content -LiteralPath $runtimeFile -Raw).Trim() -eq $NAME) -and (Smoke $current)) { Write-Output ('AITERM_PROVISION ALREADY_CURRENT ' + $V + ' x64'); exit 0 }",
101
+ " Get-ChildItem -LiteralPath $ROOT -Filter '.stage-*' -Force | ForEach-Object { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }",
102
+ " New-Item -ItemType Directory -Force -Path (Join-Path $stage 'x') | Out-Null",
103
+ " [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12",
104
+ " function Get($file) {",
105
+ " try { Invoke-WebRequest -UseBasicParsing -Uri ($BASE + '/v' + $V + '/' + $file) -OutFile (Join-Path $stage $file) }",
106
+ " catch { if ($_.Exception.Response -and [int]$_.Exception.Response.StatusCode -ge 400 -and [int]$_.Exception.Response.StatusCode -lt 500) { Fail 'RUNTIME_ARTIFACT_UNAVAILABLE' } Fail 'RUNTIME_DOWNLOAD_FAILED' }",
107
+ " }",
108
+ " $sums = 'aiterm-runtime-' + $V + '-SHA256SUMS'; $zip = $NAME + '.zip'",
109
+ " Get $sums; Get $zip",
110
+ " $want = ''",
111
+ " foreach ($line in (Get-Content -LiteralPath (Join-Path $stage $sums))) { $f = $line.Trim() -split '\\s+'; if ($f.Length -eq 2 -and ($f[1] -eq $zip -or $f[1] -eq ('*' + $zip))) { $want = $f[0].ToLower() } }",
112
+ " $got = (Get-FileHash -Algorithm SHA256 -LiteralPath (Join-Path $stage $zip)).Hash.ToLower()",
113
+ " if (-not $want -or $want -ne $got) { Fail 'RUNTIME_VERIFY_FAILED' }",
114
+ " $x = Join-Path $stage 'x'",
115
+ " if (-not (Native (Join-Path $env:SystemRoot 'System32\\tar.exe') @('-xf', (Join-Path $stage $zip), '-C', $x)).ok) { Fail 'RUNTIME_EXTRACT_FAILED' }",
116
+ " $N = Join-Path $x $NAME",
117
+ " if (-not (Test-Path -LiteralPath (Join-Path $N 'RUNTIME')) -or (Get-Content -LiteralPath (Join-Path $N 'RUNTIME') -Raw).Trim() -ne $NAME) { Fail 'RUNTIME_VERIFY_FAILED' }",
118
+ " if (-not (Smoke $N)) { Fail 'RUNTIME_SMOKE_FAILED' }",
119
+ // Running seats and psmux servers are not touched: the new directory is added beside the old one and only the junction moves.
120
+ " $dest = Join-Path $ROOT $NAME",
121
+ " $old = Target $current",
122
+ " if ($old -and ($old.TrimEnd('\\') -ieq $dest.TrimEnd('\\'))) { Unlink $current; $old = $null }",
123
+ // A leftover of the same name (its smoke failed) may still be in use: move it aside, never delete files under a running process.
124
+ " if (Test-Path -LiteralPath $dest) { try { Move-Item -LiteralPath $dest -Destination ($dest + '.old-' + $PID) } catch { Fail 'RUNTIME_ACTIVATE_FAILED' } }",
125
+ " Move-Item -LiteralPath $N -Destination $dest",
126
+ " $previous = Join-Path $ROOT 'previous'",
127
+ " Unlink $previous",
128
+ " if ($old) { New-Item -ItemType Junction -Path $previous -Target $old | Out-Null }",
129
+ " Unlink $current",
130
+ " try { New-Item -ItemType Junction -Path $current -Target $dest | Out-Null }",
131
+ " catch { if ($old) { New-Item -ItemType Junction -Path $current -Target $old | Out-Null }; Fail 'RUNTIME_ACTIVATE_FAILED' }",
132
+ // Older runtime folders go when nothing uses them; a folder a running aiterm-mcp holds stays (the delete fails and is ignored).
133
+ " $keep = @($dest, (Target $previous))",
134
+ " Get-ChildItem -LiteralPath $ROOT -Directory -Filter 'aiterm-runtime-*' -ErrorAction SilentlyContinue | Where-Object { $keep -notcontains $_.FullName } | ForEach-Object { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }",
135
+ " Write-Output ('AITERM_PROVISION PROVISIONED ' + $V + ' x64')",
136
+ "} finally {",
137
+ " Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue",
138
+ " Remove-Item -LiteralPath $lock -Recurse -Force -ErrorAction SilentlyContinue",
139
+ "}",
140
+ "",
141
+ ].join("\n");
142
+ }
72
143
  export function parseProvisionOutput(stdout) {
73
144
  const ok = /^AITERM_PROVISION (PROVISIONED|ALREADY_CURRENT) (\S+) /m.exec(stdout);
74
145
  if (ok)
@@ -85,7 +156,8 @@ export async function provision(ref, version = pkg.version) {
85
156
  if (status.credential.provider === "aiterm.native-ssh-key.v1" && !status.credential.available)
86
157
  throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", status.credential.reason ?? "the key is unavailable");
87
158
  // Throws CREDENTIAL_NOT_LOADED for a keyless binding whose key is not loaded.
88
- const args = trustedSshArguments(ref, `/bin/sh -s -- ${version} ${RUNTIME_RELEASE_BASE}`, null);
159
+ const windows = await remotePlatform(trustedTarget(binding(ref))) === "windows";
160
+ const args = trustedSshArguments(ref, windows ? WINDOWS_STDIN_SCRIPT_COMMAND : `/bin/sh -s -- ${version} ${RUNTIME_RELEASE_BASE}`, null);
89
161
  const run = await new Promise((resolve, reject) => {
90
162
  const child = spawn("ssh", args, { env: sshEnvironment(), stdio: ["pipe", "pipe", "pipe"] });
91
163
  let stdout = "", stderr = "";
@@ -95,13 +167,13 @@ export async function provision(ref, version = pkg.version) {
95
167
  child.on("error", reject);
96
168
  child.on("close", code => { clearTimeout(timer); resolve({ code, stdout, stderr }); });
97
169
  child.stdin.on("error", () => { });
98
- child.stdin.end(PROVISION_SCRIPT);
170
+ child.stdin.end(windows ? windowsProvisionScript(version, RUNTIME_RELEASE_BASE) : PROVISION_SCRIPT);
99
171
  });
100
172
  const parsed = parseProvisionOutput(run.stdout);
101
173
  if (parsed && "result" in parsed && run.code === 0)
102
174
  return { schema: "aiterm.remote-provision.v1", ref, result: parsed.result, version: parsed.version };
103
175
  if (parsed && "code" in parsed)
104
- throw new RemoteTerminalError(parsed.code, `provisioning the terminal failed (${parsed.code})`, parsed.code === "PROVISION_TMUX_MISSING" ? "install tmux with the terminal's package manager (for example apt install tmux), then provision again" : undefined);
176
+ throw new RemoteTerminalError(parsed.code, `provisioning the terminal failed (${parsed.code})`);
105
177
  if (run.code === 255) {
106
178
  const f = classifySshFailure(run.stderr);
107
179
  throw new RemoteTerminalError(f.code, f.message, f.action);
@@ -112,10 +184,18 @@ export async function provision(ref, version = pkg.version) {
112
184
  export async function runtimeSmoke(expectVersion) {
113
185
  if (pkg.version !== expectVersion)
114
186
  throw new RemoteTerminalError("RUNTIME_SMOKE_FAILED", `runtime is ${pkg.version}, expected ${expectVersion}`);
115
- const tmux = spawnSync("tmux", ["-V"], { encoding: "utf8", timeout: 10_000 });
116
- // The Linux runtime carries no tmux; its absence is the user's to fix.
117
- if (process.platform === "linux" && tmux.error?.code === "ENOENT")
118
- throw new RemoteTerminalError("PROVISION_TMUX_MISSING", "tmux is not installed on the terminal", "install tmux with the terminal's package manager, then provision again");
187
+ if (process.platform === "win32") {
188
+ // The runtime's own psmux (<runtime>\bin\psmux.exe, beside <runtime>\node\node.exe); Aiterm's lookup only in a build tree.
189
+ const ownPsmux = path.resolve(process.execPath, "../../bin/psmux.exe");
190
+ const psmux = spawnSync(fs.existsSync(ownPsmux) ? ownPsmux : psmuxBin(), ["-V"], { encoding: "utf8", timeout: 10_000 });
191
+ if (psmux.status !== 0 || !psmuxVersionSupported(psmux.stdout ?? ""))
192
+ throw new RemoteTerminalError("RUNTIME_SMOKE_FAILED", "the runtime's psmux does not run");
193
+ await verifySetupRuntime({ command: process.execPath, args: [fileURLToPath(new URL("./index.js", import.meta.url))] });
194
+ return { schema: "aiterm.runtime-smoke.v1", version: pkg.version, tmux: (/^psmux .*/mu.exec(psmux.stdout ?? "")?.[0] ?? "psmux").trim() };
195
+ }
196
+ // The runtime's own tmux (<runtime>/bin/tmux, beside <runtime>/node/bin/node); another one on PATH is only for a build tree.
197
+ const own = path.resolve(process.execPath, "../../../bin/tmux");
198
+ const tmux = spawnSync(fs.existsSync(own) ? own : "tmux", ["-V"], { encoding: "utf8", timeout: 10_000 });
119
199
  if (tmux.status !== 0)
120
200
  throw new RemoteTerminalError("RUNTIME_SMOKE_FAILED", "tmux does not run");
121
201
  await verifySetupRuntime({ command: process.execPath, args: [fileURLToPath(new URL("./index.js", import.meta.url))] });
@@ -4,7 +4,7 @@
4
4
  // serve stdio MCP for one bound connection, spawned by BellTeam terminals
5
5
  // credential-load --ref R --terminal-id ID --handle UUID --revision N --purpose ssh-key (key bytes on stdin; one JSON receipt line)
6
6
  // transcript-read --session S [--cursor-session ID --offset N] [--max-bytes N] (runs on the terminal)
7
- // authorize-key --ref R (login password on stdin until EOF; R14) provision --ref R (macOS/Linux runtime; R16)
7
+ // authorize-key --ref R [--os macos|linux|windows] (login password on stdin until EOF; R14) provision --ref R (macOS/Linux runtime; R16)
8
8
  // path-status|make-dir --path P | --path-base64 B, list-dirs [--path P | --path-base64 B] (on the terminal; R15) runtime-smoke --expect-version V (on the terminal)
9
9
  import { realpathSync } from "node:fs";
10
10
  import { fileURLToPath } from "node:url";
@@ -144,7 +144,10 @@ export function main(args) {
144
144
  return oneShot(() => {
145
145
  // Trust and the held key are checked before stdin is read (R14).
146
146
  const prepared = prepareAuthorization(option(rest, "--ref") ?? "");
147
- return readStdin().then(password => authorizeKey(prepared, password));
147
+ const system = option(rest, "--os");
148
+ if (system !== undefined && !terminalOsSchema.safeParse(system).success)
149
+ throw new RemoteTerminalError("OS_INVALID", "--os must be macos, linux or windows");
150
+ return readStdin().then(password => authorizeKey(prepared, password, system === "windows" ? "windows" : "posix"));
148
151
  }, "aiterm.remote-binding-error.v1");
149
152
  if (command === "askpass")
150
153
  return askpass(rest.join(" "), process.env[ASKPASS_SOCKET_ENV]);
@@ -10,7 +10,7 @@ import { createRequire } from "node:module";
10
10
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
11
11
  import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
12
12
  import { ensureStateRoot, writeJson0600 } from "./agent-shared.js";
13
- import { posixCommand, remotePlatform } from "./remote.js";
13
+ import { WAIT_RESOLVE, powershellForShell, remotePlatform, remoteShell, terminalCommand, terminalProgram } from "./remote.js";
14
14
  import { PRIVATE_ENV_SCHEMA } from "./private-env.js";
15
15
  import { checkRemotePath } from "./remote-path.js";
16
16
  const pkg = createRequire(import.meta.url)("../package.json");
@@ -174,7 +174,8 @@ export function classifySshFailure(stderr) {
174
174
  return { code: "HOST_TRUST_MISSING", message: "the terminal's host key is not trusted", action: "confirm the new host key" };
175
175
  if (/Permission denied|Too many authentication failures/i.test(stderr))
176
176
  return { code: "AUTH_FAILED", message: "the terminal refused the key" };
177
- if (/aiterm-mcp: (command )?not found|aiterm-mcp: No such file/i.test(stderr))
177
+ // POSIX, our own Windows guard (any language), and the English cmd / PowerShell wording when it names an Aiterm program.
178
+ if (/aiterm-[\w-]+: (command )?not found|aiterm-[\w-]+: No such file|aiterm-[\w-]+['"]? is not recognized as (an internal or external command|(the|a) name of a cmdlet)/i.test(stderr))
178
179
  return { code: "REMOTE_AITERM_UNAVAILABLE", message: "Aiterm is not installed on the terminal" };
179
180
  if (/Connection refused/i.test(stderr))
180
181
  return { code: "CONNECTION_REFUSED", message: "the terminal refused the SSH connection" };
@@ -264,11 +265,22 @@ export class SshStdioTransport {
264
265
  }
265
266
  export const REMOTE_SEAT_TOOLS = new Set(["agent_launch", "pty_send", "pty_observe", "pty_read", "pty_key", "claude_turn", "agent_stop", "pty_close"]);
266
267
  export const REMOTE_COMMAND_OPS = ["claude_version", "claude_install", "claude_update", "path_status", "make_dir", "list_dirs"];
268
+ // Fixed operations per terminal shell (R21). Windows: the official PowerShell installer; a failure stops with exit 1 and its message.
267
269
  const COMMANDS = {
268
- claude_version: "claude --version",
269
- claude_install: "curl -fsSL https://claude.ai/install.sh | bash",
270
- claude_update: "claude update",
270
+ claude_version: { posix: "claude --version 2>&1", windows: "claude --version 2>&1" },
271
+ claude_install: { posix: "curl -fsSL https://claude.ai/install.sh | bash 2>&1",
272
+ windows: "& { $ErrorActionPreference = 'Stop'; try { irm https://claude.ai/install.ps1 | iex } catch { $_.Exception.Message; exit 1 } } *>&1; exit 0" },
273
+ claude_update: { posix: "claude update 2>&1", windows: "claude update 2>&1" },
271
274
  };
275
+ // The official installers' place, which a login shell may not have on PATH yet.
276
+ const CLAUDE_VERSION_AFTER_INSTALL = {
277
+ posix: 'claude --version 2>&1 || "$HOME/.local/bin/claude" --version 2>&1',
278
+ windows: "$p = (Get-Command claude -ErrorAction SilentlyContinue).Source; if (-not $p) { $p = Join-Path $env:USERPROFILE '.local\\bin\\claude.exe' }; & $p --version 2>&1",
279
+ };
280
+ /** The remote command the forward keeper holds: it ends exactly when ssh's stdin closes. */
281
+ export function keeperCommand(shell) {
282
+ return shell === "posix" ? "cat >/dev/null" : powershellForShell(shell, "[Console]::In.ReadToEnd() | Out-Null");
283
+ }
272
284
  const WAIT_FLAGS = new Set(["--session", "--operation", "--timeout", "--cursor", "--steer", "--launch", "--input"]);
273
285
  const WAIT_VALUE = /^[A-Za-z0-9_.:-]{1,128}$/;
274
286
  /** wait_process.args minus the CLI path: only aiterm-wait's own flag/value pairs, each value a plain token. */
@@ -297,6 +309,8 @@ export const REMOTE_MINIMUM_VERSION = "0.65.0";
297
309
  // The first release with the terminal's path-status / make-dir (R15).
298
310
  export const REMOTE_PATH_OPS_VERSION = "0.69.0";
299
311
  export const REMOTE_LIST_DIRS_VERSION = "0.70.0";
312
+ // The first release whose terminal-side path operations know drive paths.
313
+ export const REMOTE_WINDOWS_PATH_VERSION = "0.70.8";
300
314
  export class RemoteTerminalConnection extends EventEmitter {
301
315
  b;
302
316
  dir;
@@ -306,8 +320,9 @@ export class RemoteTerminalConnection extends EventEmitter {
306
320
  client;
307
321
  remoteVersion;
308
322
  platform;
323
+ shell;
309
324
  closing = false;
310
- constructor(b, dir, agent, socket, identity, client, remoteVersion, platform) {
325
+ constructor(b, dir, agent, socket, identity, client, remoteVersion, platform, shell) {
311
326
  super();
312
327
  this.b = b;
313
328
  this.dir = dir;
@@ -317,6 +332,7 @@ export class RemoteTerminalConnection extends EventEmitter {
317
332
  this.client = client;
318
333
  this.remoteVersion = remoteVersion;
319
334
  this.platform = platform;
335
+ this.shell = shell;
320
336
  }
321
337
  static async open(input) {
322
338
  const target = validTarget(input.target);
@@ -334,6 +350,7 @@ export class RemoteTerminalConnection extends EventEmitter {
334
350
  throw new RemoteTerminalError("PRIVATE_ENV_INVALID", "invalid private env entry");
335
351
  // R20: the connect command is shell-specific, so the platform is known (and the declared os checked) before any MCP connection.
336
352
  const platform = await checkTerminalPlatform(trustedTarget(b), input.os);
353
+ const shell = await remoteShell(trustedTarget(b));
337
354
  // Short path: the agent socket must fit macOS's 104-byte sun_path.
338
355
  const dir = fs.mkdtempSync(path.join(os.platform() === "win32" ? os.tmpdir() : "/tmp", "aiterm-rt-"));
339
356
  fs.chmodSync(dir, 0o700);
@@ -364,7 +381,7 @@ export class RemoteTerminalConnection extends EventEmitter {
364
381
  throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", key.reason);
365
382
  fs.writeFileSync(identity, `${key.line}\n`, { mode: 0o600 });
366
383
  }
367
- const transport = new SshStdioTransport(sshArguments(b, agentSocket, identity, posixCommand("exec aiterm-mcp --private-env-stdin")), `${JSON.stringify({ schema: PRIVATE_ENV_SCHEMA, env: input.privateEnv ?? {} })}\n`);
384
+ const transport = new SshStdioTransport(sshArguments(b, agentSocket, identity, terminalCommand(shell, terminalProgram(["aiterm-mcp", "--private-env-stdin"]))), `${JSON.stringify({ schema: PRIVATE_ENV_SCHEMA, env: input.privateEnv ?? {} })}\n`);
368
385
  const client = new Client({ name: "aiterm-remote-terminal", version: pkg.version });
369
386
  try {
370
387
  await client.connect(transport, { timeout: 60_000 });
@@ -379,7 +396,7 @@ export class RemoteTerminalConnection extends EventEmitter {
379
396
  await client.close().catch(() => { });
380
397
  throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${remoteVersion}; ${REMOTE_MINIMUM_VERSION} or later is required`);
381
398
  }
382
- const connection = new RemoteTerminalConnection(b, dir, agent, agentSocket, identity, client, remoteVersion, platform);
399
+ const connection = new RemoteTerminalConnection(b, dir, agent, agentSocket, identity, client, remoteVersion, platform, shell);
383
400
  client.onclose = () => connection.ended();
384
401
  // After the caller has attached its listener to the returned connection.
385
402
  setImmediate(() => connection.emit("event", { type: "ready", at: new Date().toISOString(), remoteVersion }));
@@ -415,7 +432,7 @@ export class RemoteTerminalConnection extends EventEmitter {
415
432
  }
416
433
  exec(script, timeoutMs, signal) {
417
434
  return new Promise((resolve, reject) => {
418
- const child = spawn("ssh", sshArguments(this.b, this.socket, this.identity, posixCommand(script)), { env: sshEnvironment(), stdio: ["ignore", "pipe", "pipe"] });
435
+ const child = spawn("ssh", sshArguments(this.b, this.socket, this.identity, terminalCommand(this.shell, script)), { env: sshEnvironment(), stdio: ["ignore", "pipe", "pipe"] });
419
436
  let stdout = "", stderr = "";
420
437
  const timer = setTimeout(() => child.kill(), timeoutMs);
421
438
  signal?.addEventListener("abort", () => child.kill(), { once: true });
@@ -439,7 +456,7 @@ export class RemoteTerminalConnection extends EventEmitter {
439
456
  throw new RemoteTerminalError("TRANSCRIPT_MAX_INVALID", "invalid maxBytes");
440
457
  parts.push("--max-bytes", String(input.maxBytes));
441
458
  }
442
- const result = await this.exec(`exec aiterm-remote-terminal ${parts.join(" ")}`, 120_000);
459
+ const result = await this.exec(terminalProgram(["aiterm-remote-terminal", ...parts]), 120_000);
443
460
  const line = result.stdout.trim().split("\n").pop() ?? "";
444
461
  let parsed = null;
445
462
  try {
@@ -460,8 +477,7 @@ export class RemoteTerminalConnection extends EventEmitter {
460
477
  async wait(waitProcess, signal) {
461
478
  const flags = waitArguments(waitProcess?.args);
462
479
  // Same resolution as remoteWaitCommand: npm may link only aiterm-mcp.
463
- const resolve = 'w=$(command -v aiterm-wait) || w="$(dirname "$(readlink -f "$(command -v aiterm-mcp)")")/aiterm-wait-cli.js"';
464
- const result = await this.exec(`${resolve}; exec "$w" ${flags.join(" ")}`, 90_000_000, signal);
480
+ const result = await this.exec({ posix: `${WAIT_RESOLVE}; exec "$w" ${flags.join(" ")}`, windows: terminalProgram(["aiterm-wait", ...flags]).windows }, 90_000_000, signal);
465
481
  if (signal?.aborted)
466
482
  throw new RemoteTerminalError("WAIT_CANCELLED", "the wait was cancelled");
467
483
  const line = result.stdout.trim().split("\n").pop() ?? "";
@@ -485,23 +501,23 @@ export class RemoteTerminalConnection extends EventEmitter {
485
501
  throw new RemoteTerminalError("COMMAND_INVALID", `${op} takes no path`);
486
502
  if (!Object.hasOwn(COMMANDS, op))
487
503
  throw new RemoteTerminalError("COMMAND_UNSUPPORTED", "unknown op");
488
- const run = await this.exec(`${COMMANDS[op]} 2>&1`, op === "claude_version" ? 60_000 : 900_000);
504
+ const run = await this.exec(COMMANDS[op], op === "claude_version" ? 60_000 : 900_000);
489
505
  if (run.code === 255) {
490
506
  const f = classifySshFailure(run.stderr);
491
507
  throw new RemoteTerminalError(f.code, f.message, f.action);
492
508
  }
493
- // The official installer puts claude in ~/.local/bin, which a login shell may not have on PATH yet (Linux).
494
- const probe = op === "claude_version" ? run : await this.exec('claude --version 2>&1 || "$HOME/.local/bin/claude" --version 2>&1', 60_000);
509
+ const probe = op === "claude_version" ? run : await this.exec(CLAUDE_VERSION_AFTER_INSTALL, 60_000);
495
510
  const version = probe.code === 0 ? (/\d+\.\d+\.\d+\S*/.exec(probe.stdout)?.[0] ?? null) : null;
496
511
  return { op, exit_code: run.code, version, output_tail: run.stdout.slice(-2000) };
497
512
  }
498
513
  /** R15: the terminal's own fs answers; the path travels as base64 so no shell reads it. */
499
514
  async pathCommand(op, targetPath) {
500
- checkRemotePath(targetPath);
501
- if (!versionAtLeast(this.remoteVersion, REMOTE_PATH_OPS_VERSION))
502
- throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${this.remoteVersion}; ${REMOTE_PATH_OPS_VERSION} or later is required (provision the terminal)`);
515
+ checkRemotePath(targetPath, this.platform === "windows" ? "windows" : "posix");
516
+ const minimum = this.platform === "windows" ? REMOTE_WINDOWS_PATH_VERSION : REMOTE_PATH_OPS_VERSION;
517
+ if (!versionAtLeast(this.remoteVersion, minimum))
518
+ throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${this.remoteVersion}; ${minimum} or later is required (provision the terminal)`);
503
519
  const sub = op === "path_status" ? "path-status" : "make-dir";
504
- const result = await this.exec(`exec aiterm-remote-terminal ${sub} --path-base64 ${Buffer.from(targetPath, "utf8").toString("base64")}`, 60_000);
520
+ const result = await this.exec(terminalProgram(["aiterm-remote-terminal", sub, "--path-base64", Buffer.from(targetPath, "utf8").toString("base64")]), 60_000);
505
521
  if (result.code === 255) {
506
522
  const f = classifySshFailure(result.stderr);
507
523
  throw new RemoteTerminalError(f.code, f.message, f.action);
@@ -520,11 +536,12 @@ export class RemoteTerminalConnection extends EventEmitter {
520
536
  /** R15 list-dirs: read-only folder picker listing; no path lists the SSH user's home. */
521
537
  async listDirs(targetPath) {
522
538
  if (targetPath !== undefined)
523
- checkRemotePath(targetPath);
524
- if (!versionAtLeast(this.remoteVersion, REMOTE_LIST_DIRS_VERSION))
525
- throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${this.remoteVersion}; ${REMOTE_LIST_DIRS_VERSION} or later is required (update or provision the terminal)`);
526
- const flag = targetPath === undefined ? "" : ` --path-base64 ${Buffer.from(targetPath, "utf8").toString("base64")}`;
527
- const result = await this.exec(`exec aiterm-remote-terminal list-dirs${flag}`, 60_000);
539
+ checkRemotePath(targetPath, this.platform === "windows" ? "windows" : "posix");
540
+ const minimum = this.platform === "windows" ? REMOTE_WINDOWS_PATH_VERSION : REMOTE_LIST_DIRS_VERSION;
541
+ if (!versionAtLeast(this.remoteVersion, minimum))
542
+ throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${this.remoteVersion}; ${minimum} or later is required (update or provision the terminal)`);
543
+ const flag = targetPath === undefined ? [] : ["--path-base64", Buffer.from(targetPath, "utf8").toString("base64")];
544
+ const result = await this.exec(terminalProgram(["aiterm-remote-terminal", "list-dirs", ...flag]), 60_000);
528
545
  if (result.code === 255) {
529
546
  const f = classifySshFailure(result.stderr);
530
547
  throw new RemoteTerminalError(f.code, f.message, f.action);
@@ -569,16 +586,14 @@ function checkKeySource(ref, status, input) {
569
586
  if (status.credential.revision !== input.credentialRevision)
570
587
  throw new RemoteTerminalError("CREDENTIAL_REVISION_STALE", "the key changed; get the current value from the terminal registry and launch again");
571
588
  }
572
- const trustedTarget = (b) => ({ host: b.target.host, user: b.target.user, port: b.target.port, trusted_ref: b.ref });
573
- /** R20/T4: the terminal's real platform; macOS and Linux pass. A declared os that differs is a wrong target, Windows comes in 0.70.8. */
589
+ export const trustedTarget = (b) => ({ host: b.target.host, user: b.target.user, port: b.target.port, trusted_ref: b.ref });
590
+ /** R20/T4: the terminal's real platform (macOS, Linux or Windows). A declared os that differs is a wrong target; any other system is refused. */
574
591
  export async function checkTerminalPlatform(target, declared) {
575
592
  const actual = await remotePlatform(target);
576
593
  if (actual === null)
577
594
  throw new RemoteTerminalError("TERMINAL_PLATFORM_UNSUPPORTED", "the terminal is not a macOS, Linux or Windows system (the platform probe printed nothing recognisable)");
578
595
  if (declared !== undefined && declared !== actual)
579
596
  throw new RemoteTerminalError("TERMINAL_OS_MISMATCH", `the terminal is registered as ${declared} but runs ${actual}; correct the terminal's os or register the right machine`);
580
- if (actual === "windows")
581
- throw new RemoteTerminalError("TERMINAL_PLATFORM_UNSUPPORTED", "Windows terminals are not supported before Aiterm 0.70.8");
582
597
  return actual;
583
598
  }
584
599
  /** T1: the binding exists, the target is the binding's, both revisions are current. */
@@ -770,7 +785,7 @@ function keep(ref) {
770
785
  keeper.child.kill();
771
786
  return;
772
787
  }
773
- if (keeper.timer)
788
+ if (keeper.timer || keeper.starting)
774
789
  return;
775
790
  if (!forwardNeeded(ref)) {
776
791
  releaseLock(ref);
@@ -795,37 +810,45 @@ function keep(ref) {
795
810
  }
796
811
  const requested = b.seat_forward_port ?? 0;
797
812
  keeper.ingress = b.seat_ingress_port;
798
- let args;
799
- try {
800
- // The remote command ends when our stdin closes, so the forward dies with this process even on SIGKILL.
801
- args = trustedSshArguments(ref, "cat >/dev/null", null, ["-o", "ExitOnForwardFailure=yes", "-R", seatForwardSpec(requested, b.seat_ingress_port)]);
802
- }
803
- catch {
804
- releaseLock(ref);
805
- return;
806
- }
807
- const child = spawn("ssh", args, { env: sshEnvironment(), stdio: ["pipe", "ignore", "pipe"] });
808
- keeper.child = child;
809
- let stderr = "";
810
- child.stderr.on("data", (chunk) => {
811
- stderr = (stderr + chunk.toString("utf8")).slice(-4000);
812
- const forward = parseSeatForward(stderr);
813
- if (typeof forward === "number" && forward !== requested) {
814
- writeBinding(ref, { seat_forward_port: forward });
815
- keeper.refusals = 0;
816
- }
817
- });
818
- child.on("error", () => { });
819
- child.on("close", () => {
820
- keeper.child = null;
821
- if (parseSeatForward(stderr) === "refused" && requested !== 0 && ++keeper.refusals >= FORWARD_REFUSALS_BEFORE_NEW_PORT) {
822
- // The old P stays taken on the terminal: let sshd pick a new one (seats launched with the old P need a relaunch).
823
- writeBinding(ref, { seat_forward_port: undefined });
824
- keeper.refusals = 0;
825
- }
813
+ const again = () => {
826
814
  keeper.timer = setTimeout(() => { keeper.timer = null; keep(ref); }, FORWARD_RESTART_MS);
827
815
  keeper.timer.unref();
828
- });
816
+ };
817
+ // The remote command depends on the terminal's shell (T4): known from the cache, or probed once by this process.
818
+ keeper.starting = true;
819
+ remoteShell(trustedTarget(b)).then(shell => {
820
+ keeper.starting = false;
821
+ let args;
822
+ try {
823
+ // The remote command ends when our stdin closes, so the forward dies with this process even on SIGKILL.
824
+ args = trustedSshArguments(ref, keeperCommand(shell), null, ["-o", "ExitOnForwardFailure=yes", "-R", seatForwardSpec(requested, b.seat_ingress_port)]);
825
+ }
826
+ catch {
827
+ releaseLock(ref);
828
+ return;
829
+ }
830
+ const child = spawn("ssh", args, { env: sshEnvironment(), stdio: ["pipe", "ignore", "pipe"] });
831
+ keeper.child = child;
832
+ let stderr = "";
833
+ child.stderr.on("data", (chunk) => {
834
+ stderr = (stderr + chunk.toString("utf8")).slice(-4000);
835
+ const forward = parseSeatForward(stderr);
836
+ if (typeof forward === "number" && forward !== requested) {
837
+ writeBinding(ref, { seat_forward_port: forward });
838
+ keeper.refusals = 0;
839
+ }
840
+ });
841
+ child.on("error", () => { });
842
+ child.on("close", () => {
843
+ keeper.child = null;
844
+ if (parseSeatForward(stderr) === "refused" && requested !== 0 && ++keeper.refusals >= FORWARD_REFUSALS_BEFORE_NEW_PORT) {
845
+ // The old P stays taken on the terminal: let sshd pick a new one (seats launched with the old P need a relaunch).
846
+ writeBinding(ref, { seat_forward_port: undefined });
847
+ keeper.refusals = 0;
848
+ }
849
+ again();
850
+ });
851
+ }, () => { keeper.starting = false; again(); });
829
852
  }
830
853
  /** Every 60 s in every active process: keep (or take over from an exited holder) the forwards this state root needs. */
831
854
  export function maintainSeatForwards() {
package/dist/remote.js CHANGED
@@ -122,6 +122,10 @@ export function remoteShell(target) {
122
122
  if (!shell) {
123
123
  shell = runSsh(target, REMOTE_SHELL_PROBE).then(({ code, stdout, stderr }) => {
124
124
  if (code === 255) {
125
+ if (target.trusted_ref) {
126
+ const failure = classifySshFailure(stderr);
127
+ throw new RemoteTerminalError(failure.code, failure.message, failure.action);
128
+ }
125
129
  const detail = stderr.trim().split("\n").slice(-3).join(" / ") || "exit 255";
126
130
  throw new AitermError(`REMOTE_CONNECT_FAILED: ${remoteLabel(target)} へ接続できません(${detail})`, 2);
127
131
  }
@@ -162,7 +166,11 @@ export function remotePlatform(target) {
162
166
  const detail = stderr.trim().split("\n").slice(-3).join(" / ") || "exit 255";
163
167
  throw new AitermError(`REMOTE_CONNECT_FAILED: ${remoteLabel(target)} へ接続できません(${detail})`, 2);
164
168
  }
165
- return classifyRemotePlatform(stdout);
169
+ const found = classifyRemotePlatform(stdout);
170
+ // The same run tells which shell sshd starts, so a command build needs no second probe (T4).
171
+ if (found && !shells.has(key))
172
+ shells.set(key, Promise.resolve(found !== "windows" ? "posix" : classifyRemoteShell(stdout) === "cmd" ? "cmd" : "powershell"));
173
+ return found;
166
174
  });
167
175
  platform.catch(() => platforms.delete(key));
168
176
  platforms.set(key, platform);
@@ -178,6 +186,34 @@ export function posixCommand(script) {
178
186
  'r="$HOME/.aiterm/runtime/current/bin"; [ -x "$r/aiterm-mcp" ] && PATH="$r:$PATH"; export PATH';
179
187
  return `/bin/sh -c '${importPath}; ${script}'`;
180
188
  }
189
+ /** PowerShellの単引用符literal。`'`だけが特別で、`$`・空白・二重引用符・非ASCIIはそのまま文字になる。 */
190
+ export const powershellQuote = (value) => `'${value.replace(/'/g, "''")}'`;
191
+ /** `& 'prog' 'arg'...`。引数は全て単引用符で包む。 */
192
+ export const powershellInvoke = (argv) => `& ${argv.map(powershellQuote).join(" ")}`;
193
+ /** 固定のプログラム呼び出し。windowsのaiterm-*は、無い時に言語によらず読める`command not found`を出す。 */
194
+ export function terminalProgram(argv) {
195
+ const [program] = argv;
196
+ return {
197
+ posix: `exec ${argv.join(" ")}`,
198
+ windows: `${program.startsWith("aiterm-") ? `if (-not (Get-Command ${powershellQuote(program)} -ErrorAction SilentlyContinue)) { [Console]::Error.WriteLine(${powershellQuote(`${program}: command not found`)}); exit 127 }; ` : ""}${powershellInvoke(argv)}`,
199
+ };
200
+ }
201
+ // 製品のruntime(remote-terminal.md R16)があれば、利用者のPATH上の別のaiterm-mcpより先に使う。
202
+ // npm's .ps1 shims win over .cmd in PowerShell, and Windows PowerShell 5.1 is Restricted by default: allow scripts for this process only.
203
+ const WINDOWS_PREAMBLE = "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force -ErrorAction SilentlyContinue; $r = Join-Path $env:USERPROFILE '.aiterm\\runtime\\current\\bin'; if (Test-Path -LiteralPath (Join-Path $r 'aiterm-mcp.cmd')) { $env:PATH = $r + ';' + $env:PATH }; ";
204
+ // `pwsh -c`は最後のnative commandの失敗を全て1にする。ここで本物の終了codeを返す。
205
+ const WINDOWS_EPILOGUE = "; $ok = $?; $code = $LASTEXITCODE; if ($code) { exit $code }; if ($ok) { exit 0 }; exit 1";
206
+ /** PowerShell本文を、shellが`cmd`の時だけ`powershell -EncodedCommand`で包む(引用符の書式がcmdとPowerShellで違うため)。 */
207
+ export function powershellForShell(shell, body) {
208
+ return shell === "powershell" ? body
209
+ : `powershell -NoProfile -NonInteractive -OutputFormat Text -EncodedCommand ${Buffer.from(body, "utf16le").toString("base64")}`;
210
+ }
211
+ /** 端末のshellに合う1つのコマンド文字列。userの文字列はここへ入れない(固定文・検証済みtoken・base64だけ)。 */
212
+ export function terminalCommand(shell, script) {
213
+ return shell === "posix" ? posixCommand(script.posix) : powershellForShell(shell, `${WINDOWS_PREAMBLE}${script.windows}${WINDOWS_EPILOGUE}`);
214
+ }
215
+ /** stdinに載せたPowerShell scriptを丸ごと実行する入口(authorize-key・Windows provision)。scriptは多行・ASCIIだけ。 */
216
+ export const WINDOWS_STDIN_SCRIPT_COMMAND = powershellForShell("cmd", "Invoke-Expression ([Console]::In.ReadToEnd())");
181
217
  /** 現地のaiterm-mcpを起動するコマンド。Windowsはユーザー環境からPATHが入るので、そのまま呼ぶ。 */
182
218
  export function remoteServerCommand(shell) {
183
219
  return shell === "posix" ? posixCommand("exec aiterm-mcp") : "aiterm-mcp";
@@ -187,7 +223,9 @@ export async function callRemoteTool(target, name, args, timeoutMs = 600_000, pr
187
223
  if (privateEnv && !target.trusted_ref)
188
224
  throw new AitermError("REMOTE_PRIVATE_ENV_UNSUPPORTED: private values travel only to a terminal binding", 2);
189
225
  const shell = await remoteShell(target);
190
- const command = privateEnv ? posixCommand("exec aiterm-mcp --private-env-stdin") : remoteServerCommand(shell);
226
+ // 信頼済み端末はshellごとの正規のコマンド(runtimeの優先と終了codeを含む)。個別指定のremoteは従来のまま。
227
+ const command = target.trusted_ref ? terminalCommand(shell, terminalProgram(privateEnv ? ["aiterm-mcp", "--private-env-stdin"] : ["aiterm-mcp"]))
228
+ : privateEnv ? posixCommand("exec aiterm-mcp --private-env-stdin") : remoteServerCommand(shell);
191
229
  const { args: sshArgs, env } = sshInvocation(target, command);
192
230
  const transport = privateEnv
193
231
  ? new SshStdioTransport(sshArgs, `${JSON.stringify({ schema: PRIVATE_ENV_SCHEMA, env: privateEnv })}\n`)
@@ -226,9 +264,11 @@ export async function callRemoteTool(target, name, args, timeoutMs = 600_000, pr
226
264
  await client.close().catch(() => { });
227
265
  }
228
266
  }
267
+ // npmのbinをPATHへ通さず aiterm-mcp だけリンクしている端末がある。見つからなければ同じpackageのCLIを使う。
268
+ export const WAIT_RESOLVE = 'w=$(command -v aiterm-wait) || w="$(dirname "$(readlink -f "$(command -v aiterm-mcp)")")/aiterm-wait-cli.js"';
229
269
  const SESSION_RE = /^[A-Za-z0-9_-]{1,64}$/;
230
270
  const OPERATION_RE = /^sha256:[0-9a-f]{64}$/;
231
- export function remoteWaitCommand(shell, session, cursor, operationId, timeout, inputId) {
271
+ export function remoteWaitCommand(shell, session, cursor, operationId, timeout, inputId, trusted = false) {
232
272
  if (!SESSION_RE.test(session))
233
273
  throw new AitermError("REMOTE_SESSION_INVALID: session名が不正です", 2);
234
274
  if (operationId !== null && !OPERATION_RE.test(operationId))
@@ -242,16 +282,16 @@ export function remoteWaitCommand(shell, session, cursor, operationId, timeout,
242
282
  parts.push("--operation", operationId);
243
283
  if (inputId !== undefined)
244
284
  parts.push("--input", inputId);
285
+ if (trusted)
286
+ return terminalCommand(shell, { posix: `${WAIT_RESOLVE}; exec "$w" ${parts.join(" ")}`, windows: terminalProgram(["aiterm-wait", ...parts]).windows });
245
287
  if (shell !== "posix")
246
288
  return `aiterm-wait ${parts.join(" ")}`;
247
- // npmのbinをPATHへ通さず aiterm-mcp だけリンクしている端末がある。見つからなければ同じpackageのCLIを使う。
248
- const resolve = 'w=$(command -v aiterm-wait) || w="$(dirname "$(readlink -f "$(command -v aiterm-mcp)")")/aiterm-wait-cli.js"';
249
- return posixCommand(`${resolve}; exec "$w" ${parts.join(" ")}`);
289
+ return posixCommand(`${WAIT_RESOLVE}; exec "$w" ${parts.join(" ")}`);
250
290
  }
251
291
  /** 親が別processで起動する完了待ち。ssh越しのaiterm-waitで、exit codeは現地のaiterm-waitをそのまま返す。 */
252
292
  export async function remoteWaitProcess(target, session, cursor, inputId) {
253
293
  // 別processには鍵のパスフレーズを渡せない。ssh-agentか、張ってあるControlMasterの接続に相乗りする。
254
- const { args } = sshInvocation(target, remoteWaitCommand(await remoteShell(target), session, cursor, null, 600, inputId), { passphrase: false });
294
+ const { args } = sshInvocation(target, remoteWaitCommand(await remoteShell(target), session, cursor, null, 600, inputId, !!target.trusted_ref), { passphrase: false });
255
295
  return { executable: "ssh", args, windows_start_process_argument_list: process.platform === "win32" ? windowsStartProcessArgumentList(args) : null };
256
296
  }
257
297
  function runSsh(target, command, signal) {
@@ -277,7 +317,7 @@ export async function observeRemoteAgentDone(target, session, options) {
277
317
  if (options.signal?.aborted)
278
318
  throw new AitermError("REMOTE_OBSERVE_ABORTED: 観測を停止しました", 2);
279
319
  const remaining = infinite ? 86_400 : Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
280
- const command = remoteWaitCommand(await remoteShell(target), session, options.cursor ?? null, options.operation_id ?? null, Math.min(remaining, 86_400), options.input_id);
320
+ const command = remoteWaitCommand(await remoteShell(target), session, options.cursor ?? null, options.operation_id ?? null, Math.min(remaining, 86_400), options.input_id, !!target.trusted_ref);
281
321
  const { code, stdout, stderr } = await runSsh(target, command, options.signal);
282
322
  if (options.signal?.aborted)
283
323
  throw new AitermError("REMOTE_OBSERVE_ABORTED: 観測を停止しました", 2);
@@ -4,7 +4,7 @@ const ACTIONS = {
4
4
  TERMINAL_INVALID: "起動の指定(端末の情報か作業フォルダ)が正しくありません。BellTeamの不具合の恐れがあります。",
5
5
  TARGET_INVALID: "起動の指定(端末の情報)が正しくありません。BellTeamの不具合の恐れがあります。",
6
6
  TERMINAL_OS_MISMATCH: "端末のOSが、登録されているOSと違います。別の機械を指している恐れがあり止めました。端末の登録(OS)を確かめてください。",
7
- TERMINAL_PLATFORM_UNSUPPORTED: "この端末のOS(Windowsなど)では、まだ席を起こせません。MacかLinuxの端末を使ってください。",
7
+ TERMINAL_PLATFORM_UNSUPPORTED: "この端末のOSは、Mac・Linux・Windowsのどれとも確かめられず、席を起こせません。Mac、Linux、Windowsのどれかの端末を使ってください。",
8
8
  TERMINAL_HARNESS_UNSUPPORTED: "この端末で起こせるAIは、今はClaude CodeとCodexだけです。メンバーのAIをClaude CodeかCodexにしてください。",
9
9
  REF_INVALID: "端末の登録が見つかりません。端末の登録を確かめてください。",
10
10
  BINDING_UNKNOWN: "端末の登録が見つかりません。端末の登録を確かめてください。",
@@ -19,10 +19,10 @@ const ACTIONS = {
19
19
  CREDENTIAL_REVISION_STALE: "端末へ入る鍵が新しくなりました。新しい鍵で起こし直します。",
20
20
  CREDENTIAL_UNAVAILABLE: "端末へ入る鍵を使えません。端末の登録で鍵を確かめてください。",
21
21
  AUTH_FAILED: "端末が鍵を受け付けませんでした。端末の登録から、パスワードで鍵を許可し直してください。",
22
- CONNECTION_REFUSED: "端末がSSHの接続を断りました。端末のSSHサーバーが入になっているか確かめてください(Macは「リモートログイン」、Linuxはsshdの起動)。",
22
+ CONNECTION_REFUSED: "端末がSSHの接続を断りました。端末のSSHサーバーが入になっているか確かめてください(Macは「リモートログイン」、Linuxはsshdの起動、WindowsはオプションのOpenSSHサーバーの追加とsshdサービスの起動)。",
23
23
  UNREACHABLE: "端末につながりません。電源とネットワークを確かめてください。つながれば起こし直します。",
24
24
  CONNECTION_FAILED: "端末へのSSH接続に失敗しました。端末の電源とSSHの設定を確かめてください。",
25
- REMOTE_AITERM_UNAVAILABLE: "端末にAitermが入っていません。端末の準備(Aitermの導入)をやり直してください。",
25
+ REMOTE_AITERM_UNAVAILABLE: "端末にAitermが入っていません(またはsshで入った時のPATHにありません)。端末の準備(Aitermの導入)をやり直してください。",
26
26
  REMOTE_AITERM_TOO_OLD: "端末のAitermが古いため起こせません。端末のAitermを更新してください。",
27
27
  SEAT_FORWARD_UNAVAILABLE: "端末からBellTeamへ戻る通り道がまだ用意できていません。少し待ってから起こし直してください。",
28
28
  CWD_UNAVAILABLE: "端末に作業フォルダがありません。メンバーの作業フォルダを選び直すか、そのフォルダを作ってください。",
@@ -6,7 +6,7 @@ import { spawnSync } from "node:child_process";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { readCompletedTranscript } from "./transcript-read.js";
8
8
  import { boundTerminalTarget, classifySshFailure, trustedSshArguments } from "./remote-terminal.js";
9
- import { posixCommand } from "./remote.js";
9
+ import { remoteShell, terminalCommand, terminalProgram } from "./remote.js";
10
10
  const ERROR = "aiterm.transcript-read-error.v1";
11
11
  function option(args, name) {
12
12
  const at = args.indexOf(name);
@@ -30,14 +30,14 @@ export function transcriptFlags(args) {
30
30
  }
31
31
  return flags;
32
32
  }
33
- function run(args) {
33
+ async function run(args) {
34
34
  const flags = transcriptFlags(args);
35
35
  const target = boundTerminalTarget(flags[1]);
36
36
  if (!target) {
37
37
  const id = option(flags, "--cursor-session"), max = option(flags, "--max-bytes");
38
38
  return { line: JSON.stringify(readCompletedTranscript(flags[1], id ? { claudeSessionId: id, offset: Number(option(flags, "--offset")) } : null, max ? Number(max) : undefined)), code: 0 };
39
39
  }
40
- const ssh = spawnSync("ssh", trustedSshArguments(target.trusted_ref, posixCommand(`exec aiterm-remote-terminal transcript-read ${flags.join(" ")}`), null), { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 120_000, maxBuffer: 64 * 1024 * 1024 });
40
+ const ssh = spawnSync("ssh", trustedSshArguments(target.trusted_ref, terminalCommand(await remoteShell(target), terminalProgram(["aiterm-remote-terminal", "transcript-read", ...flags])), null), { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 120_000, maxBuffer: 64 * 1024 * 1024 });
41
41
  const line = (ssh.stdout ?? "").trim().split("\n").pop() ?? "";
42
42
  let parsed = null;
43
43
  try {
@@ -57,14 +57,9 @@ try {
57
57
  }
58
58
  catch { /* imported */ }
59
59
  if (entry) {
60
- try {
61
- const { line, code } = run(process.argv.slice(2));
62
- process.stdout.write(`${line}\n`);
63
- process.exit(code);
64
- }
65
- catch (error) {
60
+ run(process.argv.slice(2)).then(({ line, code }) => { process.stdout.write(`${line}\n`); process.exit(code); }, (error) => {
66
61
  const message = error instanceof Error ? error.message : String(error);
67
62
  process.stdout.write(`${JSON.stringify({ schema: ERROR, code: /^([A-Z][A-Z0-9_]+):/.exec(message)?.[1] ?? "AITERM_FAILED", message })}\n`);
68
63
  process.exit(2);
69
- }
64
+ });
70
65
  }
package/dist/write-ban.js CHANGED
@@ -5,6 +5,7 @@ import * as fs from "node:fs";
5
5
  import * as path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { AitermError } from "./errors.js";
8
+ import { resolveWindowsPowerShell7 } from "./windows-powershell.js";
8
9
  // Linux: Landlock via the bundled static helper (native/write-ban/aiterm-write-ban.c), so nothing has to be
9
10
  // installed on the machine. Unprivileged (works in standard Docker, where bwrap cannot create a namespace).
10
11
  // Fails closed: exit 126 before the CLI starts.
@@ -13,31 +14,45 @@ function landlockHelper() {
13
14
  throw unenforceable(`no write-ban helper for CPU ${process.arch}`);
14
15
  return fileURLToPath(new URL(`../native/write-ban/linux-${process.arch}/aiterm-write-ban`, import.meta.url));
15
16
  }
17
+ // Windows: the bundled helper (native/write-ban/aiterm-write-ban-win.c) runs the CLI under a restricted token whose
18
+ // marker SID is denied writes by an inert inheritable ACE on the folder (ADR 0140).
19
+ function windowsHelper() {
20
+ if (process.arch !== "x64")
21
+ throw unenforceable(`no write-ban helper for CPU ${process.arch}`);
22
+ return fileURLToPath(new URL("../native/write-ban/win32-x64/aiterm-write-ban.exe", import.meta.url));
23
+ }
16
24
  const unenforceable = (why) => new AitermError(`READONLY_UNENFORCEABLE: the project write-ban cannot be applied here: ${why}`, 2);
17
25
  function seatbeltProfile(folder) {
18
26
  return `(version 1)(allow default)(deny file-write* (subpath "${folder.replace(/[\\"]/g, "\\$&")}"))`;
19
27
  }
20
28
  /** argv placed before the CLI's own argv. The CLI is exec'd, so its PID and process name stay the seat's. */
21
29
  export function writeBanPrefix(ban) {
22
- return ban.method === "landlock"
23
- ? [landlockHelper(), ban.path, "--"]
24
- : ["/usr/bin/sandbox-exec", "-p", seatbeltProfile(ban.path)];
30
+ return ban.method === "landlock" ? [landlockHelper(), ban.path, "--"]
31
+ : ban.method === "restricted-token" ? [windowsHelper(), ban.path, "--"]
32
+ : ["/usr/bin/sandbox-exec", "-p", seatbeltProfile(ban.path)];
33
+ }
34
+ /** Windows: the helper starts the CLI with CreateProcess, which runs only real executables; npm shims go through pwsh. */
35
+ export function windowsWriteBanArgv(ban, argv) {
36
+ const [bin, ...rest] = argv;
37
+ const ps1 = /\.ps1$/i.test(bin) ? bin : /\.(?:cmd|bat)$/i.test(bin) ? bin.replace(/\.(?:cmd|bat)$/i, ".ps1") : null;
38
+ const cli = ps1 && fs.existsSync(ps1)
39
+ ? [resolveWindowsPowerShell7(), "-NoLogo", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", ps1, ...rest]
40
+ : /\.(?:cmd|bat)$/i.test(bin) ? [process.env.ComSpec ?? "cmd.exe", "/d", "/c", ...argv] : argv;
41
+ return [...writeBanPrefix(ban), ...cli];
25
42
  }
26
43
  /**
27
44
  * Prove on this machine that the ban can be applied before any seat starts. Without proof the fork is refused:
28
45
  * starting it would let it write the project (the one thing the Owner forbade).
29
46
  */
30
47
  export function probeWriteBan(folder, platform = process.platform) {
31
- if (platform === "win32")
32
- throw unenforceable("Windows has no same-user folder write-ban yet");
33
48
  if (!path.isAbsolute(folder) || !fs.existsSync(folder))
34
49
  throw unenforceable(`folder ${folder} does not exist`);
35
50
  const real = fs.realpathSync(folder);
36
51
  if (real === path.parse(real).root)
37
52
  throw unenforceable("the folder is the filesystem root");
38
- const ban = { path: real, method: platform === "darwin" ? "seatbelt" : "landlock" };
53
+ const ban = { path: real, method: platform === "darwin" ? "seatbelt" : platform === "win32" ? "restricted-token" : "landlock" };
39
54
  const [bin, ...args] = writeBanPrefix(ban);
40
- const probe = ban.method === "landlock" ? ["--probe", real] : [...args, "/usr/bin/true"];
55
+ const probe = ban.method === "seatbelt" ? [...args, "/usr/bin/true"] : ["--probe", real];
41
56
  const r = spawnSync(bin, probe, { encoding: "utf8", timeout: 10_000 });
42
57
  if (r.status !== 0)
43
58
  throw unenforceable((r.stderr || r.error?.message || `exit ${r.status}`).trim().split("\n").pop() ?? "probe failed");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.70.7",
3
+ "version": "0.70.8",
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": [
@@ -56,6 +56,7 @@
56
56
  "dist/*.js",
57
57
  "dist/harnesses/*.js",
58
58
  "native/write-ban/linux-*/aiterm-write-ban",
59
+ "native/write-ban/win32-x64/aiterm-write-ban.exe",
59
60
  "runtime-overlap.json",
60
61
  "state-compat.json",
61
62
  "README.md",