aiterm-mcp 0.65.1 → 0.67.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -1
- package/README.ja.md +1 -1
- package/README.md +1 -1
- package/dist/execution-native-server.js +34 -2
- package/dist/index.js +81 -13
- package/dist/remote-contract.js +39 -1
- package/dist/remote-terminal-cli.js +21 -3
- package/dist/remote-terminal.js +441 -23
- package/dist/remote.js +26 -8
- package/dist/transcript-read-cli.js +70 -0
- package/package.json +3 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.67.0] - 2026-11-09
|
|
11
|
+
|
|
12
|
+
- Terminals without a native key (docs/architecture/remote-terminal.md R13). `aiterm-remote-terminal register --host H --user U --port P` creates a keyless binding with Aiterm's own empty known_hosts (`~/.config/aiterm/known_hosts.d/<ref>`; trust via `trust-confirm`). `aiterm-remote-terminal credential-load --ref R --terminal-id ID --handle UUID --revision N --purpose ssh-key` takes the resolved OpenSSH private key only on stdin and holds it in a private per-terminal ssh-agent (memory only); the receipt carries metadata only. The terminal value then carries `credential: {handle, revision}` instead of `credentialRevision`; Aiterm checks the loaded handle and revision (`CREDENTIAL_NOT_LOADED`, `CREDENTIAL_REVISION_STALE`, `CREDENTIAL_REQUIRED`). `sudoCredential` is accepted and kept as a handle only. The agent is removed when no seat of that terminal remains.
|
|
13
|
+
|
|
14
|
+
## [0.66.0] - 2026-11-09
|
|
15
|
+
|
|
16
|
+
- One launch path for seats on another computer (Owner ruling; docs/architecture/remote-terminal.md). `agent_launch`, `claude_agent`, `codex_agent` and `grok_agent` take `terminal: {ref, target:{host,user,port}, trustRevision, credentialRevision}` (the value BellTeam terminals hands over, unchanged) and `cwd` (the project folder on that terminal, required). Omitted = local, as before. The value is checked against the Aiterm-held binding and its revisions; a malformed value, a missing or relative `cwd`, or `terminal` together with `remote` answers `TERMINAL_INVALID` with a plain message. First scope `claude-code`; other harnesses answer `TERMINAL_HARNESS_UNSUPPORTED`.
|
|
17
|
+
- After a terminal launch every call is the same as for a local seat, by `session_id` alone: `pty_send`, `pty_observe`, `pty_read`, `pty_key`, `claude_turn`, `pty_close` and the execution `agent_stop` are routed to the terminal from `<state root>/terminal-seats.json`. Receipts' `wait_process` runs as returned. New `aiterm-transcript-read --session S [--cursor-session ID --offset N] [--max-bytes N]` reads the native Claude transcript for local and terminal seats alike.
|
|
18
|
+
- Terminal SSH uses only the binding: `-F /dev/null`, its known_hosts with strict checking, its key file, its own ControlMaster. Private values (`env_vars` values from this process, and every `mcp_config` header value, replaced by `${AITERM_MCP_HEADER_n}`) travel only on the encrypted stdin line to the terminal's `aiterm-mcp --private-env-stdin`; none is written to a config file, argv, PTY or log.
|
|
19
|
+
- Seats' BellTeam MCP returns through a reverse forward held by one Aiterm process per terminal (`ssh -R 127.0.0.1:P:127.0.0.1:<BELLTEAM_REMOTE_SEAT_PORT, default 4182>`, lock in the state root). P is recorded in the binding and reused on reconnect; seat URLs under `/api/seat-mcp` are rewritten to `http://127.0.0.1:P`.
|
|
20
|
+
- `agent_launch` now accepts `append_system_prompt` and `mcp_config` for `claude-code` (they were silently dropped before; only `claude_agent` took them). Terminal Claude launches call the terminal's `claude_agent`, so terminals on 0.65.x apply both.
|
|
21
|
+
|
|
10
22
|
## [0.65.1] - 2026-11-09
|
|
11
23
|
|
|
12
24
|
- `aiterm-remote-terminal`: the `ready` event now reaches the caller; 0.65.0 emitted it before the listener was attached.
|
|
@@ -3124,7 +3136,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
|
|
|
3124
3136
|
`ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
|
|
3125
3137
|
provenance.
|
|
3126
3138
|
|
|
3127
|
-
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.
|
|
3139
|
+
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.67.0...HEAD
|
|
3140
|
+
[0.67.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.66.0...v0.67.0
|
|
3141
|
+
[0.66.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.65.1...v0.66.0
|
|
3128
3142
|
[0.65.1]: https://github.com/kitepon/aiterm-mcp/compare/v0.65.0...v0.65.1
|
|
3129
3143
|
[0.65.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.64.2...v0.65.0
|
|
3130
3144
|
[0.64.2]: https://github.com/kitepon/aiterm-mcp/compare/v0.64.1...v0.64.2
|
package/README.ja.md
CHANGED
|
@@ -215,7 +215,7 @@ runtime-error store は canonical dotagents config の `collection.enabled: true
|
|
|
215
215
|
場合だけ収集し、既定OFF、network送信は行いません。tag起点CIのnpm provenance(OIDC Trusted
|
|
216
216
|
Publishing)で公開し、GitHub Release が Official MCP Registry を再登録します。
|
|
217
217
|
|
|
218
|
-
**状態:** 開発継続中 · 現行公開版 **v0.
|
|
218
|
+
**状態:** 開発継続中 · 現行公開版 **v0.67.0** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
|
|
219
219
|
|
|
220
220
|
### 更新と巻き戻し
|
|
221
221
|
|
package/README.md
CHANGED
|
@@ -227,7 +227,7 @@ collection is off by default and performs no network I/O. It ships via
|
|
|
227
227
|
tag-triggered CI with npm provenance (OIDC Trusted Publishing); the GitHub
|
|
228
228
|
Release re-registers the Official MCP Registry entry.
|
|
229
229
|
|
|
230
|
-
**Status:** actively maintained · current public release **v0.
|
|
230
|
+
**Status:** actively maintained · current public release **v0.67.0** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
|
|
231
231
|
|
|
232
232
|
### Update and rollback
|
|
233
233
|
|
|
@@ -18,6 +18,22 @@ import { ExecutionError } from "./execution-wire.js";
|
|
|
18
18
|
import { createAitermServer } from "./index.js";
|
|
19
19
|
import { immediateStopInputSchema, immediateStopResultSchema } from "./execution-immediate-stop.js";
|
|
20
20
|
import { parseRuntimeAdoptionConfig } from "./runtime-adoption.js";
|
|
21
|
+
import { boundTerminalTarget } from "./remote-terminal.js";
|
|
22
|
+
import { callRemoteTool } from "./remote.js";
|
|
23
|
+
/** One stop key to a terminal seat, only while it runs a turn (an idle Claude would take C-c as input). */
|
|
24
|
+
async function stopTerminalSeat(session) {
|
|
25
|
+
try {
|
|
26
|
+
const target = boundTerminalTarget(session);
|
|
27
|
+
const observed = await callRemoteTool(target, "pty_observe", { session_id: session }, 60_000);
|
|
28
|
+
if (observed.structuredContent?.state !== "busy")
|
|
29
|
+
return { session_id: session, status: "idle" };
|
|
30
|
+
const sent = await callRemoteTool(target, "pty_key", { session_id: session, key: "C-c" }, 60_000);
|
|
31
|
+
return sent.isError ? { session_id: session, status: "failed", error: "TERMINAL_STOP_FAILED" } : { session_id: session, status: "sent" };
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
return { session_id: session, status: "failed", error: /^([A-Z][A-Z0-9_]+):/.exec(error instanceof Error ? error.message : "")?.[1] ?? "TERMINAL_STOP_FAILED" };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
21
37
|
/** Ordinary delivery and leaf-first cancel keys have no execution-store
|
|
22
38
|
* registration, participant gate, shared transaction or graph write. */
|
|
23
39
|
export function createNativeDeliveryServer(dependencies = {}) {
|
|
@@ -27,6 +43,22 @@ export function createNativeDeliveryServer(dependencies = {}) {
|
|
|
27
43
|
inputSchema: immediateStopInputSchema.shape,
|
|
28
44
|
outputSchema: immediateStopResultSchema.shape,
|
|
29
45
|
}, async (args, extra) => {
|
|
46
|
+
// Terminal seats (remote-terminal.md T2): same tool and session handle, the key goes over the trusted SSH.
|
|
47
|
+
const ids = args.session_id !== undefined ? [args.session_id] : args.session_ids ?? [];
|
|
48
|
+
const terminal = ids.filter(id => boundTerminalTarget(id));
|
|
49
|
+
if (terminal.length) {
|
|
50
|
+
const local = ids.filter(id => !terminal.includes(id));
|
|
51
|
+
const localTargets = local.length ? (await localStop({ ...args, session_id: undefined, session_ids: local }, extra)).targets : [];
|
|
52
|
+
const targets = [...localTargets, ...await Promise.all(terminal.map(stopTerminalSeat))];
|
|
53
|
+
const statuses = new Set(targets.map(target => target.status));
|
|
54
|
+
const status = statuses.size === 1 ? [...statuses][0] : statuses.has("sent") ? "partial" : statuses.has("failed") ? "failed" : "idle";
|
|
55
|
+
const result = { ...(args.session_id !== undefined ? { session_id: args.session_id } : {}), status, targets };
|
|
56
|
+
return { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result };
|
|
57
|
+
}
|
|
58
|
+
const result = await localStop(args, extra);
|
|
59
|
+
return { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result };
|
|
60
|
+
});
|
|
61
|
+
async function localStop(args, extra) {
|
|
30
62
|
const stop = {
|
|
31
63
|
children: dependencies.children ?? core.agentSessionChildren,
|
|
32
64
|
currentLaunchId: dependencies.currentLaunchId ?? core.interruptionLaunchId,
|
|
@@ -35,8 +67,8 @@ export function createNativeDeliveryServer(dependencies = {}) {
|
|
|
35
67
|
const result = args.pause_goals
|
|
36
68
|
? await interruptKnownSessionsAndGoals(args, { ...stop, pauseGoal: dependencies.pauseGoal ?? core.pauseAgentGoalForStop }, dependencies.goalOrigin ? dependencies.goalOrigin(extra) : goalOriginFromHost(server.server.getClientVersion()?.name, extra._meta, server.server.getClientCapabilities()))
|
|
37
69
|
: interruptKnownSessions(args, stop);
|
|
38
|
-
return
|
|
39
|
-
}
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
40
72
|
return server;
|
|
41
73
|
}
|
|
42
74
|
/** Historical injected tracking composition. Normal CLI delivery does not
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { remoteInputDescription, remoteInputSchema } from "./remote-contract.js";
|
|
2
|
+
import { remoteInputDescription, remoteInputSchema, terminalArgumentDescription, terminalArgumentSchema } from "./remote-contract.js";
|
|
3
|
+
import { boundTerminalTarget, bindTerminalSession, ensureSeatForward, extractMcpHeaders, hasSeatMcpUrl, maintainSeatForwards, REMOTE_MINIMUM_VERSION, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
|
|
4
|
+
import { launchEnvValue } from "./private-env.js";
|
|
3
5
|
import { AuthResponseError, authUiSchema, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
|
|
4
6
|
import { configurationRequestSchema, configurationToolOutputSchema, applyConfigurationRequest, reconcileConfigurationRequest } from "./configure-request.js";
|
|
5
7
|
import { AitermError, AgentAuthenticationPreflightError, AgentResumeUnavailableError, AgentResumeError } from "./errors.js";
|
|
@@ -319,10 +321,15 @@ export function createAitermServer(options = {}) {
|
|
|
319
321
|
}
|
|
320
322
|
function registerRemoteAwareTool(name, config, handler, remoteHandler = remoteToolHandler(name)) {
|
|
321
323
|
server.registerTool(name, { ...config, inputSchema: { ...config.inputSchema, remote: remoteInputField } }, async ({ remote, ...args }, extra) => {
|
|
322
|
-
if (!remote)
|
|
323
|
-
return handler(args, extra);
|
|
324
324
|
try {
|
|
325
|
-
|
|
325
|
+
// A terminal seat is addressed by session alone, like a local one (remote-terminal.md T2).
|
|
326
|
+
const target = remote ? acceptRemote(remote) : boundTerminalTarget(args.session_id);
|
|
327
|
+
if (!target)
|
|
328
|
+
return handler(args, extra);
|
|
329
|
+
const result = await remoteHandler(target, args, extra);
|
|
330
|
+
if (name === "pty_close" && !remote && !result?.isError)
|
|
331
|
+
unbindTerminalSession(args.session_id);
|
|
332
|
+
return result;
|
|
326
333
|
}
|
|
327
334
|
catch (e) {
|
|
328
335
|
return fail(e);
|
|
@@ -1179,17 +1186,22 @@ export function createAitermServer(options = {}) {
|
|
|
1179
1186
|
const agentCompletionDesc = NON_BLOCKING_RULE + "自動配送以外の結果回収は pty_read(agent_transcript:true)。";
|
|
1180
1187
|
const agentEnvironmentDesc = `通常CLIと同じHOME・cwd・project/user/local設定・MCP・plugin・skill・permission/trustを共有する。` +
|
|
1181
1188
|
`aitermは完了相関stateだけをlaunch単位で所有する。起動されたagentにはsub-agent自己認識、親session、` +
|
|
1182
|
-
`delegation depth/lineage、delegation_allowed=true
|
|
1189
|
+
`delegation depth/lineage、delegation_allowed=trueを注入し、必要な追加委譲は許可する。` +
|
|
1190
|
+
`別のcomputer(登録済みの端末)で起こす時は、この起動にterminal(端末の登録元が渡す値をそのまま)とcwd(その端末のproject folder)を付ける。` +
|
|
1191
|
+
`ここで起こしてからcd・sshしない。秘密の値はどの引数・prompt・送信文にも書かず、env_varsに名前だけを書く。`;
|
|
1183
1192
|
const initialPromptDeliverySchema = z.object({
|
|
1184
1193
|
status: z.enum(["not_requested", "not_sent", "submitted_unconfirmed", "started"]),
|
|
1185
1194
|
reason: z.string(), turn_started: z.boolean().nullable(),
|
|
1186
1195
|
});
|
|
1187
1196
|
const agentStartupSchema = z.object({ status: z.enum(["ready", "not_checked", "blocked"]), reason: z.string() });
|
|
1188
|
-
async function launchRemoteAgent(target, harness, args, extra) {
|
|
1197
|
+
async function launchRemoteAgent(target, harness, args, extra, privateEnv) {
|
|
1189
1198
|
if (args.image && args.image.length > 0)
|
|
1190
1199
|
throw new core.AitermError("REMOTE_IMAGE_UNSUPPORTED: 別端末への画像添付には未対応です", 2);
|
|
1191
1200
|
const delivery = args.prompt || args.throughline_source_session ? await deliveryForRequest(extra, true) : null;
|
|
1192
|
-
|
|
1201
|
+
// A terminal's claude_agent takes append_system_prompt / mcp_config since 0.65.0; its agent_launch drops them until this release.
|
|
1202
|
+
const result = target.trusted_ref && harness === "claude-code"
|
|
1203
|
+
? await callRemoteTool(target, "claude_agent", args, 600_000, privateEnv)
|
|
1204
|
+
: await callRemoteTool(target, "agent_launch", { harness, ...args }, 600_000, privateEnv);
|
|
1193
1205
|
const structured = result.structuredContent;
|
|
1194
1206
|
if (!structured)
|
|
1195
1207
|
return { content: [...result.content, remoteNote(target, result)], isError: true };
|
|
@@ -1209,12 +1221,58 @@ export function createAitermServer(options = {}) {
|
|
|
1209
1221
|
content: [...result.content, remoteNote(target, result),
|
|
1210
1222
|
...(unconfirmed && !noted
|
|
1211
1223
|
? [{ type: "text", text: core.initialPromptUnconfirmedNote(structured.session_id, structured.initial_prompt.reason) }] : []),
|
|
1212
|
-
{ type: "text", text:
|
|
1224
|
+
{ type: "text", text: `${target.trusted_ref ? "以後このsessionは、session_idだけで呼ぶ(terminalもremoteも付けない)。" : "以後このsessionを操作する時は、同じremoteを付けて呼ぶ。"}${deliveryIdLine(delivery)}` }],
|
|
1213
1225
|
structuredContent: { ...structured, ...waited, ...(delivery?.result() ? { parent_delivery: delivery.result() } : {}),
|
|
1214
1226
|
remote_host: remoteLabel(target), remote_version: result.remote_version },
|
|
1215
1227
|
...(result.isError && !unconfirmed ? { isError: true } : {}),
|
|
1216
1228
|
};
|
|
1217
1229
|
}
|
|
1230
|
+
const terminalVersions = new Map();
|
|
1231
|
+
/** A seat on a BellTeam terminal (remote-terminal.md "One launch path"). Same launch arguments plus terminal + cwd. */
|
|
1232
|
+
async function launchTerminalAgent(harness, terminal, args, extra) {
|
|
1233
|
+
try {
|
|
1234
|
+
if (args.remote)
|
|
1235
|
+
throw new AitermError("TERMINAL_INVALID: use terminal or remote, not both; for a registered terminal pass only terminal", 2);
|
|
1236
|
+
if (harness !== "claude-code")
|
|
1237
|
+
throw new AitermError(`TERMINAL_HARNESS_UNSUPPORTED: terminal seats support harness claude-code first; ${harness} is not available on a terminal yet`, 2);
|
|
1238
|
+
if (typeof args.cwd !== "string" || !args.cwd.startsWith("/"))
|
|
1239
|
+
throw new AitermError("TERMINAL_INVALID: cwd is required with terminal: the absolute project folder on that terminal (never launch locally and cd)", 2);
|
|
1240
|
+
if (args.require_existing_resume)
|
|
1241
|
+
throw new AitermError("TERMINAL_INVALID: require_existing_resume is local-only", 2);
|
|
1242
|
+
const target = terminalRemoteTarget(terminal);
|
|
1243
|
+
// The private line is sent before the server answers; check its version first so an old one never sees it.
|
|
1244
|
+
let version = terminalVersions.get(target.trusted_ref);
|
|
1245
|
+
if (!version) {
|
|
1246
|
+
version = (await callRemoteTool(target, "pty_list", {}, 60_000)).remote_version ?? "0.0.0";
|
|
1247
|
+
terminalVersions.set(target.trusted_ref, version);
|
|
1248
|
+
}
|
|
1249
|
+
if (!versionAtLeast(version, REMOTE_MINIMUM_VERSION))
|
|
1250
|
+
throw new AitermError(`REMOTE_AITERM_TOO_OLD: the terminal runs Aiterm ${version}; ${REMOTE_MINIMUM_VERSION} or later is required (update Aiterm on the terminal)`, 2);
|
|
1251
|
+
const privateEnv = {};
|
|
1252
|
+
for (const name of args.env_vars ?? []) {
|
|
1253
|
+
const value = launchEnvValue(name);
|
|
1254
|
+
if (value !== undefined)
|
|
1255
|
+
privateEnv[name] = value;
|
|
1256
|
+
}
|
|
1257
|
+
let mcpConfig = args.mcp_config;
|
|
1258
|
+
if (mcpConfig) {
|
|
1259
|
+
const extracted = extractMcpHeaders(mcpConfig);
|
|
1260
|
+
Object.assign(privateEnv, extracted.env);
|
|
1261
|
+
mcpConfig = extracted.config;
|
|
1262
|
+
if (hasSeatMcpUrl(mcpConfig))
|
|
1263
|
+
mcpConfig = rewriteSeatMcpConfig(mcpConfig, await ensureSeatForward(target.trusted_ref));
|
|
1264
|
+
}
|
|
1265
|
+
const envVars = [...new Set([...(args.env_vars ?? []), ...Object.keys(privateEnv)])];
|
|
1266
|
+
const result = await launchRemoteAgent(target, harness, { ...args, ...(envVars.length ? { env_vars: envVars } : {}), ...(mcpConfig ? { mcp_config: mcpConfig } : {}) }, extra, privateEnv);
|
|
1267
|
+
const session = result?.structuredContent?.session_id;
|
|
1268
|
+
if (typeof session === "string")
|
|
1269
|
+
bindTerminalSession(session, target.trusted_ref);
|
|
1270
|
+
return result;
|
|
1271
|
+
}
|
|
1272
|
+
catch (e) {
|
|
1273
|
+
return fail(e);
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1218
1276
|
async function launchAgent(kind, args, extra) {
|
|
1219
1277
|
const supportsWriteScope = kind !== "claude";
|
|
1220
1278
|
const { prompt, image, throughline_source_session, throughline_supplement_file, model, reasoning_effort, fast, env_vars, cwd, session_name, launch_operation_id, write_scope, trust_project, require_existing_resume, configuration_root, append_system_prompt, mcp_config } = args;
|
|
@@ -1344,7 +1402,8 @@ export function createAitermServer(options = {}) {
|
|
|
1344
1402
|
fast: z.boolean().nullish().describe(fastModeLaunchDesc),
|
|
1345
1403
|
env_vars: z.array(z.string()).optional().describe("起動したagentへ現在のMCP processから継承する環境変数名。値はtool引数へ渡さない"),
|
|
1346
1404
|
trust_project: z.boolean().optional().describe("対象projectを信頼し、既知のworkspace・project hooks・MCP初期同意を起動中に進める"),
|
|
1347
|
-
cwd: z.string().nullish().describe("
|
|
1405
|
+
cwd: z.string().nullish().describe("作業ディレクトリ(対象リポのルート等・任意)。terminalを付ける時は必須で、その端末上のproject folderの絶対パス"),
|
|
1406
|
+
terminal: terminalArgumentSchema.optional().describe(terminalArgumentDescription),
|
|
1348
1407
|
session_name: z.string().nullish().describe("セッション名(省略で自動採番)"),
|
|
1349
1408
|
...(kind === "claude" ? {
|
|
1350
1409
|
append_system_prompt: z.string().min(1).optional().describe("Launch instructions added to the system prompt; kept in Aiterm state, not in the project or home"),
|
|
@@ -1375,7 +1434,7 @@ export function createAitermServer(options = {}) {
|
|
|
1375
1434
|
fast_error: fastModeFailureSchema.nullable().optional().describe("fastを頼まれたが、通常の速度で起こした時の訳"),
|
|
1376
1435
|
...writeScopeOutputSchema,
|
|
1377
1436
|
},
|
|
1378
|
-
}, async (args, extra) => launchAgent(kind, args, extra));
|
|
1437
|
+
}, async ({ terminal, ...args }, extra) => terminal ? launchTerminalAgent(core.agentHarness(kind), terminal, args, extra) : launchAgent(kind, args, extra));
|
|
1379
1438
|
}
|
|
1380
1439
|
server.registerTool("agent_launch", {
|
|
1381
1440
|
description: "エージェントを単一の標準入口から永続sessionへ起動する。harnessはagent loop・認証・hook・transcriptを所有する実行基盤、" +
|
|
@@ -1396,11 +1455,14 @@ export function createAitermServer(options = {}) {
|
|
|
1396
1455
|
fast: z.boolean().nullish().describe(fastModeLaunchDesc),
|
|
1397
1456
|
env_vars: z.array(z.string()).optional().describe("現在のMCP processから継承する環境変数名"),
|
|
1398
1457
|
trust_project: z.boolean().optional().describe("対象projectを信頼し、既知のworkspace・project hooks・MCP初期同意を起動中に進める"),
|
|
1399
|
-
cwd: z.string().nullish().describe("
|
|
1458
|
+
cwd: z.string().nullish().describe("作業ディレクトリ(絶対パス・任意)。terminalを付ける時は必須で、その端末上のproject folderの絶対パス"),
|
|
1400
1459
|
session_name: z.string().nullish().describe("Aiterm session名(省略で自動採番)"),
|
|
1401
1460
|
write_scope: z.string().min(1).optional().describe("能力宣言。read-onlyは対応harnessの標準read-only面で実効禁止する"),
|
|
1402
1461
|
launch_operation_id: z.string().regex(/^sha256:[0-9a-f]{64}$/).optional().describe("Claude Codeのpromptなしexact replay相関だけで使用"),
|
|
1403
1462
|
remote: remoteInputField,
|
|
1463
|
+
terminal: terminalArgumentSchema.optional().describe(terminalArgumentDescription),
|
|
1464
|
+
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"),
|
|
1465
|
+
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"),
|
|
1404
1466
|
},
|
|
1405
1467
|
outputSchema: {
|
|
1406
1468
|
schema: z.literal("aiterm.agent-launch-result.v1"),
|
|
@@ -1423,7 +1485,11 @@ export function createAitermServer(options = {}) {
|
|
|
1423
1485
|
write_scope: z.string().optional(),
|
|
1424
1486
|
write_scope_enforcement: z.enum(["enforced_read_only", "declaration_only_unsupported"]).optional(),
|
|
1425
1487
|
},
|
|
1426
|
-
}, async ({ harness, remote, ...args }, extra) => {
|
|
1488
|
+
}, async ({ harness, remote, terminal, ...args }, extra) => {
|
|
1489
|
+
if (harness !== "claude-code" && (args.append_system_prompt !== undefined || args.mcp_config !== undefined))
|
|
1490
|
+
return fail(new AitermError("append_system_prompt and mcp_config are claude-code only", 2));
|
|
1491
|
+
if (terminal)
|
|
1492
|
+
return launchTerminalAgent(harness, terminal, { ...args, ...(remote ? { remote } : {}) }, extra);
|
|
1427
1493
|
if (remote && args.require_existing_resume)
|
|
1428
1494
|
return fail(typeof args.session_name === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(args.session_name)
|
|
1429
1495
|
? new AgentResumeUnavailableError(args.session_name)
|
|
@@ -1473,8 +1539,10 @@ export function createAitermServer(options = {}) {
|
|
|
1473
1539
|
server.server.oninitialized = () => {
|
|
1474
1540
|
core.setParentClient(server.server.getClientVersion()?.name ?? null);
|
|
1475
1541
|
// Standby must not start recovery/heartbeat timers or claim records; activation starts them.
|
|
1476
|
-
if (!adoption || adoption.state === "active")
|
|
1542
|
+
if (!adoption || adoption.state === "active") {
|
|
1477
1543
|
startParentManagers();
|
|
1544
|
+
maintainSeatForwards();
|
|
1545
|
+
}
|
|
1478
1546
|
};
|
|
1479
1547
|
// One close per manager: retire awaits it, a later transport close reuses the same promise.
|
|
1480
1548
|
let managersClosed = null;
|
package/dist/remote-contract.js
CHANGED
|
@@ -11,11 +11,49 @@ export const remoteTargetSchema = z.object({
|
|
|
11
11
|
identity_file: z.string().min(1).optional(),
|
|
12
12
|
passphrase_env: z.string().regex(envNamePattern).optional(),
|
|
13
13
|
ssh_options: z.array(z.string().regex(sshOptionPattern)).max(32).optional(),
|
|
14
|
+
// Set only by Aiterm from a terminal binding (remote-terminal.md); never accepted from tool input.
|
|
15
|
+
trusted_ref: z.string().uuid().optional(),
|
|
14
16
|
}).strict();
|
|
15
|
-
export const remoteInputSchema = remoteTargetSchema.extend({
|
|
17
|
+
export const remoteInputSchema = remoteTargetSchema.omit({ trusted_ref: true }).extend({
|
|
16
18
|
passphrase: z.string().min(1).optional(),
|
|
17
19
|
}).strict().refine((value) => !(value.passphrase && value.passphrase_env), {
|
|
18
20
|
message: "passphraseとpassphrase_envは同時に指定できません",
|
|
19
21
|
});
|
|
20
22
|
export const remoteInputDescription = "別端末のAitermで実行する時のSSH接続情報。hostだけならssh_configの接続名として使う。" +
|
|
21
23
|
"Aitermは接続情報を保存・管理しない。passphraseは会話記録に残るため、ssh-agentかpassphrase_env(環境変数名)を推奨する。";
|
|
24
|
+
const revision = (field) => z.string().regex(/^sha256:[0-9a-f]{64}$/, `terminal.${field} must be the sha256:<hex> revision the terminal registry returned with this binding; pass it unchanged`);
|
|
25
|
+
/** A credential owner's handle for a key; the value itself never travels in an argument. */
|
|
26
|
+
export const credentialHandleSchema = z.object({
|
|
27
|
+
handle: z.string().uuid("credential.handle must be the handle (UUID) the terminal registry gave, unchanged"),
|
|
28
|
+
revision: z.number().int().positive("credential.revision must be the handle's positive integer revision, unchanged").max(Number.MAX_SAFE_INTEGER),
|
|
29
|
+
}).strict();
|
|
30
|
+
/** The launch tools' terminal target (remote-terminal.md "One launch path"). Copied unchanged from BellTeam terminals. */
|
|
31
|
+
export const terminalArgumentSchema = z.object({
|
|
32
|
+
ref: z.string().uuid("terminal.ref must be the binding ref (UUID) the terminal registry gave for this terminal"),
|
|
33
|
+
target: z.object({
|
|
34
|
+
host: z.string().min(1, "terminal.target.host is required"),
|
|
35
|
+
user: z.string().min(1, "terminal.target.user is required"),
|
|
36
|
+
port: z.number().int().min(1).max(65535),
|
|
37
|
+
}).strict(),
|
|
38
|
+
trustRevision: revision("trustRevision"),
|
|
39
|
+
credentialRevision: revision("credentialRevision").optional(),
|
|
40
|
+
credential: credentialHandleSchema.optional(),
|
|
41
|
+
sudoCredential: credentialHandleSchema.optional(),
|
|
42
|
+
}).strict().superRefine((value, context) => {
|
|
43
|
+
if ((value.credential === undefined) === (value.credentialRevision === undefined))
|
|
44
|
+
context.addIssue({ code: "custom",
|
|
45
|
+
message: "terminal needs exactly one key source: credential {handle, revision} from the registry, or credentialRevision for a native key" });
|
|
46
|
+
});
|
|
47
|
+
export const terminalArgumentDescription = "Run this seat on another computer (a registered terminal) over SSH. Value: exactly the terminal value your host system's terminal registry hands over, " +
|
|
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. " +
|
|
50
|
+
"Never put tokens, passwords or other secrets in any argument, prompt or typed text; pass secret values only by name in env_vars. " +
|
|
51
|
+
"After launch, use session_id alone for pty_send, pty_observe, pty_read, pty_key, claude_turn, agent_stop and pty_close; Aiterm routes them to the terminal. " +
|
|
52
|
+
"Errors and next step: TERMINAL_INVALID = malformed value, missing/relative cwd, or combined with remote: pass the registry's value unchanged with cwd. " +
|
|
53
|
+
"TARGET_MISMATCH / BINDING_UNKNOWN = the value is not this terminal's binding: ask the terminal registry again. " +
|
|
54
|
+
"HOST_TRUST_STALE / CREDENTIAL_REVISION_STALE = the binding changed: get the current value from the terminal registry and launch again. " +
|
|
55
|
+
"HOST_KEY_MISMATCH / HOST_TRUST_MISSING = the terminal's host key is not the trusted one: the Owner must confirm the new host key; do not retry. " +
|
|
56
|
+
"CREDENTIAL_REQUIRED / CREDENTIAL_NOT_LOADED = this terminal's key comes from a credential handle that the registry must load first; never paste a key anywhere. " +
|
|
57
|
+
"AUTH_FAILED = the terminal refused the key. UNREACHABLE = the terminal is offline; try later. " +
|
|
58
|
+
"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. TERMINAL_HARNESS_UNSUPPORTED = use harness claude-code.";
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// aiterm-remote-terminal (remote-terminal.md). Run as the UID that can read the terminal key.
|
|
3
3
|
// status --ref R | register ... | trust-confirm --ref R --fingerprint F (one JSON line; exit 0 result, 2 error)
|
|
4
4
|
// serve stdio MCP for one bound connection, spawned by BellTeam terminals
|
|
5
|
+
// credential-load --ref R --terminal-id ID --handle UUID --revision N --purpose ssh-key (key bytes on stdin; one JSON receipt line)
|
|
5
6
|
// transcript-read --session S [--cursor-session ID --offset N] [--max-bytes N] (runs on the terminal)
|
|
6
7
|
import { realpathSync } from "node:fs";
|
|
7
8
|
import { fileURLToPath } from "node:url";
|
|
@@ -9,8 +10,9 @@ import { createRequire } from "node:module";
|
|
|
9
10
|
import { z } from "zod";
|
|
10
11
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
11
12
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
12
|
-
import { RemoteTerminalConnection, RemoteTerminalError, bindingStatus, confirmHostKey, registerBinding } from "./remote-terminal.js";
|
|
13
|
+
import { RemoteTerminalConnection, RemoteTerminalError, bindingStatus, confirmHostKey, loadCredential, registerBinding } from "./remote-terminal.js";
|
|
13
14
|
import { readCompletedTranscript } from "./transcript-read.js";
|
|
15
|
+
import { credentialHandleSchema } from "./remote-contract.js";
|
|
14
16
|
const pkg = createRequire(import.meta.url)("../package.json");
|
|
15
17
|
function option(args, name) {
|
|
16
18
|
const at = args.indexOf(name);
|
|
@@ -50,7 +52,8 @@ function serve() {
|
|
|
50
52
|
server.registerTool("remote_terminal_open", {
|
|
51
53
|
description: "Open the bound connection for this process",
|
|
52
54
|
inputSchema: { ref: z.string(), target: z.object({ host: z.string(), user: z.string(), port: z.number().int() }).strict(),
|
|
53
|
-
trustRevision: z.string(), credentialRevision: z.string()
|
|
55
|
+
trustRevision: z.string(), credentialRevision: z.string().optional(), credential: credentialHandleSchema.optional(),
|
|
56
|
+
sudoCredential: credentialHandleSchema.optional(), privateEnv: z.record(z.string(), z.string()).optional() },
|
|
54
57
|
}, guarded(async (args) => {
|
|
55
58
|
if (connection)
|
|
56
59
|
throw new RemoteTerminalError("ALREADY_OPEN", "this process already holds a connection");
|
|
@@ -104,8 +107,23 @@ export function main(args) {
|
|
|
104
107
|
if (command === "register")
|
|
105
108
|
return oneShot(() => registerBinding({
|
|
106
109
|
target: { host: option(rest, "--host") ?? "", user: option(rest, "--user") ?? "", port: Number(option(rest, "--port") ?? "22") },
|
|
107
|
-
keyFile: option(rest, "--key-file") ??
|
|
110
|
+
keyFile: option(rest, "--key-file") ?? null, knownHostsFile: option(rest, "--known-hosts") ?? null, hostKeyAlias: option(rest, "--host-key-alias") ?? null,
|
|
108
111
|
}), "aiterm.remote-binding-error.v1");
|
|
112
|
+
if (command === "credential-load") {
|
|
113
|
+
// Key bytes only on stdin until EOF (remote-terminal.md R13); flags carry metadata only.
|
|
114
|
+
const chunks = [];
|
|
115
|
+
process.stdin.on("data", (chunk) => chunks.push(chunk));
|
|
116
|
+
process.stdin.on("end", () => {
|
|
117
|
+
const key = Buffer.concat(chunks);
|
|
118
|
+
for (const chunk of chunks)
|
|
119
|
+
chunk.fill(0);
|
|
120
|
+
loadCredential({ ref: option(rest, "--ref") ?? "", terminalId: option(rest, "--terminal-id") ?? "", handle: option(rest, "--handle") ?? "",
|
|
121
|
+
revision: option(rest, "--revision") ?? "", purpose: option(rest, "--purpose") ?? "" }, key)
|
|
122
|
+
.then(receipt => { process.stdout.write(`${JSON.stringify(receipt)}\n`); process.exit(0); })
|
|
123
|
+
.catch(error => { process.stdout.write(`${JSON.stringify(errorDto(error, "aiterm.remote-binding-error.v1"))}\n`); process.exit(2); });
|
|
124
|
+
});
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
109
127
|
if (command === "trust-confirm")
|
|
110
128
|
return oneShot(() => confirmHostKey(option(rest, "--ref") ?? "", option(rest, "--fingerprint") ?? ""), "aiterm.remote-binding-error.v1");
|
|
111
129
|
if (command === "transcript-read")
|
package/dist/remote-terminal.js
CHANGED
|
@@ -9,7 +9,7 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
9
9
|
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
|
-
import { writeJson0600 } from "./agent-shared.js";
|
|
12
|
+
import { ensureStateRoot, writeJson0600 } from "./agent-shared.js";
|
|
13
13
|
import { posixCommand } from "./remote.js";
|
|
14
14
|
import { PRIVATE_ENV_SCHEMA } from "./private-env.js";
|
|
15
15
|
const pkg = createRequire(import.meta.url)("../package.json");
|
|
@@ -68,16 +68,25 @@ function binding(ref) {
|
|
|
68
68
|
throw new RemoteTerminalError("BINDING_UNKNOWN", "no binding has this ref");
|
|
69
69
|
return found;
|
|
70
70
|
}
|
|
71
|
+
/** Without keyFile the key comes from a credential handle at open/launch; without knownHostsFile Aiterm keeps an empty one per binding. */
|
|
71
72
|
export function registerBinding(input) {
|
|
72
73
|
const target = validTarget(input.target);
|
|
73
74
|
for (const file of [input.keyFile, input.knownHostsFile]) {
|
|
74
|
-
if (!path.isAbsolute(file))
|
|
75
|
+
if (file && !path.isAbsolute(file))
|
|
75
76
|
throw new RemoteTerminalError("PATH_INVALID", "key and known_hosts paths must be absolute");
|
|
76
77
|
}
|
|
77
78
|
if (input.hostKeyAlias != null && !HOST.test(input.hostKeyAlias))
|
|
78
79
|
throw new RemoteTerminalError("ALIAS_INVALID", "host key alias is not a host name");
|
|
79
80
|
const bindings = readStore();
|
|
80
|
-
const
|
|
81
|
+
const ref = randomUUID();
|
|
82
|
+
let knownHostsFile = input.knownHostsFile || null;
|
|
83
|
+
if (!knownHostsFile) {
|
|
84
|
+
const dir = path.join(path.dirname(storePath()), "known_hosts.d");
|
|
85
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
86
|
+
knownHostsFile = path.join(dir, ref);
|
|
87
|
+
fs.writeFileSync(knownHostsFile, "", { mode: 0o600, flag: "wx" });
|
|
88
|
+
}
|
|
89
|
+
const next = { ref, target, key_file: input.keyFile || null, known_hosts_file: knownHostsFile,
|
|
81
90
|
host_key_alias: input.hostKeyAlias ?? null, created_at: new Date().toISOString() };
|
|
82
91
|
writeJson0600(storePath(), { schema: "aiterm.remote-bindings.v1", bindings: [...bindings, next] });
|
|
83
92
|
return bindingStatus(next.ref);
|
|
@@ -120,13 +129,15 @@ function trustEntries(b) {
|
|
|
120
129
|
const digest = (text) => `sha256:${createHash("sha256").update(text).digest("hex")}`;
|
|
121
130
|
export function bindingStatus(ref) {
|
|
122
131
|
const b = binding(ref);
|
|
123
|
-
const key = publicKey(b.key_file);
|
|
132
|
+
const key = b.key_file ? publicKey(b.key_file) : null;
|
|
124
133
|
const trust = trustEntries(b);
|
|
125
134
|
return {
|
|
126
135
|
schema: "aiterm.remote-binding-status.v1", ref, target: b.target,
|
|
127
|
-
credential:
|
|
128
|
-
? { provider: "aiterm.
|
|
129
|
-
:
|
|
136
|
+
credential: key === null
|
|
137
|
+
? { provider: "aiterm.credential-handle.v1", revision: null, fingerprint: null, available: false, reason: "KEY_FROM_CREDENTIAL" }
|
|
138
|
+
: "reason" in key
|
|
139
|
+
? { provider: "aiterm.native-ssh-key.v1", revision: null, fingerprint: null, available: false, reason: key.reason }
|
|
140
|
+
: { provider: "aiterm.native-ssh-key.v1", revision: digest(key.line), fingerprint: keyFingerprint(key.blob), available: true, reason: null },
|
|
130
141
|
trust: Array.isArray(trust)
|
|
131
142
|
? { provider: "aiterm.known-hosts.v1", revision: digest(trust.join("\n")), available: true, reason: null,
|
|
132
143
|
fingerprints: trust.map(entry => keyFingerprint(Buffer.from(entry.split(" ").at(-1), "base64"))) }
|
|
@@ -164,6 +175,39 @@ export function classifySshFailure(stderr) {
|
|
|
164
175
|
return { code: "UNREACHABLE", message: "the terminal cannot be reached" };
|
|
165
176
|
return { code: "CONNECTION_FAILED", message: "the SSH connection failed" };
|
|
166
177
|
}
|
|
178
|
+
/** -R spec for the seats' BellTeam MCP (remote-terminal.md R12). P=0 lets the terminal's sshd pick the port. */
|
|
179
|
+
export function seatForwardSpec(terminalPort, env = process.env) {
|
|
180
|
+
const port = Number(env.BELLTEAM_REMOTE_SEAT_PORT ?? 4182);
|
|
181
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
182
|
+
throw new RemoteTerminalError("SEAT_FORWARD_UNAVAILABLE", "BELLTEAM_REMOTE_SEAT_PORT is not a port");
|
|
183
|
+
return `127.0.0.1:${terminalPort}:127.0.0.1:${port}`;
|
|
184
|
+
}
|
|
185
|
+
/** ssh stderr -> the allocated terminal port, "refused", or null while unknown. */
|
|
186
|
+
export function parseSeatForward(stderr) {
|
|
187
|
+
const allocated = /Allocated port (\d+) for remote forward/.exec(stderr);
|
|
188
|
+
if (allocated)
|
|
189
|
+
return Number(allocated[1]);
|
|
190
|
+
return /remote port forwarding failed/i.test(stderr) ? "refused" : null;
|
|
191
|
+
}
|
|
192
|
+
/** Seat MCP URLs (path /api/seat-mcp...) get the forward's terminal-local origin; everything else stays as given. */
|
|
193
|
+
export function rewriteSeatMcpConfig(config, port) {
|
|
194
|
+
const servers = config.mcpServers;
|
|
195
|
+
if (!servers || typeof servers !== "object")
|
|
196
|
+
return config;
|
|
197
|
+
const rewritten = {};
|
|
198
|
+
for (const [name, server] of Object.entries(servers)) {
|
|
199
|
+
const url = server?.url;
|
|
200
|
+
let parsed = null;
|
|
201
|
+
try {
|
|
202
|
+
parsed = typeof url === "string" ? new URL(url) : null;
|
|
203
|
+
}
|
|
204
|
+
catch { /* not a URL: unchanged */ }
|
|
205
|
+
rewritten[name] = parsed && /^\/api\/seat-mcp(\/|$)/.test(parsed.pathname)
|
|
206
|
+
? { ...server, url: `http://127.0.0.1:${port}${parsed.pathname}${parsed.search}` }
|
|
207
|
+
: server;
|
|
208
|
+
}
|
|
209
|
+
return { ...config, mcpServers: rewritten };
|
|
210
|
+
}
|
|
167
211
|
export function sshArguments(b, agentSocket, identityFile, remoteCommand) {
|
|
168
212
|
return ["-F", "/dev/null", "-T", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes",
|
|
169
213
|
"-o", `UserKnownHostsFile=${b.known_hosts_file}`, "-o", "GlobalKnownHostsFile=/dev/null", "-o", "CheckHostIP=no",
|
|
@@ -180,7 +224,7 @@ function sshEnvironment() {
|
|
|
180
224
|
return env;
|
|
181
225
|
}
|
|
182
226
|
/** MCP over an ssh child whose stdin first carries the private env line (remote-terminal.md R5). */
|
|
183
|
-
class SshStdioTransport {
|
|
227
|
+
export class SshStdioTransport {
|
|
184
228
|
args;
|
|
185
229
|
privateLine;
|
|
186
230
|
onclose;
|
|
@@ -236,7 +280,7 @@ export function waitArguments(args) {
|
|
|
236
280
|
throw new RemoteTerminalError("WAIT_INVALID", "wait_process needs --session");
|
|
237
281
|
return rest;
|
|
238
282
|
}
|
|
239
|
-
function versionAtLeast(actual, required) {
|
|
283
|
+
export function versionAtLeast(actual, required) {
|
|
240
284
|
const a = actual.split(/[.-]/).slice(0, 3).map(Number), r = required.split(/[.-]/).slice(0, 3).map(Number);
|
|
241
285
|
for (let i = 0; i < 3; i++)
|
|
242
286
|
if ((a[i] ?? 0) !== (r[i] ?? 0))
|
|
@@ -274,10 +318,7 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
274
318
|
throw new RemoteTerminalError(status.trust.reason ?? "HOST_TRUST_MISSING", "host trust is unavailable", "confirm the new host key");
|
|
275
319
|
if (status.trust.revision !== input.trustRevision)
|
|
276
320
|
throw new RemoteTerminalError("HOST_TRUST_STALE", "the host trust revision changed; re-read status");
|
|
277
|
-
|
|
278
|
-
throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", status.credential.reason ?? "the key is unavailable");
|
|
279
|
-
if (status.credential.revision !== input.credentialRevision)
|
|
280
|
-
throw new RemoteTerminalError("CREDENTIAL_REVISION_STALE", "the key revision changed; re-read status");
|
|
321
|
+
checkKeySource(input.ref, status, input);
|
|
281
322
|
for (const [name, value] of Object.entries(input.privateEnv ?? {}))
|
|
282
323
|
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || typeof value !== "string")
|
|
283
324
|
throw new RemoteTerminalError("PRIVATE_ENV_INVALID", "invalid private env entry");
|
|
@@ -294,15 +335,24 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
294
335
|
throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", "the private agent did not start");
|
|
295
336
|
await new Promise(resolve => setTimeout(resolve, 50));
|
|
296
337
|
}
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
338
|
+
// A keyless binding authenticates with the credential agent loaded by credential-load (R13); checkKeySource checked it.
|
|
339
|
+
const loaded = b.key_file ? null : readCredential(b.ref);
|
|
340
|
+
let agentSocket = socket, identity = path.join(dir, "id.pub");
|
|
341
|
+
if (loaded) {
|
|
342
|
+
agentSocket = loaded.socket;
|
|
343
|
+
identity = credentialPublicKeyFile(b.ref);
|
|
344
|
+
}
|
|
345
|
+
else {
|
|
346
|
+
const keyFile = b.key_file;
|
|
347
|
+
const added = spawnSync("ssh-add", ["-q", keyFile], { env: { ...sshEnvironment(), SSH_AUTH_SOCK: socket }, stdio: ["ignore", "ignore", "pipe"], timeout: 10_000 });
|
|
348
|
+
if (added.status !== 0)
|
|
349
|
+
throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", "the key could not be loaded");
|
|
350
|
+
const key = publicKey(keyFile);
|
|
351
|
+
if ("reason" in key)
|
|
352
|
+
throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", key.reason);
|
|
353
|
+
fs.writeFileSync(identity, `${key.line}\n`, { mode: 0o600 });
|
|
354
|
+
}
|
|
355
|
+
const transport = new SshStdioTransport(sshArguments(b, agentSocket, identity, posixCommand("exec aiterm-mcp --private-env-stdin")), `${JSON.stringify({ schema: PRIVATE_ENV_SCHEMA, env: input.privateEnv ?? {} })}\n`);
|
|
306
356
|
const client = new Client({ name: "aiterm-remote-terminal", version: pkg.version });
|
|
307
357
|
try {
|
|
308
358
|
await client.connect(transport, { timeout: 60_000 });
|
|
@@ -317,7 +367,7 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
317
367
|
await client.close().catch(() => { });
|
|
318
368
|
throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${remoteVersion}; ${REMOTE_MINIMUM_VERSION} or later is required`);
|
|
319
369
|
}
|
|
320
|
-
const connection = new RemoteTerminalConnection(b, dir, agent,
|
|
370
|
+
const connection = new RemoteTerminalConnection(b, dir, agent, agentSocket, identity, client, remoteVersion);
|
|
321
371
|
client.onclose = () => connection.ended();
|
|
322
372
|
// After the caller has attached its listener to the returned connection.
|
|
323
373
|
setImmediate(() => connection.emit("event", { type: "ready", at: new Date().toISOString(), remoteVersion }));
|
|
@@ -432,3 +482,371 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
432
482
|
return { closed: true };
|
|
433
483
|
}
|
|
434
484
|
}
|
|
485
|
+
/** T1 key source: a credential handle (its revision checked by the resolver) or the binding's native key revision, never both. */
|
|
486
|
+
function checkKeySource(ref, status, input) {
|
|
487
|
+
if (input.credential) {
|
|
488
|
+
if (input.credentialRevision !== undefined)
|
|
489
|
+
throw new RemoteTerminalError("TERMINAL_INVALID", "give credential or credentialRevision, not both: with a credential handle the registry omits credentialRevision");
|
|
490
|
+
if (status.credential.provider !== "aiterm.credential-handle.v1")
|
|
491
|
+
throw new RemoteTerminalError("TERMINAL_INVALID", "this terminal has a native key; pass credentialRevision instead of credential");
|
|
492
|
+
const loaded = readCredential(ref);
|
|
493
|
+
if (!loaded || loaded.handle !== input.credential.handle || !agentAlive(loaded.socket))
|
|
494
|
+
throw new RemoteTerminalError("CREDENTIAL_NOT_LOADED", "the terminal's credential is not loaded; resolve the handle and run credential-load, then launch again");
|
|
495
|
+
if (loaded.revision !== input.credential.revision)
|
|
496
|
+
throw new RemoteTerminalError("CREDENTIAL_REVISION_STALE", "the loaded credential has another revision; run credential-load with the current one, then launch again");
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
if (status.credential.provider === "aiterm.credential-handle.v1")
|
|
500
|
+
throw new RemoteTerminalError("CREDENTIAL_REQUIRED", "this terminal has no native key; pass the terminal's credential handle from the registry");
|
|
501
|
+
if (!status.credential.available)
|
|
502
|
+
throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", status.credential.reason ?? "the key is unavailable");
|
|
503
|
+
if (status.credential.revision !== input.credentialRevision)
|
|
504
|
+
throw new RemoteTerminalError("CREDENTIAL_REVISION_STALE", "the key changed; get the current value from the terminal registry and launch again");
|
|
505
|
+
}
|
|
506
|
+
const trustedTarget = (b) => ({ host: b.target.host, user: b.target.user, port: b.target.port, trusted_ref: b.ref });
|
|
507
|
+
/** T1: the binding exists, the target is the binding's, both revisions are current. */
|
|
508
|
+
export function terminalRemoteTarget(input) {
|
|
509
|
+
const b = binding(input.ref);
|
|
510
|
+
const target = validTarget(input.target);
|
|
511
|
+
if (b.target.host !== target.host || b.target.user !== target.user || b.target.port !== target.port)
|
|
512
|
+
throw new RemoteTerminalError("TARGET_MISMATCH", "terminal.target differs from this binding; get the current value from the terminal registry");
|
|
513
|
+
const status = bindingStatus(input.ref);
|
|
514
|
+
if (!status.trust.available)
|
|
515
|
+
throw new RemoteTerminalError(status.trust.reason ?? "HOST_TRUST_MISSING", "the terminal's host key is not trusted (confirm the new host key)");
|
|
516
|
+
if (status.trust.revision !== input.trustRevision)
|
|
517
|
+
throw new RemoteTerminalError("HOST_TRUST_STALE", "the host trust changed; get the current value from the terminal registry and launch again");
|
|
518
|
+
checkKeySource(input.ref, status, input);
|
|
519
|
+
return trustedTarget(b);
|
|
520
|
+
}
|
|
521
|
+
/** ssh argv for a trusted target: no user config, the binding's known_hosts only, its key file only. */
|
|
522
|
+
export function trustedSshArguments(ref, remoteCommand, controlPath, extra = []) {
|
|
523
|
+
const b = binding(ref);
|
|
524
|
+
let identity;
|
|
525
|
+
if (b.key_file)
|
|
526
|
+
identity = ["-o", "IdentityAgent=none", "-o", "IdentitiesOnly=yes", "-o", `IdentityFile=${b.key_file}`];
|
|
527
|
+
else {
|
|
528
|
+
// R13: only the key credential-load put into this terminal's private agent (its public half selects it).
|
|
529
|
+
const loaded = readCredential(ref);
|
|
530
|
+
if (!loaded || !fs.existsSync(loaded.socket))
|
|
531
|
+
throw new RemoteTerminalError("CREDENTIAL_NOT_LOADED", "the terminal's credential is not loaded; resolve the handle and run credential-load");
|
|
532
|
+
identity = ["-o", `IdentityAgent=${loaded.socket}`, "-o", "IdentitiesOnly=yes", "-o", `IdentityFile=${credentialPublicKeyFile(ref)}`];
|
|
533
|
+
}
|
|
534
|
+
return ["-F", "/dev/null", "-T", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes",
|
|
535
|
+
"-o", `UserKnownHostsFile=${b.known_hosts_file}`, "-o", "GlobalKnownHostsFile=/dev/null", "-o", "CheckHostIP=no",
|
|
536
|
+
...(b.host_key_alias ? ["-o", `HostKeyAlias=${b.host_key_alias}`] : []),
|
|
537
|
+
...identity,
|
|
538
|
+
...(controlPath ? ["-o", "ControlMaster=auto", "-o", `ControlPath=${controlPath}`, "-o", "ControlPersist=600"] : ["-o", "ControlMaster=no", "-o", "ControlPath=none"]),
|
|
539
|
+
"-o", "ConnectTimeout=15", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=4", ...extra,
|
|
540
|
+
"-l", b.target.user, "-p", String(b.target.port), "--", b.target.host, ...(remoteCommand === null ? [] : [remoteCommand])];
|
|
541
|
+
}
|
|
542
|
+
// T2: which sessions live on which terminal. Small; read on every call so every Aiterm process sees the same map.
|
|
543
|
+
function seatsFile() { return path.join(ensureStateRoot(), "terminal-seats.json"); }
|
|
544
|
+
function readSeats() {
|
|
545
|
+
try {
|
|
546
|
+
const parsed = JSON.parse(fs.readFileSync(seatsFile(), "utf8"));
|
|
547
|
+
return parsed?.schema === "aiterm.terminal-seats.v1" && parsed.seats && typeof parsed.seats === "object" ? parsed.seats : {};
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
return {};
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
function writeSeats(seats) { writeJson0600(seatsFile(), { schema: "aiterm.terminal-seats.v1", seats }); }
|
|
554
|
+
export function bindTerminalSession(session, ref) { writeSeats({ ...readSeats(), [session]: ref }); }
|
|
555
|
+
export function unbindTerminalSession(session) {
|
|
556
|
+
const seats = readSeats();
|
|
557
|
+
if (!(session in seats))
|
|
558
|
+
return;
|
|
559
|
+
delete seats[session];
|
|
560
|
+
writeSeats(seats);
|
|
561
|
+
}
|
|
562
|
+
/** A later call's target, by session only. null = a local session. */
|
|
563
|
+
export function boundTerminalTarget(session) {
|
|
564
|
+
if (typeof session !== "string")
|
|
565
|
+
return null;
|
|
566
|
+
const ref = readSeats()[session];
|
|
567
|
+
return ref ? trustedTarget(binding(ref)) : null;
|
|
568
|
+
}
|
|
569
|
+
const SEAT_PATH = /^\/api\/seat-mcp(\/|$)/;
|
|
570
|
+
export function hasSeatMcpUrl(config) {
|
|
571
|
+
return Object.values((config.mcpServers ?? {})).some(server => {
|
|
572
|
+
try {
|
|
573
|
+
return typeof server?.url === "string" && SEAT_PATH.test(new URL(server.url).pathname);
|
|
574
|
+
}
|
|
575
|
+
catch {
|
|
576
|
+
return false;
|
|
577
|
+
}
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
/** Header values leave the config file: each becomes ${AITERM_MCP_HEADER_n}, its value goes to the private env line. */
|
|
581
|
+
export function extractMcpHeaders(config) {
|
|
582
|
+
const env = {};
|
|
583
|
+
const servers = {};
|
|
584
|
+
for (const [name, server] of Object.entries((config.mcpServers ?? {}))) {
|
|
585
|
+
const headers = server?.headers;
|
|
586
|
+
if (!headers || typeof headers !== "object") {
|
|
587
|
+
servers[name] = server;
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
const moved = {};
|
|
591
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
592
|
+
// Already an env reference: Claude expands it from the seat env (the name must be in env_vars).
|
|
593
|
+
if (typeof value !== "string" || value.includes("${")) {
|
|
594
|
+
moved[key] = value;
|
|
595
|
+
continue;
|
|
596
|
+
}
|
|
597
|
+
const envName = `AITERM_MCP_HEADER_${Object.keys(env).length}`;
|
|
598
|
+
env[envName] = value;
|
|
599
|
+
moved[key] = `\${${envName}}`;
|
|
600
|
+
}
|
|
601
|
+
servers[name] = { ...server, headers: moved };
|
|
602
|
+
}
|
|
603
|
+
return { config: config.mcpServers ? { ...config, mcpServers: servers } : config, env };
|
|
604
|
+
}
|
|
605
|
+
// ---- R12 forward keeper: one Aiterm process per terminal holds the seats' BellTeam MCP route (T3) ----
|
|
606
|
+
const FORWARD_RESTART_MS = 15_000, FORWARD_REFUSALS_BEFORE_NEW_PORT = 4, LAUNCH_GRACE_MS = 120_000;
|
|
607
|
+
const keepers = new Map();
|
|
608
|
+
let maintainTimer = null;
|
|
609
|
+
function writeBinding(ref, change) {
|
|
610
|
+
const bindings = readStore().map(item => item.ref === ref ? { ...item, ...change } : item);
|
|
611
|
+
writeJson0600(storePath(), { schema: "aiterm.remote-bindings.v1", bindings });
|
|
612
|
+
}
|
|
613
|
+
function lockFile(ref) { return path.join(ensureStateRoot(), `terminal-forward-${ref}.lock`); }
|
|
614
|
+
/** T3: true when this process holds the keeper lock for ref (taking it from a dead owner). */
|
|
615
|
+
function holdLock(ref) {
|
|
616
|
+
const file = lockFile(ref);
|
|
617
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
618
|
+
try {
|
|
619
|
+
fs.writeFileSync(file, JSON.stringify({ pid: process.pid }), { flag: "wx", mode: 0o600 });
|
|
620
|
+
return true;
|
|
621
|
+
}
|
|
622
|
+
catch (error) {
|
|
623
|
+
if (error.code !== "EEXIST")
|
|
624
|
+
return false;
|
|
625
|
+
let pid = 0;
|
|
626
|
+
try {
|
|
627
|
+
pid = Number(JSON.parse(fs.readFileSync(file, "utf8")).pid);
|
|
628
|
+
}
|
|
629
|
+
catch { /* unreadable: treat as dead */ }
|
|
630
|
+
if (pid === process.pid)
|
|
631
|
+
return true;
|
|
632
|
+
// shortcut: a reused pid looks alive; the next owner check after that process exits takes over.
|
|
633
|
+
try {
|
|
634
|
+
if (pid > 0) {
|
|
635
|
+
process.kill(pid, 0);
|
|
636
|
+
return false;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
catch { /* owner gone */ }
|
|
640
|
+
fs.rmSync(file, { force: true });
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
return false;
|
|
644
|
+
}
|
|
645
|
+
function releaseLock(ref) {
|
|
646
|
+
try {
|
|
647
|
+
if (Number(JSON.parse(fs.readFileSync(lockFile(ref), "utf8")).pid) === process.pid)
|
|
648
|
+
fs.rmSync(lockFile(ref), { force: true });
|
|
649
|
+
}
|
|
650
|
+
catch { /* none */ }
|
|
651
|
+
}
|
|
652
|
+
function forwardNeeded(ref) {
|
|
653
|
+
return (keepers.get(ref)?.launchUntil ?? 0) > Date.now() || Object.values(readSeats()).includes(ref);
|
|
654
|
+
}
|
|
655
|
+
function keep(ref) {
|
|
656
|
+
const keeper = keepers.get(ref) ?? { child: null, refusals: 0, timer: null, launchUntil: 0 };
|
|
657
|
+
keepers.set(ref, keeper);
|
|
658
|
+
if (keeper.child) {
|
|
659
|
+
if (!forwardNeeded(ref))
|
|
660
|
+
keeper.child.kill();
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
if (keeper.timer)
|
|
664
|
+
return;
|
|
665
|
+
if (!forwardNeeded(ref)) {
|
|
666
|
+
releaseLock(ref);
|
|
667
|
+
keepers.delete(ref);
|
|
668
|
+
releaseIdleCredential(ref);
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
if (!holdLock(ref))
|
|
672
|
+
return;
|
|
673
|
+
let b;
|
|
674
|
+
try {
|
|
675
|
+
b = binding(ref);
|
|
676
|
+
}
|
|
677
|
+
catch {
|
|
678
|
+
releaseLock(ref);
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
const requested = b.seat_forward_port ?? 0;
|
|
682
|
+
let args;
|
|
683
|
+
try {
|
|
684
|
+
// The remote command ends when our stdin closes, so the forward dies with this process even on SIGKILL.
|
|
685
|
+
args = trustedSshArguments(ref, "cat >/dev/null", null, ["-o", "ExitOnForwardFailure=yes", "-R", seatForwardSpec(requested)]);
|
|
686
|
+
}
|
|
687
|
+
catch {
|
|
688
|
+
releaseLock(ref);
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
const child = spawn("ssh", args, { env: sshEnvironment(), stdio: ["pipe", "ignore", "pipe"] });
|
|
692
|
+
keeper.child = child;
|
|
693
|
+
let stderr = "";
|
|
694
|
+
child.stderr.on("data", (chunk) => {
|
|
695
|
+
stderr = (stderr + chunk.toString("utf8")).slice(-4000);
|
|
696
|
+
const forward = parseSeatForward(stderr);
|
|
697
|
+
if (typeof forward === "number" && forward !== requested) {
|
|
698
|
+
writeBinding(ref, { seat_forward_port: forward });
|
|
699
|
+
keeper.refusals = 0;
|
|
700
|
+
}
|
|
701
|
+
});
|
|
702
|
+
child.on("error", () => { });
|
|
703
|
+
child.on("close", () => {
|
|
704
|
+
keeper.child = null;
|
|
705
|
+
if (parseSeatForward(stderr) === "refused" && requested !== 0 && ++keeper.refusals >= FORWARD_REFUSALS_BEFORE_NEW_PORT) {
|
|
706
|
+
// The old P stays taken on the terminal: let sshd pick a new one (seats launched with the old P need a relaunch).
|
|
707
|
+
writeBinding(ref, { seat_forward_port: undefined });
|
|
708
|
+
keeper.refusals = 0;
|
|
709
|
+
}
|
|
710
|
+
keeper.timer = setTimeout(() => { keeper.timer = null; keep(ref); }, FORWARD_RESTART_MS);
|
|
711
|
+
keeper.timer.unref();
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
/** Every 60 s: keep (or take over) the forwards this process's state root needs. */
|
|
715
|
+
export function maintainSeatForwards() {
|
|
716
|
+
const refs = new Set([...Object.values(readSeats()), ...keepers.keys(), ...loadedCredentialRefs()]);
|
|
717
|
+
for (const ref of refs)
|
|
718
|
+
keep(ref);
|
|
719
|
+
if (refs.size && !maintainTimer) {
|
|
720
|
+
maintainTimer = setInterval(maintainSeatForwards, 60_000);
|
|
721
|
+
maintainTimer.unref();
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
/** The terminal-local port for seat URLs; starts the keeper if no process holds it yet. */
|
|
725
|
+
export async function ensureSeatForward(ref, timeoutMs = 30_000) {
|
|
726
|
+
const keeper = keepers.get(ref) ?? { child: null, refusals: 0, timer: null, launchUntil: 0 };
|
|
727
|
+
keeper.launchUntil = Date.now() + LAUNCH_GRACE_MS;
|
|
728
|
+
keepers.set(ref, keeper);
|
|
729
|
+
maintainSeatForwards();
|
|
730
|
+
const deadline = Date.now() + timeoutMs;
|
|
731
|
+
for (;;) {
|
|
732
|
+
const port = binding(ref).seat_forward_port;
|
|
733
|
+
if (port)
|
|
734
|
+
return port;
|
|
735
|
+
if (Date.now() > deadline)
|
|
736
|
+
throw new RemoteTerminalError("SEAT_FORWARD_UNAVAILABLE", "the seat's MCP route back to this computer is not ready; launch again later");
|
|
737
|
+
await new Promise(resolve => setTimeout(resolve, 250));
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
// ---- R13 credential agent: a keyless terminal's key, loaded by execution over stdin, held only in a private ssh-agent ----
|
|
741
|
+
const LOAD_GRACE_MS = 120_000, MAX_KEY_BYTES = 64 * 1024;
|
|
742
|
+
function credentialDir() {
|
|
743
|
+
const dir = path.join(path.dirname(storePath()), "credentials");
|
|
744
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
745
|
+
return dir;
|
|
746
|
+
}
|
|
747
|
+
const credentialMetaFile = (ref) => path.join(credentialDir(), `${ref}.json`);
|
|
748
|
+
export const credentialPublicKeyFile = (ref) => path.join(credentialDir(), `${ref}.pub`);
|
|
749
|
+
function agentSocketPath(ref) {
|
|
750
|
+
// Short and stable across processes: macOS-style 104-byte sun_path limits also apply here.
|
|
751
|
+
const dir = path.join("/tmp", `aiterm-ka-${process.getuid?.() ?? 0}`);
|
|
752
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
753
|
+
const stat = fs.lstatSync(dir);
|
|
754
|
+
if (!stat.isDirectory() || stat.uid !== (process.getuid?.() ?? 0) || (stat.mode & 0o777) !== 0o700)
|
|
755
|
+
throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", "the credential agent directory is not a private directory of this user");
|
|
756
|
+
return path.join(dir, `${ref.slice(0, 8)}.sock`);
|
|
757
|
+
}
|
|
758
|
+
function agentEnv(socket) { return { ...sshEnvironment(), SSH_AUTH_SOCK: socket }; }
|
|
759
|
+
function agentAlive(socket) {
|
|
760
|
+
if (!fs.existsSync(socket))
|
|
761
|
+
return false;
|
|
762
|
+
const listed = spawnSync("ssh-add", ["-l"], { env: agentEnv(socket), stdio: ["ignore", "ignore", "ignore"], timeout: 10_000 });
|
|
763
|
+
return listed.status === 0; // 1 = alive but empty, which cannot authenticate either
|
|
764
|
+
}
|
|
765
|
+
export function readCredential(ref) {
|
|
766
|
+
try {
|
|
767
|
+
const meta = JSON.parse(fs.readFileSync(credentialMetaFile(ref), "utf8"));
|
|
768
|
+
return meta?.schema === "aiterm.credential-agent.v1" && meta.ref === ref ? meta : null;
|
|
769
|
+
}
|
|
770
|
+
catch {
|
|
771
|
+
return null;
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
function loadedCredentialRefs() {
|
|
775
|
+
try {
|
|
776
|
+
return fs.readdirSync(credentialDir()).filter(name => name.endsWith(".json")).map(name => name.slice(0, -5)).filter(ref => REF.test(ref));
|
|
777
|
+
}
|
|
778
|
+
catch {
|
|
779
|
+
return [];
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
export function releaseCredential(ref) {
|
|
783
|
+
const meta = readCredential(ref);
|
|
784
|
+
if (meta?.agent_pid)
|
|
785
|
+
try {
|
|
786
|
+
process.kill(meta.agent_pid);
|
|
787
|
+
}
|
|
788
|
+
catch { /* already gone */ }
|
|
789
|
+
for (const file of [credentialMetaFile(ref), credentialPublicKeyFile(ref), meta?.socket].filter((f) => !!f))
|
|
790
|
+
fs.rmSync(file, { force: true });
|
|
791
|
+
}
|
|
792
|
+
/** No terminal seat of this ref and no launch pending: the key leaves memory. */
|
|
793
|
+
function releaseIdleCredential(ref) {
|
|
794
|
+
const meta = readCredential(ref);
|
|
795
|
+
if (!meta || Object.values(readSeats()).includes(ref) || Date.now() - Date.parse(meta.loaded_at) < LOAD_GRACE_MS)
|
|
796
|
+
return;
|
|
797
|
+
releaseCredential(ref);
|
|
798
|
+
}
|
|
799
|
+
/** credential-load (R13): key bytes only from the caller's stdin; the receipt carries metadata only. */
|
|
800
|
+
export async function loadCredential(input, key) {
|
|
801
|
+
try {
|
|
802
|
+
if (input.purpose !== "ssh-key")
|
|
803
|
+
throw new RemoteTerminalError("CREDENTIAL_PURPOSE_UNSUPPORTED", "only --purpose ssh-key is loaded; a sudo secret is never loaded here");
|
|
804
|
+
if (!/^[A-Za-z0-9._-]{1,128}$/.test(input.terminalId))
|
|
805
|
+
throw new RemoteTerminalError("TERMINAL_ID_INVALID", "--terminal-id is required");
|
|
806
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(input.handle))
|
|
807
|
+
throw new RemoteTerminalError("CREDENTIAL_HANDLE_INVALID", "--handle must be a UUID");
|
|
808
|
+
const revision = Number(input.revision);
|
|
809
|
+
if (!/^[1-9]\d{0,15}$/.test(input.revision) || !Number.isSafeInteger(revision))
|
|
810
|
+
throw new RemoteTerminalError("CREDENTIAL_REVISION_INVALID", "--revision must be a positive integer");
|
|
811
|
+
const b = binding(input.ref);
|
|
812
|
+
if (b.key_file)
|
|
813
|
+
throw new RemoteTerminalError("TERMINAL_INVALID", "this terminal has a native key; a credential is loaded only for keyless terminals");
|
|
814
|
+
if (key.length === 0 || key.length > MAX_KEY_BYTES || !key.includes("PRIVATE KEY-----"))
|
|
815
|
+
throw new RemoteTerminalError("CREDENTIAL_INVALID", "stdin is not an OpenSSH private key");
|
|
816
|
+
const socket = agentSocketPath(b.ref);
|
|
817
|
+
let pid = readCredential(b.ref)?.agent_pid ?? null;
|
|
818
|
+
if (!agentAliveOrEmpty(socket)) {
|
|
819
|
+
fs.rmSync(socket, { force: true });
|
|
820
|
+
// Detached: the agent outlives this one-shot and holds the key in memory only.
|
|
821
|
+
const agent = spawn("ssh-agent", ["-D", "-a", socket], { env: sshEnvironment(), stdio: "ignore", detached: true });
|
|
822
|
+
agent.unref();
|
|
823
|
+
pid = agent.pid ?? null;
|
|
824
|
+
const deadline = Date.now() + 5000;
|
|
825
|
+
while (!fs.existsSync(socket)) {
|
|
826
|
+
if (Date.now() > deadline)
|
|
827
|
+
throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", "the credential agent did not start");
|
|
828
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
spawnSync("ssh-add", ["-D"], { env: agentEnv(socket), stdio: ["ignore", "ignore", "ignore"], timeout: 10_000 });
|
|
832
|
+
const added = spawnSync("ssh-add", ["-q", "-"], { env: agentEnv(socket), input: key, stdio: ["pipe", "ignore", "ignore"], timeout: 10_000 });
|
|
833
|
+
if (added.status !== 0)
|
|
834
|
+
throw new RemoteTerminalError("CREDENTIAL_INVALID", "the agent did not accept the key (passphrase-protected or malformed)");
|
|
835
|
+
const listed = spawnSync("ssh-add", ["-L"], { env: agentEnv(socket), encoding: "utf8", timeout: 10_000 });
|
|
836
|
+
const line = listed.stdout.trim().split("\n")[0]?.split(/\s+/).slice(0, 2).join(" ") ?? "";
|
|
837
|
+
const fingerprint = keyFingerprint(Buffer.from(line.split(" ")[1] ?? "", "base64"));
|
|
838
|
+
fs.writeFileSync(credentialPublicKeyFile(b.ref), `${line}\n`, { mode: 0o600 });
|
|
839
|
+
writeJson0600(credentialMetaFile(b.ref), { schema: "aiterm.credential-agent.v1", ref: b.ref, terminal_id: input.terminalId, handle: input.handle,
|
|
840
|
+
revision, fingerprint, agent_pid: pid, socket, loaded_at: new Date().toISOString() });
|
|
841
|
+
return { schema: "aiterm.credential-load.v1", accepted: true, ref: b.ref, terminal_id: input.terminalId, handle: input.handle, revision, fingerprint };
|
|
842
|
+
}
|
|
843
|
+
finally {
|
|
844
|
+
key.fill(0);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
function agentAliveOrEmpty(socket) {
|
|
848
|
+
if (!fs.existsSync(socket))
|
|
849
|
+
return false;
|
|
850
|
+
const listed = spawnSync("ssh-add", ["-l"], { env: agentEnv(socket), stdio: ["ignore", "ignore", "ignore"], timeout: 10_000 });
|
|
851
|
+
return listed.status === 0 || listed.status === 1;
|
|
852
|
+
}
|
package/dist/remote.js
CHANGED
|
@@ -10,12 +10,14 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
|
|
|
10
10
|
import { AitermError, observeAgentDone, readAgentTranscriptResult, windowsStartProcessArgumentList } from "./core.js";
|
|
11
11
|
import { ensureStateRoot, stateRoot } from "./agent-shared.js";
|
|
12
12
|
import { currentUid } from "./state-root.js";
|
|
13
|
+
import { PRIVATE_ENV_SCHEMA } from "./private-env.js";
|
|
14
|
+
import { SshStdioTransport, classifySshFailure, trustedSshArguments } from "./remote-terminal.js";
|
|
13
15
|
const pkg = createRequire(import.meta.url)("../package.json");
|
|
14
16
|
export { remoteTargetSchema, remoteInputSchema, remoteInputDescription } from "./remote-contract.js";
|
|
15
17
|
// 平文で受け取ったパスフレーズは、このMCP processのメモリにだけ置く。ControlMasterが落ちた後の再接続に使う。
|
|
16
18
|
const passphrases = new Map();
|
|
17
19
|
export function remoteKey(target) {
|
|
18
|
-
return createHash("sha256").update(JSON.stringify([target.host, target.user ?? null, target.port ?? null])).digest("hex").slice(0, 12);
|
|
20
|
+
return createHash("sha256").update(JSON.stringify([target.host, target.user ?? null, target.port ?? null, target.trusted_ref ?? null])).digest("hex").slice(0, 12);
|
|
19
21
|
}
|
|
20
22
|
export function remoteLabel(target) {
|
|
21
23
|
return `${target.user ? `${target.user}@` : ""}${target.host}${target.port ? `:${target.port}` : ""}`;
|
|
@@ -32,7 +34,7 @@ function remoteDir() {
|
|
|
32
34
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
33
35
|
return dir;
|
|
34
36
|
}
|
|
35
|
-
function controlPath() {
|
|
37
|
+
function controlPath(trustedRef) {
|
|
36
38
|
// TMPDIRやXDG_RUNTIME_DIRは長くなり得る。%Cの40字とOpenSSHの一時suffix(17字)を含めても
|
|
37
39
|
// macOSの104 byte制限に収まる短い領域へ、state rootごとに共有ソケットだけを置く。
|
|
38
40
|
const namespace = createHash("sha256").update(stateRoot()).digest("hex").slice(0, 20);
|
|
@@ -43,7 +45,8 @@ function controlPath() {
|
|
|
43
45
|
if (!stat.isDirectory() || stat.uid !== currentUid() || (stat.mode & 0o777) !== 0o700) {
|
|
44
46
|
throw new AitermError("REMOTE_CONTROL_DIR_INVALID: SSH共有ソケットの領域が自分所有の0700ディレクトリではありません", 2);
|
|
45
47
|
}
|
|
46
|
-
|
|
48
|
+
// A trusted binding never shares a master opened by an ad-hoc target to the same host.
|
|
49
|
+
return path.join(dir, trustedRef ? `t-${trustedRef.slice(0, 8)}-%C` : "cm-%C");
|
|
47
50
|
}
|
|
48
51
|
function askpassScript() {
|
|
49
52
|
const file = path.join(remoteDir(), "askpass.sh");
|
|
@@ -69,6 +72,8 @@ export function sshInvocation(target, remoteCommand, options = {}) {
|
|
|
69
72
|
for (const [key, value] of Object.entries(process.env))
|
|
70
73
|
if (typeof value === "string" && !key.startsWith("AITERM_SSH_"))
|
|
71
74
|
env[key] = value;
|
|
75
|
+
if (target.trusted_ref)
|
|
76
|
+
return { args: trustedSshArguments(target.trusted_ref, remoteCommand, process.platform === "win32" ? null : controlPath(target.trusted_ref)), env };
|
|
72
77
|
const args = ["-T", "-o", "ConnectTimeout=15", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=4"];
|
|
73
78
|
// 同じ接続先への後続呼び出しと完了待ちを一本のSSHに相乗りさせる。Windows版OpenSSHはControlMaster非対応。
|
|
74
79
|
if (process.platform !== "win32") {
|
|
@@ -138,18 +143,31 @@ export function posixCommand(script) {
|
|
|
138
143
|
export function remoteServerCommand(shell) {
|
|
139
144
|
return shell === "posix" ? posixCommand("exec aiterm-mcp") : "aiterm-mcp";
|
|
140
145
|
}
|
|
141
|
-
/** 現地のaiterm-mcpへ1回だけMCP接続し、指定toolを呼んで閉じる。 */
|
|
142
|
-
export async function callRemoteTool(target, name, args, timeoutMs = 600_000) {
|
|
143
|
-
|
|
144
|
-
|
|
146
|
+
/** 現地のaiterm-mcpへ1回だけMCP接続し、指定toolを呼んで閉じる。privateEnvは暗号化されたstdinの先頭行だけで渡す(remote-terminal.md R5)。 */
|
|
147
|
+
export async function callRemoteTool(target, name, args, timeoutMs = 600_000, privateEnv) {
|
|
148
|
+
if (privateEnv && !target.trusted_ref)
|
|
149
|
+
throw new AitermError("REMOTE_PRIVATE_ENV_UNSUPPORTED: private values travel only to a terminal binding", 2);
|
|
150
|
+
const shell = await remoteShell(target);
|
|
151
|
+
const command = privateEnv ? posixCommand("exec aiterm-mcp --private-env-stdin") : remoteServerCommand(shell);
|
|
152
|
+
const { args: sshArgs, env } = sshInvocation(target, command);
|
|
153
|
+
const transport = privateEnv
|
|
154
|
+
? new SshStdioTransport(sshArgs, `${JSON.stringify({ schema: PRIVATE_ENV_SCHEMA, env: privateEnv })}\n`)
|
|
155
|
+
: new StdioClientTransport({ command: "ssh", args: sshArgs, env, stderr: "pipe" });
|
|
145
156
|
let stderr = "";
|
|
146
|
-
|
|
157
|
+
if (transport instanceof StdioClientTransport)
|
|
158
|
+
transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString("utf8")).slice(-2000); });
|
|
147
159
|
const client = new Client({ name: "aiterm-remote", version: pkg.version });
|
|
148
160
|
try {
|
|
149
161
|
try {
|
|
150
162
|
await client.connect(transport, { timeout: 60_000 });
|
|
151
163
|
}
|
|
152
164
|
catch (error) {
|
|
165
|
+
if (transport instanceof SshStdioTransport)
|
|
166
|
+
stderr = transport.stderr;
|
|
167
|
+
if (target.trusted_ref) {
|
|
168
|
+
const failure = classifySshFailure(stderr);
|
|
169
|
+
throw new AitermError(`${failure.code}: ${failure.message}${failure.action ? ` (${failure.action})` : ""}`, 2);
|
|
170
|
+
}
|
|
153
171
|
const detail = stderr.trim().split("\n").slice(-3).join(" / ") || (error instanceof Error ? error.message : String(error));
|
|
154
172
|
throw new AitermError(`REMOTE_CONNECT_FAILED: ${remoteLabel(target)} のAitermへ接続できません(${detail})`, 2);
|
|
155
173
|
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// aiterm-transcript-read --session S [--cursor-session ID --offset N] [--max-bytes N] (remote-terminal.md "One launch path")
|
|
3
|
+
// One JSON line. A local seat is read here; a terminal seat is read by the same reader on its terminal over the trusted SSH.
|
|
4
|
+
import { realpathSync } from "node:fs";
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { readCompletedTranscript } from "./transcript-read.js";
|
|
8
|
+
import { boundTerminalTarget, classifySshFailure, trustedSshArguments } from "./remote-terminal.js";
|
|
9
|
+
import { posixCommand } from "./remote.js";
|
|
10
|
+
const ERROR = "aiterm.transcript-read-error.v1";
|
|
11
|
+
function option(args, name) {
|
|
12
|
+
const at = args.indexOf(name);
|
|
13
|
+
return at >= 0 ? args[at + 1] : undefined;
|
|
14
|
+
}
|
|
15
|
+
/** Validated reader flags; every value is a plain token, so the remote command needs no quoting. */
|
|
16
|
+
export function transcriptFlags(args) {
|
|
17
|
+
const session = option(args, "--session") ?? "", id = option(args, "--cursor-session"), offset = option(args, "--offset"), max = option(args, "--max-bytes");
|
|
18
|
+
if (!/^[A-Za-z0-9_-]{1,64}$/.test(session))
|
|
19
|
+
throw new Error("SESSION_INVALID: --session is required");
|
|
20
|
+
const flags = ["--session", session];
|
|
21
|
+
if (id !== undefined || offset !== undefined) {
|
|
22
|
+
if (!/^[0-9a-f-]{36}$/i.test(id ?? "") || !/^\d{1,15}$/.test(offset ?? ""))
|
|
23
|
+
throw new Error("TRANSCRIPT_CURSOR_INVALID: --cursor-session and --offset go together");
|
|
24
|
+
flags.push("--cursor-session", id, "--offset", offset);
|
|
25
|
+
}
|
|
26
|
+
if (max !== undefined) {
|
|
27
|
+
if (!/^[1-9]\d{0,9}$/.test(max))
|
|
28
|
+
throw new Error("TRANSCRIPT_MAX_INVALID: --max-bytes must be a positive integer");
|
|
29
|
+
flags.push("--max-bytes", max);
|
|
30
|
+
}
|
|
31
|
+
return flags;
|
|
32
|
+
}
|
|
33
|
+
function run(args) {
|
|
34
|
+
const flags = transcriptFlags(args);
|
|
35
|
+
const target = boundTerminalTarget(flags[1]);
|
|
36
|
+
if (!target) {
|
|
37
|
+
const id = option(flags, "--cursor-session"), max = option(flags, "--max-bytes");
|
|
38
|
+
return { line: JSON.stringify(readCompletedTranscript(flags[1], id ? { claudeSessionId: id, offset: Number(option(flags, "--offset")) } : null, max ? Number(max) : undefined)), code: 0 };
|
|
39
|
+
}
|
|
40
|
+
const ssh = spawnSync("ssh", trustedSshArguments(target.trusted_ref, posixCommand(`exec aiterm-remote-terminal transcript-read ${flags.join(" ")}`), null), { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 120_000, maxBuffer: 64 * 1024 * 1024 });
|
|
41
|
+
const line = (ssh.stdout ?? "").trim().split("\n").pop() ?? "";
|
|
42
|
+
let parsed = null;
|
|
43
|
+
try {
|
|
44
|
+
parsed = JSON.parse(line);
|
|
45
|
+
}
|
|
46
|
+
catch { /* classified below */ }
|
|
47
|
+
if (parsed?.schema === "aiterm.transcript-read.v1")
|
|
48
|
+
return { line, code: 0 };
|
|
49
|
+
if (parsed?.schema === ERROR)
|
|
50
|
+
return { line, code: 2 };
|
|
51
|
+
const failure = ssh.status === 255 ? classifySshFailure(ssh.stderr ?? "") : { code: "COMMAND_FAILED", message: "the transcript reader failed on the terminal" };
|
|
52
|
+
return { line: JSON.stringify({ schema: ERROR, ...failure }), code: 2 };
|
|
53
|
+
}
|
|
54
|
+
let entry = false;
|
|
55
|
+
try {
|
|
56
|
+
entry = !!process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
57
|
+
}
|
|
58
|
+
catch { /* imported */ }
|
|
59
|
+
if (entry) {
|
|
60
|
+
try {
|
|
61
|
+
const { line, code } = run(process.argv.slice(2));
|
|
62
|
+
process.stdout.write(`${line}\n`);
|
|
63
|
+
process.exit(code);
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
67
|
+
process.stdout.write(`${JSON.stringify({ schema: ERROR, code: /^([A-Z][A-Z0-9_]+):/.exec(message)?.[1] ?? "AITERM_FAILED", message })}\n`);
|
|
68
|
+
process.exit(2);
|
|
69
|
+
}
|
|
70
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiterm-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.67.0",
|
|
4
4
|
"mcpName": "io.github.kitepon/aiterm-mcp",
|
|
5
5
|
"description": "Persistent terminal MCP with one harness-based launcher for Claude Code, Codex CLI, Grok CLI, Cursor Agent CLI, and Antigravity CLI, plus durable PTYs for SSH, containers, and REPLs.",
|
|
6
6
|
"keywords": [
|
|
@@ -49,7 +49,8 @@
|
|
|
49
49
|
"aiterm-update": "dist/update-cli.js",
|
|
50
50
|
"aiterm-idle-check": "dist/agent-idle-cli.js",
|
|
51
51
|
"aiterm-resume-state": "dist/resume-state-cli.js",
|
|
52
|
-
"aiterm-remote-terminal": "dist/remote-terminal-cli.js"
|
|
52
|
+
"aiterm-remote-terminal": "dist/remote-terminal-cli.js",
|
|
53
|
+
"aiterm-transcript-read": "dist/transcript-read-cli.js"
|
|
53
54
|
},
|
|
54
55
|
"files": [
|
|
55
56
|
"dist/*.js",
|