aiterm-mcp 0.70.27 → 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,17 @@ 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
+
17
+ ## [0.70.28] - 2026-11-11
18
+
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.
20
+
10
21
  ## [0.70.27] - 2026-11-11
11
22
 
12
23
  - `pty_list` now lists a Claude agent seat whose terminal is gone with no lifecycle record (for example, it vanished with a container restart) as `current_command: "vanished"`, with its `last_input_at` and `limit_end`. Before, such a seat had no row until the next send adopted it, so a restart dropped a limit-held seat's record. Seat turns read it as idle. The next send still adopts and resumes it as before.
@@ -3314,7 +3325,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3314
3325
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3315
3326
  provenance.
3316
3327
 
3317
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.27...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
3330
+ [0.70.28]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.27...v0.70.28
3318
3331
  [0.70.27]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.26...v0.70.27
3319
3332
  [0.70.26]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.25...v0.70.26
3320
3333
  [0.70.25]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.24...v0.70.25
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.27** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.70.29** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
219
219
 
220
220
  ### 更新と巻き戻し
221
221
 
@@ -873,7 +873,7 @@ Owner認証済みの本体だけが、既存のローカルbellteam MCP接続に
873
873
 
874
874
  結果は正本のbinding、capabilities、availability、outcome、mutation、readbackを分ける。goal省略は未確認、availableかつgoal:nullだけが「ゴールなし」。createのactiveを含む明示要求fieldは全て正規読戻しとの一致を確認する。変化した状態は観測値を残して結果不明とし、再送しない。clearは現在turnの停止ではなく、resumeはpausedから、目的を変える編集はCodexの使用量を初期化する。Ownerの明示的な全体停止だけ、native delivery入口のagent_stopへpause_goals:trueと同じuser metadataを渡す。子のgoal一時停止と停止キー一回を親より先に完了し、独立rootは並行する。goal未確認はキー送信済みでもpartialを保持。通常の一Bot中断のwireは維持し、AI ONでgoalを暗黙に再開しない。
875
875
 
876
- Claude Code 2.1.310は同じ生存TUIへのinspectと利用者由来create・目的文edit・clearに対応する。空のcomposerと元TTY所有を確認し、新しいnative goal dialogと同native root sessionのattachmentを照合し、確認したdialogだけを閉じる。draftは消さず、未知/切れた表示はunavailable。Claude結果はaiterm.agent-goal-result.v2で、goalはnull又は{kind:claude-code,phase:active,native,reported_turns?}。達成と明示clearは別native_historyへ保持し、欠測会計は作らない。Codexのv1は維持。Claude pause/resumeは未対応で、全体停止でもactive goalのpause未確認を保持する。
876
+ Claude Code 2.1.310以上の2.1系(実測2.1.310・2.1.322)は同じ生存TUIへのinspectと利用者由来create・目的文edit・clearに対応する。空のcomposerと元TTY所有を確認し、新しいnative goal dialogと同native root sessionのattachmentを照合し、確認したdialogだけを閉じる。draftは消さず、未知/切れた表示はunavailable。Claude結果はaiterm.agent-goal-result.v2で、goalはnull又は{kind:claude-code,phase:active,native,reported_turns?}。達成と明示clearは別native_historyへ保持し、欠測会計は作らない。Codexのv1は維持。それ以外の版は入力前に`availability:"unsupported"`、reason `claude_code_version_unverified:<版>`。Claude pause/resumeは未対応で、全体停止でもactive goalのpause未確認を保持する。
877
877
 
878
878
  Claude公式claude.com/cai/oauth/authorizeのPKCE認証要求と非秘密code=true表示flagを認識する。callbackの認可codeやtokenは公開しない。
879
879
 
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.27** · 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
 
