aiterm-mcp 0.70.8 → 0.70.10

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.
@@ -5,12 +5,14 @@ import { authUrl, authUserCode } from "../agent-auth.js";
5
5
  import * as fs from "node:fs";
6
6
  import * as os from "node:os";
7
7
  import * as path from "node:path";
8
+ import { fileURLToPath } from "node:url";
8
9
  import { randomBytes, createHash } from "node:crypto";
9
10
  import { z } from "zod";
10
11
  import { AitermError, launchInputRefusal } from "../errors.js";
11
12
  import { spawnAgentControlCommand } from "../agent-resolver.js";
12
13
  import * as steer from "aiterm-steer-delivery";
13
14
  import { AITERM_PROFILE } from "../steer-profile.js";
15
+ import { setupNodeExecutable } from "../setup-node.js";
14
16
  import { catalogInvalid, catalogUnavailable, checkedCatalog } from "../model-catalog.js";
15
17
  import { shq, subagentInstruction, writeScopeLaunchNote, safeStatSize, readFileRange, sleep, agentMetadataPath, writeAgentMetadata, writeJson0600, agentEventPath, createEmpty0600, agentLineageFields, AGENT_DONE_POLL_MS, AGENT_EVENT_MAX_BYTES, AGENT_EVENT_TAIL_BYTES, AGENT_TURN_BOUNDARY_TAIL_BYTES, readTailLinesNewestFirst, scanLinesNewestFirst, CODEX_TRANSCRIPT_INCREMENT_MAX_BYTES, agentHarness, assertSessionName, agentsDir, } from "../agent-shared.js";
16
18
  import { confirmedAgentResumeRecoveryOrigin, readAgentLifecycle, readAgentResumeRecipe, agentResumeRecipeDigest } from "../agent-lifecycle.js";
@@ -911,8 +913,11 @@ const MCP_SERVER_NAME = /^[A-Za-z0-9_-]{1,64}$/;
911
913
  const HEADER_NAME = /^[A-Za-z0-9-]{1,128}$/;
912
914
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
913
915
  const toml = (value) => JSON.stringify(value); // JSON strings are valid TOML basic strings
914
- /** `mcp_config` -> one `-c` value per server. Refuses (CODEX_MCP_CONFIG_UNSUPPORTED) what Codex's http server table cannot say. */
915
- export function codexMcpOverrides(mcp) {
916
+ /** `mcp_config` -> one `-c` value per server. Refuses (CODEX_MCP_CONFIG_UNSUPPORTED) what Codex's http server table cannot say.
917
+ * `userStdio`: names the user's config.toml already defines as stdio servers. `-c` merges key by key into that table and
918
+ * Codex refuses `command` + `url`, so such a server is taken over as stdio running Aiterm's relay to the same url and headers
919
+ * (mcp-http-bridge.ts); the user's other keys of that table (env, cwd, timeouts, enabled_tools) still apply. */
920
+ export function codexMcpOverrides(mcp, userStdio = new Set()) {
916
921
  const refuse = (message) => { throw new AitermError(`CODEX_MCP_CONFIG_UNSUPPORTED: ${message}`, 2); };
917
922
  const servers = mcp?.mcpServers;
918
923
  if (!mcp || typeof mcp !== "object" || Object.keys(mcp).some(key => key !== "mcpServers") || !servers || typeof servers !== "object" || Array.isArray(servers))
@@ -935,7 +940,7 @@ export function codexMcpOverrides(mcp) {
935
940
  if (!url || (url.protocol !== "http:" && url.protocol !== "https:"))
936
941
  return refuse(`server '${name}': url must be an http(s) URL`);
937
942
  const fields = [`url=${toml(spec.url)}`];
938
- const envHeaders = [], literalHeaders = [], seen = new Set();
943
+ const envHeaders = [], literalHeaders = [], seen = new Set(), bridgeArgs = [], envNames = [];
939
944
  let bearer = null;
940
945
  if (spec.headers !== undefined && (!spec.headers || typeof spec.headers !== "object" || Array.isArray(spec.headers)))
941
946
  return refuse(`server '${name}': headers must be an object`);
@@ -955,11 +960,19 @@ export function codexMcpOverrides(mcp) {
955
960
  bearer = envName;
956
961
  else
957
962
  envHeaders.push(`${toml(header)}=${toml(envName)}`);
963
+ bridgeArgs.push(...(bearerName !== undefined ? ["--bearer-env", envName] : ["--env-header", `${header}=${envName}`]));
964
+ envNames.push(envName);
958
965
  }
959
966
  else if (value.includes("${"))
960
967
  return refuse(`server '${name}': header '${header}' mixes text with \${NAME}; only the whole value or 'Bearer \${NAME}' can be given`);
961
- else
968
+ else {
962
969
  literalHeaders.push(`${toml(header)}=${toml(value)}`);
970
+ bridgeArgs.push("--header", `${header}=${value}`);
971
+ }
972
+ }
973
+ if (userStdio.has(name)) {
974
+ const args = [fileURLToPath(new URL("../mcp-http-bridge.js", import.meta.url)), spec.url, ...bridgeArgs];
975
+ return `mcp_servers.${name}={command=${toml(setupNodeExecutable(process.execPath))},args=[${args.map(toml).join(",")}],env_vars=[${envNames.map(toml).join(",")}],enabled=true,disabled_tools=[]}`;
963
976
  }
964
977
  if (bearer !== null)
965
978
  fields.push(`bearer_token_env_var=${toml(bearer)}`);
@@ -970,16 +983,9 @@ export function codexMcpOverrides(mcp) {
970
983
  return `mcp_servers.${name}={${fields.join(",")}}`;
971
984
  });
972
985
  }
