aiterm-mcp 0.70.7 → 0.70.9
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 +24 -1
- package/README.ja.md +3 -1
- package/README.md +3 -1
- package/dist/agent-metadata-reader.js +10 -2
- package/dist/agent-resolver.js +10 -0
- package/dist/core.js +60 -19
- package/dist/errors.js +6 -0
- package/dist/harnesses/antigravity.js +48 -3
- package/dist/harnesses/caller-mcp.js +94 -0
- package/dist/harnesses/cursor.js +50 -5
- package/dist/harnesses/grok.js +52 -3
- package/dist/index.js +23 -15
- package/dist/remote-authorize.js +51 -6
- package/dist/remote-contract.js +4 -4
- package/dist/remote-path.js +29 -5
- package/dist/remote-provision.js +94 -14
- package/dist/remote-terminal-cli.js +8 -5
- package/dist/remote-terminal.js +164 -63
- package/dist/remote.js +48 -8
- package/dist/terminal-launch-error.js +12 -9
- package/dist/transcript-read-cli.js +5 -10
- package/dist/write-ban.js +22 -7
- package/native/write-ban/win32-x64/aiterm-write-ban.exe +0 -0
- package/package.json +2 -1
package/dist/remote-provision.js
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
|
-
// provision (remote-terminal.md R16): install this Aiterm version as a product-owned runtime on a macOS or
|
|
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
|
|
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})
|
|
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
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
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";
|
|
@@ -108,9 +108,9 @@ function serve() {
|
|
|
108
108
|
}
|
|
109
109
|
});
|
|
110
110
|
server.registerTool("remote_terminal_command", {
|
|
111
|
-
description: "Fixed operation on the terminal: Claude Code setup, or a path check / mkdir / read-only folder listing",
|
|
112
|
-
inputSchema: { op: z.enum(REMOTE_COMMAND_OPS), path: z.string().optional() },
|
|
113
|
-
}, guarded(({ op, path }) => bound().command(op, path)));
|
|
111
|
+
description: "Fixed operation on the terminal: a CLI's version / install / update / login state (cli_*, harness required), Claude Code setup (claude_*), or a path check / mkdir / read-only folder listing",
|
|
112
|
+
inputSchema: { op: z.enum(REMOTE_COMMAND_OPS), path: z.string().optional(), harness: z.string().optional() },
|
|
113
|
+
}, guarded(({ op, path, harness }) => bound().command(op, path, harness)));
|
|
114
114
|
server.registerTool("remote_terminal_close", { description: "Close the bound connection and exit", inputSchema: {} }, guarded(async () => { const result = connection ? await connection.close() : { closed: true }; setTimeout(() => process.exit(0), 100); return result; }));
|
|
115
115
|
server.connect(new StdioServerTransport()).catch(error => { console.error("aiterm-remote-terminal fatal:", error); process.exit(1); });
|
|
116
116
|
}
|
|
@@ -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
|
-
|
|
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]);
|
package/dist/remote-terminal.js
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
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" };
|
|
@@ -263,12 +264,59 @@ export class SshStdioTransport {
|
|
|
263
264
|
async close() { this.child?.kill(); }
|
|
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
|
-
export const REMOTE_COMMAND_OPS = ["claude_version", "claude_install", "claude_update", "path_status", "make_dir", "list_dirs"
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
267
|
+
export const REMOTE_COMMAND_OPS = ["claude_version", "claude_install", "claude_update", "path_status", "make_dir", "list_dirs",
|
|
268
|
+
"cli_version", "cli_install", "cli_update", "cli_auth_status"];
|
|
269
|
+
export const CLI_HARNESSES = ["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"];
|
|
270
|
+
const CLAUDE_ALIASES = { claude_version: "cli_version", claude_install: "cli_install", claude_update: "cli_update" };
|
|
271
|
+
const posixInstall = (url, shell = "bash") => `curl -fsSL ${url} | ${shell} 2>&1`;
|
|
272
|
+
// A failure stops with exit 1 and its message (the official installers are `irm | iex`).
|
|
273
|
+
const windowsInstall = (url) => `& { $ErrorActionPreference = 'Stop'; try { irm ${url} | iex } catch { $_.Exception.Message; exit 1 } } *>&1; exit 0`;
|
|
274
|
+
const readJson = (text) => { try {
|
|
275
|
+
return JSON.parse(text.trim());
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
return null;
|
|
279
|
+
} };
|
|
280
|
+
const CLI = {
|
|
281
|
+
"claude-code": { bin: "claude", posixDir: "$HOME/.local/bin", winPath: "Join-Path $env:USERPROFILE '.local\\bin\\claude.exe'",
|
|
282
|
+
install: { posix: posixInstall("https://claude.ai/install.sh"), windows: windowsInstall("https://claude.ai/install.ps1") },
|
|
283
|
+
auth: ["auth", "status", "--json"],
|
|
284
|
+
classify: (code, out) => { const j = readJson(out); return j?.loggedIn === false ? false : j?.loggedIn === true && code === 0 ? true : null; } },
|
|
285
|
+
"codex-cli": { bin: "codex", posixDir: "$HOME/.local/bin", winPath: "Join-Path $env:LOCALAPPDATA 'Programs\\OpenAI\\Codex\\bin\\codex.exe'",
|
|
286
|
+
install: { posix: posixInstall("https://chatgpt.com/codex/install.sh", "CODEX_NON_INTERACTIVE=true sh"), windows: windowsInstall("https://chatgpt.com/codex/install.ps1") },
|
|
287
|
+
auth: ["login", "status"],
|
|
288
|
+
classify: (code, out, err) => { const t = `${out}\n${err}`; return /Not logged in/i.test(t) ? false : code === 0 && /Logged in/i.test(t) ? true : null; } },
|
|
289
|
+
"grok-cli": { bin: "grok", posixDir: "$HOME/.grok/bin", winPath: "Join-Path $env:USERPROFILE '.grok\\bin\\grok.exe'",
|
|
290
|
+
install: { posix: posixInstall("https://x.ai/cli/install.sh"), windows: windowsInstall("https://x.ai/cli/install.ps1") },
|
|
291
|
+
auth: ["models"], recheckMs: 1500,
|
|
292
|
+
classify: (code, out, err) => { const t = `${out}\n${err}`; return /You are not authenticated|Not signed in/i.test(t) ? false : code === 0 && /Available models/i.test(t) ? true : null; } },
|
|
293
|
+
"cursor-cli": { bin: "cursor-agent", posixDir: "$HOME/.local/bin", winPath: "Join-Path $env:LOCALAPPDATA 'cursor-agent\\cursor-agent.cmd'",
|
|
294
|
+
install: { posix: "curl https://cursor.com/install -fsS | bash 2>&1", windows: "& { $ErrorActionPreference = 'Stop'; try { irm 'https://cursor.com/install?win32=true' | iex } catch { $_.Exception.Message; exit 1 } } *>&1; exit 0" },
|
|
295
|
+
auth: ["status"],
|
|
296
|
+
classify: (code, out, err) => {
|
|
297
|
+
const t = `${out}\n${err}`;
|
|
298
|
+
return /not logged in|unauthenticated|sign in/i.test(t) ? false : /unable to fetch user details/i.test(t) ? null : code === 0 ? true : null;
|
|
299
|
+
} },
|
|
300
|
+
"antigravity-cli": { bin: "agy", posixDir: "$HOME/.local/bin", winPath: "Join-Path $env:LOCALAPPDATA 'agy\\bin\\agy.exe'",
|
|
301
|
+
install: { posix: posixInstall("https://antigravity.google/cli/install.sh"), windows: windowsInstall("https://antigravity.google/cli/install.ps1") },
|
|
302
|
+
auth: ["models"],
|
|
303
|
+
classify: (code, out, err) => code === 0 && /^\S+\t.+/m.test(out) ? true : /Please sign in to view available models/.test(err) ? false : null },
|
|
271
304
|
};
|
|
305
|
+
/** Version of a CLI: on PATH, else in its installer's place (a login shell may not have that on PATH yet). */
|
|
306
|
+
const cliVersionScript = (c) => ({
|
|
307
|
+
posix: `${c.bin} --version 2>&1 || "${c.posixDir}/${c.bin}" --version 2>&1`,
|
|
308
|
+
windows: `$p = (Get-Command ${c.bin} -ErrorAction SilentlyContinue).Source; if (-not $p) { $p = ${c.winPath} }; & $p --version 2>&1`,
|
|
309
|
+
});
|
|
310
|
+
const cliUpdateScript = (c) => ({ posix: `${c.bin} update 2>&1`, windows: `${c.bin} update 2>&1` });
|
|
311
|
+
/** Exit 127 when the CLI is in neither place, so "not installed" is told from "not logged in". */
|
|
312
|
+
const cliAuthScript = (c) => ({
|
|
313
|
+
posix: `b=$(command -v ${c.bin}) || b="${c.posixDir}/${c.bin}"; [ -x "$b" ] || exit 127; "$b" ${c.auth.join(" ")}`,
|
|
314
|
+
windows: `$p = (Get-Command ${c.bin} -ErrorAction SilentlyContinue).Source; if (-not $p) { $p = ${c.winPath}; if (-not (Test-Path -LiteralPath $p)) { exit 127 } }; & $p ${c.auth.join(" ")}`,
|
|
315
|
+
});
|
|
316
|
+
/** The remote command the forward keeper holds: it ends exactly when ssh's stdin closes. */
|
|
317
|
+
export function keeperCommand(shell) {
|
|
318
|
+
return shell === "posix" ? "cat >/dev/null" : powershellForShell(shell, "[Console]::In.ReadToEnd() | Out-Null");
|
|
319
|
+
}
|
|
272
320
|
const WAIT_FLAGS = new Set(["--session", "--operation", "--timeout", "--cursor", "--steer", "--launch", "--input"]);
|
|
273
321
|
const WAIT_VALUE = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
274
322
|
/** wait_process.args minus the CLI path: only aiterm-wait's own flag/value pairs, each value a plain token. */
|
|
@@ -297,6 +345,10 @@ export const REMOTE_MINIMUM_VERSION = "0.65.0";
|
|
|
297
345
|
// The first release with the terminal's path-status / make-dir (R15).
|
|
298
346
|
export const REMOTE_PATH_OPS_VERSION = "0.69.0";
|
|
299
347
|
export const REMOTE_LIST_DIRS_VERSION = "0.70.0";
|
|
348
|
+
// The first release whose terminal-side path operations know drive paths.
|
|
349
|
+
export const REMOTE_WINDOWS_PATH_VERSION = "0.70.8";
|
|
350
|
+
// The first release of the harness-generic cli_* ops, and the first a terminal may run Grok, Cursor and Antigravity seats on.
|
|
351
|
+
export const REMOTE_CLI_OPS_VERSION = "0.70.9";
|
|
300
352
|
export class RemoteTerminalConnection extends EventEmitter {
|
|
301
353
|
b;
|
|
302
354
|
dir;
|
|
@@ -306,8 +358,9 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
306
358
|
client;
|
|
307
359
|
remoteVersion;
|
|
308
360
|
platform;
|
|
361
|
+
shell;
|
|
309
362
|
closing = false;
|
|
310
|
-
constructor(b, dir, agent, socket, identity, client, remoteVersion, platform) {
|
|
363
|
+
constructor(b, dir, agent, socket, identity, client, remoteVersion, platform, shell) {
|
|
311
364
|
super();
|
|
312
365
|
this.b = b;
|
|
313
366
|
this.dir = dir;
|
|
@@ -317,6 +370,7 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
317
370
|
this.client = client;
|
|
318
371
|
this.remoteVersion = remoteVersion;
|
|
319
372
|
this.platform = platform;
|
|
373
|
+
this.shell = shell;
|
|
320
374
|
}
|
|
321
375
|
static async open(input) {
|
|
322
376
|
const target = validTarget(input.target);
|
|
@@ -334,6 +388,7 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
334
388
|
throw new RemoteTerminalError("PRIVATE_ENV_INVALID", "invalid private env entry");
|
|
335
389
|
// R20: the connect command is shell-specific, so the platform is known (and the declared os checked) before any MCP connection.
|
|
336
390
|
const platform = await checkTerminalPlatform(trustedTarget(b), input.os);
|
|
391
|
+
const shell = await remoteShell(trustedTarget(b));
|
|
337
392
|
// Short path: the agent socket must fit macOS's 104-byte sun_path.
|
|
338
393
|
const dir = fs.mkdtempSync(path.join(os.platform() === "win32" ? os.tmpdir() : "/tmp", "aiterm-rt-"));
|
|
339
394
|
fs.chmodSync(dir, 0o700);
|
|
@@ -364,7 +419,7 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
364
419
|
throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", key.reason);
|
|
365
420
|
fs.writeFileSync(identity, `${key.line}\n`, { mode: 0o600 });
|
|
366
421
|
}
|
|
367
|
-
const transport = new SshStdioTransport(sshArguments(b, agentSocket, identity,
|
|
422
|
+
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
423
|
const client = new Client({ name: "aiterm-remote-terminal", version: pkg.version });
|
|
369
424
|
try {
|
|
370
425
|
await client.connect(transport, { timeout: 60_000 });
|
|
@@ -379,7 +434,7 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
379
434
|
await client.close().catch(() => { });
|
|
380
435
|
throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${remoteVersion}; ${REMOTE_MINIMUM_VERSION} or later is required`);
|
|
381
436
|
}
|
|
382
|
-
const connection = new RemoteTerminalConnection(b, dir, agent, agentSocket, identity, client, remoteVersion, platform);
|
|
437
|
+
const connection = new RemoteTerminalConnection(b, dir, agent, agentSocket, identity, client, remoteVersion, platform, shell);
|
|
383
438
|
client.onclose = () => connection.ended();
|
|
384
439
|
// After the caller has attached its listener to the returned connection.
|
|
385
440
|
setImmediate(() => connection.emit("event", { type: "ready", at: new Date().toISOString(), remoteVersion }));
|
|
@@ -415,7 +470,7 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
415
470
|
}
|
|
416
471
|
exec(script, timeoutMs, signal) {
|
|
417
472
|
return new Promise((resolve, reject) => {
|
|
418
|
-
const child = spawn("ssh", sshArguments(this.b, this.socket, this.identity,
|
|
473
|
+
const child = spawn("ssh", sshArguments(this.b, this.socket, this.identity, terminalCommand(this.shell, script)), { env: sshEnvironment(), stdio: ["ignore", "pipe", "pipe"] });
|
|
419
474
|
let stdout = "", stderr = "";
|
|
420
475
|
const timer = setTimeout(() => child.kill(), timeoutMs);
|
|
421
476
|
signal?.addEventListener("abort", () => child.kill(), { once: true });
|
|
@@ -439,7 +494,7 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
439
494
|
throw new RemoteTerminalError("TRANSCRIPT_MAX_INVALID", "invalid maxBytes");
|
|
440
495
|
parts.push("--max-bytes", String(input.maxBytes));
|
|
441
496
|
}
|
|
442
|
-
const result = await this.exec(
|
|
497
|
+
const result = await this.exec(terminalProgram(["aiterm-remote-terminal", ...parts]), 120_000);
|
|
443
498
|
const line = result.stdout.trim().split("\n").pop() ?? "";
|
|
444
499
|
let parsed = null;
|
|
445
500
|
try {
|
|
@@ -460,8 +515,7 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
460
515
|
async wait(waitProcess, signal) {
|
|
461
516
|
const flags = waitArguments(waitProcess?.args);
|
|
462
517
|
// Same resolution as remoteWaitCommand: npm may link only aiterm-mcp.
|
|
463
|
-
const
|
|
464
|
-
const result = await this.exec(`${resolve}; exec "$w" ${flags.join(" ")}`, 90_000_000, signal);
|
|
518
|
+
const result = await this.exec({ posix: `${WAIT_RESOLVE}; exec "$w" ${flags.join(" ")}`, windows: terminalProgram(["aiterm-wait", ...flags]).windows }, 90_000_000, signal);
|
|
465
519
|
if (signal?.aborted)
|
|
466
520
|
throw new RemoteTerminalError("WAIT_CANCELLED", "the wait was cancelled");
|
|
467
521
|
const line = result.stdout.trim().split("\n").pop() ?? "";
|
|
@@ -476,32 +530,72 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
476
530
|
throw new RemoteTerminalError("COMMAND_FAILED", "aiterm-wait returned no receipt");
|
|
477
531
|
}
|
|
478
532
|
}
|
|
479
|
-
async command(op, targetPath) {
|
|
533
|
+
async command(op, targetPath, harness) {
|
|
534
|
+
if (harness !== undefined && !op.startsWith("cli_"))
|
|
535
|
+
throw new RemoteTerminalError("COMMAND_INVALID", `${op} takes no harness`);
|
|
480
536
|
if (op === "path_status" || op === "make_dir")
|
|
481
537
|
return this.pathCommand(op, targetPath);
|
|
482
538
|
if (op === "list_dirs")
|
|
483
539
|
return this.listDirs(targetPath);
|
|
484
540
|
if (targetPath !== undefined)
|
|
485
541
|
throw new RemoteTerminalError("COMMAND_INVALID", `${op} takes no path`);
|
|
486
|
-
|
|
542
|
+
const alias = CLAUDE_ALIASES[op];
|
|
543
|
+
const cliOp = alias ?? op;
|
|
544
|
+
if (!cliOp.startsWith("cli_"))
|
|
487
545
|
throw new RemoteTerminalError("COMMAND_UNSUPPORTED", "unknown op");
|
|
488
|
-
const
|
|
546
|
+
const h = alias ? "claude-code" : harness;
|
|
547
|
+
if (!h || !Object.hasOwn(CLI, h))
|
|
548
|
+
throw new RemoteTerminalError("COMMAND_INVALID", `${op} needs harness: one of ${CLI_HARNESSES.join(", ")}`);
|
|
549
|
+
if (!alias && !versionAtLeast(this.remoteVersion, REMOTE_CLI_OPS_VERSION))
|
|
550
|
+
throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${this.remoteVersion}; ${REMOTE_CLI_OPS_VERSION} or later is required (update Aiterm on the terminal)`);
|
|
551
|
+
const spec = CLI[h];
|
|
552
|
+
if (cliOp === "cli_auth_status")
|
|
553
|
+
return this.cliAuthStatus(h, spec);
|
|
554
|
+
const cell = this.shell === "posix" ? "posix" : "windows";
|
|
555
|
+
const installer = spec.install[cell];
|
|
556
|
+
if (cliOp === "cli_install" && installer === null)
|
|
557
|
+
throw new RemoteTerminalError("CLI_INSTALL_UNSUPPORTED", `no official one-line installer is known for ${h} on ${this.platform}`);
|
|
558
|
+
const script = cliOp === "cli_version" ? cliVersionScript(spec) : cliOp === "cli_update" ? cliUpdateScript(spec) : { posix: spec.install.posix ?? "", windows: spec.install.windows ?? "" };
|
|
559
|
+
const run = await this.exec(script, cliOp === "cli_version" ? 60_000 : 900_000);
|
|
489
560
|
if (run.code === 255) {
|
|
490
561
|
const f = classifySshFailure(run.stderr);
|
|
491
562
|
throw new RemoteTerminalError(f.code, f.message, f.action);
|
|
492
563
|
}
|
|
493
|
-
|
|
494
|
-
const probe = op === "claude_version" ? run : await this.exec('claude --version 2>&1 || "$HOME/.local/bin/claude" --version 2>&1', 60_000);
|
|
564
|
+
const probe = cliOp === "cli_version" ? run : await this.exec(cliVersionScript(spec), 60_000);
|
|
495
565
|
const version = probe.code === 0 ? (/\d+\.\d+\.\d+\S*/.exec(probe.stdout)?.[0] ?? null) : null;
|
|
496
|
-
|
|
566
|
+
const result = { exit_code: run.code, version, output_tail: run.stdout.slice(-2000) };
|
|
567
|
+
return alias ? { op, ...result } : { op, harness: h, ...result };
|
|
568
|
+
}
|
|
569
|
+
/** The login state and nothing of the CLI's own answer: `{op, harness, logged_in}`. */
|
|
570
|
+
async cliAuthStatus(h, spec) {
|
|
571
|
+
const ask = async () => {
|
|
572
|
+
const r = await this.exec(cliAuthScript(spec), 60_000);
|
|
573
|
+
if (r.code === 255) {
|
|
574
|
+
const f = classifySshFailure(r.stderr);
|
|
575
|
+
throw new RemoteTerminalError(f.code, f.message, f.action);
|
|
576
|
+
}
|
|
577
|
+
if (r.code === 127)
|
|
578
|
+
throw new RemoteTerminalError("CLI_NOT_INSTALLED", `${h} is not installed on the terminal (neither on PATH nor in its installer's place)`);
|
|
579
|
+
return spec.classify(r.code, r.stdout, r.stderr);
|
|
580
|
+
};
|
|
581
|
+
let answer = await ask();
|
|
582
|
+
// A live login can answer "not authenticated" once while it refreshes an old token (grokAuthStatus asks again the same way).
|
|
583
|
+
if (answer === false && spec.recheckMs) {
|
|
584
|
+
await new Promise(resolve => setTimeout(resolve, spec.recheckMs));
|
|
585
|
+
answer = await ask();
|
|
586
|
+
}
|
|
587
|
+
if (answer === null)
|
|
588
|
+
throw new RemoteTerminalError("AUTH_STATUS_UNCONFIRMED", `the login state of ${h} could not be read from its status answer`);
|
|
589
|
+
return { op: "cli_auth_status", harness: h, logged_in: answer };
|
|
497
590
|
}
|
|
498
591
|
/** R15: the terminal's own fs answers; the path travels as base64 so no shell reads it. */
|
|
499
592
|
async pathCommand(op, targetPath) {
|
|
500
|
-
checkRemotePath(targetPath);
|
|
501
|
-
|
|
502
|
-
|
|
593
|
+
checkRemotePath(targetPath, this.platform === "windows" ? "windows" : "posix");
|
|
594
|
+
const minimum = this.platform === "windows" ? REMOTE_WINDOWS_PATH_VERSION : REMOTE_PATH_OPS_VERSION;
|
|
595
|
+
if (!versionAtLeast(this.remoteVersion, minimum))
|
|
596
|
+
throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${this.remoteVersion}; ${minimum} or later is required (provision the terminal)`);
|
|
503
597
|
const sub = op === "path_status" ? "path-status" : "make-dir";
|
|
504
|
-
const result = await this.exec(
|
|
598
|
+
const result = await this.exec(terminalProgram(["aiterm-remote-terminal", sub, "--path-base64", Buffer.from(targetPath, "utf8").toString("base64")]), 60_000);
|
|
505
599
|
if (result.code === 255) {
|
|
506
600
|
const f = classifySshFailure(result.stderr);
|
|
507
601
|
throw new RemoteTerminalError(f.code, f.message, f.action);
|
|
@@ -520,11 +614,12 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
520
614
|
/** R15 list-dirs: read-only folder picker listing; no path lists the SSH user's home. */
|
|
521
615
|
async listDirs(targetPath) {
|
|
522
616
|
if (targetPath !== undefined)
|
|
523
|
-
checkRemotePath(targetPath);
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
const
|
|
617
|
+
checkRemotePath(targetPath, this.platform === "windows" ? "windows" : "posix");
|
|
618
|
+
const minimum = this.platform === "windows" ? REMOTE_WINDOWS_PATH_VERSION : REMOTE_LIST_DIRS_VERSION;
|
|
619
|
+
if (!versionAtLeast(this.remoteVersion, minimum))
|
|
620
|
+
throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${this.remoteVersion}; ${minimum} or later is required (update or provision the terminal)`);
|
|
621
|
+
const flag = targetPath === undefined ? [] : ["--path-base64", Buffer.from(targetPath, "utf8").toString("base64")];
|
|
622
|
+
const result = await this.exec(terminalProgram(["aiterm-remote-terminal", "list-dirs", ...flag]), 60_000);
|
|
528
623
|
if (result.code === 255) {
|
|
529
624
|
const f = classifySshFailure(result.stderr);
|
|
530
625
|
throw new RemoteTerminalError(f.code, f.message, f.action);
|
|
@@ -569,16 +664,14 @@ function checkKeySource(ref, status, input) {
|
|
|
569
664
|
if (status.credential.revision !== input.credentialRevision)
|
|
570
665
|
throw new RemoteTerminalError("CREDENTIAL_REVISION_STALE", "the key changed; get the current value from the terminal registry and launch again");
|
|
571
666
|
}
|
|
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
|
|
667
|
+
export const trustedTarget = (b) => ({ host: b.target.host, user: b.target.user, port: b.target.port, trusted_ref: b.ref });
|
|
668
|
+
/** 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
669
|
export async function checkTerminalPlatform(target, declared) {
|
|
575
670
|
const actual = await remotePlatform(target);
|
|
576
671
|
if (actual === null)
|
|
577
672
|
throw new RemoteTerminalError("TERMINAL_PLATFORM_UNSUPPORTED", "the terminal is not a macOS, Linux or Windows system (the platform probe printed nothing recognisable)");
|
|
578
673
|
if (declared !== undefined && declared !== actual)
|
|
579
674
|
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
675
|
return actual;
|
|
583
676
|
}
|
|
584
677
|
/** T1: the binding exists, the target is the binding's, both revisions are current. */
|
|
@@ -770,7 +863,7 @@ function keep(ref) {
|
|
|
770
863
|
keeper.child.kill();
|
|
771
864
|
return;
|
|
772
865
|
}
|
|
773
|
-
if (keeper.timer)
|
|
866
|
+
if (keeper.timer || keeper.starting)
|
|
774
867
|
return;
|
|
775
868
|
if (!forwardNeeded(ref)) {
|
|
776
869
|
releaseLock(ref);
|
|
@@ -795,37 +888,45 @@ function keep(ref) {
|
|
|
795
888
|
}
|
|
796
889
|
const requested = b.seat_forward_port ?? 0;
|
|
797
890
|
keeper.ingress = b.seat_ingress_port;
|
|
798
|
-
|
|
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
|
-
}
|
|
891
|
+
const again = () => {
|
|
826
892
|
keeper.timer = setTimeout(() => { keeper.timer = null; keep(ref); }, FORWARD_RESTART_MS);
|
|
827
893
|
keeper.timer.unref();
|
|
828
|
-
}
|
|
894
|
+
};
|
|
895
|
+
// The remote command depends on the terminal's shell (T4): known from the cache, or probed once by this process.
|
|
896
|
+
keeper.starting = true;
|
|
897
|
+
remoteShell(trustedTarget(b)).then(shell => {
|
|
898
|
+
keeper.starting = false;
|
|
899
|
+
let args;
|
|
900
|
+
try {
|
|
901
|
+
// The remote command ends when our stdin closes, so the forward dies with this process even on SIGKILL.
|
|
902
|
+
args = trustedSshArguments(ref, keeperCommand(shell), null, ["-o", "ExitOnForwardFailure=yes", "-R", seatForwardSpec(requested, b.seat_ingress_port)]);
|
|
903
|
+
}
|
|
904
|
+
catch {
|
|
905
|
+
releaseLock(ref);
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
const child = spawn("ssh", args, { env: sshEnvironment(), stdio: ["pipe", "ignore", "pipe"] });
|
|
909
|
+
keeper.child = child;
|
|
910
|
+
let stderr = "";
|
|
911
|
+
child.stderr.on("data", (chunk) => {
|
|
912
|
+
stderr = (stderr + chunk.toString("utf8")).slice(-4000);
|
|
913
|
+
const forward = parseSeatForward(stderr);
|
|
914
|
+
if (typeof forward === "number" && forward !== requested) {
|
|
915
|
+
writeBinding(ref, { seat_forward_port: forward });
|
|
916
|
+
keeper.refusals = 0;
|
|
917
|
+
}
|
|
918
|
+
});
|
|
919
|
+
child.on("error", () => { });
|
|
920
|
+
child.on("close", () => {
|
|
921
|
+
keeper.child = null;
|
|
922
|
+
if (parseSeatForward(stderr) === "refused" && requested !== 0 && ++keeper.refusals >= FORWARD_REFUSALS_BEFORE_NEW_PORT) {
|
|
923
|
+
// The old P stays taken on the terminal: let sshd pick a new one (seats launched with the old P need a relaunch).
|
|
924
|
+
writeBinding(ref, { seat_forward_port: undefined });
|
|
925
|
+
keeper.refusals = 0;
|
|
926
|
+
}
|
|
927
|
+
again();
|
|
928
|
+
});
|
|
929
|
+
}, () => { keeper.starting = false; again(); });
|
|
829
930
|
}
|
|
830
931
|
/** Every 60 s in every active process: keep (or take over from an exited holder) the forwards this state root needs. */
|
|
831
932
|
export function maintainSeatForwards() {
|