aiterm-mcp 0.65.1 → 0.66.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 +10 -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 +27 -1
- package/dist/remote-terminal.js +262 -3
- 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,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.66.0] - 2026-11-09
|
|
11
|
+
|
|
12
|
+
- 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`.
|
|
13
|
+
- 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.
|
|
14
|
+
- 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.
|
|
15
|
+
- 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`.
|
|
16
|
+
- `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.
|
|
17
|
+
|
|
10
18
|
## [0.65.1] - 2026-11-09
|
|
11
19
|
|
|
12
20
|
- `aiterm-remote-terminal`: the `ready` event now reaches the caller; 0.65.0 emitted it before the listener was attached.
|
|
@@ -3124,7 +3132,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
|
|
|
3124
3132
|
`ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
|
|
3125
3133
|
provenance.
|
|
3126
3134
|
|
|
3127
|
-
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.
|
|
3135
|
+
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.66.0...HEAD
|
|
3136
|
+
[0.66.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.65.1...v0.66.0
|
|
3128
3137
|
[0.65.1]: https://github.com/kitepon/aiterm-mcp/compare/v0.65.0...v0.65.1
|
|
3129
3138
|
[0.65.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.64.2...v0.65.0
|
|
3130
3139
|
[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.66.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.66.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,37 @@ 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
|
+
/** The launch tools' terminal target (remote-terminal.md "One launch path"). Copied unchanged from BellTeam terminals. */
|
|
26
|
+
export const terminalArgumentSchema = z.object({
|
|
27
|
+
ref: z.string().uuid("terminal.ref must be the binding ref (UUID) the terminal registry gave for this terminal"),
|
|
28
|
+
target: z.object({
|
|
29
|
+
host: z.string().min(1, "terminal.target.host is required"),
|
|
30
|
+
user: z.string().min(1, "terminal.target.user is required"),
|
|
31
|
+
port: z.number().int().min(1).max(65535),
|
|
32
|
+
}).strict(),
|
|
33
|
+
trustRevision: revision("trustRevision"),
|
|
34
|
+
credentialRevision: revision("credentialRevision"),
|
|
35
|
+
}).strict();
|
|
36
|
+
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, " +
|
|
37
|
+
"{ref, target:{host,user,port}, trustRevision, credentialRevision}; copy it unchanged, never invent or edit it, never use a host name or ssh command instead. " +
|
|
38
|
+
"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. " +
|
|
39
|
+
"Never put tokens, passwords or other secrets in any argument, prompt or typed text; pass secret values only by name in env_vars. " +
|
|
40
|
+
"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. " +
|
|
41
|
+
"Errors and next step: TERMINAL_INVALID = malformed value, missing/relative cwd, or combined with remote: pass the registry's value unchanged with cwd. " +
|
|
42
|
+
"TARGET_MISMATCH / BINDING_UNKNOWN = the value is not this terminal's binding: ask the terminal registry again. " +
|
|
43
|
+
"HOST_TRUST_STALE / CREDENTIAL_REVISION_STALE = the binding changed: get the current value from the terminal registry and launch again. " +
|
|
44
|
+
"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. " +
|
|
45
|
+
"AUTH_FAILED = the terminal refused the key. UNREACHABLE = the terminal is offline; try later. " +
|
|
46
|
+
"REMOTE_AITERM_TOO_OLD = update Aiterm on the terminal. CWD_UNAVAILABLE = the folder does not exist there; do not pick another folder. " +
|
|
47
|
+
"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.";
|
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");
|
|
@@ -164,6 +164,39 @@ export function classifySshFailure(stderr) {
|
|
|
164
164
|
return { code: "UNREACHABLE", message: "the terminal cannot be reached" };
|
|
165
165
|
return { code: "CONNECTION_FAILED", message: "the SSH connection failed" };
|
|
166
166
|
}
|
|
167
|
+
/** -R spec for the seats' BellTeam MCP (remote-terminal.md R12). P=0 lets the terminal's sshd pick the port. */
|
|
168
|
+
export function seatForwardSpec(terminalPort, env = process.env) {
|
|
169
|
+
const port = Number(env.BELLTEAM_REMOTE_SEAT_PORT ?? 4182);
|
|
170
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
171
|
+
throw new RemoteTerminalError("SEAT_FORWARD_UNAVAILABLE", "BELLTEAM_REMOTE_SEAT_PORT is not a port");
|
|
172
|
+
return `127.0.0.1:${terminalPort}:127.0.0.1:${port}`;
|
|
173
|
+
}
|
|
174
|
+
/** ssh stderr -> the allocated terminal port, "refused", or null while unknown. */
|
|
175
|
+
export function parseSeatForward(stderr) {
|
|
176
|
+
const allocated = /Allocated port (\d+) for remote forward/.exec(stderr);
|
|
177
|
+
if (allocated)
|
|
178
|
+
return Number(allocated[1]);
|
|
179
|
+
return /remote port forwarding failed/i.test(stderr) ? "refused" : null;
|
|
180
|
+
}
|
|
181
|
+
/** Seat MCP URLs (path /api/seat-mcp...) get the forward's terminal-local origin; everything else stays as given. */
|
|
182
|
+
export function rewriteSeatMcpConfig(config, port) {
|
|
183
|
+
const servers = config.mcpServers;
|
|
184
|
+
if (!servers || typeof servers !== "object")
|
|
185
|
+
return config;
|
|
186
|
+
const rewritten = {};
|
|
187
|
+
for (const [name, server] of Object.entries(servers)) {
|
|
188
|
+
const url = server?.url;
|
|
189
|
+
let parsed = null;
|
|
190
|
+
try {
|
|
191
|
+
parsed = typeof url === "string" ? new URL(url) : null;
|
|
192
|
+
}
|
|
193
|
+
catch { /* not a URL: unchanged */ }
|
|
194
|
+
rewritten[name] = parsed && /^\/api\/seat-mcp(\/|$)/.test(parsed.pathname)
|
|
195
|
+
? { ...server, url: `http://127.0.0.1:${port}${parsed.pathname}${parsed.search}` }
|
|
196
|
+
: server;
|
|
197
|
+
}
|
|
198
|
+
return { ...config, mcpServers: rewritten };
|
|
199
|
+
}
|
|
167
200
|
export function sshArguments(b, agentSocket, identityFile, remoteCommand) {
|
|
168
201
|
return ["-F", "/dev/null", "-T", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes",
|
|
169
202
|
"-o", `UserKnownHostsFile=${b.known_hosts_file}`, "-o", "GlobalKnownHostsFile=/dev/null", "-o", "CheckHostIP=no",
|
|
@@ -180,7 +213,7 @@ function sshEnvironment() {
|
|
|
180
213
|
return env;
|
|
181
214
|
}
|
|
182
215
|
/** MCP over an ssh child whose stdin first carries the private env line (remote-terminal.md R5). */
|
|
183
|
-
class SshStdioTransport {
|
|
216
|
+
export class SshStdioTransport {
|
|
184
217
|
args;
|
|
185
218
|
privateLine;
|
|
186
219
|
onclose;
|
|
@@ -236,7 +269,7 @@ export function waitArguments(args) {
|
|
|
236
269
|
throw new RemoteTerminalError("WAIT_INVALID", "wait_process needs --session");
|
|
237
270
|
return rest;
|
|
238
271
|
}
|
|
239
|
-
function versionAtLeast(actual, required) {
|
|
272
|
+
export function versionAtLeast(actual, required) {
|
|
240
273
|
const a = actual.split(/[.-]/).slice(0, 3).map(Number), r = required.split(/[.-]/).slice(0, 3).map(Number);
|
|
241
274
|
for (let i = 0; i < 3; i++)
|
|
242
275
|
if ((a[i] ?? 0) !== (r[i] ?? 0))
|
|
@@ -432,3 +465,229 @@ export class RemoteTerminalConnection extends EventEmitter {
|
|
|
432
465
|
return { closed: true };
|
|
433
466
|
}
|
|
434
467
|
}
|
|
468
|
+
const trustedTarget = (b) => ({ host: b.target.host, user: b.target.user, port: b.target.port, trusted_ref: b.ref });
|
|
469
|
+
/** T1: the binding exists, the target is the binding's, both revisions are current. */
|
|
470
|
+
export function terminalRemoteTarget(input) {
|
|
471
|
+
const b = binding(input.ref);
|
|
472
|
+
const target = validTarget(input.target);
|
|
473
|
+
if (b.target.host !== target.host || b.target.user !== target.user || b.target.port !== target.port)
|
|
474
|
+
throw new RemoteTerminalError("TARGET_MISMATCH", "terminal.target differs from this binding; get the current value from the terminal registry");
|
|
475
|
+
const status = bindingStatus(input.ref);
|
|
476
|
+
if (!status.trust.available)
|
|
477
|
+
throw new RemoteTerminalError(status.trust.reason ?? "HOST_TRUST_MISSING", "the terminal's host key is not trusted (confirm the new host key)");
|
|
478
|
+
if (status.trust.revision !== input.trustRevision)
|
|
479
|
+
throw new RemoteTerminalError("HOST_TRUST_STALE", "the host trust changed; get the current value from the terminal registry and launch again");
|
|
480
|
+
if (!status.credential.available)
|
|
481
|
+
throw new RemoteTerminalError("CREDENTIAL_UNAVAILABLE", status.credential.reason ?? "the key is unavailable");
|
|
482
|
+
if (status.credential.revision !== input.credentialRevision)
|
|
483
|
+
throw new RemoteTerminalError("CREDENTIAL_REVISION_STALE", "the key changed; get the current value from the terminal registry and launch again");
|
|
484
|
+
return trustedTarget(b);
|
|
485
|
+
}
|
|
486
|
+
/** ssh argv for a trusted target: no user config, the binding's known_hosts only, its key file only. */
|
|
487
|
+
export function trustedSshArguments(ref, remoteCommand, controlPath, extra = []) {
|
|
488
|
+
const b = binding(ref);
|
|
489
|
+
return ["-F", "/dev/null", "-T", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes",
|
|
490
|
+
"-o", `UserKnownHostsFile=${b.known_hosts_file}`, "-o", "GlobalKnownHostsFile=/dev/null", "-o", "CheckHostIP=no",
|
|
491
|
+
...(b.host_key_alias ? ["-o", `HostKeyAlias=${b.host_key_alias}`] : []),
|
|
492
|
+
"-o", "IdentityAgent=none", "-o", "IdentitiesOnly=yes", "-o", `IdentityFile=${b.key_file}`,
|
|
493
|
+
...(controlPath ? ["-o", "ControlMaster=auto", "-o", `ControlPath=${controlPath}`, "-o", "ControlPersist=600"] : ["-o", "ControlMaster=no", "-o", "ControlPath=none"]),
|
|
494
|
+
"-o", "ConnectTimeout=15", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=4", ...extra,
|
|
495
|
+
"-l", b.target.user, "-p", String(b.target.port), "--", b.target.host, ...(remoteCommand === null ? [] : [remoteCommand])];
|
|
496
|
+
}
|
|
497
|
+
// T2: which sessions live on which terminal. Small; read on every call so every Aiterm process sees the same map.
|
|
498
|
+
function seatsFile() { return path.join(ensureStateRoot(), "terminal-seats.json"); }
|
|
499
|
+
function readSeats() {
|
|
500
|
+
try {
|
|
501
|
+
const parsed = JSON.parse(fs.readFileSync(seatsFile(), "utf8"));
|
|
502
|
+
return parsed?.schema === "aiterm.terminal-seats.v1" && parsed.seats && typeof parsed.seats === "object" ? parsed.seats : {};
|
|
503
|
+
}
|
|
504
|
+
catch {
|
|
505
|
+
return {};
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
function writeSeats(seats) { writeJson0600(seatsFile(), { schema: "aiterm.terminal-seats.v1", seats }); }
|
|
509
|
+
export function bindTerminalSession(session, ref) { writeSeats({ ...readSeats(), [session]: ref }); }
|
|
510
|
+
export function unbindTerminalSession(session) {
|
|
511
|
+
const seats = readSeats();
|
|
512
|
+
if (!(session in seats))
|
|
513
|
+
return;
|
|
514
|
+
delete seats[session];
|
|
515
|
+
writeSeats(seats);
|
|
516
|
+
}
|
|
517
|
+
/** A later call's target, by session only. null = a local session. */
|
|
518
|
+
export function boundTerminalTarget(session) {
|
|
519
|
+
if (typeof session !== "string")
|
|
520
|
+
return null;
|
|
521
|
+
const ref = readSeats()[session];
|
|
522
|
+
return ref ? trustedTarget(binding(ref)) : null;
|
|
523
|
+
}
|
|
524
|
+
const SEAT_PATH = /^\/api\/seat-mcp(\/|$)/;
|
|
525
|
+
export function hasSeatMcpUrl(config) {
|
|
526
|
+
return Object.values((config.mcpServers ?? {})).some(server => {
|
|
527
|
+
try {
|
|
528
|
+
return typeof server?.url === "string" && SEAT_PATH.test(new URL(server.url).pathname);
|
|
529
|
+
}
|
|
530
|
+
catch {
|
|
531
|
+
return false;
|
|
532
|
+
}
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
/** Header values leave the config file: each becomes ${AITERM_MCP_HEADER_n}, its value goes to the private env line. */
|
|
536
|
+
export function extractMcpHeaders(config) {
|
|
537
|
+
const env = {};
|
|
538
|
+
const servers = {};
|
|
539
|
+
for (const [name, server] of Object.entries((config.mcpServers ?? {}))) {
|
|
540
|
+
const headers = server?.headers;
|
|
541
|
+
if (!headers || typeof headers !== "object") {
|
|
542
|
+
servers[name] = server;
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
const moved = {};
|
|
546
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
547
|
+
// Already an env reference: Claude expands it from the seat env (the name must be in env_vars).
|
|
548
|
+
if (typeof value !== "string" || value.includes("${")) {
|
|
549
|
+
moved[key] = value;
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
const envName = `AITERM_MCP_HEADER_${Object.keys(env).length}`;
|
|
553
|
+
env[envName] = value;
|
|
554
|
+
moved[key] = `\${${envName}}`;
|
|
555
|
+
}
|
|
556
|
+
servers[name] = { ...server, headers: moved };
|
|
557
|
+
}
|
|
558
|
+
return { config: config.mcpServers ? { ...config, mcpServers: servers } : config, env };
|
|
559
|
+
}
|
|
560
|
+
// ---- R12 forward keeper: one Aiterm process per terminal holds the seats' BellTeam MCP route (T3) ----
|
|
561
|
+
const FORWARD_RESTART_MS = 15_000, FORWARD_REFUSALS_BEFORE_NEW_PORT = 4, LAUNCH_GRACE_MS = 120_000;
|
|
562
|
+
const keepers = new Map();
|
|
563
|
+
let maintainTimer = null;
|
|
564
|
+
function writeBinding(ref, change) {
|
|
565
|
+
const bindings = readStore().map(item => item.ref === ref ? { ...item, ...change } : item);
|
|
566
|
+
writeJson0600(storePath(), { schema: "aiterm.remote-bindings.v1", bindings });
|
|
567
|
+
}
|
|
568
|
+
function lockFile(ref) { return path.join(ensureStateRoot(), `terminal-forward-${ref}.lock`); }
|
|
569
|
+
/** T3: true when this process holds the keeper lock for ref (taking it from a dead owner). */
|
|
570
|
+
function holdLock(ref) {
|
|
571
|
+
const file = lockFile(ref);
|
|
572
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
573
|
+
try {
|
|
574
|
+
fs.writeFileSync(file, JSON.stringify({ pid: process.pid }), { flag: "wx", mode: 0o600 });
|
|
575
|
+
return true;
|
|
576
|
+
}
|
|
577
|
+
catch (error) {
|
|
578
|
+
if (error.code !== "EEXIST")
|
|
579
|
+
return false;
|
|
580
|
+
let pid = 0;
|
|
581
|
+
try {
|
|
582
|
+
pid = Number(JSON.parse(fs.readFileSync(file, "utf8")).pid);
|
|
583
|
+
}
|
|
584
|
+
catch { /* unreadable: treat as dead */ }
|
|
585
|
+
if (pid === process.pid)
|
|
586
|
+
return true;
|
|
587
|
+
// shortcut: a reused pid looks alive; the next owner check after that process exits takes over.
|
|
588
|
+
try {
|
|
589
|
+
if (pid > 0) {
|
|
590
|
+
process.kill(pid, 0);
|
|
591
|
+
return false;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
catch { /* owner gone */ }
|
|
595
|
+
fs.rmSync(file, { force: true });
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
return false;
|
|
599
|
+
}
|
|
600
|
+
function releaseLock(ref) {
|
|
601
|
+
try {
|
|
602
|
+
if (Number(JSON.parse(fs.readFileSync(lockFile(ref), "utf8")).pid) === process.pid)
|
|
603
|
+
fs.rmSync(lockFile(ref), { force: true });
|
|
604
|
+
}
|
|
605
|
+
catch { /* none */ }
|
|
606
|
+
}
|
|
607
|
+
function forwardNeeded(ref) {
|
|
608
|
+
return (keepers.get(ref)?.launchUntil ?? 0) > Date.now() || Object.values(readSeats()).includes(ref);
|
|
609
|
+
}
|
|
610
|
+
function keep(ref) {
|
|
611
|
+
const keeper = keepers.get(ref) ?? { child: null, refusals: 0, timer: null, launchUntil: 0 };
|
|
612
|
+
keepers.set(ref, keeper);
|
|
613
|
+
if (keeper.child) {
|
|
614
|
+
if (!forwardNeeded(ref))
|
|
615
|
+
keeper.child.kill();
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
if (keeper.timer)
|
|
619
|
+
return;
|
|
620
|
+
if (!forwardNeeded(ref)) {
|
|
621
|
+
releaseLock(ref);
|
|
622
|
+
keepers.delete(ref);
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
if (!holdLock(ref))
|
|
626
|
+
return;
|
|
627
|
+
let b;
|
|
628
|
+
try {
|
|
629
|
+
b = binding(ref);
|
|
630
|
+
}
|
|
631
|
+
catch {
|
|
632
|
+
releaseLock(ref);
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
const requested = b.seat_forward_port ?? 0;
|
|
636
|
+
let args;
|
|
637
|
+
try {
|
|
638
|
+
// The remote command ends when our stdin closes, so the forward dies with this process even on SIGKILL.
|
|
639
|
+
args = trustedSshArguments(ref, "cat >/dev/null", null, ["-o", "ExitOnForwardFailure=yes", "-R", seatForwardSpec(requested)]);
|
|
640
|
+
}
|
|
641
|
+
catch {
|
|
642
|
+
releaseLock(ref);
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
const child = spawn("ssh", args, { env: sshEnvironment(), stdio: ["pipe", "ignore", "pipe"] });
|
|
646
|
+
keeper.child = child;
|
|
647
|
+
let stderr = "";
|
|
648
|
+
child.stderr.on("data", (chunk) => {
|
|
649
|
+
stderr = (stderr + chunk.toString("utf8")).slice(-4000);
|
|
650
|
+
const forward = parseSeatForward(stderr);
|
|
651
|
+
if (typeof forward === "number" && forward !== requested) {
|
|
652
|
+
writeBinding(ref, { seat_forward_port: forward });
|
|
653
|
+
keeper.refusals = 0;
|
|
654
|
+
}
|
|
655
|
+
});
|
|
656
|
+
child.on("error", () => { });
|
|
657
|
+
child.on("close", () => {
|
|
658
|
+
keeper.child = null;
|
|
659
|
+
if (parseSeatForward(stderr) === "refused" && requested !== 0 && ++keeper.refusals >= FORWARD_REFUSALS_BEFORE_NEW_PORT) {
|
|
660
|
+
// The old P stays taken on the terminal: let sshd pick a new one (seats launched with the old P need a relaunch).
|
|
661
|
+
writeBinding(ref, { seat_forward_port: undefined });
|
|
662
|
+
keeper.refusals = 0;
|
|
663
|
+
}
|
|
664
|
+
keeper.timer = setTimeout(() => { keeper.timer = null; keep(ref); }, FORWARD_RESTART_MS);
|
|
665
|
+
keeper.timer.unref();
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
/** Every 60 s: keep (or take over) the forwards this process's state root needs. */
|
|
669
|
+
export function maintainSeatForwards() {
|
|
670
|
+
const refs = new Set([...Object.values(readSeats()), ...keepers.keys()]);
|
|
671
|
+
for (const ref of refs)
|
|
672
|
+
keep(ref);
|
|
673
|
+
if (refs.size && !maintainTimer) {
|
|
674
|
+
maintainTimer = setInterval(maintainSeatForwards, 60_000);
|
|
675
|
+
maintainTimer.unref();
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
/** The terminal-local port for seat URLs; starts the keeper if no process holds it yet. */
|
|
679
|
+
export async function ensureSeatForward(ref, timeoutMs = 30_000) {
|
|
680
|
+
const keeper = keepers.get(ref) ?? { child: null, refusals: 0, timer: null, launchUntil: 0 };
|
|
681
|
+
keeper.launchUntil = Date.now() + LAUNCH_GRACE_MS;
|
|
682
|
+
keepers.set(ref, keeper);
|
|
683
|
+
maintainSeatForwards();
|
|
684
|
+
const deadline = Date.now() + timeoutMs;
|
|
685
|
+
for (;;) {
|
|
686
|
+
const port = binding(ref).seat_forward_port;
|
|
687
|
+
if (port)
|
|
688
|
+
return port;
|
|
689
|
+
if (Date.now() > deadline)
|
|
690
|
+
throw new RemoteTerminalError("SEAT_FORWARD_UNAVAILABLE", "the seat's MCP route back to this computer is not ready; launch again later");
|
|
691
|
+
await new Promise(resolve => setTimeout(resolve, 250));
|
|
692
|
+
}
|
|
693
|
+
}
|
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.66.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",
|