aiterm-mcp 0.70.28 → 0.70.29

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 CHANGED
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.70.29] - 2026-11-12
11
+
12
+ - `agent_models` takes `claude_login` (claude-code only, a slot name such as `1st`). Aiterm reads `<parent in AITERM_CLAUDE_CONFIG_ROOTS>/<slot>/oauth-token` and lists models on that login, the one a seat of that slot runs with. When `configuration_root` is omitted and the slot directory is itself a Claude root (it has `.claude.json`), it is also the root, as for that slot's seats. The token never leaves Aiterm. A missing or malformed token file answers `CLAUDE_LOGIN_UNAVAILABLE` without reading a list. Without `claude_login` nothing changes.
13
+ - A Claude list read on a token login (`CLAUDE_CODE_OAUTH_TOKEN`) runs in its own catalog-only root per root and login, seeded with only the root's `oauthAccount`. Claude Code decides the served catalog with `oauthAccount`, which a token login never fetches. Without it the list was the short one (5 rows, e.g. `claude-fable-5-1[1m]`), unlike the seat's `/model` picker (14 rows: `opus` "Opus 5.5", `fable` "Fable 5.2", …). Measured on both BellTeam slots.
14
+ - `agent_configure` on a Claude seat reads its catalog (alias match, fast check, dropping fast) with the seat's own root and login, read from the seat's live process (Linux `/proc/<pid>/environ`, macOS `ps -wwE`). Before, it used Aiterm's own login, so a model the seat could pick could be refused as `CLAUDE_MODEL_NOT_IN_PICKER`. Where the seat's environment cannot be read (Windows), it keeps Aiterm's env as before.
15
+ - `agent_goal` on a session bound to a terminal is forwarded to the terminal's Aiterm by session, like `agent_configure`, and returns the terminal's `aiterm.agent-goal-result` unchanged. A user origin rides the private stdin line that only the Aiterm holding the binding can send; an older terminal treats the mutation as automatic and refuses it (`user_authorization_required`).
16
+
10
17
  ## [0.70.28] - 2026-11-11
11
18
 
12
19
  - `agent_goal` on Claude Code accepts 2.1.310 and later 2.1 releases. It was pinned to exactly 2.1.310, so every 2.1.322 seat read as `unavailable` (`goal_native_session_unavailable`). The 2.1.322 dialog, transcript attachment and session registration were measured and match. Any other Claude version now returns `availability: "unsupported"` with reason `claude_code_version_unverified:<version>`, without touching the seat.
@@ -3318,7 +3325,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3318
3325
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3319
3326
  provenance.
3320
3327
 
3321
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.28...HEAD
3328
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.29...HEAD
3329
+ [0.70.29]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.28...v0.70.29
3322
3330
  [0.70.28]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.27...v0.70.28
3323
3331
  [0.70.27]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.26...v0.70.27
3324
3332
  [0.70.26]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.25...v0.70.26
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.70.28** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.70.29** · 動作対象は 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.70.28** · 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).
230
+ **Status:** actively maintained · current public release **v0.70.29** · 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,8 @@ export const agentGoalInputSchema = agentGoalInputObject.superRefine((value, con
18
18
  context.addIssue({ code: "custom", message: "fields do not apply to this action" });
19
19
  });
20
20
  export const GOAL_HOST_META_KEY = "aiterm/goal";
21
+ /** The caller's user origin relayed to a terminal's Aiterm on the private stdin line (never process env). */
22
+ export const GOAL_ORIGIN_PRIVATE_ENV = "AITERM_GOAL_ORIGIN";
21
23
  const hostOrigin = z.object({ origin: z.literal("user") }).strict();
22
24
  /** Host provenance on the existing local MCP channel, not authentication.
23
25
  * The controller must authenticate the user and reject seat ingress before stamping
@@ -9,13 +9,15 @@ import { claudeDefaultConfigRoot } from "./claude-config-root.js";
9
9
  const FRESH_MS = 10 * 60_000;
10
10
  /**
11
11
  * The catalog-only root for the root `env` selects, holding only the root's access token. null when the root has no
12
- * file credential (macOS Keychain), the env authenticates by token/API key, or the access token is near expiry:
12
+ * file credential (macOS Keychain), the env authenticates by API key, or the access token is near expiry:
13
13
  * the caller then runs on the root itself as before, which lets Claude Code refresh there.
14
14
  */