@@ -945,7 +945,7 @@ Only an authenticated host action may stamp MCP metadata `{"aiterm/goal":{"origi
945
945
 
946
946
  `aiterm.agent-goal-result.v1` includes native binding, per-action capabilities, availability, operation outcome, mutation acknowledgment, and readback status. A missing goal field is unknown; `available` with `goal:null` is an authoritative empty goal. All explicitly requested native fields, including the active status requested by create, must match the readback. A changed result remains unknown with the observed native state. Unknown mutations are never retried. `clear` does not interrupt a running turn, `resume` requires `paused`, and a new objective resets Codex usage accounting. For an explicit Owner whole-application stop, the native delivery entry accepts `agent_stop` with `pause_goals:true` and the same user metadata. Each selected descendant completes goal pause and one ordinary interruption key before its parent; independent roots proceed concurrently. Unconfirmed goal pause stays partial even when a key was sent. Ordinary per-Bot interruption is unchanged, and enabling AI does not resume goals.
947
947
 
948
- Claude Code 2.1.310 supports `inspect` and user-authorized `create`, objective-only `edit`, and `clear` on the same live TUI. It opens the native goal dialog from a strictly empty composer, verifies the original TTY owner, combines the fresh dialog with matching native root-session attachments, and dismisses only the recognized dialog. A draft or unknown viewport returns unavailable without clearing it. Wrapped conditions that cannot be matched exactly remain unavailable. Claude replies use `aiterm.agent-goal-result.v2`: `goal` is null or `{kind:"claude-code",phase:"active",native,reported_turns?}`, with an optional separate `native_history` for achieved versus explicitly cleared goals. Missing native accounting stays missing. Codex replies retain v1. Claude pause/resume remain unsupported; whole-app stop must retain an active Claude goal as unconfirmed when native pause is unsupported.
948
+ Claude Code 2.1.310 and later 2.1 releases (measured on 2.1.310 and 2.1.322) support `inspect` and user-authorized `create`, objective-only `edit`, and `clear` on the same live TUI. It opens the native goal dialog from a strictly empty composer, verifies the original TTY owner, combines the fresh dialog with matching native root-session attachments, and dismisses only the recognized dialog. A draft or unknown viewport returns unavailable without clearing it. Wrapped conditions that cannot be matched exactly remain unavailable. Claude replies use `aiterm.agent-goal-result.v2`: `goal` is null or `{kind:"claude-code",phase:"active",native,reported_turns?}`, with an optional separate `native_history` for achieved versus explicitly cleared goals. Missing native accounting stays missing. Codex replies retain v1. Another Claude version returns `availability: "unsupported"` with reason `claude_code_version_unverified:<version>` before any input. Claude pause/resume remain unsupported; whole-app stop must retain an active Claude goal as unconfirmed when native pause is unsupported.
949
949
 
950
950
  Claude authorization receipts recognize the official `claude.com/cai/oauth/authorize` PKCE request and its nonsecret `code=true` display flag. Callback authorization codes and tokens remain excluded.
951
951
 
@@ -167,6 +167,8 @@ export async function manageClaudeAgentGoal(input, runtime, origin = "automatic"
167
167
  return { ...result, outcome: "outcome_unknown", mutation: "outcome_unknown", readback: "failed", reason: "native_goal_mutation_unconfirmed" };
168
168
  const reasons = new Set(["native_goal_status_input_unconfirmed", "native_goal_fresh_dialog_unavailable", "native_goal_dialog_changed", "native_goal_binding_mismatch"]);
169
169
  const reason = error instanceof AgentGoalNotIssuedError ? error.reason : error instanceof Error && reasons.has(error.message) ? error.message : "native_goal_fresh_status_unavailable";
170
+ if (error instanceof AgentGoalNotIssuedError && error.outcome === "unsupported")
171
+ return { ...result, availability: "unsupported", outcome: "unsupported", reason };
170
172
  return { ...result, reason, readback: "failed" };
171
173
  }
172
174
  }
@@ -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);
@@ -6021,9 +6022,9 @@ async function agentGoalInContext(input, origin, expectedGoal, sendHeld = false)
6021
6022
  throw new ExecutionError("EXECUTION_STALE_GENERATION");
6022
6023
  const tty = paneTtyOf(input.session_id);
6023
6024
  const owner = target.native_process;
6024
- const rejectOwner = (reason = "goal_input_owner_unavailable") => {
6025
+ const rejectOwner = (reason = "goal_input_owner_unavailable", outcome) => {
6025
6026
  if (!inputStarted)
6026
- throw new AgentGoalNotIssuedError(reason);
6027
+ throw new AgentGoalNotIssuedError(reason, outcome);
6027
6028
  throw new Error("Goal input owner changed after input began");
6028
6029
  };
6029
6030
  if (target.harness === "claude-code") {
@@ -6040,6 +6041,8 @@ async function agentGoalInContext(input, origin, expectedGoal, sendHeld = false)
6040
6041
  rejectOwner("goal_native_session_unavailable");
6041
6042
  }
6042
6043
  const ownership = generation && owner ? claudeCurrentSessionOwner(registration, { pid: owner.pid, sessionId: target.vendor_session_id, ...generation }) : "unavailable";
6044
+ if (typeof ownership === "object")
6045
+ rejectOwner(`claude_code_version_unverified:${ownership.unsupported}`, "unsupported");
6043
6046
  if (ownership !== "match")
6044
6047
  rejectOwner(ownership === "mismatch" ? "goal_native_session_mismatch" : "goal_native_session_unavailable");
6045
6048
  }
@@ -6297,11 +6300,35 @@ export async function configureAgent(name, opts, expectedLaunchId) {
6297
6300
  throw failure;
6298
6301
  }
6299
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
+ }
6300
6325
  /** 返りの null は、席の画面が番の最中を示していて、何も打っていない時。 */
6301
6326
  async function configureAgentInLock(name, model, effort, fast, beforeChange) {
6302
6327
  // 席の控えは、行列の順番が来てから読む(前の送信が書いた分を、古い控えで上書きしない)。
6303
6328
  const meta = loadAgentMetadata(name);
6304
6329
  bindCompletedInitialPrompt(meta);
6330
+ let seatEnv;
6331
+ const claudeSeatEnv = () => seatEnv === undefined ? (seatEnv = claudeSeatCatalogEnv(name, meta)) : seatEnv;
6305
6332
  // Codexは回答を流している間、動作中の行を出さない(ADR 0101)。送信と同じく記録の番の開始を見て、動いている席へ命令を打たない。
6306
6333
  if (isAgentTuiBusy(meta.kind, captureScreen(name, AGENT_TUI_READY_LINES))
6307
6334
  || (meta.kind === "codex" && codexRunningTurn(meta) !== null && observeSession(name).harness_alive === true))
@@ -6378,7 +6405,7 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
6378
6405
  if (target === undefined) {
6379
6406
  throw new FastModeError("FAST_MODE_UNCONFIRMED", `この席のmodelが控えに無く(前の版のAitermが起こした席)、fastの対応を確かめられません。modelも渡してください。${untouched}`);
6380
6407
  }
6381
- 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() });
6382
6409
  if (unavailable)
6383
6410
  throw new FastModeError("FAST_MODE_UNAVAILABLE", `${unavailable.message.replace(/^FAST_MODE_UNAVAILABLE: /, "")}${untouched}`);
6384
6411
  }
@@ -6394,7 +6421,7 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
6394
6421
  const bin = meta.agent_executable ?? resolveAgentBin(meta.kind);
6395
6422
  if (!bin)
6396
6423
  return;
6397
- 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);
6398
6425
  if (!catalog.fast_ids?.[model])
6399
6426
  recordAgentFast(meta, false);
6400
6427
  };
@@ -6405,7 +6432,7 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
6405
6432
  throw new AitermError("Claude Code の reasoning_effort は low/medium/high/xhigh/max/ultracode のいずれかです。設定は変えていません。", 2);
6406
6433
  }
6407
6434
  if (model || level)
6408
- 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);
6409
6436
  if (effort && !level) {
6410
6437
  beforeChange();
6411
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));
@@ -1,11 +1,19 @@
1
1
  // Claude owns goal state. A fresh local status command, never a historical
2
2
  // attachment alone, establishes current state for the bound native session.
3
3
  import { z } from "zod";
4
- const currentSessionSchema = z.object({ pid: z.number().int().positive(), sessionId: z.string().uuid(), procStart: z.string().regex(/^\d+$/u), pidDomain: z.string(), version: z.literal("2.1.310"), kind: z.literal("interactive") });
4
+ // Measured /goal surface: 2.1.310 and 2.1.322 (dialog, attachment, sessions/<pid>.json).
5
+ // Patch updates of the 2.1 line keep it; every step below still proves the screen and records.
6
+ export function claudeGoalVersionSupported(version) {
7
+ const patch = typeof version === "string" ? /^2\.1\.(\d+)$/u.exec(version)?.[1] : undefined;
8
+ return patch !== undefined && Number(patch) >= 310;
9
+ }
10
+ const currentSessionSchema = z.object({ pid: z.number().int().positive(), sessionId: z.string().uuid(), procStart: z.string().regex(/^\d+$/u), pidDomain: z.string(), version: z.string(), kind: z.literal("interactive") });
5
11
  export function claudeCurrentSessionOwner(record, expected) {
6
12
  const parsed = currentSessionSchema.safeParse(record);
7
13
  if (!parsed.success || parsed.data.pid !== expected.pid || parsed.data.procStart !== expected.procStart || parsed.data.pidDomain !== expected.pidDomain)
8
14
  return "unavailable";
15
+ if (!claudeGoalVersionSupported(parsed.data.version))
16
+ return { unsupported: parsed.data.version };
9
17
  return parsed.data.sessionId === expected.sessionId ? "match" : "mismatch";
10
18
  }
11
19
  export const claudeNativeGoalStatusSchema = z.object({
@@ -23,7 +31,7 @@ export const claudeGoalHistorySchema = z.object({
23
31
  kind: z.literal("claude-code"), terminal: z.enum(["achieved", "cleared"]), native: claudeNativeGoalStatusSchema,
24
32
  }).strict();
25
33
  const querySchema = z.object({ uuid: z.string().min(1), timestamp: z.string().datetime(),
26
- sessionId: z.string().min(1), isSidechain: z.literal(false), version: z.literal("2.1.310"),
34
+ sessionId: z.string().min(1), isSidechain: z.literal(false), version: z.string().refine(claudeGoalVersionSupported),
27
35
  type: z.literal("system"), subtype: z.literal("local_command"), content: z.string(),
28
36
  commandRun: z.object({ command: z.literal("goal"), args: z.literal("") }),
29
37
  });
@@ -125,8 +133,8 @@ export function claudeGoalComposerEmpty(screen) {
125
133
  }
126
134
  export function observeClaudeGoalDialog(screen, rows, sessionId) {
127
135
  const lines = plain(screen).split("\n").map(line => line.trim());
128
- const knownVersion = lines.some(line => /Claude Code v2\.1\.310(?:\s|$)/u.test(line))
129
- || rows.some(value => { const row = value; return row?.sessionId === sessionId && row.isSidechain === false && row.version === "2.1.310"; });
136
+ const knownVersion = lines.some(line => claudeGoalVersionSupported(/Claude Code v(\S+)(?:\s|$)/u.exec(line)?.[1]))
137
+ || rows.some(value => { const row = value; return row?.sessionId === sessionId && row.isSidechain === false && claudeGoalVersionSupported(row.version); });
130
138
  if (!knownVersion)
131
139
  return null;
132
140
  let end = lines.length - 1;
@@ -140,7 +148,7 @@ export function observeClaudeGoalDialog(screen, rows, sessionId) {
140
148
  const row = value;
141
149
  if (row?.type !== "attachment" || row.attachment?.type !== "goal_status")
142
150
  continue;
143
- if (row.sessionId !== sessionId || row.isSidechain !== false || row.version !== "2.1.310")
151
+ if (row.sessionId !== sessionId || row.isSidechain !== false || !claudeGoalVersionSupported(row.version))
144
152
  throw new Error("native_goal_binding_mismatch");
145
153
  const native = claudeNativeGoalStatusSchema.parse(row.attachment);
146
154
  if (native.met) {
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.27",
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": [