aiterm-mcp 0.70.6 → 0.70.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -1
- package/README.ja.md +1 -1
- package/README.md +1 -1
- package/dist/agent-metadata-reader.js +4 -1
- package/dist/agent-resolver.js +10 -0
- package/dist/core.js +31 -9
- package/dist/errors.js +6 -0
- package/dist/harnesses/codex.js +144 -3
- package/dist/index.js +51 -29
- package/dist/process-runtime.js +1 -1
- package/dist/process-tree-stop.js +8 -2
- package/dist/remote-authorize.js +51 -6
- package/dist/remote-contract.js +9 -4
- package/dist/remote-path.js +29 -5
- package/dist/remote-provision.js +108 -10
- package/dist/remote-terminal-cli.js +8 -5
- package/dist/remote-terminal.js +93 -54
- package/dist/remote.js +85 -8
- package/dist/terminal-launch-error.js +13 -9
- package/dist/transcript-read-cli.js +5 -10
- package/dist/write-ban.js +32 -42
- package/docs/RELEASE.md +1 -1
- package/native/write-ban/linux-arm64/aiterm-write-ban +0 -0
- package/native/write-ban/linux-x64/aiterm-write-ban +0 -0
- package/native/write-ban/win32-x64/aiterm-write-ban.exe +0 -0
- package/package.json +3 -1
package/dist/index.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { loadAgentMetadata } from "./agent-metadata-reader.js";
|
|
3
3
|
import { remoteInputDescription, remoteInputSchema, terminalArgumentDescription, terminalArgumentSchema } from "./remote-contract.js";
|
|
4
|
-
import { boundTerminalTarget, bindTerminalSession, terminalSeatGroups, ensureSeatForward, extractMcpHeaders, maintainSeatForwards, REMOTE_MINIMUM_VERSION, seatIngressPort, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
|
|
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";
|
|
8
|
-
import { AitermError, AgentAuthenticationPreflightError, AgentResumeUnavailableError, AgentResumeError } from "./errors.js";
|
|
9
|
+
import { AitermError, AgentAuthenticationPreflightError, AgentResumeUnavailableError, AgentResumeError, launchInputRefusal } from "./errors.js";
|
|
9
10
|
/**
|
|
10
11
|
* aiterm-mcp — AI が握るローカル永続端末を stdio MCP サーバとして公開する(Node/TS 版)。
|
|
11
12
|
*
|
|
@@ -20,6 +21,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
|
20
21
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
21
22
|
import { readPrivateEnvLine, setPrivateEnv } from "./private-env.js";
|
|
22
23
|
import { withTerminalLaunchAction, withErrorCode, launchNotStartedMeta } from "./terminal-launch-error.js";
|
|
24
|
+
import { codexMcpOverrides } from "./harnesses/codex.js";
|
|
23
25
|
import { CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
24
26
|
import { z } from "zod";
|
|
25
27
|
import { agentModelsResult } from "./model-catalog.js";
|
|
@@ -261,7 +263,7 @@ export function createAitermServer(options = {}) {
|
|
|
261
263
|
};
|
|
262
264
|
if (e instanceof AitermError && e.launchNotStarted)
|
|
263
265
|
return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
|
|
264
|
-
_meta: launchNotStartedMeta(e.launchNotStarted.harness) };
|
|
266
|
+
_meta: launchNotStartedMeta(e.launchNotStarted.harness, e.launchNotStarted.phase) };
|
|
265
267
|
return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true };
|
|
266
268
|
}
|
|
267
269
|
/**
|
|
@@ -840,15 +842,16 @@ export function createAitermServer(options = {}) {
|
|
|
840
842
|
try {
|
|
841
843
|
const local = core.readSeatTurns(sessions.filter(session => session.harness !== null).map(session => session.session_id));
|
|
842
844
|
// Terminal seats: the same call relayed with the same _meta; each terminal answers only for its own bound sessions.
|
|
843
|
-
// Inside the caller's 5 s pty_list budget (tool catalog timeout_ms): a
|
|
845
|
+
// Inside the caller's 5 s pty_list budget (tool catalog timeout_ms): a terminal that fails or is slow contributes
|
|
846
|
+
// no rows, and its sessions are listed in `unread` so the caller keeps their last state instead of reading them as gone.
|
|
844
847
|
const remote = await Promise.all(terminalSeatGroups().map(({ target, sessions: bound }) => Promise.race([
|
|
845
848
|
callRemoteTool(target, "pty_list", {}, 4_000, undefined, requestMeta).then(result => {
|
|
846
849
|
const seats = result._meta?.[SEAT_TURNS_RESULT_META_KEY]?.seats;
|
|
847
|
-
return Array.isArray(seats) ? seats.filter((seat) => bound.includes(seat?.session_id)) : [];
|
|
848
|
-
}, () => []),
|
|
849
|
-
new Promise(resolve => setTimeout(resolve, 4_000, []).unref()),
|
|
850
|
+
return Array.isArray(seats) ? { seats: seats.filter((seat) => bound.includes(seat?.session_id)), unread: [] } : { seats: [], unread: bound };
|
|
851
|
+
}, () => ({ seats: [], unread: bound })),
|
|
852
|
+
new Promise(resolve => setTimeout(resolve, 4_000, { seats: [], unread: bound }).unref()),
|
|
850
853
|
])));
|
|
851
|
-
return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { ...local, seats: [...local.seats, ...remote.
|
|
854
|
+
return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { ...local, seats: [...local.seats, ...remote.flatMap(r => r.seats)], unread: remote.flatMap(r => r.unread) } } };
|
|
852
855
|
}
|
|
853
856
|
catch (e) {
|
|
854
857
|
return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { schema: "aiterm.seat-turns.v1", error: e instanceof Error ? e.message : String(e) } } };
|
|
@@ -1219,11 +1222,15 @@ export function createAitermServer(options = {}) {
|
|
|
1219
1222
|
async function launchRemoteAgent(target, harness, args, extra, privateEnv) {
|
|
1220
1223
|
if (args.image && args.image.length > 0)
|
|
1221
1224
|
throw new core.AitermError("REMOTE_IMAGE_UNSUPPORTED: 別端末への画像添付には未対応です", 2);
|
|
1222
|
-
// An Aiterm without fork_from would drop it and start a writable seat (ADR 0140)
|
|
1223
|
-
|
|
1225
|
+
// An Aiterm without fork_from would drop it and start a writable seat (ADR 0140), and one without Codex caller fields
|
|
1226
|
+
// would drop or refuse them: check the version first.
|
|
1227
|
+
const needs = args.fork_from ? { minimum: FORK_MINIMUM_VERSION, what: "fork_from" }
|
|
1228
|
+
: harness === "codex-cli" && (args.append_system_prompt !== undefined || args.mcp_config !== undefined)
|
|
1229
|
+
? { minimum: CODEX_REMOTE_MINIMUM_VERSION, what: "append_system_prompt / mcp_config for codex-cli" } : null;
|
|
1230
|
+
if (needs) {
|
|
1224
1231
|
const version = (await callRemoteTool(target, "pty_list", {}, 60_000)).remote_version ?? "0.0.0";
|
|
1225
|
-
if (!versionAtLeast(version,
|
|
1226
|
-
throw new AitermError(`REMOTE_AITERM_TOO_OLD: the remote runs Aiterm ${version};
|
|
1232
|
+
if (!versionAtLeast(version, needs.minimum))
|
|
1233
|
+
throw new AitermError(`REMOTE_AITERM_TOO_OLD: the remote runs Aiterm ${version}; ${needs.what} needs ${needs.minimum} or later`, 2);
|
|
1227
1234
|
}
|
|
1228
1235
|
const delivery = args.prompt || args.throughline_source_session ? await deliveryForRequest(extra, true) : null;
|
|
1229
1236
|
// A terminal's claude_agent takes append_system_prompt / mcp_config since 0.65.0; its agent_launch drops them until this release.
|
|
@@ -1259,27 +1266,34 @@ export function createAitermServer(options = {}) {
|
|
|
1259
1266
|
}
|
|
1260
1267
|
/** First release whose agent_launch knows fork_from (ADR 0140). */
|
|
1261
1268
|
const FORK_MINIMUM_VERSION = "0.70.6";
|
|
1269
|
+
/** First release whose agent_launch takes append_system_prompt / mcp_config for codex-cli, and the first a terminal may run a Codex seat on. */
|
|
1270
|
+
const CODEX_REMOTE_MINIMUM_VERSION = "0.70.7";
|
|
1262
1271
|
const terminalVersions = new Map();
|
|
1263
1272
|
/** A seat on a BellTeam terminal (remote-terminal.md "One launch path"). Same launch arguments plus terminal + cwd. */
|
|
1264
1273
|
async function launchTerminalAgent(harness, terminal, args, extra) {
|
|
1265
1274
|
try {
|
|
1266
1275
|
if (args.remote)
|
|
1267
1276
|
throw new AitermError("TERMINAL_INVALID: use terminal or remote, not both; for a registered terminal pass only terminal", 2);
|
|
1268
|
-
if (harness !== "claude-code")
|
|
1269
|
-
throw new AitermError(`TERMINAL_HARNESS_UNSUPPORTED: terminal seats support
|
|
1270
|
-
|
|
1271
|
-
|
|
1277
|
+
if (harness !== "claude-code" && harness !== "codex-cli")
|
|
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);
|
|
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);
|
|
1272
1282
|
if (args.require_existing_resume)
|
|
1273
1283
|
throw new AitermError("TERMINAL_INVALID: require_existing_resume is local-only", 2);
|
|
1274
1284
|
const target = terminalRemoteTarget(terminal);
|
|
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);
|
|
1275
1288
|
// The private line is sent before the server answers; check its version first so an old one never sees it.
|
|
1276
1289
|
let version = terminalVersions.get(target.trusted_ref);
|
|
1277
1290
|
if (!version) {
|
|
1278
1291
|
version = (await callRemoteTool(target, "pty_list", {}, 60_000)).remote_version ?? "0.0.0";
|
|
1279
1292
|
terminalVersions.set(target.trusted_ref, version);
|
|
1280
1293
|
}
|
|
1281
|
-
|
|
1282
|
-
|
|
1294
|
+
const minimum = harness === "codex-cli" ? CODEX_REMOTE_MINIMUM_VERSION : REMOTE_MINIMUM_VERSION;
|
|
1295
|
+
if (!versionAtLeast(version, minimum))
|
|
1296
|
+
throw new AitermError(`REMOTE_AITERM_TOO_OLD: the terminal runs Aiterm ${version}; ${minimum} or later is required (update Aiterm on the terminal)`, 2);
|
|
1283
1297
|
const privateEnv = {};
|
|
1284
1298
|
for (const name of args.env_vars ?? []) {
|
|
1285
1299
|
const value = launchEnvValue(name);
|
|
@@ -1291,6 +1305,14 @@ export function createAitermServer(options = {}) {
|
|
|
1291
1305
|
const extracted = extractMcpHeaders(mcpConfig);
|
|
1292
1306
|
Object.assign(privateEnv, extracted.env);
|
|
1293
1307
|
mcpConfig = extracted.config;
|
|
1308
|
+
// Codex cannot say every header shape: refuse here, not on the terminal after the private line was sent.
|
|
1309
|
+
if (harness === "codex-cli")
|
|
1310
|
+
try {
|
|
1311
|
+
codexMcpOverrides(mcpConfig);
|
|
1312
|
+
}
|
|
1313
|
+
catch (e) {
|
|
1314
|
+
throw launchInputRefusal(harness, e.message);
|
|
1315
|
+
}
|
|
1294
1316
|
const ingress = seatIngressPort(mcpConfig);
|
|
1295
1317
|
if (ingress)
|
|
1296
1318
|
mcpConfig = rewriteSeatMcpConfig(mcpConfig, await ensureSeatForward(target.trusted_ref, ingress));
|
|
@@ -1300,10 +1322,10 @@ export function createAitermServer(options = {}) {
|
|
|
1300
1322
|
const session = result?.structuredContent?.session_id;
|
|
1301
1323
|
if (typeof session === "string")
|
|
1302
1324
|
bindTerminalSession(session, target.trusted_ref);
|
|
1303
|
-
return withErrorCode(withTerminalLaunchAction(result));
|
|
1325
|
+
return withErrorCode(withTerminalLaunchAction(result, harness));
|
|
1304
1326
|
}
|
|
1305
1327
|
catch (e) {
|
|
1306
|
-
return withErrorCode(withTerminalLaunchAction(fail(e)));
|
|
1328
|
+
return withErrorCode(withTerminalLaunchAction(fail(e), harness));
|
|
1307
1329
|
}
|
|
1308
1330
|
}
|
|
1309
1331
|
async function launchAgent(kind, args, extra) {
|
|
@@ -1312,10 +1334,10 @@ export function createAitermServer(options = {}) {
|
|
|
1312
1334
|
let delivery = null;
|
|
1313
1335
|
try {
|
|
1314
1336
|
if (!supportsWriteScope && write_scope !== undefined) {
|
|
1315
|
-
throw
|
|
1337
|
+
throw launchInputRefusal(core.agentHarness(kind), "claude-code harnessはwrite_scopeに対応していません。指定を外してください");
|
|
1316
1338
|
}
|
|
1317
1339
|
if (require_existing_resume && ((image?.length ?? 0) > 0 || prompt != null || throughline_source_session != null || throughline_supplement_file != null))
|
|
1318
|
-
throw
|
|
1340
|
+
throw launchInputRefusal(core.agentHarness(kind), "require_existing_resume is promptless");
|
|
1319
1341
|
if (!require_existing_resume)
|
|
1320
1342
|
await core.maintainAgentIdleClocks();
|
|
1321
1343
|
const initialPrompt = image && image.length > 0 ? core.attachImages(prompt ?? "", image) : prompt ?? undefined;
|
|
@@ -1497,12 +1519,12 @@ export function createAitermServer(options = {}) {
|
|
|
1497
1519
|
launch_operation_id: z.string().regex(/^sha256:[0-9a-f]{64}$/).optional().describe("Claude Codeのpromptなしexact replay相関だけで使用"),
|
|
1498
1520
|
remote: remoteInputField,
|
|
1499
1521
|
terminal: terminalArgumentSchema.optional().describe(terminalArgumentDescription),
|
|
1500
|
-
append_system_prompt: z.string().min(1).optional().describe("claude-code only. Launch instructions added to the system prompt; kept in Aiterm state, not in the project or home. Never put secrets here"),
|
|
1501
|
-
mcp_config: z.object({ mcpServers: z.record(z.string(), z.unknown()) }).strict().optional().describe("claude-code only. Extra MCP servers for this seat. Secret header values: write ${NAME} and list NAME in env_vars"),
|
|
1522
|
+
append_system_prompt: z.string().min(1).optional().describe("claude-code and codex-cli only. Launch instructions added to the system prompt (Codex: appended to developer_instructions after Aiterm's marker, at most 64 KiB); kept in Aiterm state, not in the project or home. Never put secrets here"),
|
|
1523
|
+
mcp_config: z.object({ mcpServers: z.record(z.string(), z.unknown()) }).strict().optional().describe("claude-code and codex-cli only. Extra MCP servers for this seat. Secret header values: write ${NAME} and list NAME in env_vars. Codex takes only http servers {type?: \"http\", url, headers}: 'Authorization: Bearer ${NAME}' or a header whose whole value is ${NAME}; other shapes are refused before the seat starts"),
|
|
1502
1524
|
fork_from: z.object({
|
|
1503
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)"),
|
|
1504
1526
|
fork_id: z.string().min(1).max(200).optional().describe("Caller's fork ID, passed to the seat as THROUGHLINE_FORK_ID"),
|
|
1505
|
-
}).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.
|
|
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"),
|
|
1506
1528
|
},
|
|
1507
1529
|
outputSchema: {
|
|
1508
1530
|
schema: z.literal("aiterm.agent-launch-result.v1"),
|
|
@@ -1525,17 +1547,17 @@ export function createAitermServer(options = {}) {
|
|
|
1525
1547
|
write_scope: z.string().optional(),
|
|
1526
1548
|
write_scope_enforcement: z.enum(["enforced_read_only", "declaration_only_unsupported"]).optional(),
|
|
1527
1549
|
fork_of: z.object({ session_id: z.string(), vendor_session_id: z.string(),
|
|
1528
|
-
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"),
|
|
1529
1551
|
},
|
|
1530
1552
|
}, async ({ harness, remote, terminal, ...args }, extra) => {
|
|
1531
|
-
if (harness !== "claude-code" && (args.append_system_prompt !== undefined || args.mcp_config !== undefined))
|
|
1532
|
-
return fail(
|
|
1553
|
+
if (harness !== "claude-code" && harness !== "codex-cli" && (args.append_system_prompt !== undefined || args.mcp_config !== undefined))
|
|
1554
|
+
return fail(launchInputRefusal(harness, `append_system_prompt and mcp_config are claude-code and codex-cli only; ${harness} cannot take them`));
|
|
1533
1555
|
if (terminal)
|
|
1534
1556
|
return launchTerminalAgent(harness, terminal, { ...args, ...(remote ? { remote } : {}) }, extra);
|
|
1535
1557
|
if (remote && args.require_existing_resume)
|
|
1536
1558
|
return fail(typeof args.session_name === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(args.session_name)
|
|
1537
1559
|
? new AgentResumeUnavailableError(args.session_name)
|
|
1538
|
-
:
|
|
1560
|
+
: launchInputRefusal(harness, "require_existing_resume requires session_name"));
|
|
1539
1561
|
if (!remote)
|
|
1540
1562
|
return launchAgent(kindForHarness(harness), args, extra);
|
|
1541
1563
|
try {
|
package/dist/process-runtime.js
CHANGED
|
@@ -171,7 +171,7 @@ export function signalRuntimeProcess(target, signal, group) {
|
|
|
171
171
|
"try {",
|
|
172
172
|
"[void]$target.Handle",
|
|
173
173
|
`if(([DateTimeOffset]$target.StartTime.ToUniversalTime()).ToUnixTimeMilliseconds() -ne ${Date.parse(target.started_identity)}) { exit 4 }`,
|
|
174
|
-
signal === "
|
|
174
|
+
signal === "SIGKILL" ? "$target.Kill()" : "[void]$target.CloseMainWindow()",
|
|
175
175
|
"} finally { $target.Dispose() }",
|
|
176
176
|
].join("\n");
|
|
177
177
|
const result = spawnSync(resolveWindowsPowerShell7(), ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand",
|
|
@@ -5,7 +5,9 @@ const nativeRuntime = {
|
|
|
5
5
|
read: () => readRuntimeProcesses(true), signal: signalRuntimeProcess,
|
|
6
6
|
pause: ms => new Promise(resolve => setTimeout(resolve, ms)), now: () => performance.now(),
|
|
7
7
|
};
|
|
8
|
-
/** TERM, a five-second grace, then KILL; only the original pane tree and verified groups are selected.
|
|
8
|
+
/** TERM, a five-second grace, then KILL; only the original pane tree and verified groups are selected.
|
|
9
|
+
* An interactive shell ignores TERM, so once its children are gone and only the pane root is left it is hung up,
|
|
10
|
+
* as a closing terminal would. A root that started alone keeps the full grace. */
|
|
9
11
|
export async function stopProcessTree(root, verify, runtime = nativeRuntime) {
|
|
10
12
|
if (!Number.isSafeInteger(root.pid) || root.pid <= 1 || root.pid === process.pid)
|
|
11
13
|
throw new Error("invalid_process_tree_root");
|
|
@@ -67,7 +69,7 @@ export async function stopProcessTree(root, verify, runtime = nativeRuntime) {
|
|
|
67
69
|
terminated.add(key(member));
|
|
68
70
|
}
|
|
69
71
|
});
|
|
70
|
-
let until = null;
|
|
72
|
+
let until = null, hungUp = false;
|
|
71
73
|
for (;;) {
|
|
72
74
|
const alive = refresh();
|
|
73
75
|
if (alive.length === 0)
|
|
@@ -77,6 +79,10 @@ export async function stopProcessTree(root, verify, runtime = nativeRuntime) {
|
|
|
77
79
|
for (const row of childrenFirst(alive))
|
|
78
80
|
if (!terminated.has(key(row)))
|
|
79
81
|
signal(row, "SIGTERM");
|
|
82
|
+
if (until !== null && !hungUp && tree.length > 1 && alive.length === 1 && alive[0].pid === root.pid) {
|
|
83
|
+
signal(alive[0], "SIGHUP");
|
|
84
|
+
hungUp = true;
|
|
85
|
+
}
|
|
80
86
|
until ??= runtime.now() + 5000;
|
|
81
87
|
await runtime.pause(Math.min(100, Math.max(0, until - runtime.now())));
|
|
82
88
|
}
|
package/dist/remote-authorize.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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) {
|
package/dist/remote-contract.js
CHANGED
|
@@ -27,6 +27,8 @@ export const credentialHandleSchema = z.object({
|
|
|
27
27
|
handle: z.string().uuid("credential.handle must be the handle (UUID) the terminal registry gave, unchanged"),
|
|
28
28
|
revision: z.number().int().positive("credential.revision must be the handle's positive integer revision, unchanged").max(Number.MAX_SAFE_INTEGER),
|
|
29
29
|
}).strict();
|
|
30
|
+
/** The terminal's operating system as BellTeam registers it; Aiterm compares it with what the terminal really is (R20). */
|
|
31
|
+
export const terminalOsSchema = z.enum(["macos", "linux", "windows"]);
|
|
30
32
|
/** The launch tools' terminal target (remote-terminal.md "One launch path"). Copied unchanged from BellTeam terminals. */
|
|
31
33
|
export const terminalArgumentSchema = z.object({
|
|
32
34
|
ref: z.string().uuid("terminal.ref must be the binding ref (UUID) the terminal registry gave for this terminal"),
|
|
@@ -35,6 +37,7 @@ export const terminalArgumentSchema = z.object({
|
|
|
35
37
|
user: z.string().min(1, "terminal.target.user is required"),
|
|
36
38
|
port: z.number().int().min(1).max(65535),
|
|
37
39
|
}).strict(),
|
|
40
|
+
os: terminalOsSchema.optional(),
|
|
38
41
|
trustRevision: revision("trustRevision"),
|
|
39
42
|
credentialRevision: revision("credentialRevision").optional(),
|
|
40
43
|
credential: credentialHandleSchema.optional(),
|
|
@@ -45,15 +48,17 @@ export const terminalArgumentSchema = z.object({
|
|
|
45
48
|
message: "terminal needs exactly one key source: credential {handle, revision} from the registry, or credentialRevision for a native key" });
|
|
46
49
|
});
|
|
47
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, " +
|
|
48
|
-
"{ref, target:{host,user,port}, trustRevision, and credentialRevision or credential {handle, revision}}; copy it unchanged, never invent or edit it, never use a host name or ssh command instead. " +
|
|
49
|
-
"Omit it to launch on this computer. Give cwd in the same call: the absolute project folder on that terminal. Never launch locally and then cd or ssh. " +
|
|
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 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. " +
|
|
50
53
|
"Never put tokens, passwords or other secrets in any argument, prompt or typed text; pass secret values only by name in env_vars. " +
|
|
51
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. " +
|
|
52
|
-
"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. " +
|
|
53
56
|
"TARGET_MISMATCH / BINDING_UNKNOWN = the value is not this terminal's binding: ask the terminal registry again. " +
|
|
54
57
|
"HOST_TRUST_STALE / CREDENTIAL_REVISION_STALE = the binding changed: get the current value from the terminal registry and launch again. " +
|
|
55
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. " +
|
|
56
59
|
"CREDENTIAL_REQUIRED / CREDENTIAL_NOT_LOADED = this terminal's key comes from a credential handle that the registry must load first; never paste a key anywhere. " +
|
|
57
60
|
"AUTH_FAILED = the terminal refused the key. UNREACHABLE = the terminal is offline; try later. CONNECTION_REFUSED = the terminal refused the SSH connection (SSH may be off there); try later. " +
|
|
58
61
|
"REMOTE_AITERM_TOO_OLD = update Aiterm on the terminal. CWD_UNAVAILABLE = the folder does not exist there; do not pick another folder. " +
|
|
59
|
-
"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."
|
|
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
|
+
"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 = the terminal is not a macOS, Linux or Windows system, so it cannot run seats.";
|
package/dist/remote-path.js
CHANGED
|
@@ -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
|
-
|
|
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 (
|
|
12
|
-
|
|
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.
|
|
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()) {
|
package/dist/remote-provision.js
CHANGED
|
@@ -1,23 +1,38 @@
|
|
|
1
|
-
// provision (remote-terminal.md R16): install this Aiterm version as a product-owned runtime on a macOS 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. */
|
|
11
15
|
export const PROVISION_SCRIPT = String.raw `set -u
|
|
12
16
|
V="$1"; BASE="$2"
|
|
13
17
|
fail() { echo "AITERM_PROVISION_ERROR $1"; exit 3; }
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
+
case "$(uname -s)" in
|
|
19
|
+
Darwin)
|
|
20
|
+
OS=darwin
|
|
21
|
+
case "$(uname -m)" in
|
|
22
|
+
arm64) A=arm64 ;;
|
|
23
|
+
x86_64) if [ "$(sysctl -in hw.optional.arm64 2>/dev/null)" = 1 ]; then A=arm64; else A=x64; fi ;;
|
|
24
|
+
*) fail PROVISION_PLATFORM_UNSUPPORTED ;;
|
|
25
|
+
esac ;;
|
|
26
|
+
Linux)
|
|
27
|
+
OS=linux
|
|
28
|
+
case "$(uname -m)" in
|
|
29
|
+
x86_64) A=x64 ;;
|
|
30
|
+
aarch64|arm64) A=arm64 ;;
|
|
31
|
+
*) fail PROVISION_PLATFORM_UNSUPPORTED ;;
|
|
32
|
+
esac ;;
|
|
18
33
|
*) fail PROVISION_PLATFORM_UNSUPPORTED ;;
|
|
19
34
|
esac
|
|
20
|
-
NAME="aiterm-runtime-$V
|
|
35
|
+
NAME="aiterm-runtime-$V-$OS-$A"
|
|
21
36
|
ROOT="$HOME/.aiterm/runtime"
|
|
22
37
|
mkdir -p "$ROOT" 2>/dev/null && chmod 700 "$HOME/.aiterm" "$ROOT" 2>/dev/null || fail RUNTIME_DIR_UNAVAILABLE
|
|
23
38
|
smoke() { "$1/bin/aiterm-remote-terminal" runtime-smoke --expect-version "$V" >/dev/null 2>&1 </dev/null; }
|
|
@@ -54,6 +69,77 @@ if ! mv "$N" "$ROOT/current"; then
|
|
|
54
69
|
fi
|
|
55
70
|
echo "AITERM_PROVISION PROVISIONED $V $A"
|
|
56
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
|
+
}
|
|
57
143
|
export function parseProvisionOutput(stdout) {
|
|
58
144
|
const ok = /^AITERM_PROVISION (PROVISIONED|ALREADY_CURRENT) (\S+) /m.exec(stdout);
|
|
59
145
|
if (ok)
|
|
@@ -70,7 +156,8 @@ export async function provision(ref, version = pkg.version) {
|
|
|
70
156
|
if (status.credential.provider === "aiterm.native-ssh-key.v1" && !status.credential.available)
|
|
71
157
|
throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", status.credential.reason ?? "the key is unavailable");
|
|
72
158
|
// Throws CREDENTIAL_NOT_LOADED for a keyless binding whose key is not loaded.
|
|
73
|
-
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);
|
|
74
161
|
const run = await new Promise((resolve, reject) => {
|
|
75
162
|
const child = spawn("ssh", args, { env: sshEnvironment(), stdio: ["pipe", "pipe", "pipe"] });
|
|
76
163
|
let stdout = "", stderr = "";
|
|
@@ -80,7 +167,7 @@ export async function provision(ref, version = pkg.version) {
|
|
|
80
167
|
child.on("error", reject);
|
|
81
168
|
child.on("close", code => { clearTimeout(timer); resolve({ code, stdout, stderr }); });
|
|
82
169
|
child.stdin.on("error", () => { });
|
|
83
|
-
child.stdin.end(PROVISION_SCRIPT);
|
|
170
|
+
child.stdin.end(windows ? windowsProvisionScript(version, RUNTIME_RELEASE_BASE) : PROVISION_SCRIPT);
|
|
84
171
|
});
|
|
85
172
|
const parsed = parseProvisionOutput(run.stdout);
|
|
86
173
|
if (parsed && "result" in parsed && run.code === 0)
|
|
@@ -97,7 +184,18 @@ export async function provision(ref, version = pkg.version) {
|
|
|
97
184
|
export async function runtimeSmoke(expectVersion) {
|
|
98
185
|
if (pkg.version !== expectVersion)
|
|
99
186
|
throw new RemoteTerminalError("RUNTIME_SMOKE_FAILED", `runtime is ${pkg.version}, expected ${expectVersion}`);
|
|
100
|
-
|
|
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 });
|
|
101
199
|
if (tmux.status !== 0)
|
|
102
200
|
throw new RemoteTerminalError("RUNTIME_SMOKE_FAILED", "tmux does not run");
|
|
103
201
|
await verifySetupRuntime({ command: process.execPath, args: [fileURLToPath(new URL("./index.js", import.meta.url))] });
|