15
15
  export function claudeCatalogRoot(env, now = Date.now()) {
16
- if (env.CLAUDE_CODE_OAUTH_TOKEN || env.ANTHROPIC_API_KEY || env.ANTHROPIC_AUTH_TOKEN)
16
+ if (env.ANTHROPIC_API_KEY || env.ANTHROPIC_AUTH_TOKEN)
17
17
  return null;
18
18
  const root = env.CLAUDE_CONFIG_DIR || claudeDefaultConfigRoot(env);
19
+ if (env.CLAUDE_CODE_OAUTH_TOKEN)
20
+ return claudeLoginCatalogRoot(env, root, env.CLAUDE_CODE_OAUTH_TOKEN);
19
21
  let oauth;
20
22
  try {
21
23
  oauth = JSON.parse(fs.readFileSync(path.join(root, ".credentials.json"), "utf8"))?.claudeAiOauth;
@@ -30,13 +32,20 @@ export function claudeCatalogRoot(env, now = Date.now()) {
30
32
  real = fs.realpathSync(root);
31
33
  }
32
34
  catch { }
33
- const dir = path.join(ensureStateRoot(), "claude-catalog", createHash("sha256").update(real).digest("hex").slice(0, 16));
34
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
35
+ const dir = catalogDir(real);
35
36
  // The refresh token is single-use: a refresh here would sign the root out, so the copy cannot refresh.
36
37
  const { refreshToken: _refresh, ...access } = oauth;
37
38
  const tmp = path.join(dir, `.credentials.${randomUUID()}.tmp`);
38
39
  fs.writeFileSync(tmp, JSON.stringify({ claudeAiOauth: access }), { mode: 0o600 });
39
40
  fs.renameSync(tmp, path.join(dir, ".credentials.json"));
41
+ return settled(env, dir);
42
+ }
43
+ function catalogDir(key) {
44
+ const dir = path.join(ensureStateRoot(), "claude-catalog", createHash("sha256").update(key).digest("hex").slice(0, 16));
45
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
46
+ return dir;
47
+ }
48
+ function settled(env, dir) {
40
49
  const digestFile = path.join(dir, "last-catalog.sha256");
41
50
  return {
42
51
  env: { ...env, CLAUDE_CONFIG_DIR: dir },
@@ -49,3 +58,38 @@ export function claudeCatalogRoot(env, now = Date.now()) {
49
58
  remember: digest => fs.writeFileSync(digestFile, digest, { mode: 0o600 }),
50
59
  };
51
60
  }
61
+ /**
62
+ * A token login (CLAUDE_CODE_OAUTH_TOKEN, as a seat runs) gets its own catalog-only root per root and login.
63
+ * Claude Code evaluates the served catalog with the root's `oauthAccount`, which a token login never fetches:
64
+ * without it the list is the short one, with it the one the seat's picker shows (harness-contracts.md C2).
65
+ */
66
+ function claudeLoginCatalogRoot(env, root, token) {
67
+ let real = root;
68
+ try {
69
+ real = fs.realpathSync(root);
70
+ }
71
+ catch { }
72
+ const dir = catalogDir(`${real}\0login\0${createHash("sha256").update(token).digest("hex")}`);
73
+ const globalFile = env.CLAUDE_CONFIG_DIR ? path.join(root, ".claude.json") : path.join(env.HOME ?? path.dirname(root), ".claude.json");
74
+ let account;
75
+ try {
76
+ account = JSON.parse(fs.readFileSync(globalFile, "utf8"))?.oauthAccount;
77
+ }
78
+ catch { }
79
+ const own = path.join(dir, ".claude.json");
80
+ let config = {};
81
+ try {
82
+ config = JSON.parse(fs.readFileSync(own, "utf8")) ?? {};
83
+ }
84
+ catch { }
85
+ if (JSON.stringify(config.oauthAccount) !== JSON.stringify(account)) {
86
+ if (account === undefined)
87
+ delete config.oauthAccount;
88
+ else
89
+ config.oauthAccount = account;
90
+ const tmp = path.join(dir, `.claude.${randomUUID()}.tmp`);
91
+ fs.writeFileSync(tmp, JSON.stringify(config), { mode: 0o600 });
92
+ fs.renameSync(tmp, own);
93
+ }
94
+ return settled(env, dir);
95
+ }
@@ -32,6 +32,33 @@ export function resolveClaudeConfigurationRoot(requested, env = process.env) {
32
32
  throw rejected("configuration_rootは既定のroot(~/.claude)か、AITERM_CLAUDE_CONFIG_ROOTSに並べた親の直下のディレクトリだけです。");
33
33
  return { root: actual, selector: actual };
34
34
  }
35
+ const LOGIN_TOKEN = /^sk-ant-oat01-[A-Za-z0-9_-]{20,}$/u;
36
+ /**
37
+ * The login a seat launcher gives a slot: `<parent in AITERM_CLAUDE_CONFIG_ROOTS>/<slot>/oauth-token` as
38
+ * CLAUDE_CODE_OAUTH_TOKEN. When `rootSelected` is false and the slot directory is itself a Claude root (it has
39
+ * `.claude.json`), it is also the root, as for a seat of that slot. Refused rather than read on another account's login.
40
+ */
41
+ export function withClaudeSlotLogin(env, slot, rootSelected = false) {
42
+ const unavailable = () => new AitermError(`CLAUDE_LOGIN_UNAVAILABLE: claude_login '${slot}' のoauth-tokenを` +
43
+ "AITERM_CLAUDE_CONFIG_ROOTSの下に読めません。一覧は読んでいません。", 2);
44
+ if (!/^[A-Za-z0-9_-]{1,64}$/u.test(slot))
45
+ throw unavailable();
46
+ for (const parent of (env.AITERM_CLAUDE_CONFIG_ROOTS ?? "").split(path.delimiter).filter(parent => path.isAbsolute(parent))) {
47
+ let token;
48
+ try {
49
+ token = fs.readFileSync(path.join(parent, slot, "oauth-token"), "utf8").trim();
50
+ }
51
+ catch {
52
+ continue;
53
+ }
54
+ if (!LOGIN_TOKEN.test(token))
55
+ throw unavailable();
56
+ const own = !rootSelected && fs.existsSync(path.join(parent, slot, ".claude.json"))
57
+ ? withClaudeConfigRoot(env, resolveClaudeConfigurationRoot(path.join(parent, slot), env)) : env;
58
+ return { ...own, CLAUDE_CODE_OAUTH_TOKEN: token };
59
+ }
60
+ throw unavailable();
61
+ }
35
62
  /** The same environment with this root selected. */
36
63
  export function withClaudeConfigRoot(env, selected) {
37
64
  const next = { ...env };
package/dist/core.js CHANGED
@@ -51,9 +51,9 @@ import { isCursorMcpClient } from "aiterm-steer-delivery";
51
51
  import { antigravityBinding, antigravityAuthChoiceKey, antigravityCurrentModel, antigravityStartupAction, antigravityAgentArgv, writeAntigravityCallerFiles, checkAntigravityCallerInput, antigravityPromptWithCaller, antigravityQuotaLimit, antigravityModelChoices, antigravityAuthStatus, antigravityAuthPane, antigravityTranscriptText, bindAntigravitySession, createAntigravityAgentMetadata, mergeAntigravityHooks } from "./harnesses/antigravity.js";
52
52
  import { paneTokenHint } from "./harnesses/pane-tokens.js";
53
53
  import { unfinishedDeliveriesOwnedBy } from "./parent-delivery-owners.js";
54
- import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, signalRuntimeProcess, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, macKeepAwakeProcess, processElapsedSeconds } from "./process-runtime.js";
54
+ import { readLinuxProcessRegistrationIdentity, readProcessEnvironment, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, signalRuntimeProcess, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, macKeepAwakeProcess, processElapsedSeconds } from "./process-runtime.js";
55
55
  import { liveNodeExecutable } from "./live-node.js";
56
- import { resolveClaudeConfigurationRoot, withClaudeConfigRoot } from "./claude-config-root.js";
56
+ import { resolveClaudeConfigurationRoot, withClaudeConfigRoot, withClaudeSlotLogin } from "./claude-config-root.js";
57
57
  import { probeWriteBan, writeBanPrefix, windowsWriteBanArgv } from "./write-ban.js";
58
58
  import { AitermError, launchAuthRequired, launchInputRefusal, AgentResumeUnavailableError, AgentResumeError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
59
59
  import { isWin, SOCKDIR, SOCK, tmuxCommand, readOnlyTmuxList, PtyDiagnosticError, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, withNativeSessionSetupRollback, hasNativeSessionSetupRollback, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, rememberPaneShell, } from "./tmux-runtime.js";
@@ -5430,10 +5430,11 @@ export async function authenticateAgent(kind, options) {
5430
5430
  * promptもturnも送らない。取得不能・形式異常はfallbackせずエラーにする。
5431
5431
  */
5432
5432
  export async function listAgentModels(kind, options = {}) {
5433
- if (options.configuration_root !== undefined && kind !== "claude")
5434
- throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: configuration_rootはclaude-code harnessだけで使えます。", 2);
5435
- const claudeEnv = options.configuration_root === undefined ? process.env
5433
+ if ((options.configuration_root !== undefined || options.claude_login !== undefined) && kind !== "claude")
5434
+ throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: configuration_rootとclaude_loginはclaude-code harnessだけで使えます。", 2);
5435
+ const rooted = options.configuration_root === undefined ? process.env
5436
5436
  : withClaudeConfigRoot(process.env, resolveClaudeConfigurationRoot(options.configuration_root));
5437
+ const claudeEnv = options.claude_login === undefined ? rooted : withClaudeSlotLogin(rooted, options.claude_login, options.configuration_root !== undefined);
5437
5438
  const cwd = options.cwd ?? process.cwd();
5438
5439
  if (!path.isAbsolute(cwd))
5439
5440
  throw new AitermError("cwd は絶対パスで指定してください", 2);
@@ -6299,11 +6300,35 @@ export async function configureAgent(name, opts, expectedLaunchId) {
6299
6300
  throw failure;
6300
6301
  }
6301
6302
  }
6303
+ /**
6304
+ * The env a Claude catalog read for this seat runs with: the seat's own root and login, read from its live native process
6305
+ * (model-configuration.md). null when the process or its environment cannot be read; callers then keep their own env.
6306
+ */
6307
+ function claudeSeatCatalogEnv(name, meta) {
6308
+ const pane = tmux("display-message", "-p", "-t", `=${name}:`, "#{pane_pid}");
6309
+ const pid = Number(pane.stdout.trim());
6310
+ if (pane.code !== 0 || !Number.isSafeInteger(pid) || pid < 1)
6311
+ return null;
6312
+ const rows = readRuntimeProcesses();
6313
+ const candidates = selectHarnessProcesses(meta, rows, processSubtree(rows, pid));
6314
+ const seat = candidates.length === 1 ? readProcessEnvironment(candidates[0].pid, [CLAUDE_LOGIN_ENV, "CLAUDE_CONFIG_DIR"]) : null;
6315
+ if (!seat)
6316
+ return null;
6317
+ const env = { ...process.env };
6318
+ for (const [key, value] of Object.entries(seat))
6319
+ if (value === null)
6320
+ delete env[key];
6321
+ else
6322
+ env[key] = value;
6323
+ return env;
6324
+ }
6302
6325
  /** 返りの null は、席の画面が番の最中を示していて、何も打っていない時。 */
6303
6326
  async function configureAgentInLock(name, model, effort, fast, beforeChange) {
6304
6327
  // 席の控えは、行列の順番が来てから読む(前の送信が書いた分を、古い控えで上書きしない)。
6305
6328
  const meta = loadAgentMetadata(name);
6306
6329
  bindCompletedInitialPrompt(meta);
6330
+ let seatEnv;
6331
+ const claudeSeatEnv = () => seatEnv === undefined ? (seatEnv = claudeSeatCatalogEnv(name, meta)) : seatEnv;
6307
6332
  // Codexは回答を流している間、動作中の行を出さない(ADR 0101)。送信と同じく記録の番の開始を見て、動いている席へ命令を打たない。
6308
6333
  if (isAgentTuiBusy(meta.kind, captureScreen(name, AGENT_TUI_READY_LINES))
6309
6334
  || (meta.kind === "codex" && codexRunningTurn(meta) !== null && observeSession(name).harness_alive === true))
@@ -6380,7 +6405,7 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
6380
6405
  if (target === undefined) {
6381
6406
  throw new FastModeError("FAST_MODE_UNCONFIRMED", `この席のmodelが控えに無く(前の版のAitermが起こした席)、fastの対応を確かめられません。modelも渡してください。${untouched}`);
6382
6407
  }
6383
- const unavailable = await assertClaudeFastSupported(bin, meta.cwd ?? process.cwd(), target, untouched, { ...process.env, CLAUDE_CONFIG_DIR: meta.claude_home ?? claudeConfigDir() });
6408
+ const unavailable = await assertClaudeFastSupported(bin, meta.cwd ?? process.cwd(), target, untouched, claudeSeatEnv() ?? { ...process.env, CLAUDE_CONFIG_DIR: meta.claude_home ?? claudeConfigDir() });
6384
6409
  if (unavailable)
6385
6410
  throw new FastModeError("FAST_MODE_UNAVAILABLE", `${unavailable.message.replace(/^FAST_MODE_UNAVAILABLE: /, "")}${untouched}`);
6386
6411
  }
@@ -6396,7 +6421,7 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
6396
6421
  const bin = meta.agent_executable ?? resolveAgentBin(meta.kind);
6397
6422
  if (!bin)
6398
6423
  return;
6399
- const catalog = meta.kind === "claude" ? await claudeModelChoices(bin, meta.cwd ?? process.cwd()) : await codexModelChoices(bin, true);
6424
+ const catalog = meta.kind === "claude" ? await claudeModelChoices(bin, meta.cwd ?? process.cwd(), claudeSeatEnv() ?? process.env) : await codexModelChoices(bin, true);
6400
6425
  if (!catalog.fast_ids?.[model])
6401
6426
  recordAgentFast(meta, false);
6402
6427
  };
@@ -6407,7 +6432,7 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
6407
6432
  throw new AitermError("Claude Code の reasoning_effort は low/medium/high/xhigh/max/ultracode のいずれかです。設定は変えていません。", 2);
6408
6433
  }
6409
6434
  if (model || level)
6410
- await configureClaudeForSessionOnly(name, meta, model, level, beforeChange, { ...agentModelUi(name), ready: () => waitAgentTuiReady(name, meta, AGENT_TUI_READY_TIMEOUT_MS) });
6435
+ await configureClaudeForSessionOnly(name, meta, model, level, beforeChange, { ...agentModelUi(name), ready: () => waitAgentTuiReady(name, meta, AGENT_TUI_READY_TIMEOUT_MS) }, claudeSeatEnv() ?? process.env);
6411
6436
  if (effort && !level) {
6412
6437
  beforeChange();
6413
6438
  await sendAgentPromptText(name, `/effort ${effort}`);
@@ -6,7 +6,7 @@ const CLAUDE_MODEL_PICKER_TIMEOUT_MS = 8_000;
6
6
  const CLAUDE_MODEL_PICKER_KEY_TIMEOUT_MS = 1_500;
7
7
  const CLAUDE_MODEL_SWITCH_TIMEOUT_MS = 15_000;
8
8
  const CLAUDE_EFFORT_ORDER = ["low", "medium", "high", "xhigh", "max"];
9
- export async function configureClaudeForSessionOnly(name, meta, model, effort, beforeChange, ui) {
9
+ export async function configureClaudeForSessionOnly(name, meta, model, effort, beforeChange, ui, catalogEnv = process.env) {
10
10
  let selectionIssued = false;
11
11
  const screen = () => ui.screen();
12
12
  const until = async (read, timeoutMs) => {
@@ -98,7 +98,7 @@ export async function configureClaudeForSessionOnly(name, meta, model, effort, b
98
98
  return refuse("CLAUDE_MODEL_CATALOG_UNAVAILABLE", "Claude CodeのCLIが見つかりません");
99
99
  let catalog;
100
100
  try {
101
- catalog = await claudeModelChoices(bin, meta.cwd ?? process.cwd());
101
+ catalog = await claudeModelChoices(bin, meta.cwd ?? process.cwd(), catalogEnv);
102
102
  }
103
103
  catch (error) {
104
104
  return refuse("CLAUDE_MODEL_CATALOG_UNAVAILABLE", error instanceof Error ? error.message : String(error));
package/dist/index.js CHANGED
@@ -19,14 +19,14 @@ import { AitermError, AgentResumeUnavailableError, AgentResumeError, launchInput
19
19
  */
20
20
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
21
21
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
22
- import { readPrivateEnvLine, setPrivateEnv } from "./private-env.js";
22
+ import { readPrivateEnvLine, setPrivateEnv, privateEnvValue } from "./private-env.js";
23
23
  import { withTerminalLaunchAction, withErrorCode, launchNotStartedMeta } from "./terminal-launch-error.js";
24
24
  import { codexMcpOverrides } from "./harnesses/codex.js";
25
25
  import { CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
26
26
  import { z } from "zod";
27
27
  import { agentModelsResult } from "./model-catalog.js";
28
28
  import { agentGoalWireResultSchema, agentGoalOutputSchema } from "./agent-goal-native-result.js";
29
- import { agentGoalInputSchema, goalOriginFromHost } from "./agent-goal.js";
29
+ import { agentGoalInputSchema, goalOriginFromHost, GOAL_ORIGIN_PRIVATE_ENV } from "./agent-goal.js";
30
30
  import * as core from "./core.js";
31
31
  import { runtimeErrorStoreDiagnostic } from "./runtime-error-store.js";
32
32
  import { triggerRuntimeErrorReport } from "./runtime-error-report.js";
@@ -37,7 +37,7 @@ import { ExecutionError, executionErrorResult } from "./execution-wire.js";
37
37
  import { attachExecutionControlRegistrar } from "./execution-tools.js";
38
38
  import { ParentDeliveryManager, deliveryKey } from "./parent-delivery.js";
39
39
  import { failureObservationSchema } from "./parent-delivery-record.js";
40
- import { acceptRemote, callRemoteTool, loopDeadline, observeRemoteAgentDone, remoteLabel, remoteWaitProcess } from "./remote.js";
40
+ import { acceptRemote, callRemoteTool, REMOTE_CLIENT_NAME, loopDeadline, observeRemoteAgentDone, remoteLabel, remoteWaitProcess } from "./remote.js";
41
41
  import { codexParentFromRequest } from "./codex-parent-receiver.js";
42
42
  import { claudeParentFromRequest, discardClaudeHookRequest } from "./claude-parent-receiver.js";
43
43
  import { parentDeliveryDiagnostic } from "./parent-hook-diagnostic.js";
@@ -1125,9 +1125,24 @@ export function createAitermServer(options = {}) {
1125
1125
  outputSchema: agentGoalOutputSchema,
1126
1126
  }, async (args, extra) => {
1127
1127
  try {
1128
- const origin = goalOrigin ? goalOrigin(extra) : goalOriginFromHost(server.server.getClientVersion()?.name, extra._meta, server.server.getClientCapabilities());
1128
+ const client = server.server.getClientVersion()?.name;
1129
+ // A terminal's goal call from the Aiterm that holds its binding carries the caller's origin on the private line,
1130
+ // which only that Aiterm can send (remote-terminal.md R5).
1131
+ const relayed = client === REMOTE_CLIENT_NAME && privateEnvValue(GOAL_ORIGIN_PRIVATE_ENV) === "user" ? "user" : undefined;
1132
+ const origin = relayed ?? (goalOrigin ? goalOrigin(extra) : goalOriginFromHost(client, extra._meta, server.server.getClientCapabilities()));
1129
1133
  if (origin !== "user" && origin !== "automatic")
1130
1134
  throw new Error("Invalid trusted goal provenance");
1135
+ // A terminal seat is addressed by session alone, like agent_configure (remote-terminal.md T2).
1136
+ const terminal = boundTerminalTarget(args.session_id);
1137
+ if (terminal) {
1138
+ try {
1139
+ const remote = await callRemoteTool(terminal, "agent_goal", args, undefined, origin === "user" ? { [GOAL_ORIGIN_PRIVATE_ENV]: "user" } : undefined, extra?._meta);
1140
+ return withErrorCode(remoteResult(terminal, remote));
1141
+ }
1142
+ catch (e) {
1143
+ return withErrorCode(fail(e));
1144
+ }
1145
+ }
1131
1146
  const result = agentGoalWireResultSchema.parse(await core.agentGoal(agentGoalInputSchema.parse(args), origin));
1132
1147
  return { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: { ...result },
1133
1148
  ...(["rejected", "outcome_unknown", "unavailable", "unsupported"].includes(result.outcome) ? { isError: true } : {}) };
@@ -1195,6 +1210,7 @@ export function createAitermServer(options = {}) {
1195
1210
  cwd: z.string().nullish().describe("CLIを実行する作業ディレクトリ(絶対パス・任意)。project設定で候補が変わるharness向け"),
1196
1211
  include_hidden: z.boolean().optional().describe("Codexが一覧で隠すmodelも返す(既定false)。他のharnessには隠すmodelが無い"),
1197
1212
  configuration_root: z.string().min(1).optional().describe("claude-code harnessだけ。一覧を読むアカウントの設定root(CLAUDE_CONFIG_DIR)。受ける範囲はagent_launchと同じ(既定のroot、またはAITERM_CLAUDE_CONFIG_ROOTSに並べた親の直下)。他はAGENT_CONFIGURATION_ROOT_REJECTED。省略は既定のroot"),
1213
+ claude_login: z.string().min(1).optional().describe("claude-code harnessだけ。一覧を読むlogin(slot名、例 1st)。AITERM_CLAUDE_CONFIG_ROOTSの下の<slot>/oauth-tokenを、席の起動と同じCLAUDE_CODE_OAUTH_TOKENとして使う。tokenはAitermの外へ出さない。読めない時はCLAUDE_LOGIN_UNAVAILABLE。省略はこのAitermのenvのlogin"),
1198
1214
  },
1199
1215
  outputSchema: {
1200
1216
  schema: z.literal("aiterm.agent-models.v1"),
@@ -1207,9 +1223,9 @@ export function createAitermServer(options = {}) {
1207
1223
  fast_unavailable: fastModeFailureSchema.nullable().optional().describe("このアカウント・この端末では、どのmodelでもfastを使えない時の訳(harnessが先に答えられる時だけ。今はClaude Code)。使える・分からない時はnull"),
1208
1224
  models: z.array(agentModelChoiceSchema),
1209
1225
  },
1210
- }, async ({ harness, cwd, include_hidden, configuration_root }) => {
1226
+ }, async ({ harness, cwd, include_hidden, configuration_root, claude_login }) => {
1211
1227
  try {
1212
- const catalog = await core.listAgentModels(kindForHarness(harness), { cwd, include_hidden, configuration_root });
1228
+ const catalog = await core.listAgentModels(kindForHarness(harness), { cwd, include_hidden, configuration_root, claude_login });
1213
1229
  const result = agentModelsResult(harness, catalog);
1214
1230
  return {
1215
1231
  content: [{ type: "text", text: JSON.stringify(result) }],
@@ -26,6 +26,10 @@ export function setPrivateEnv(env) {
26
26
  for (const [name, value] of Object.entries(env))
27
27
  values.set(name, value);
28
28
  }
29
+ /** A value that came only on the private stdin line, never this process's env. */
30
+ export function privateEnvValue(name) {
31
+ return values.get(name);
32
+ }
29
33
  /** The value a launch uses for an env_vars name: the private value first, then this process's env. */
30
34
  export function launchEnvValue(name, env = process.env) {
31
35
  return values.get(name) ?? env[name];
@@ -8,6 +8,33 @@ import { AitermError } from "./errors.js";
8
8
  import { lazyRelayExecutable } from "./lazy-relay.js";
9
9
  import { isWin } from "./tmux-runtime.js";
10
10
  import { resolveWindowsPowerShell7 } from "./windows-powershell.js";
11
+ /**
12
+ * The named variables of one live process's environment (null = unset), or null when this OS gives no way to read it.
13
+ * Linux reads /proc/<pid>/environ; macOS reads `ps -wwE`, which prints the environment after the arguments.
14
+ */
15
+ export function readProcessEnvironment(pid, names, platform = process.platform, psOutput) {
16
+ if (platform === "linux" && psOutput === undefined) {
17
+ let raw;
18
+ try {
19
+ raw = fs.readFileSync(`/proc/${pid}/environ`, "utf8");
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ const env = new Map(raw.split("\0").filter(Boolean).map(entry => [entry.slice(0, entry.indexOf("=")), entry.slice(entry.indexOf("=") + 1)]));
25
+ return Object.fromEntries(names.map(name => [name, env.get(name) ?? null]));
26
+ }
27
+ if (platform !== "darwin")
28
+ return null;
29
+ if (psOutput === undefined) {
30
+ const ps = spawnSync("/bin/ps", ["-wwE", "-p", String(pid), "-o", "command="], { encoding: "utf8", timeout: 5000, env: { ...process.env, LC_ALL: "C" } });
31
+ if (ps.error || ps.status !== 0 || !ps.stdout.trim())
32
+ return null;
33
+ psOutput = ps.stdout;
34
+ }
35
+ // shortcut: ps joins entries with spaces, so a value with a space is cut there; Aiterm's values (token, root path) have none.
36
+ return Object.fromEntries(names.map(name => [name, [...psOutput.trimEnd().matchAll(new RegExp(`(?:^| )${name}=(\\S*)`, "gu"))].at(-1)?.[1] ?? null]));
37
+ }
11
38
  /** Claude's native macOS keep-awake helper does no user work of its own. */
12
39
  export function macKeepAwakeProcess(row, harness, platform = process.platform) {
13
40
  const started = Date.parse(row.started_identity), parentStarted = Date.parse(harness?.started_identity ?? "");
package/dist/remote.js CHANGED
@@ -221,6 +221,7 @@ export const WINDOWS_STDIN_SCRIPT_COMMAND = powershellForShell("cmd", "Invoke-Ex
221
221
  export function remoteServerCommand(shell) {
222
222
  return shell === "posix" ? posixCommand("exec aiterm-mcp") : "aiterm-mcp";
223
223
  }
224
+ export const REMOTE_CLIENT_NAME = "aiterm-remote";
224
225
  /** 現地のaiterm-mcpへ1回だけMCP接続し、指定toolを呼んで閉じる。privateEnvは暗号化されたstdinの先頭行だけで渡す(remote-terminal.md R5)。 */
225
226
  export async function callRemoteTool(target, name, args, timeoutMs = 600_000, privateEnv, meta) {
226
227
  if (privateEnv && !target.trusted_ref)
@@ -236,7 +237,7 @@ export async function callRemoteTool(target, name, args, timeoutMs = 600_000, pr
236
237
  let stderr = "";
237
238
  if (transport instanceof StdioClientTransport)
238
239
  transport.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString("utf8")).slice(-2000); });
239
- const client = new Client({ name: "aiterm-remote", version: pkg.version });
240
+ const client = new Client({ name: REMOTE_CLIENT_NAME, version: pkg.version });
240
241
  try {
241
242
  try {
242
243
  await client.connect(transport, { timeout: 60_000 });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.70.28",
3
+ "version": "0.70.29",
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": [