973
- /** Pre-start check of the caller fields for a Codex launch. `-c` merges key by key into a same-name table of
974
- * config.toml, so an http server of that name is overridden but a user stdio server (`command`) cannot be:
975
- * Codex would fail to load its config ("url is not supported for stdio"). Refused before anything starts.
976
- * shortcut: reads only `[mcp_servers.NAME]` section headers, an inline or dotted-key definition is not seen (Codex then refuses at start); upgrade with a TOML parser. */
977
- export function checkCodexCallerInput(prompt, mcp, codexHome) {
978
- if (prompt != null && (!prompt.trim() || Buffer.byteLength(prompt, "utf8") > CODEX_CALLER_PROMPT_MAX))
979
- throw new AitermError("append_system_prompt must be non-empty and at most 64 KiB for codex-cli (it travels in argv)", 2);
980
- if (mcp == null)
981
- return;
982
- const overrides = codexMcpOverrides(mcp);
986
+ /** Names of the stdio MCP servers in the user's config.toml (codexMcpOverrides takes those over with the relay).
987
+ * shortcut: reads only `[mcp_servers.NAME]` section headers, an inline or dotted-key definition is not seen (Codex then refuses that seat's config at start); upgrade with a TOML parser. */
988
+ export function codexUserStdioServers(codexHome) {
983
989
  let body = "";
984
990
  try {
985
991
  body = fs.readFileSync(path.join(codexHome, "config.toml"), "utf8");
@@ -1000,15 +1006,18 @@ export function checkCodexCallerInput(prompt, mcp, codexHome) {
1000
1006
  if (inside && /^\s*command\s*=/.test(line))
1001
1007
  stdio.add(inside);
1002
1008
  }
1003
- for (const override of overrides) {
1004
- const name = override.slice("mcp_servers.".length, override.indexOf("="));
1005
- if (stdio.has(name))
1006
- throw new AitermError(`CODEX_MCP_SERVER_CONFLICT: ~/.codex/config.toml already defines a stdio MCP server named '${name}', which a -c override cannot turn into an http server; rename it there or use another server name`, 2);
1007
- }
1009
+ return stdio;
1010
+ }
1011
+ /** Pre-start check of the caller fields for a Codex launch: the text size and the server shapes. */
1012
+ export function checkCodexCallerInput(prompt, mcp) {
1013
+ if (prompt != null && (!prompt.trim() || Buffer.byteLength(prompt, "utf8") > CODEX_CALLER_PROMPT_MAX))
1014
+ throw new AitermError("append_system_prompt must be non-empty and at most 64 KiB for codex-cli (it travels in argv)", 2);
1015
+ if (mcp != null)
1016
+ codexMcpOverrides(mcp);
1008
1017
  }
1009
1018
  /** Both caller files, as Claude's writeClaudeCallerFiles: Aiterm state, 0600, never the project or the Codex home. */
1010
1019
  export function writeCodexCallerFiles(meta, prompt, mcp) {
1011
- checkCodexCallerInput(prompt, mcp, meta.codex_home ?? realCodexHome());
1020
+ checkCodexCallerInput(prompt, mcp);
1012
1021
  if (prompt !== null) {
1013
1022
  const file = agentCodexCallerPromptPath(meta.aiterm_session);
1014
1023
  fs.writeFileSync(file, prompt, { mode: 0o600 });
@@ -1024,7 +1033,7 @@ export function writeCodexCallerFiles(meta, prompt, mcp) {
1024
1033
  /** The caller launch fields of a Codex input, refused as a not-started input refusal (phase "input"). */
1025
1034
  export function refuseCodexCallerInput(prompt, mcp) {
1026
1035
  try {
1027
- checkCodexCallerInput(prompt, mcp, realCodexHome());
1036
+ checkCodexCallerInput(prompt, mcp);
1028
1037
  }
1029
1038
  catch (e) {
1030
1039
  throw e instanceof AitermError ? launchInputRefusal("codex-cli", e.message) : e;
@@ -1053,7 +1062,7 @@ export function codexAgentArgv(bin, model, effort, prompt, meta) {
1053
1062
  parts.push("-c", `developer_instructions=${subagentInstruction(meta)}${meta.codex_caller_prompt_file ? `\n\n${fs.readFileSync(meta.codex_caller_prompt_file, "utf8")}` : ""}`);
1054
1063
  }
1055
1064
  if (meta?.kind === "codex" && meta.codex_caller_mcp_file)
1056
- for (const override of codexMcpOverrides(JSON.parse(fs.readFileSync(meta.codex_caller_mcp_file, "utf8"))))
1065
+ for (const override of codexMcpOverrides(JSON.parse(fs.readFileSync(meta.codex_caller_mcp_file, "utf8")), codexUserStdioServers(meta.codex_home ?? realCodexHome())))
1057
1066
  parts.push("-c", override);
1058
1067
  if (prompt)
1059
1068
  parts.push(prompt); // 初手プロンプト(任意)
@@ -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 new AitermError("Cursor Agent CLIが未認証です。sessionは作成していません。通常端末で公式の `agent login` を一度だけ完了してください。", 2);
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 `${subagentInstruction(meta)}\n\n${prompt}`;
590
+ return `${cursorLineagePreface(meta)}\n\n${prompt}`;
546
591
  }
547
592
  export function cursorLaunchNote(model, effort, meta) {
548
593
  const effective = cursorModelArgument(model, effort);
@@ -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
- parts.push("--session-id", meta.vendor_session_id ?? "", "--rules", subagentInstruction(meta));
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,7 @@
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
5
  import { terminalCwdFits } from "./remote-path.js";
6
6
  import { launchEnvValue } from "./private-env.js";
7
7
  import { AuthResponseError, authUiSchema, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
@@ -260,10 +260,11 @@ export function createAitermServer(options = {}) {
260
260
  content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
261
261
  structuredContent: { schema: "aiterm.agent-launch-error.v1", harness: "claude-code", code: e.reasonCode,
262
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") } : {}),
263
264
  };
264
265
  if (e instanceof AitermError && e.launchNotStarted)
265
266
  return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
266
- _meta: launchNotStartedMeta(e.launchNotStarted.harness, e.launchNotStarted.phase) };
267
+ _meta: launchNotStartedMeta(e.launchNotStarted.harness, e.launchNotStarted.phase, e.launchNotStarted.code) };
267
268
  return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true };
268
269
  }
269
270
  /**
@@ -834,6 +835,7 @@ export function createAitermServer(options = {}) {
834
835
  return fail(e);
835
836
  }
836
837
  });
838
+ const remoteSeatTurnsInFlight = new Map();
837
839
  // Declared controller caller markers opt into current-turn metadata (ADR 0122).
838
840
  // 説明と引数には出さない(steer-follow.ts の冒頭)。それ以外の呼び手には何も足さない。
839
841
  async function seatTurnsMeta(sessions, requestMeta) {
@@ -844,14 +846,26 @@ export function createAitermServer(options = {}) {
844
846
  // Terminal seats: the same call relayed with the same _meta; each terminal answers only for its own bound sessions.
845
847
  // Inside the caller's 5 s pty_list budget (tool catalog timeout_ms): a terminal that fails or is slow contributes
846
848
  // no rows, and its sessions are listed in `unread` so the caller keeps their last state instead of reading them as gone.
847
- const remote = await Promise.all(terminalSeatGroups().map(({ target, sessions: bound }) => Promise.race([
848
- callRemoteTool(target, "pty_list", {}, 4_000, undefined, requestMeta).then(result => {
849
- const seats = result._meta?.[SEAT_TURNS_RESULT_META_KEY]?.seats;
850
- return Array.isArray(seats) ? { seats: seats.filter((seat) => bound.includes(seat?.session_id)), unread: [] } : { seats: [], unread: bound };
851
- }, () => ({ seats: [], unread: bound })),
852
- new Promise(resolve => setTimeout(resolve, 4_000, { seats: [], unread: bound }).unref()),
853
- ])));
854
- return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { ...local, seats: [...local.seats, ...remote.flatMap(r => r.seats)], unread: remote.flatMap(r => r.unread) } } };
849
+ // Overlapping callers share one in-flight relay per terminal: each relay starts its own reader on the terminal, and
850
+ // two readers of one seat at once leave one of them without the span lock (that seat comes back in its `unread`).
851
+ const remote = await Promise.all(terminalSeatGroups().map(({ target, sessions: bound }) => {
852
+ const key = JSON.stringify([target, requestMeta]);
853
+ let call = remoteSeatTurnsInFlight.get(key);
854
+ if (!call) {
855
+ call = callRemoteTool(target, "pty_list", {}, 4_000, undefined, requestMeta)
856
+ .then(result => result._meta?.[SEAT_TURNS_RESULT_META_KEY] ?? null, () => null)
857
+ .finally(() => remoteSeatTurnsInFlight.delete(key));
858
+ remoteSeatTurnsInFlight.set(key, call);
859
+ }
860
+ return Promise.race([
861
+ call.then(answer => Array.isArray(answer?.seats)
862
+ ? { seats: answer.seats.filter((seat) => bound.includes(seat?.session_id)),
863
+ unread: Array.isArray(answer.unread) ? answer.unread.filter((name) => bound.includes(name)) : [] }
864
+ : { seats: [], unread: bound }),
865
+ new Promise(resolve => setTimeout(resolve, 4_000, { seats: [], unread: bound }).unref()),
866
+ ]);
867
+ }));
868
+ return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { ...local, seats: [...local.seats, ...remote.flatMap(r => r.seats)], unread: [...local.unread, ...remote.flatMap(r => r.unread)] } } };
855
869
  }
856
870
  catch (e) {
857
871
  return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { schema: "aiterm.seat-turns.v1", error: e instanceof Error ? e.message : String(e) } } };
@@ -1268,14 +1282,21 @@ export function createAitermServer(options = {}) {
1268
1282
  const FORK_MINIMUM_VERSION = "0.70.6";
1269
1283
  /** First release whose agent_launch takes append_system_prompt / mcp_config for codex-cli, and the first a terminal may run a Codex seat on. */
1270
1284
  const CODEX_REMOTE_MINIMUM_VERSION = "0.70.7";
1285
+ /** The oldest terminal Aiterm per harness: Grok, Cursor and Antigravity seats need 0.70.9 (checked before any private value is sent). */
1286
+ const TERMINAL_MINIMUM_VERSION = {
1287
+ "claude-code": REMOTE_MINIMUM_VERSION, "codex-cli": CODEX_REMOTE_MINIMUM_VERSION,
1288
+ "grok-cli": REMOTE_CLI_OPS_VERSION, "cursor-cli": REMOTE_CLI_OPS_VERSION, "antigravity-cli": REMOTE_CLI_OPS_VERSION,
1289
+ };
1271
1290
  const terminalVersions = new Map();
1272
1291
  /** A seat on a BellTeam terminal (remote-terminal.md "One launch path"). Same launch arguments plus terminal + cwd. */
1273
1292
  async function launchTerminalAgent(harness, terminal, args, extra) {
1274
1293
  try {
1275
1294
  if (args.remote)
1276
1295
  throw new AitermError("TERMINAL_INVALID: use terminal or remote, not both; for a registered terminal pass only terminal", 2);
1277
- if (harness !== "claude-code" && harness !== "codex-cli")
1278
- throw new AitermError(`TERMINAL_HARNESS_UNSUPPORTED: terminal seats support harnesses claude-code and codex-cli; ${harness} is not available on a terminal yet`, 2);
1296
+ const minimum = TERMINAL_MINIMUM_VERSION[harness];
1297
+ // Every real harness is routed since 0.70.9; this only guards a name outside the five.
1298
+ if (!minimum)
1299
+ throw new AitermError(`TERMINAL_HARNESS_UNSUPPORTED: ${harness} is not a harness a terminal can run`, 2);
1279
1300
  const cwdForm = "TERMINAL_INVALID: cwd is required with terminal: the absolute project folder on that terminal in its own form (a POSIX path starting with / on macOS and Linux, X:\\folder with backslashes on Windows; never launch locally and cd)";
1280
1301
  if (!terminalCwdFits(args.cwd, terminal.os))
1281
1302
  throw new AitermError(cwdForm, 2);
@@ -1291,7 +1312,6 @@ export function createAitermServer(options = {}) {
1291
1312
  version = (await callRemoteTool(target, "pty_list", {}, 60_000)).remote_version ?? "0.0.0";
1292
1313
  terminalVersions.set(target.trusted_ref, version);
1293
1314
  }
1294
- const minimum = harness === "codex-cli" ? CODEX_REMOTE_MINIMUM_VERSION : REMOTE_MINIMUM_VERSION;
1295
1315
  if (!versionAtLeast(version, minimum))
1296
1316
  throw new AitermError(`REMOTE_AITERM_TOO_OLD: the terminal runs Aiterm ${version}; ${minimum} or later is required (update Aiterm on the terminal)`, 2);
1297
1317
  const privateEnv = {};
@@ -1519,8 +1539,8 @@ export function createAitermServer(options = {}) {
1519
1539
  launch_operation_id: z.string().regex(/^sha256:[0-9a-f]{64}$/).optional().describe("Claude Codeのpromptなしexact replay相関だけで使用"),
1520
1540
  remote: remoteInputField,
1521
1541
  terminal: terminalArgumentSchema.optional().describe(terminalArgumentDescription),
1522
- append_system_prompt: z.string().min(1).optional().describe("claude-code and codex-cli only. Launch instructions added to the system prompt (Codex: appended to developer_instructions after Aiterm's marker, at most 64 KiB); kept in Aiterm state, not in the project or home. Never put secrets here"),
1523
- mcp_config: z.object({ mcpServers: z.record(z.string(), z.unknown()) }).strict().optional().describe("claude-code and codex-cli only. Extra MCP servers for this seat. Secret header values: write ${NAME} and list NAME in env_vars. Codex takes only http servers {type?: \"http\", url, headers}: 'Authorization: Bearer ${NAME}' or a header whose whole value is ${NAME}; other shapes are refused before the seat starts"),
1542
+ 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)"),
1543
+ 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; Codex, Grok and Antigravity replace a same-name user server for this seat (Codex: a user stdio server of that name runs Aiterm's relay to the given url instead)"),
1524
1544
  fork_from: z.object({
1525
1545
  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)"),
1526
1546
  fork_id: z.string().min(1).max(200).optional().describe("Caller's fork ID, passed to the seat as THROUGHLINE_FORK_ID"),
@@ -1550,8 +1570,6 @@ export function createAitermServer(options = {}) {
1550
1570
  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"),
1551
1571
  },
1552
1572
  }, async ({ harness, remote, terminal, ...args }, extra) => {
1553
- if (harness !== "claude-code" && harness !== "codex-cli" && (args.append_system_prompt !== undefined || args.mcp_config !== undefined))
1554
- return fail(launchInputRefusal(harness, `append_system_prompt and mcp_config are claude-code and codex-cli only; ${harness} cannot take them`));
1555
1573
  if (terminal)
1556
1574
  return launchTerminalAgent(harness, terminal, { ...args, ...(remote ? { remote } : {}) }, extra);
1557
1575
  if (remote && args.require_existing_resume)
@@ -12,6 +12,8 @@ const recordSchema = z.object({ binding: z.string().min(1), span: spanSchema.nul
12
12
  settled_from: z.string().nullable().optional() }).strict();
13
13
  const ownerSchema = z.object({ pid: z.number().int().positive(), started_identity: stamp, token: z.string() }).strict();
14
14
  export const managedSpanDirectory = (meta) => agentMetadataPath(meta.aiterm_session, meta.launch_id).replace(/\.agent\.json$/, ".seat-span.d");
15
+ /** Another live reader holds the span this instant: no observation this tick (seat-turns `unread`), not an unknown turn. */
16
+ export const SPAN_HELD = Symbol("span-held");
15
17
  /** Same callback owns live capture and the short identity transaction. Never waits or sends input. */
16
18
  export function withManagedSpan(meta, capture) {
17
19
  const directory = managedSpanDirectory(meta);
@@ -39,10 +41,10 @@ export function withManagedSpan(meta, capture) {
39
41
  return observed.state === "absent" || observed.state === "present" && observed.actor.started_identity !== prior.started_identity;
40
42
  };
41
43
  if (!dead())
42
- return null;
44
+ return SPAN_HELD;
43
45
  const after = fs.lstatSync(lock, { bigint: true });
44
46
  if (before.dev !== after.dev || before.ino !== after.ino || !dead())
45
- return null;
47
+ return SPAN_HELD;
46
48
  // Retain this nonempty destination: a competing reap cannot move a later owner's lock over it.
47
49
  fs.renameSync(lock, path.join(directory, `retired-${before.dev}-${before.ino}`));
48
50
  fs.renameSync(candidate, lock);
@@ -95,7 +97,8 @@ export function observeManagedSpan(file, binding, evidence, terminal, at, positi
95
97
  return { state: "running", turn_id, started_at, event_cursor: null, interim_from, wait_process: null };
96
98
  }
97
99
  // A launch that never showed busy nor any terminal has no turn to hide: its settled ready is idle.
98
- if (!terminal && (record?.span || record?.terminal) || record?.span && terminal === record.terminal)
100
+ // An idle compaction has no Stop of its own; its notice settles the span its spinner opened.
101
+ if (evidence !== "ready_compacted" && (!terminal && (record?.span || record?.terminal) || record?.span && terminal === record.terminal))
99
102
  return null;
100
103
  if (!record)
101
104
  record = { binding, span: null, terminal, ready: null };
@@ -0,0 +1,47 @@
1
+ // A stdio MCP server that relays every message to one streamable-HTTP MCP server.
2
+ // Codex merges `-c mcp_servers.NAME={...}` key by key into the user's table of that name, so a seat's http server
3
+ // cannot replace a user stdio server (`command` + `url` is refused). The seat instead takes over that stdio entry
4
+ // with this relay (codex.ts codexMcpOverrides), leaving ~/.codex/config.toml untouched.
5
+ // argv: <url> then pairs: --header NAME=VALUE (literal) | --env-header NAME=ENV | --bearer-env ENV
6
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
8
+ import { isJSONRPCRequest } from "@modelcontextprotocol/sdk/types.js";
9
+ const fail = (message) => { process.stderr.write(`aiterm mcp bridge: ${message}\n`); process.exit(1); };
10
+ function bridgeHeaders(args, env) {
11
+ const headers = {};
12
+ for (let i = 0; i < args.length; i += 2) {
13
+ const [flag, value] = [args[i], args[i + 1] ?? ""];
14
+ const eq = value.indexOf("=");
15
+ const envValue = (name) => env[name] ?? fail(`${name} has no value`);
16
+ if (flag === "--bearer-env")
17
+ headers.Authorization = `Bearer ${envValue(value)}`;
18
+ else if (flag === "--header" && eq > 0)
19
+ headers[value.slice(0, eq)] = value.slice(eq + 1);
20
+ else if (flag === "--env-header" && eq > 0)
21
+ headers[value.slice(0, eq)] = envValue(value.slice(eq + 1));
22
+ else
23
+ fail(`unknown argument ${flag}`);
24
+ }
25
+ return headers;
26
+ }
27
+ const [url, ...rest] = process.argv.slice(2);
28
+ const remote = new StreamableHTTPClientTransport(new URL(url ?? fail("no url")), { requestInit: { headers: bridgeHeaders(rest, process.env) } });
29
+ const local = new StdioServerTransport();
30
+ local.onmessage = message => void remote.send(message).catch((error) => {
31
+ // A request the server never answered would hang the Codex tool call; answer it with the transport error.
32
+ if (isJSONRPCRequest(message))
33
+ void local.send({ jsonrpc: "2.0", id: message.id, error: { code: -32603, message: `aiterm mcp bridge: ${error.message}` } });
34
+ });
35
+ remote.onmessage = message => {
36
+ const version = message.result?.protocolVersion;
37
+ if (typeof version === "string")
38
+ remote.setProtocolVersion(version);
39
+ void local.send(message);
40
+ };
41
+ remote.onerror = error => process.stderr.write(`aiterm mcp bridge: ${error.message}\n`);
42
+ // Codex closing our stdin ends the seat's use of the server; an open SSE stream must not keep this process alive.
43
+ const stop = () => void remote.close().finally(() => process.exit(0));
44
+ local.onclose = stop;
45
+ process.stdin.on("end", stop);
46
+ await remote.start();
47
+ await local.start();
@@ -59,6 +59,6 @@ export const terminalArgumentDescription = "Run this seat on another computer (a
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. TERMINAL_HARNESS_UNSUPPORTED = use harness claude-code or codex-cli (codex-cli needs Aiterm 0.70.7 on the terminal). " +
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
64
  "TERMINAL_PLATFORM_UNSUPPORTED = the terminal is not a macOS, Linux or Windows system, so it cannot run seats.";
@@ -108,9 +108,9 @@ function serve() {
108
108
  }
109
109
  });
110
110
  server.registerTool("remote_terminal_command", {
111
- description: "Fixed operation on the terminal: Claude Code setup, or a path check / mkdir / read-only folder listing",
112
- inputSchema: { op: z.enum(REMOTE_COMMAND_OPS), path: z.string().optional() },
113
- }, guarded(({ op, path }) => bound().command(op, path)));
111
+ description: "Fixed operation on the terminal: a CLI's version / install / update / login state (cli_*, harness required), Claude Code setup (claude_*), or a path check / mkdir / read-only folder listing",
112
+ inputSchema: { op: z.enum(REMOTE_COMMAND_OPS), path: z.string().optional(), harness: z.string().optional() },
113
+ }, guarded(({ op, path, harness }) => bound().command(op, path, harness)));
114
114
  server.registerTool("remote_terminal_close", { description: "Close the bound connection and exit", inputSchema: {} }, guarded(async () => { const result = connection ? await connection.close() : { closed: true }; setTimeout(() => process.exit(0), 100); return result; }));
115
115
  server.connect(new StdioServerTransport()).catch(error => { console.error("aiterm-remote-terminal fatal:", error); process.exit(1); });
116
116
  }