aiterm-mcp 0.70.7 → 0.70.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -1
- package/README.ja.md +3 -1
- package/README.md +3 -1
- package/dist/agent-metadata-reader.js +10 -2
- package/dist/agent-resolver.js +10 -0
- package/dist/core.js +60 -19
- package/dist/errors.js +6 -0
- package/dist/harnesses/antigravity.js +48 -3
- package/dist/harnesses/caller-mcp.js +94 -0
- package/dist/harnesses/cursor.js +50 -5
- package/dist/harnesses/grok.js +52 -3
- package/dist/index.js +23 -15
- package/dist/remote-authorize.js +51 -6
- package/dist/remote-contract.js +4 -4
- package/dist/remote-path.js +29 -5
- package/dist/remote-provision.js +94 -14
- package/dist/remote-terminal-cli.js +8 -5
- package/dist/remote-terminal.js +164 -63
- package/dist/remote.js +48 -8
- package/dist/terminal-launch-error.js +12 -9
- package/dist/transcript-read-cli.js +5 -10
- package/dist/write-ban.js +22 -7
- package/native/write-ban/win32-x64/aiterm-write-ban.exe +0 -0
- package/package.json +2 -1
package/dist/harnesses/cursor.js
CHANGED
|
@@ -5,11 +5,12 @@ import * as fs from "node:fs";
|
|
|
5
5
|
import * as os from "node:os";
|
|
6
6
|
import * as path from "node:path";
|
|
7
7
|
import { randomBytes } from "node:crypto";
|
|
8
|
-
import { AitermError } from "../errors.js";
|
|
8
|
+
import { AitermError, launchAuthRequired } from "../errors.js";
|
|
9
9
|
import { spawnAgentControlCommand } from "../agent-resolver.js";
|
|
10
10
|
import { checkedCatalog } from "../model-catalog.js";
|
|
11
11
|
import { FastModeError } from "../fast-mode.js";
|
|
12
|
-
import { AGENT_DONE_POLL_MS, CURSOR_SCREEN_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, agentEventPath, agentHarness, agentLineageFields, agentMetadataPath, createEmpty0600, readFileRange, safeStatSize, shq, sleep, subagentInstruction, writeAgentMetadata, writeScopeLaunchNote, } from "../agent-shared.js";
|
|
12
|
+
import { AGENT_DONE_POLL_MS, CURSOR_SCREEN_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, agentEventPath, agentHarness, agentLineageFields, agentMetadataPath, agentsDir, assertSessionName, createEmpty0600, readFileRange, safeStatSize, shq, sleep, subagentInstruction, writeAgentMetadata, writeScopeLaunchNote, writeText0600, } from "../agent-shared.js";
|
|
13
|
+
import { assertCallerEnv, checkCallerInput, readCallerText, writeCallerJson } from "./caller-mcp.js";
|
|
13
14
|
const CURSOR_TRANSCRIPT_MATCH_MAX_BYTES = 1024 * 1024;
|
|
14
15
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
15
16
|
// Cursor Agentはextended keyboard protocolを有効にするため、通常のtmux Enterではなく
|
|
@@ -508,12 +509,49 @@ export function assertCursorAuthenticationReady(bin) {
|
|
|
508
509
|
if (result.error == null && result.status === 0 && !/not logged in|unauthenticated|sign in/i.test(output))
|
|
509
510
|
return;
|
|
510
511
|
if (/not logged in|unauthenticated|sign in/i.test(output)) {
|
|
511
|
-
throw
|
|
512
|
+
throw launchAuthRequired("cursor-cli", "Cursor Agent CLIが未認証です。sessionは作成していません。通常端末で公式の `agent login` を一度だけ完了してください。");
|
|
512
513
|
}
|
|
513
514
|
const timedOut = result.error && result.error.code === "ETIMEDOUT";
|
|
514
515
|
throw new AitermError(`Cursor Agent CLIの認証状態を起動前に確認できません${timedOut ? "(5秒でtimeout)" : ""}。sessionは作成していません。` +
|
|
515
516
|
"通常端末で `agent status` が成功することを確認してください。", 2);
|
|
516
517
|
}
|
|
518
|
+
// ---- Caller launch fields (launch-identity-input.md "Caller launch fields"). Cursor has no per-run instruction channel, so the
|
|
519
|
+
// text joins Aiterm's first-prompt block; the servers are a per-seat plugin folder passed as --plugin-dir. Both live in Aiterm state.
|
|
520
|
+
export function agentCursorCallerPromptPath(name) {
|
|
521
|
+
assertSessionName(name);
|
|
522
|
+
return path.join(agentsDir(), `${name}.cursor-caller-prompt.md`);
|
|
523
|
+
}
|
|
524
|
+
/** The plugin folder's name becomes part of each server's name (plugin-aiterm-caller-<name>), so it is fixed under a per-seat parent. */
|
|
525
|
+
export function agentCursorCallerPluginDir(name) {
|
|
526
|
+
assertSessionName(name);
|
|
527
|
+
return path.join(agentsDir(), `${name}.cursor-plugin`, "aiterm-caller");
|
|
528
|
+
}
|
|
529
|
+
/** Cursor expands ${env:NAME} in headers from the seat's environment, so no secret value is written. */
|
|
530
|
+
export function cursorCallerMcpJson(servers) {
|
|
531
|
+
return { mcpServers: Object.fromEntries(servers.map(server => [server.name, {
|
|
532
|
+
url: server.url,
|
|
533
|
+
...(server.headers.length ? { headers: Object.fromEntries(server.headers.map(header => [header.name,
|
|
534
|
+
header.kind === "bearer" ? `Bearer \${env:${header.value}}` : header.kind === "env" ? `\${env:${header.value}}` : header.value])) } : {}),
|
|
535
|
+
}])) };
|
|
536
|
+
}
|
|
537
|
+
export function checkCursorCallerInput(prompt, mcp) {
|
|
538
|
+
return checkCallerInput("CURSOR", prompt, mcp);
|
|
539
|
+
}
|
|
540
|
+
export function writeCursorCallerFiles(meta, prompt, mcp, valueOf) {
|
|
541
|
+
const servers = checkCursorCallerInput(prompt, mcp);
|
|
542
|
+
assertCallerEnv("CURSOR", servers, valueOf);
|
|
543
|
+
if (prompt !== null) {
|
|
544
|
+
const file = agentCursorCallerPromptPath(meta.aiterm_session);
|
|
545
|
+
writeText0600(file, prompt);
|
|
546
|
+
meta.cursor_caller_prompt_file = file;
|
|
547
|
+
}
|
|
548
|
+
if (mcp !== null) {
|
|
549
|
+
const dir = agentCursorCallerPluginDir(meta.aiterm_session);
|
|
550
|
+
writeCallerJson(path.join(dir, ".cursor-plugin", "plugin.json"), { name: "aiterm-caller", version: "1.0.0", description: "MCP servers Aiterm adds for this seat" });
|
|
551
|
+
writeCallerJson(path.join(dir, "mcp.json"), cursorCallerMcpJson(servers));
|
|
552
|
+
meta.cursor_caller_mcp_dir = dir;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
517
555
|
/** 起動argv(先頭が実行ファイル)。paneのshellに合わせた引用は呼び出し側が行う。 */
|
|
518
556
|
export function cursorAgentArgv(bin, model, effort, prompt, meta, fast = false) {
|
|
519
557
|
validateCursorModelEffort(model, effort);
|
|
@@ -524,6 +562,8 @@ export function cursorAgentArgv(bin, model, effort, prompt, meta, fast = false)
|
|
|
524
562
|
// managed agentは人の対話承認を待てない。Cursor公式の無人運転フラグで
|
|
525
563
|
// workspace・MCP server・各tool callの確認をadapter内に閉じ込める。
|
|
526
564
|
parts.push("--force", "--approve-mcps", "--trust");
|
|
565
|
+
if (meta?.kind === "cursor" && meta.cursor_caller_mcp_dir)
|
|
566
|
+
parts.push("--plugin-dir", meta.cursor_caller_mcp_dir);
|
|
527
567
|
if (meta?.kind === "cursor" && meta.write_scope === "read-only")
|
|
528
568
|
parts.push("--mode", "ask");
|
|
529
569
|
if (prompt)
|
|
@@ -533,7 +573,7 @@ export function cursorAgentArgv(bin, model, effort, prompt, meta, fast = false)
|
|
|
533
573
|
export function buildCursorAgentCmd(bin, model, effort, prompt, meta, fast = false) {
|
|
534
574
|
// 固定の語彙(--force、--mode ask等)は引用しない。実行ファイル、model、promptだけを引用する。
|
|
535
575
|
const argv = cursorAgentArgv(bin, model, effort, prompt, meta, fast);
|
|
536
|
-
return argv.map((part, index) => index === 0 || argv[index - 1] === "--model" || (prompt !== null && index === argv.length - 1) ? shq(part) : part).join(" ");
|
|
576
|
+
return argv.map((part, index) => index === 0 || argv[index - 1] === "--model" || argv[index - 1] === "--plugin-dir" || (prompt !== null && index === argv.length - 1) ? shq(part) : part).join(" ");
|
|
537
577
|
}
|
|
538
578
|
/**
|
|
539
579
|
* Windows native paneのPowerShell 7で走らせる起動行。WindowsのCursor Agentは、Git Bash配下で起動すると
|
|
@@ -541,8 +581,13 @@ export function buildCursorAgentCmd(bin, model, effort, prompt, meta, fast = fal
|
|
|
541
581
|
* Git Bash配下は全てprompt_historyだけ残りstore.dbが作られず、PowerShell 7 paneからは同じhookで通る)。
|
|
542
582
|
*/
|
|
543
583
|
export { windowsAgentLaunchLine as cursorPwshLaunchLine, windowsAgentArgv as cursorPwshArgv } from "../agent-resolver.js";
|
|
584
|
+
/** Aiterm's lineage block, then the caller's text: the one block that precedes the first prompt (Cursor has no system channel). */
|
|
585
|
+
export function cursorLineagePreface(meta) {
|
|
586
|
+
const caller = readCallerText(meta.cursor_caller_prompt_file);
|
|
587
|
+
return caller === null ? subagentInstruction(meta) : `${subagentInstruction(meta)}\n\n${caller}`;
|
|
588
|
+
}
|
|
544
589
|
export function cursorPromptWithLineage(meta, prompt) {
|
|
545
|
-
return `${
|
|
590
|
+
return `${cursorLineagePreface(meta)}\n\n${prompt}`;
|
|
546
591
|
}
|
|
547
592
|
export function cursorLaunchNote(model, effort, meta) {
|
|
548
593
|
const effective = cursorModelArgument(model, effort);
|
package/dist/harnesses/grok.js
CHANGED
|
@@ -9,8 +9,54 @@ import * as path from "node:path";
|
|
|
9
9
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
10
10
|
import { AitermError } from "../errors.js";
|
|
11
11
|
import { runAgentProtocolCommand, spawnAgentControlCommand } from "../agent-resolver.js";
|
|
12
|
+
import { assertCallerEnv, checkCallerInput, readCallerText, resolveCallerHeader } from "./caller-mcp.js";
|
|
12
13
|
import { catalogInvalid, catalogUnavailable, checkedCatalog, findJsonLine, processSummary } from "../model-catalog.js";
|
|
13
|
-
import { shq, subagentInstruction, writeScopeLaunchNote, safeStatSize, readFileRange, sleep, agentMetadataPath, writeAgentMetadata, agentEventPath, createEmpty0600, agentLineageFields, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, AGENT_TURN_BOUNDARY_TAIL_BYTES, readTailLinesNewestFirst, GROK_TRANSCRIPT_INCREMENT_MAX_BYTES, agentHarness, } from "../agent-shared.js";
|
|
14
|
+
import { shq, subagentInstruction, writeScopeLaunchNote, safeStatSize, readFileRange, sleep, agentMetadataPath, agentsDir, assertSessionName, writeAgentMetadata, writeText0600, agentEventPath, createEmpty0600, agentLineageFields, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, AGENT_TURN_BOUNDARY_TAIL_BYTES, readTailLinesNewestFirst, GROK_TRANSCRIPT_INCREMENT_MAX_BYTES, agentHarness, } from "../agent-shared.js";
|
|
15
|
+
// ---- Caller launch fields (launch-identity-input.md "Caller launch fields"). The text joins the one --rules value;
|
|
16
|
+
// the servers are a per-seat agent definition passed as --agent. Both files live in Aiterm state (0600), never in ~/.grok or the project.
|
|
17
|
+
export function agentGrokCallerPromptPath(name) {
|
|
18
|
+
assertSessionName(name);
|
|
19
|
+
return path.join(agentsDir(), `${name}.grok-caller-prompt.md`);
|
|
20
|
+
}
|
|
21
|
+
export function agentGrokCallerAgentPath(name) {
|
|
22
|
+
assertSessionName(name);
|
|
23
|
+
return path.join(agentsDir(), `${name}.grok-caller-agent.md`);
|
|
24
|
+
}
|
|
25
|
+
/** Grok does not expand ${VAR} in headers: 'Bearer ${NAME}' is bearer_token_env_var (read from the seat env at run time),
|
|
26
|
+
* any other ${NAME} is written as the seat's value. `mcpServers` must be a LIST of entries (a map keyed by name silently
|
|
27
|
+
* drops the whole file); the body stays empty so the default agent's prompt and tools are unchanged. YAML flow style is JSON. */
|
|
28
|
+
export function grokCallerAgentDefinition(servers, valueOf) {
|
|
29
|
+
const entries = servers.map(server => {
|
|
30
|
+
const headers = {};
|
|
31
|
+
let bearer;
|
|
32
|
+
for (const header of server.headers) {
|
|
33
|
+
if (header.kind === "bearer")
|
|
34
|
+
bearer = header.value;
|
|
35
|
+
else
|
|
36
|
+
headers[header.name] = resolveCallerHeader("GROK", header, valueOf);
|
|
37
|
+
}
|
|
38
|
+
return { name: server.name, type: "http", url: server.url, ...(Object.keys(headers).length ? { headers } : {}), ...(bearer ? { bearer_token_env_var: bearer } : {}) };
|
|
39
|
+
});
|
|
40
|
+
return `---\nname: aiterm-caller\ndescription: MCP servers Aiterm adds for this seat\nmcpServers: ${JSON.stringify(entries)}\n---\n`;
|
|
41
|
+
}
|
|
42
|
+
/** Pre-start check of the caller fields for a Grok launch (the servers, for the env check by the caller). */
|
|
43
|
+
export function checkGrokCallerInput(prompt, mcp) {
|
|
44
|
+
return checkCallerInput("GROK", prompt, mcp);
|
|
45
|
+
}
|
|
46
|
+
export function writeGrokCallerFiles(meta, prompt, mcp, valueOf) {
|
|
47
|
+
const servers = checkGrokCallerInput(prompt, mcp);
|
|
48
|
+
assertCallerEnv("GROK", servers, valueOf);
|
|
49
|
+
if (prompt !== null) {
|
|
50
|
+
const file = agentGrokCallerPromptPath(meta.aiterm_session);
|
|
51
|
+
writeText0600(file, prompt);
|
|
52
|
+
meta.grok_caller_prompt_file = file;
|
|
53
|
+
}
|
|
54
|
+
if (mcp !== null) {
|
|
55
|
+
const file = agentGrokCallerAgentPath(meta.aiterm_session);
|
|
56
|
+
writeText0600(file, grokCallerAgentDefinition(servers, valueOf));
|
|
57
|
+
meta.grok_caller_mcp_file = file;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
14
60
|
const GROK_MODELS_MAX_BYTES = 1024 * 1024;
|
|
15
61
|
const GROK_MODELS_TIMEOUT_MS = 15_000;
|
|
16
62
|
// grok CLI はモデル未指定だと端末側 default に従うため、ツール契約として既定 slug を固定する。
|
|
@@ -410,7 +456,10 @@ export function grokAgentArgv(kind, bin, model, effort, prompt, meta) {
|
|
|
410
456
|
parts.push("--sandbox", "read-only", "--always-approve");
|
|
411
457
|
}
|
|
412
458
|
if (meta?.kind === "grok" && meta.hook_route === "shared_grok_home") {
|
|
413
|
-
|
|
459
|
+
// Aiterm's lineage text stays first; the caller's text joins the same value (one --rules).
|
|
460
|
+
parts.push("--session-id", meta.vendor_session_id ?? "", "--rules", subagentInstruction(meta) + (meta.grok_caller_prompt_file ? `\n\n${readCallerText(meta.grok_caller_prompt_file)}` : ""));
|
|
461
|
+
if (meta.grok_caller_mcp_file)
|
|
462
|
+
parts.push("--agent", meta.grok_caller_mcp_file);
|
|
414
463
|
}
|
|
415
464
|
if (meta?.kind === "grok" && prompt)
|
|
416
465
|
parts.push("--verbatim");
|
|
@@ -420,7 +469,7 @@ export function grokAgentArgv(kind, bin, model, effort, prompt, meta) {
|
|
|
420
469
|
}
|
|
421
470
|
export function buildGrokAgentCmd(kind, bin, model, effort, prompt, meta) {
|
|
422
471
|
const argv = grokAgentArgv(kind, bin, model, effort, prompt, meta);
|
|
423
|
-
const values = new Set(["--model", "--reasoning-effort", "--session-id", "--rules"]);
|
|
472
|
+
const values = new Set(["--model", "--reasoning-effort", "--session-id", "--rules", "--agent"]);
|
|
424
473
|
return argv.map((arg, index) => index === 0 || values.has(argv[index - 1]) || (prompt && index === argv.length - 1)
|
|
425
474
|
? shq(arg) : arg).join(" ");
|
|
426
475
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { loadAgentMetadata } from "./agent-metadata-reader.js";
|
|
3
3
|
import { remoteInputDescription, remoteInputSchema, terminalArgumentDescription, terminalArgumentSchema } from "./remote-contract.js";
|
|
4
|
-
import { boundTerminalTarget, bindTerminalSession, terminalSeatGroups, ensureSeatForward, extractMcpHeaders, maintainSeatForwards, REMOTE_MINIMUM_VERSION, seatIngressPort, checkTerminalPlatform, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
|
|
4
|
+
import { boundTerminalTarget, bindTerminalSession, terminalSeatGroups, ensureSeatForward, extractMcpHeaders, maintainSeatForwards, REMOTE_MINIMUM_VERSION, REMOTE_CLI_OPS_VERSION, seatIngressPort, checkTerminalPlatform, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
|
|
5
|
+
import { terminalCwdFits } from "./remote-path.js";
|
|
5
6
|
import { launchEnvValue } from "./private-env.js";
|
|
6
7
|
import { AuthResponseError, authUiSchema, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
|
|
7
8
|
import { configurationRequestSchema, configurationToolOutputSchema, applyConfigurationRequest, reconcileConfigurationRequest } from "./configure-request.js";
|
|
@@ -259,10 +260,11 @@ export function createAitermServer(options = {}) {
|
|
|
259
260
|
content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
|
|
260
261
|
structuredContent: { schema: "aiterm.agent-launch-error.v1", harness: "claude-code", code: e.reasonCode,
|
|
261
262
|
phase: "authentication_preflight", effect: "not_issued", session_created: false, message: msg },
|
|
263
|
+
...(e.reasonCode === "CLAUDE_AUTH_NOT_AUTHENTICATED" ? { _meta: launchNotStartedMeta("claude-code", "input", "AGENT_AUTH_REQUIRED") } : {}),
|
|
262
264
|
};
|
|
263
265
|
if (e instanceof AitermError && e.launchNotStarted)
|
|
264
266
|
return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
|
|
265
|
-
_meta: launchNotStartedMeta(e.launchNotStarted.harness, e.launchNotStarted.phase) };
|
|
267
|
+
_meta: launchNotStartedMeta(e.launchNotStarted.harness, e.launchNotStarted.phase, e.launchNotStarted.code) };
|
|
266
268
|
return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true };
|
|
267
269
|
}
|
|
268
270
|
/**
|
|
@@ -1267,28 +1269,36 @@ export function createAitermServer(options = {}) {
|
|
|
1267
1269
|
const FORK_MINIMUM_VERSION = "0.70.6";
|
|
1268
1270
|
/** First release whose agent_launch takes append_system_prompt / mcp_config for codex-cli, and the first a terminal may run a Codex seat on. */
|
|
1269
1271
|
const CODEX_REMOTE_MINIMUM_VERSION = "0.70.7";
|
|
1272
|
+
/** The oldest terminal Aiterm per harness: Grok, Cursor and Antigravity seats need 0.70.9 (checked before any private value is sent). */
|
|
1273
|
+
const TERMINAL_MINIMUM_VERSION = {
|
|
1274
|
+
"claude-code": REMOTE_MINIMUM_VERSION, "codex-cli": CODEX_REMOTE_MINIMUM_VERSION,
|
|
1275
|
+
"grok-cli": REMOTE_CLI_OPS_VERSION, "cursor-cli": REMOTE_CLI_OPS_VERSION, "antigravity-cli": REMOTE_CLI_OPS_VERSION,
|
|
1276
|
+
};
|
|
1270
1277
|
const terminalVersions = new Map();
|
|
1271
1278
|
/** A seat on a BellTeam terminal (remote-terminal.md "One launch path"). Same launch arguments plus terminal + cwd. */
|
|
1272
1279
|
async function launchTerminalAgent(harness, terminal, args, extra) {
|
|
1273
1280
|
try {
|
|
1274
1281
|
if (args.remote)
|
|
1275
1282
|
throw new AitermError("TERMINAL_INVALID: use terminal or remote, not both; for a registered terminal pass only terminal", 2);
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1283
|
+
const minimum = TERMINAL_MINIMUM_VERSION[harness];
|
|
1284
|
+
// Every real harness is routed since 0.70.9; this only guards a name outside the five.
|
|
1285
|
+
if (!minimum)
|
|
1286
|
+
throw new AitermError(`TERMINAL_HARNESS_UNSUPPORTED: ${harness} is not a harness a terminal can run`, 2);
|
|
1287
|
+
const cwdForm = "TERMINAL_INVALID: cwd is required with terminal: the absolute project folder on that terminal in its own form (a POSIX path starting with / on macOS and Linux, X:\\folder with backslashes on Windows; never launch locally and cd)";
|
|
1288
|
+
if (!terminalCwdFits(args.cwd, terminal.os))
|
|
1289
|
+
throw new AitermError(cwdForm, 2);
|
|
1281
1290
|
if (args.require_existing_resume)
|
|
1282
1291
|
throw new AitermError("TERMINAL_INVALID: require_existing_resume is local-only", 2);
|
|
1283
1292
|
const target = terminalRemoteTarget(terminal);
|
|
1284
|
-
|
|
1293
|
+
// Without a declared os the cwd form is checked against the probed system, still before any session.
|
|
1294
|
+
if (!terminalCwdFits(args.cwd, await checkTerminalPlatform(target, terminal.os)))
|
|
1295
|
+
throw new AitermError(cwdForm, 2);
|
|
1285
1296
|
// The private line is sent before the server answers; check its version first so an old one never sees it.
|
|
1286
1297
|
let version = terminalVersions.get(target.trusted_ref);
|
|
1287
1298
|
if (!version) {
|
|
1288
1299
|
version = (await callRemoteTool(target, "pty_list", {}, 60_000)).remote_version ?? "0.0.0";
|
|
1289
1300
|
terminalVersions.set(target.trusted_ref, version);
|
|
1290
1301
|
}
|
|
1291
|
-
const minimum = harness === "codex-cli" ? CODEX_REMOTE_MINIMUM_VERSION : REMOTE_MINIMUM_VERSION;
|
|
1292
1302
|
if (!versionAtLeast(version, minimum))
|
|
1293
1303
|
throw new AitermError(`REMOTE_AITERM_TOO_OLD: the terminal runs Aiterm ${version}; ${minimum} or later is required (update Aiterm on the terminal)`, 2);
|
|
1294
1304
|
const privateEnv = {};
|
|
@@ -1516,12 +1526,12 @@ export function createAitermServer(options = {}) {
|
|
|
1516
1526
|
launch_operation_id: z.string().regex(/^sha256:[0-9a-f]{64}$/).optional().describe("Claude Codeのpromptなしexact replay相関だけで使用"),
|
|
1517
1527
|
remote: remoteInputField,
|
|
1518
1528
|
terminal: terminalArgumentSchema.optional().describe(terminalArgumentDescription),
|
|
1519
|
-
append_system_prompt: z.string().min(1).optional().describe("
|
|
1520
|
-
mcp_config: z.object({ mcpServers: z.record(z.string(), z.unknown()) }).strict().optional().describe("
|
|
1529
|
+
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. Never put secrets here. Codex: appended to developer_instructions after Aiterm's marker; Grok: appended to --rules; at most 64 KiB for both. Cursor and Antigravity have no system-prompt channel: the text goes in front of the first prompt (Antigravity needs a prompt; at most 64 KiB)"),
|
|
1530
|
+
mcp_config: z.object({ mcpServers: z.record(z.string(), z.unknown()) }).strict().optional().describe("Extra MCP servers for this seat. Secret header values: write ${NAME} and list NAME in env_vars. Codex, Grok, Cursor and Antigravity take only http servers {type?: \"http\", url, headers}: a literal header, 'Authorization: Bearer ${NAME}' or a header whose whole value is ${NAME}; other shapes, and a ${NAME} with no value at launch, are refused before the seat starts. Cursor runs a server as plugin-aiterm-caller-<name> beside a same-name user server; Grok and Antigravity replace a same-name user server for this seat"),
|
|
1521
1531
|
fork_from: z.object({
|
|
1522
1532
|
session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/).describe("The main Aiterm seat on the same machine (the terminal or remote when given)"),
|
|
1523
1533
|
fork_id: z.string().min(1).max(200).optional().describe("Caller's fork ID, passed to the seat as THROUGHLINE_FORK_ID"),
|
|
1524
|
-
}).strict().optional().describe("claude-code and codex-cli. Start a disposable fork of that seat's latest saved conversation, in its cwd, with the main's tools and MCP. Every write inside that cwd (the project folder) is refused below the tools for the whole process tree (Linux Landlock, macOS sandbox-exec); everything else is allowed.
|
|
1534
|
+
}).strict().optional().describe("claude-code and codex-cli. Start a disposable fork of that seat's latest saved conversation, in its cwd, with the main's tools and MCP. Every write inside that cwd (the project folder) is refused below the tools for the whole process tree (Linux Landlock, macOS sandbox-exec, Windows restricted token + folder deny ACE); everything else is allowed. Requires a prompt; no write_scope. Close it after its answer"),
|
|
1525
1535
|
},
|
|
1526
1536
|
outputSchema: {
|
|
1527
1537
|
schema: z.literal("aiterm.agent-launch-result.v1"),
|
|
@@ -1544,11 +1554,9 @@ export function createAitermServer(options = {}) {
|
|
|
1544
1554
|
write_scope: z.string().optional(),
|
|
1545
1555
|
write_scope_enforcement: z.enum(["enforced_read_only", "declaration_only_unsupported"]).optional(),
|
|
1546
1556
|
fork_of: z.object({ session_id: z.string(), vendor_session_id: z.string(),
|
|
1547
|
-
write_ban: z.object({ path: z.string(), method: z.enum(["landlock", "seatbelt"]) }) }).optional().describe("The seat this fork copies and the folder it cannot write"),
|
|
1557
|
+
write_ban: z.object({ path: z.string(), method: z.enum(["landlock", "seatbelt", "restricted-token"]) }) }).optional().describe("The seat this fork copies and the folder it cannot write"),
|
|
1548
1558
|
},
|
|
1549
1559
|
}, async ({ harness, remote, terminal, ...args }, extra) => {
|
|
1550
|
-
if (harness !== "claude-code" && harness !== "codex-cli" && (args.append_system_prompt !== undefined || args.mcp_config !== undefined))
|
|
1551
|
-
return fail(launchInputRefusal(harness, `append_system_prompt and mcp_config are claude-code and codex-cli only; ${harness} cannot take them`));
|
|
1552
1560
|
if (terminal)
|
|
1553
1561
|
return launchTerminalAgent(harness, terminal, { ...args, ...(remote ? { remote } : {}) }, extra);
|
|
1554
1562
|
if (remote && args.require_existing_resume)
|
package/dist/remote-authorize.js
CHANGED
|
@@ -5,6 +5,7 @@ import * as fs from "node:fs";
|
|
|
5
5
|
import * as net from "node:net";
|
|
6
6
|
import * as path from "node:path";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { WINDOWS_STDIN_SCRIPT_COMMAND } from "./remote.js";
|
|
8
9
|
import { RemoteTerminalError, agentAlive, binding, bindingStatus, classifySshFailure, credentialPublicKeyFile, publicKey, readCredential, sshEnvironment } from "./remote-terminal.js";
|
|
9
10
|
export const ASKPASS_SOCKET_ENV = "AITERM_ASKPASS_SOCKET";
|
|
10
11
|
const PUBLIC_KEY = /^[A-Za-z0-9@.-]+ [A-Za-z0-9+/]+={0,3}$/;
|
|
@@ -69,7 +70,50 @@ export function authorizedKeysScript(key) {
|
|
|
69
70
|
"",
|
|
70
71
|
].join("\n");
|
|
71
72
|
}
|
|
72
|
-
|
|
73
|
+
/** PowerShell variant (5.1 and 7, ASCII only, run from stdin). Decides the file from the user's group and sshd_config, then the same protocol:
|
|
74
|
+
* markers on stdout (the nested exit code is not reliable under `pwsh -c`), ERROR 21 = the folder, 22 = the file or its ACL. */
|
|
75
|
+
export function windowsAuthorizedKeysScript(key) {
|
|
76
|
+
const [type, blob] = key.split(" ");
|
|
77
|
+
return [
|
|
78
|
+
"$ErrorActionPreference = 'Stop'",
|
|
79
|
+
`$key = '${key}'; $type = '${type}'; $blob = '${blob}'`,
|
|
80
|
+
"function Done($text) { Write-Output ('AITERM_AUTHORIZE ' + $text); exit 0 }",
|
|
81
|
+
"function Fail($n) { Write-Output ('AITERM_AUTHORIZE_ERROR ' + $n); exit $n }",
|
|
82
|
+
// sshd reads administrators_authorized_keys instead of the user's file only for Administrators and only with the default Match block.
|
|
83
|
+
"$shared = $false",
|
|
84
|
+
"try {",
|
|
85
|
+
" $admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",
|
|
86
|
+
" $cfg = Join-Path $env:ProgramData 'ssh\\sshd_config'",
|
|
87
|
+
" if ($admin -and (Test-Path -LiteralPath $cfg)) {",
|
|
88
|
+
" $in = $false",
|
|
89
|
+
" foreach ($line in [IO.File]::ReadAllLines($cfg)) {",
|
|
90
|
+
" $t = $line.Trim()",
|
|
91
|
+
" if ($t -match '^Match\\s') { $in = ($t -match '^Match\\s+Group\\s+administrators\\s*$') }",
|
|
92
|
+
" elseif ($in -and $t -match '^AuthorizedKeysFile\\s+__PROGRAMDATA__/ssh/administrators_authorized_keys\\s*$') { $shared = $true }",
|
|
93
|
+
" }",
|
|
94
|
+
" }",
|
|
95
|
+
"} catch { $shared = $false }",
|
|
96
|
+
"$dir = Join-Path $env:USERPROFILE '.ssh'",
|
|
97
|
+
"if ($shared) { $file = Join-Path $env:ProgramData 'ssh\\administrators_authorized_keys' } else { $file = Join-Path $dir 'authorized_keys' }",
|
|
98
|
+
"try { if (-not $shared) { New-Item -ItemType Directory -Force -Path $dir | Out-Null } } catch { Fail 21 }",
|
|
99
|
+
"try {",
|
|
100
|
+
" $text = ''",
|
|
101
|
+
" if (Test-Path -LiteralPath $file) { $text = [IO.File]::ReadAllText($file) }",
|
|
102
|
+
" foreach ($line in ($text -split '\\r?\\n')) {",
|
|
103
|
+
" $f = $line.Trim() -split '\\s+'",
|
|
104
|
+
" for ($i = 0; $i -lt $f.Length - 1; $i++) { if ($f[$i] -eq $type -and $f[$i + 1] -eq $blob) { Done 'ALREADY_AUTHORIZED' } }",
|
|
105
|
+
" }",
|
|
106
|
+
' $nl = "`n"; if ($text.Contains("`r`n")) { $nl = "`r`n" }',
|
|
107
|
+
" $prefix = ''; if ($text.Length -gt 0 -and -not $text.EndsWith(\"`n\")) { $prefix = $nl }",
|
|
108
|
+
" [IO.File]::AppendAllText($file, $prefix + $key + $nl, (New-Object System.Text.UTF8Encoding($false)))",
|
|
109
|
+
// sshd ignores the shared file unless only Administrators and SYSTEM may use it (well-known SIDs: names are localized).
|
|
110
|
+
" if ($shared) { & icacls.exe $file /inheritance:r /grant '*S-1-5-32-544:F' /grant '*S-1-5-18:F' | Out-Null; if ($LASTEXITCODE -ne 0) { throw 'acl' } }",
|
|
111
|
+
"} catch { Fail 22 }",
|
|
112
|
+
"Done 'AUTHORIZED'",
|
|
113
|
+
"",
|
|
114
|
+
].join("\n");
|
|
115
|
+
}
|
|
116
|
+
export function passwordSshArguments(b, system = "posix") {
|
|
73
117
|
return ["-F", "/dev/null", "-T", "-o", "BatchMode=no", "-o", "StrictHostKeyChecking=yes",
|
|
74
118
|
"-o", `UserKnownHostsFile=${b.known_hosts_file}`, "-o", "GlobalKnownHostsFile=/dev/null", "-o", "CheckHostIP=no",
|
|
75
119
|
...(b.host_key_alias ? ["-o", `HostKeyAlias=${b.host_key_alias}`] : []),
|
|
@@ -77,10 +121,10 @@ export function passwordSshArguments(b) {
|
|
|
77
121
|
"-o", "PreferredAuthentications=password", "-o", "PasswordAuthentication=yes", "-o", "KbdInteractiveAuthentication=no",
|
|
78
122
|
"-o", "GSSAPIAuthentication=no", "-o", "HostbasedAuthentication=no", "-o", "NumberOfPasswordPrompts=1",
|
|
79
123
|
"-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ConnectTimeout=15",
|
|
80
|
-
"-l", b.target.user, "-p", String(b.target.port), "--", b.target.host, "/bin/sh -s"];
|
|
124
|
+
"-l", b.target.user, "-p", String(b.target.port), "--", b.target.host, system === "windows" ? WINDOWS_STDIN_SCRIPT_COMMAND : "/bin/sh -s"];
|
|
81
125
|
}
|
|
82
126
|
const shq = (value) => `'${value.replace(/'/g, "'\\''")}'`;
|
|
83
|
-
export async function authorizeKey(prepared, password) {
|
|
127
|
+
export async function authorizeKey(prepared, password, system = "posix") {
|
|
84
128
|
const dir = fs.mkdtempSync(path.join("/tmp", "aiterm-ap-"));
|
|
85
129
|
let served = 0;
|
|
86
130
|
const server = net.createServer(connection => { served += 1; if (served === 1)
|
|
@@ -97,7 +141,7 @@ export async function authorizeKey(prepared, password) {
|
|
|
97
141
|
fs.writeFileSync(helper, `#!/bin/sh\nexec ${shq(process.execPath)} ${shq(cli)} askpass "$@"\n`, { mode: 0o700 });
|
|
98
142
|
const env = { ...sshEnvironment(), SSH_ASKPASS: helper, SSH_ASKPASS_REQUIRE: "force", DISPLAY: process.env.DISPLAY ?? "aiterm:0", [ASKPASS_SOCKET_ENV]: socket };
|
|
99
143
|
const run = await new Promise((resolve, reject) => {
|
|
100
|
-
const child = spawn("ssh", passwordSshArguments(prepared.b), { env, stdio: ["pipe", "pipe", "pipe"] });
|
|
144
|
+
const child = spawn("ssh", passwordSshArguments(prepared.b, system), { env, stdio: ["pipe", "pipe", "pipe"] });
|
|
101
145
|
let stdout = "", stderr = "";
|
|
102
146
|
const timer = setTimeout(() => child.kill(), 120_000);
|
|
103
147
|
child.stdout.on("data", (chunk) => { stdout += chunk.toString("utf8"); });
|
|
@@ -105,12 +149,13 @@ export async function authorizeKey(prepared, password) {
|
|
|
105
149
|
child.on("error", reject);
|
|
106
150
|
child.on("close", code => { clearTimeout(timer); resolve({ code, stdout, stderr }); });
|
|
107
151
|
child.stdin.on("error", () => { });
|
|
108
|
-
child.stdin.end(authorizedKeysScript(prepared.key));
|
|
152
|
+
child.stdin.end(system === "windows" ? windowsAuthorizedKeysScript(prepared.key) : authorizedKeysScript(prepared.key));
|
|
109
153
|
});
|
|
110
154
|
const marker = /AITERM_AUTHORIZE (AUTHORIZED|ALREADY_AUTHORIZED)/.exec(run.stdout)?.[1];
|
|
111
155
|
if (run.code === 0 && marker)
|
|
112
156
|
return { schema: "aiterm.remote-key-authorization.v1", ref: prepared.b.ref, result: marker };
|
|
113
|
-
|
|
157
|
+
const failed = Number(/AITERM_AUTHORIZE_ERROR (21|22)/.exec(run.stdout)?.[1] ?? run.code);
|
|
158
|
+
if (failed === 21 || failed === 22)
|
|
114
159
|
throw new RemoteTerminalError("AUTHORIZED_KEYS_WRITE_FAILED", "~/.ssh/authorized_keys could not be written on the terminal");
|
|
115
160
|
const denied = /Permission denied \(([^)]*)\)/.exec(run.stderr);
|
|
116
161
|
if (denied) {
|
package/dist/remote-contract.js
CHANGED
|
@@ -49,16 +49,16 @@ export const terminalArgumentSchema = z.object({
|
|
|
49
49
|
});
|
|
50
50
|
export const terminalArgumentDescription = "Run this seat on another computer (a registered terminal) over SSH. Value: exactly the terminal value your host system's terminal registry hands over, " +
|
|
51
51
|
"{ref, target:{host,user,port}, os?, trustRevision, and credentialRevision or credential {handle, revision}}; copy it unchanged, never invent or edit it, never use a host name or ssh command instead. " +
|
|
52
|
-
"Omit it to launch on this computer. Give cwd in the same call: the absolute project folder on that terminal (a POSIX path starting with /). Never launch locally and then cd or ssh. " +
|
|
52
|
+
"Omit it to launch on this computer. Give cwd in the same call: the absolute project folder on that terminal in its own form (a POSIX path starting with / on macOS and Linux, a drive path like C:\\folder with backslashes on Windows). Never launch locally and then cd or ssh. " +
|
|
53
53
|
"Never put tokens, passwords or other secrets in any argument, prompt or typed text; pass secret values only by name in env_vars. " +
|
|
54
54
|
"After launch, use session_id alone for pty_send, pty_observe, pty_read, pty_key, claude_turn, agent_stop and pty_close; Aiterm routes them to the terminal. " +
|
|
55
|
-
"Errors and next step: TERMINAL_INVALID = malformed value, missing/relative cwd, or combined with remote: pass the registry's value unchanged with cwd. " +
|
|
55
|
+
"Errors and next step: TERMINAL_INVALID = malformed value, missing/relative cwd (or one in the other system's form), or combined with remote: pass the registry's value unchanged with cwd. " +
|
|
56
56
|
"TARGET_MISMATCH / BINDING_UNKNOWN = the value is not this terminal's binding: ask the terminal registry again. " +
|
|
57
57
|
"HOST_TRUST_STALE / CREDENTIAL_REVISION_STALE = the binding changed: get the current value from the terminal registry and launch again. " +
|
|
58
58
|
"HOST_KEY_MISMATCH / HOST_TRUST_MISSING = the terminal's host key is not the trusted one: the Owner must confirm the new host key; do not retry. " +
|
|
59
59
|
"CREDENTIAL_REQUIRED / CREDENTIAL_NOT_LOADED = this terminal's key comes from a credential handle that the registry must load first; never paste a key anywhere. " +
|
|
60
60
|
"AUTH_FAILED = the terminal refused the key. UNREACHABLE = the terminal is offline; try later. CONNECTION_REFUSED = the terminal refused the SSH connection (SSH may be off there); try later. " +
|
|
61
61
|
"REMOTE_AITERM_TOO_OLD = update Aiterm on the terminal. CWD_UNAVAILABLE = the folder does not exist there; do not pick another folder. " +
|
|
62
|
-
"SEAT_FORWARD_UNAVAILABLE = the seat's MCP route back to this computer is not ready (launch again later), or the seat MCP URLs are not http://127.0.0.1:<one port>/api/seat-mcp.
|
|
62
|
+
"SEAT_FORWARD_UNAVAILABLE = the seat's MCP route back to this computer is not ready (launch again later), or the seat MCP URLs are not http://127.0.0.1:<one port>/api/seat-mcp. All five harnesses run on a terminal; REMOTE_AITERM_TOO_OLD names the Aiterm version the harness needs there (claude-code 0.65.0, codex-cli 0.70.7, grok-cli / cursor-cli / antigravity-cli 0.70.9). TERMINAL_HARNESS_UNSUPPORTED = the harness name is none of the five. AGENT_LAUNCH_NOT_STARTED with _meta aiterm/launch_error code AGENT_AUTH_REQUIRED = the CLI on the terminal is not logged in; the Owner logs it in there, then launch again. " +
|
|
63
63
|
"TERMINAL_OS_MISMATCH = the terminal is not the operating system os says: the registry's os is wrong or the binding points at another machine; ask the terminal registry, do not retry. " +
|
|
64
|
-
"TERMINAL_PLATFORM_UNSUPPORTED =
|
|
64
|
+
"TERMINAL_PLATFORM_UNSUPPORTED = the terminal is not a macOS, Linux or Windows system, so it cannot run seats.";
|
package/dist/remote-path.js
CHANGED
|
@@ -6,10 +6,32 @@ import { RemoteTerminalError } from "./remote-terminal.js";
|
|
|
6
6
|
const MISSING = { schema: "aiterm.remote-path.v1", exists: false, directory: false, writable: false };
|
|
7
7
|
const denied = (code) => code === "EACCES" || code === "EPERM";
|
|
8
8
|
const notPermitted = () => new RemoteTerminalError("FOLDER_NOT_PERMITTED", "the folder cannot be used by the terminal's SSH user (privacy consent, ACL or permissions)");
|
|
9
|
-
|
|
9
|
+
// Drive-absolute with backslashes: UNC (\\server), device (\\?\), drive-relative (C:x), `/` separators and the characters
|
|
10
|
+
// Windows forbids in a name (a second `:` would be an alternate data stream) are refused.
|
|
11
|
+
// eslint-disable-next-line no-control-regex
|
|
12
|
+
const WINDOWS_ABSOLUTE = /^[A-Za-z]:\\[^<>:"/|?*\x00-\x1f\x7f]*$/;
|
|
13
|
+
/** The native absolute form of a terminal's system: `/...` on macOS and Linux, `X:\...` on Windows. */
|
|
14
|
+
export function isNativeAbsolute(value, system) {
|
|
15
|
+
if (typeof value !== "string")
|
|
16
|
+
return false;
|
|
10
17
|
// eslint-disable-next-line no-control-regex
|
|
11
|
-
if (
|
|
12
|
-
|
|
18
|
+
if (/[\x00-\x1f\x7f]/.test(value))
|
|
19
|
+
return false;
|
|
20
|
+
return system === "windows" ? WINDOWS_ABSOLUTE.test(value) : path.posix.isAbsolute(value);
|
|
21
|
+
}
|
|
22
|
+
/** A launch `cwd` in the form of the terminal's system; without a known system either native form passes (the probed one is checked later). */
|
|
23
|
+
export function terminalCwdFits(cwd, platform) {
|
|
24
|
+
if (typeof cwd !== "string")
|
|
25
|
+
return false;
|
|
26
|
+
if (platform === "windows")
|
|
27
|
+
return isNativeAbsolute(cwd, "windows");
|
|
28
|
+
return cwd.startsWith("/") || (platform === undefined && isNativeAbsolute(cwd, "windows"));
|
|
29
|
+
}
|
|
30
|
+
/** The terminal's own system by default (this code runs on the terminal); the container side names the terminal's system. */
|
|
31
|
+
export function checkRemotePath(value, system = process.platform === "win32" ? "windows" : "posix") {
|
|
32
|
+
if (typeof value !== "string" || !isNativeAbsolute(value, system) || Buffer.byteLength(value) > 4096)
|
|
33
|
+
throw new RemoteTerminalError("PATH_INVALID", system === "windows"
|
|
34
|
+
? "path must be a drive-absolute path like C:\\folder (backslashes, no UNC, no control characters)" : "path must be an absolute path without control characters");
|
|
13
35
|
}
|
|
14
36
|
function errno(error) { return error?.code; }
|
|
15
37
|
/** Can this directory be listed? A privacy-protected folder (macOS TCC) refuses it with EPERM. */
|
|
@@ -84,11 +106,13 @@ export function inspectPath(target) {
|
|
|
84
106
|
return { schema: "aiterm.remote-path.v1", exists: true, directory: true, writable: writable(target) };
|
|
85
107
|
}
|
|
86
108
|
export const LIST_DIRS_MAX = 500;
|
|
109
|
+
// Folders every drive root has: listing them raises access errors or shows system internals, never a project.
|
|
110
|
+
const WINDOWS_SYSTEM_FOLDERS = new Set(["$recycle.bin", "system volume information"]);
|
|
87
111
|
/** Read-only folder picker listing (R15): subfolders only, no dot names, sorted, at most LIST_DIRS_MAX. */
|
|
88
112
|
export function listDirectories(target, home = os.homedir()) {
|
|
89
113
|
const dir = target === undefined ? home : target;
|
|
90
114
|
checkRemotePath(dir);
|
|
91
|
-
const base = { schema: "aiterm.remote-dirs.v1", home, path: path.
|
|
115
|
+
const base = { schema: "aiterm.remote-dirs.v1", home, path: path.resolve(dir) };
|
|
92
116
|
const state = folderState(base.path);
|
|
93
117
|
if (state !== "directory")
|
|
94
118
|
return { ...base, exists: state === "file", directory: false, entries: null, truncated: false };
|
|
@@ -103,7 +127,7 @@ export function listDirectories(target, home = os.homedir()) {
|
|
|
103
127
|
}
|
|
104
128
|
const names = [];
|
|
105
129
|
for (const entry of dirents) {
|
|
106
|
-
if (entry.name.startsWith("."))
|
|
130
|
+
if (entry.name.startsWith(".") || (process.platform === "win32" && WINDOWS_SYSTEM_FOLDERS.has(entry.name.toLowerCase())))
|
|
107
131
|
continue;
|
|
108
132
|
let folder = entry.isDirectory();
|
|
109
133
|
if (!folder && entry.isSymbolicLink()) {
|