aiterm-mcp 0.63.17 → 0.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.64.0] - 2026-11-08
11
+
12
+ - Per-seat Claude configuration roots (hosts with several Claude accounts). `agent_launch` (claude-code) and `claude_agent` accept `configuration_root`: the default root (`~/.claude`; the seat then runs with `CLAUDE_CONFIG_DIR` unset) or a directory directly under a parent listed in `AITERM_CLAUDE_CONFIG_ROOTS` (path-delimited) of the MCP process. The seat runs with that `CLAUDE_CONFIG_DIR`, and the resume recipe keeps it. Any other path, another harness, or `env_vars` containing `CLAUDE_CONFIG_DIR` together with it answer `AGENT_CONFIGURATION_ROOT_REJECTED` before a seat is created. `AITERM_CLAUDE_CONFIG_ROOTS` never reaches a seat's environment, so a seat's own Aiterm can use only the default root.
13
+ - Resuming a hibernated Claude seat (`session_name`, optionally `require_existing_resume`) with a different `configuration_root` keeps the same conversation under the new root when `<root>/projects/<cwd slug>/<vendor_session_id>.jsonl` exists there. Otherwise it answers `AGENT_RESUME_UNAVAILABLE` (resume-only) or `AGENT_RESUME_CONFLICT`, and nothing starts. All other settings must still match the saved recipe.
14
+ - `agent_auth` (claude-code) accepts `configuration_root` for start, status, respond and cancel. Login and status run under that root. A session started under one root refuses another root. An `authenticated` result carries `account_label`: the e-mail from `claude auth status --json`, display text only, or null.
15
+ - `pty_close` takes `hibernate: true` for Claude and Codex agent seats. It stops the seat now through the idle clock's stopping → hibernated lifecycle, keeps the conversation and resume recipe, and returns outcome `hibernated`. The next `agent_launch` with that `session_name` resumes it. A running turn, unfinished turn end, post-startup child processes or pending child deliveries answer `AGENT_BUSY: <reason>` and leave the seat as it was. Other cases answer `AGENT_HIBERNATE_UNAVAILABLE: <reason>`. A Claude turn that ended on a rate limit counts as ended at that transcript error, even while the CLI waits in its limit footer or menu, and the saved recipe is used. The idle clock itself is unchanged.
16
+ - A Claude transcript error "You've hit your <word> limit" (for example weekly) is `failure.category: rate_limited` even without HTTP 429.
17
+
18
+ ## [0.63.18] - 2026-11-08
19
+
20
+ - `pty_read(agent_transcript:true, input_id)` reads the Claude answer of the input that `pty_send` returned in its dispatch receipt. It selects that input's `agent_done` and does not refuse because a later turn is active, so a reply typed right after a turn ends no longer breaks the read of the previous answer. The answer is returned only while the per-launch result file still holds that event's digest and bytes. No completion yet answers `AITERM_TRANSCRIPT_INPUT_PENDING`; a result already replaced by a later turn answers `AITERM_TRANSCRIPT_INPUT_REPLACED`. `input_id` with a non-Claude session or with `operation_id` is an argument error. structuredContent is unchanged.
21
+ - Transcript read errors now start with a code token, rendered as `aiterm: <CODE>: <text>`: `TRANSCRIPT_TURN_ACTIVE` (an unbound Claude read while a turn is active), `TRANSCRIPT_UNAVAILABLE`, `TRANSCRIPT_NOT_FOUND` and `TRANSCRIPT_RESULT_MISMATCH`. Match the token, not the text.
22
+ - The macOS CI job removes Aiterm test tmux servers left by a cancelled or timed-out job before and after it runs.
23
+
10
24
  ## [0.63.17] - 2026-11-08
11
25
 
12
26
  - A managed seat whose native terminal vanished while its records survived (for example after a container restart emptied tmux) is no longer refused with `AGENT_RESUME_UNCONFIRMED: 作成したnative端末が置き換わっています。` on every send. When the native list is known and the seat has no lifecycle or pending resume, an ordinary `pty_send`/dispatch records the existing `origin:restart` hibernation and cold-resumes the same Claude or Codex conversation, then delivers the body. A seat that cannot be resumed (other harnesses, missing vendor conversation, recipe or proof) answers `AGENT_SESSION_REQUIRED` with nothing sent and its records unchanged, so a fresh `agent_launch` under the same name reaches it. Unknown native state and live natives keep their existing checks.
@@ -3088,7 +3102,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3088
3102
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3089
3103
  provenance.
3090
3104
 
3091
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.17...HEAD
3105
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.64.0...HEAD
3106
+ [0.64.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.18...v0.64.0
3107
+ [0.63.18]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.17...v0.63.18
3092
3108
  [0.63.17]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.16...v0.63.17
3093
3109
  [0.63.16]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.15...v0.63.16
3094
3110
  [0.63.15]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.14...v0.63.15
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.63.17** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.64.0** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
219
219
 
220
220
  ### 更新と巻き戻し
221
221
 
@@ -611,7 +611,7 @@ Claudeの相関済み承認は既存の`claude_approval`を使う。
611
611
  | --- | --- | --- |
612
612
  | `pty_open` | 端末を1個開き`session_id`を返す | `name?`, `shell?`, `env_vars?` |
613
613
  | `pty_send` | テキストを送る。agent sessionでは子のturnが実行中なら現在のturnへ差し込み(`agent_steer`)、それ以外は非ブロックdispatchとして`event_cursor`を返す(`agent_dispatch`)。差し込みでGrokが待ち行列へ入れない時とCursorの入力欄に残った時は失敗する | `session_id`, `text`, `enter=true`, `mark`, `force`, `require_agent=false`, `preface`, `rtk`, `raw` |
614
- | `pty_read` | 出力を削減して読む(既定は増分) | `session_id`, `wait`, `until`, `until_regex`, `timeout`, `screen`, `full`, `lines`, `line_range`, `raw`, `rtk`, `agent_transcript`, `operation_id` |
614
+ | `pty_read` | 出力を削減して読む(既定は増分) | `session_id`, `wait`, `until`, `until_regex`, `timeout`, `screen`, `full`, `lines`, `line_range`, `raw`, `rtk`, `agent_transcript`, `operation_id`, `input_id` |
615
615
  | `pty_key` | 制御キーを送る | `session_id`, `key`(`C-c`/`Enter`/`Up`…) |
616
616
  | `pty_close` | 冪等に閉じ、`closed` / `already_closed`を返す | `session_id` |
617
617
  | `pty_list` | textと構造化したsession一覧。管理対象の起動ID `launch_id` は一覧取得時の値で、通常PTYやmetadata不明時はnull、旧remote版は省略。操作前の最新の紐付け確認は引き続き必要。明示した非秘密環境変数も照会できる | `env_keys?` |
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.63.17** · 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.64.0** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
231
231
 
232
232
  ### Update and rollback
233
233
 
@@ -651,7 +651,7 @@ continue to use `claude_approval`.
651
651
  | --- | --- | --- |
652
652
  | `pty_open` | Open one terminal and return a `session_id` | `name?`, `shell?`, `env_vars?` |
653
653
  | `pty_send` | Send text. On an agent session Aiterm picks the route when it sends: if the child's turn is running, it steers the text into that turn (`agent_steer`); otherwise it is a non-blocking **dispatch** returning an `event_cursor` (`agent_dispatch`). Steering fails when Grok does not queue the text or Cursor leaves it in the composer | `session_id`, `text`, `enter=true`, `mark`, `force`, `require_agent=false`, `preface`, `rtk`, `raw` |
654
- | `pty_read` | Read output, token-reduced (incremental by default) | `session_id`, `wait`, `until`, `until_regex`, `timeout`, `screen`, `full`, `lines`, `line_range`, `raw`, `rtk`, `agent_transcript`, `operation_id` |
654
+ | `pty_read` | Read output, token-reduced (incremental by default) | `session_id`, `wait`, `until`, `until_regex`, `timeout`, `screen`, `full`, `lines`, `line_range`, `raw`, `rtk`, `agent_transcript`, `operation_id`, `input_id` |
655
655
  | `pty_key` | Send a control key | `session_id`, `key` (`C-c`/`Enter`/`Up`…) |
656
656
  | `pty_close` | Close idempotently; return `closed` / `already_closed` | `session_id` |
657
657
  | `pty_list` | Text and structured session list (managed sessions include snapshot `launch_id` and harness conversation ID `vendor_session_id`; `launch_id` is null for ordinary/unmanaged PTYs and may be absent on older remote versions, so callers retain fresh binding checks before operations), with explicitly requested non-secret environment values | `env_keys?` |
@@ -6,15 +6,20 @@ export function idleMinutes(value = process.env.AITERM_IDLE_MINUTES) {
6
6
  throw new Error("AITERM_IDLE_MINUTES must be a positive finite duration");
7
7
  return minutes;
8
8
  }
9
- export function decideIdleSeat(seat, now, minutes = 30, expectedAnchor) {
9
+ /**
10
+ * `immediate` is an explicit hibernate request: no deadline and no attachment refusal. A Claude turn that ended on a
11
+ * rate limit (no Stop event; the CLI then waits in its limit footer or menu) counts as ended at that error.
12
+ */
13
+ export function decideIdleSeat(seat, now, minutes = 30, expectedAnchor, immediate = false) {
10
14
  const result = { outcome: "skipped", reason: "observation_unconfirmed", anchor: null, due_at: null, stalled: false };
11
- if (!Number.isFinite(now) || !Number.isFinite(minutes * 60_000) || minutes <= 0)
15
+ if (!Number.isFinite(now) || (!immediate && (!Number.isFinite(minutes * 60_000) || minutes <= 0)))
12
16
  return result;
13
- if (seat.state !== "idle" || seat.reason !== "composer_ready")
17
+ const limited = immediate && seat.rate_limited_at ? seat.rate_limited_at : null;
18
+ if (!limited && (seat.state !== "idle" || seat.reason !== "composer_ready"))
14
19
  return { ...result, reason: seat.state === "busy" ? "turn_running" : seat.state,
15
20
  stalled: seat.state === "busy" && seat.window_activity_at !== null && Number.isFinite(seat.window_activity_at)
16
21
  && now - seat.window_activity_at >= 60 * 60_000 };
17
- if (seat.attached !== false)
22
+ if (!immediate && seat.attached !== false)
18
23
  return { ...result, reason: seat.attached === true ? "attached" : "attachment_unconfirmed" };
19
24
  if (seat.pending_child_deliveries !== 0)
20
25
  return { ...result, reason: "child_delivery_pending_or_unknown" };
@@ -24,25 +29,26 @@ export function decideIdleSeat(seat, now, minutes = 30, expectedAnchor) {
24
29
  return { ...result, reason: "conversation_id_unavailable" };
25
30
  if (!seat.resume_ready)
26
31
  return { ...result, reason: "resume_unavailable" };
27
- if (seat.turn_settled !== true)
32
+ if (!limited && seat.turn_settled !== true)
28
33
  return { ...result, reason: "turn_end_unconfirmed" };
29
- const anchor = seat.activity.last_turn_end_at ?? (!seat.activity.tracked ? seat.created_at : null);
34
+ const anchor = limited ?? seat.activity.last_turn_end_at ?? (!seat.activity.tracked ? seat.created_at : null);
30
35
  if (anchor === null || !Number.isFinite(Date.parse(anchor)))
31
36
  return { ...result, reason: "turn_end_time_unavailable" };
32
37
  const input = seat.activity.last_input_at;
33
38
  if (input !== null && (!Number.isFinite(Date.parse(input)) || Date.parse(input) > Date.parse(anchor)))
34
39
  return { ...result, reason: "input_without_turn_end" };
35
- const due = Date.parse(anchor) + minutes * 60_000;
40
+ const due = Date.parse(anchor) + (immediate ? 0 : minutes * 60_000);
36
41
  if (!Number.isFinite(due))
37
42
  return result;
38
43
  if (expectedAnchor !== undefined && expectedAnchor !== anchor)
39
44
  return { ...result, reason: "superseded_timer", anchor, due_at: due };
40
- if (now >= due && !seat.native_configuration_confirmed)
45
+ // A rate-limited CLI shows its limit footer or menu, not the composer the settings check reads; the saved recipe stands.
46
+ if (now >= due && !limited && !seat.native_configuration_confirmed)
41
47
  return { ...result, reason: "native_configuration_unconfirmed", anchor, due_at: due };
42
48
  return { ...result, outcome: now < due ? "not_due" : "ready", reason: now < due ? "before_deadline" : "idle_timeout", anchor, due_at: due };
43
49
  }
44
50
  /** The owner supplies the same seat admission used by input; no independent queue is created. */
45
- export async function checkIdleSeat(runtime, expectedLaunch, minutes = 30, expectedAnchor) {
51
+ export async function checkIdleSeat(runtime, expectedLaunch, minutes = 30, expectedAnchor, immediate = false) {
46
52
  return runtime.exclusive(async () => {
47
53
  let issued = false;
48
54
  let effectIssued = false;
@@ -53,14 +59,15 @@ export async function checkIdleSeat(runtime, expectedLaunch, minutes = 30, expec
53
59
  const lastInputAt = before.activity.last_input_at;
54
60
  result = before.launch_id !== expectedLaunch
55
61
  ? { outcome: "skipped", reason: "generation_replaced", anchor: null, due_at: null, stalled: false }
56
- : decideIdleSeat(before, runtime.now(), minutes, expectedAnchor);
62
+ : decideIdleSeat(before, runtime.now(), minutes, expectedAnchor, immediate);
57
63
  if (result.outcome === "ready") {
58
64
  const anchor = result.anchor;
59
65
  const verify = () => {
60
66
  const current = runtime.snapshot();
61
- const decision = decideIdleSeat(current, runtime.now(), minutes, anchor);
67
+ const decision = decideIdleSeat(current, runtime.now(), minutes, anchor, immediate);
68
+ // After the stop signal, an explicit hibernate only requires that no new input arrived (the stopping CLI may redraw anything).
62
69
  if (current.launch_id !== expectedLaunch || current.activity.last_input_at !== lastInputAt
63
- || (effectIssued ? current.attached === true || ["busy", "blocked"].includes(current.state) : decision.outcome !== "ready"))
70
+ || (effectIssued ? !immediate && (current.attached === true || ["busy", "blocked"].includes(current.state)) : decision.outcome !== "ready"))
64
71
  throw new Error("idle_precondition_changed");
65
72
  };
66
73
  verify();
@@ -0,0 +1,43 @@
1
+ // Claude Codeの設定root(CLAUDE_CONFIG_DIR)を席・認証ごとに選ぶ時の受入。資格情報は読まない。
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { AitermError } from "./errors.js";
6
+ const rejected = (detail) => new AitermError(`AGENT_CONFIGURATION_ROOT_REJECTED: ${detail}`, 2);
7
+ const real = (value) => { try {
8
+ return fs.realpathSync(value);
9
+ }
10
+ catch {
11
+ return null;
12
+ } };
13
+ export function claudeDefaultConfigRoot(env = process.env) {
14
+ return path.join(env.HOME ?? os.homedir(), ".claude");
15
+ }
16
+ /**
17
+ * Accept the default root, or a direct child of a parent listed in AITERM_CLAUDE_CONFIG_ROOTS.
18
+ * Protects against running a seat or a login on credentials of an unintended directory.
19
+ */
20
+ export function resolveClaudeConfigurationRoot(requested, env = process.env) {
21
+ if (!path.isAbsolute(requested))
22
+ throw rejected("configuration_rootは絶対パスで指定してください。");
23
+ const fallback = path.resolve(claudeDefaultConfigRoot(env));
24
+ const actual = real(requested);
25
+ if (path.resolve(requested) === fallback || (actual !== null && actual === real(fallback)))
26
+ return { root: fallback, selector: null };
27
+ if (actual === null || !fs.statSync(actual).isDirectory())
28
+ throw rejected("configuration_rootのディレクトリがありません。");
29
+ const parents = (env.AITERM_CLAUDE_CONFIG_ROOTS ?? "").split(path.delimiter)
30
+ .filter(parent => path.isAbsolute(parent)).map(real).filter(parent => parent !== null);
31
+ if (!parents.includes(path.dirname(actual)))
32
+ throw rejected("configuration_rootは既定のroot(~/.claude)か、AITERM_CLAUDE_CONFIG_ROOTSに並べた親の直下のディレクトリだけです。");
33
+ return { root: actual, selector: actual };
34
+ }
35
+ /** The same environment with this root selected. */
36
+ export function withClaudeConfigRoot(env, selected) {
37
+ const next = { ...env };
38
+ if (selected.selector === null)
39
+ delete next.CLAUDE_CONFIG_DIR;
40
+ else
41
+ next.CLAUDE_CONFIG_DIR = selected.selector;
42
+ return next;
43
+ }
package/dist/core.js CHANGED
@@ -51,6 +51,7 @@ import { paneTokenHint } from "./harnesses/pane-tokens.js";
51
51
  import { unfinishedDeliveriesOwnedBy } from "./parent-delivery-owners.js";
52
52
  import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, signalRuntimeProcess, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, macKeepAwakeProcess, processElapsedSeconds } from "./process-runtime.js";
53
53
  import { liveNodeExecutable } from "./live-node.js";
54
+ import { resolveClaudeConfigurationRoot, withClaudeConfigRoot } from "./claude-config-root.js";
54
55
  import { AitermError, AgentResumeUnavailableError, AgentResumeError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
55
56
  import { isWin, SOCKDIR, SOCK, tmuxCommand, readOnlyTmuxList, PtyDiagnosticError, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, } from "./tmux-runtime.js";
56
57
  import { AGENT_DEFAULT_PREFACE, sleep, currentUid, runtimeStateBase, safeStatSize, readFileRange, writeJson0600, createEmpty0600, shq, LAUNCH_ID_RE, AGENT_LINEAGE_RE, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, publishAgentGeneration, agentMetadataPath, writeAgentMetadata, AGENT_EVENT_TAIL_BYTES, agentLabel, agentHarness, subagentInstruction, } from "./agent-shared.js";
@@ -63,7 +64,7 @@ import { readFileOrNull, restoreJsonSetting, withUserConfigLock, restoreUserDefa
63
64
  import { isDeepStrictEqual } from "node:util";
64
65
  import { grokAuthPlan, grokAuthStatus, grokAuthPane, GROK_MODEL_DEFAULTS, realGrokHome, resolveAndValidateGrokAuth, assertGrokModelAvailable, grokModelChoices, grokModelFromFooter, grokFooterModelName, grokModelDefaultsFromBody, restoreGrokModelDefaults, grokEventsTranscript, grokSessionDirectory, latestGrokCompletion, grokTurnSettled, observeGrokDone, buildGrokAgentCmd, grokAgentArgv, grokLaunchNote, grokEnvTokens, grokEnvEntries, grokTuiReady, grokPaneObservation, GROK_INTERRUPT_KEY, grokRateLimitDialog, grokPromptAwaitingAccept, grokUnacceptedPromptRestored, grokStartupAction, grokFooterHasConfiguration, grokTranscriptText, createGrokAgentMetadata, } from "./harnesses/grok.js";
65
66
  import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexCompletedTurnId, codexWorkingResumeConfiguration, captureCodexRecoveryProof, captureCodexResumeProof, readCodexResumeProof, codexResumeProofDigest, codexRootTranscript, codexRunningTurn, codexInterruptionRecord, observeCodexDone, buildCodexAgentCmd, codexAgentArgv, codexResumeArgv, codexLaunchNote, codexPaneObservation, CODEX_INTERRUPT_KEY, codexHelperProcess, codexRateLimitModelSwitchDialog, codexApprovalDialog, codexStartupAction, codexModelChoice, codexEffortChoice, codexMoreReasoningChoice, codexTranscriptText, createCodexAgentMetadata, codexModelChoices, codexFastCommandOffered, codexFooterShowsFast, codexServiceTierNotices, restoreCodexDefaults, restoreCodexDefaultInFile, } from "./harnesses/codex.js";
66
- import { claudeAuthPlan, claudeAuthStatus, claudeAuthPane, OPERATION_ID_RE, CLAUDE_RESULT_MAX_BYTES, CLAUDE_EFFORTS, agentClaudeOperationPath, agentClaudeApprovalReceiptPath, agentClaudeDispatchReceiptPath, validateOperationId, readClaudeResultText, assertClaudeAuthenticationReady, claudeModelChoices, claudeConfigDir, claudeFastIndicatorShown, claudeFastResult, buildClaudeAgentCmd, claudeAgentArgv, claudeResumeArgv, claudeLaunchNote, claudePaneObservation, CLAUDE_INTERRUPT_KEY, claudeUsageLimit, claudeLiveSelectMenu, claudeStartupAction, createClaudeAgentMetadata, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, claudeFailureCategory, } from "./harnesses/claude.js";
67
+ import { claudeAuthPlan, claudeAuthStatus, claudeAuthPane, OPERATION_ID_RE, CLAUDE_RESULT_MAX_BYTES, CLAUDE_EFFORTS, agentClaudeOperationPath, agentClaudeApprovalReceiptPath, agentClaudeDispatchReceiptPath, validateOperationId, readClaudeResultText, assertClaudeAuthenticationReady, claudeModelChoices, claudeConfigDir, claudeProjectSlug, claudeFastIndicatorShown, claudeFastResult, buildClaudeAgentCmd, claudeAgentArgv, claudeResumeArgv, claudeLaunchNote, claudePaneObservation, CLAUDE_INTERRUPT_KEY, claudeUsageLimit, claudeLiveSelectMenu, claudeStartupAction, createClaudeAgentMetadata, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, claudeFailureCategory, } from "./harnesses/claude.js";
67
68
  import { cursorAuthPlan, cursorAuthStatus, cursorAuthPane, bindCursorTranscriptSession, cursorTurnBoundary, latestCursorCompletion, cursorTranscript, cursorTranscriptSessionId, observeCursorDone, cursorTranscriptText, assertCursorAuthenticationReady, assertCursorModelAvailable, cursorModelChoices, cursorModelIsFastVariant, cursorFastParameter, cursorHeaderShowsFast, cursorPickerView, cursorEffortSelected, cursorParameterRows, cursorUserConfigPath, CURSOR_DEFAULT_MODEL_KEYS, realCursorHome, buildCursorAgentCmd, cursorAgentArgv, cursorPromptWithLineage, createCursorAgentMetadata, cursorLaunchNote, cursorEffortNavigation, cursorTuiReady, cursorPaneObservation, CURSOR_INTERRUPT_KEY, cursorPromptHooksRunning, cursorUsageLimit, CURSOR_SUBMIT_SEQUENCE, validateCursorModelEffort, } from "./harnesses/cursor.js";
68
69
  import { interimFromNow, readInterimWords, recordInterimBoundary } from "./interim-words.js";
69
70
  import { codexSeatTurn, grokSteerAcceptance, observeSteerDone, readSteerEntry, recordSteer } from "./steer-follow.js";
@@ -1769,7 +1770,7 @@ export function observeSessionGeneration(name) {
1769
1770
  launch_id: exists ? tryLoadAgentMetadata(name)?.launch_id ?? null : null };
1770
1771
  }
1771
1772
  /** Internal lifecycle worker; not an MCP input route and never creates an effect scope. */
1772
- export async function checkAgentIdle(expectedInput, expectedAnchor) {
1773
+ export async function checkAgentIdle(expectedInput, expectedAnchor, immediate = false) {
1773
1774
  const expected = executionLaunchSchema.parse(expectedInput), name = expected.session_id;
1774
1775
  assertExecutionContext(name);
1775
1776
  assertExecutionResumeSupported();
@@ -1866,13 +1867,14 @@ export async function checkAgentIdle(expectedInput, expectedAnchor) {
1866
1867
  attached: slot?.attached ?? (effectIssued ? false : null), turn_settled: settled,
1867
1868
  pending_child_deliveries: live.pending_child_deliveries,
1868
1869
  post_startup_process_count: live.activity.post_startup_process_count,
1869
- window_activity_at: slot?.window_activity_at ?? null };
1870
+ window_activity_at: slot?.window_activity_at ?? null,
1871
+ ...(immediate && meta.kind === "claude" ? { rate_limited_at: claudeRateLimitedAt(meta) } : {}) };
1870
1872
  };
1871
1873
  return checkIdleSeat({
1872
1874
  exclusive: body => withAgentSendLock(name, async () => {
1873
1875
  try {
1874
1876
  const before = snapshot();
1875
- if (decideIdleSeat(before, Date.now(), minutes, expectedAnchor).reason === "native_configuration_unconfirmed") {
1877
+ if (decideIdleSeat(before, Date.now(), minutes, expectedAnchor, immediate).reason === "native_configuration_unconfirmed") {
1876
1878
  const meta = metadata(), recipe = refreshAgentResumeRecipe(meta);
1877
1879
  configurationStartedAt = Math.floor(Date.now() / 1000) * 1000;
1878
1880
  if (recipe && await inspectAgentIdleSettings(name, meta, recipe))
@@ -1941,7 +1943,29 @@ export async function checkAgentIdle(expectedInput, expectedAnchor) {
1941
1943
  if (tryLoadAgentMetadata(name)?.launch_id === expected.launch_id)
1942
1944
  writeJson0600(agentMetadataPath(name, expected.launch_id).replace(/\.agent\.json$/, ".idle-check.json"), result);
1943
1945
  },
1944
- }, expected.launch_id, minutes, expectedAnchor);
1946
+ }, expected.launch_id, minutes, expectedAnchor, immediate);
1947
+ }
1948
+ /** The rate_limited API error that ended the turn after the last input, as the wait result classifies it. */
1949
+ function claudeRateLimitedAt(meta) {
1950
+ const input = Date.parse(readAgentActivity(meta).last_input_at ?? "");
1951
+ const error = Number.isFinite(input) ? claudeApiErrorAfter(meta, input) : null;
1952
+ return error?.at && claudeFailureCategory(error) === "rate_limited" ? error.at : null;
1953
+ }
1954
+ const HIBERNATE_BUSY_REASONS = new Set(["turn_running", "turn_end_unconfirmed", "input_without_turn_end",
1955
+ "child_delivery_pending_or_unknown", "background_work_or_unknown"]);
1956
+ /** pty_close with hibernate: stop the seat now through the idle lifecycle, keeping its conversation for resume. */
1957
+ export async function hibernateAgentSession(name) {
1958
+ assertSessionName(name);
1959
+ const meta = loadAgentMetadata(name);
1960
+ const result = await checkAgentIdle({ session_id: name, launch_id: meta.launch_id }, undefined, true);
1961
+ if (result.outcome === "hibernated")
1962
+ return { schema: "aiterm.pty-close-result.v1", session_id: name, outcome: "hibernated" };
1963
+ // Killing a running turn or its background work loses that work; the caller asks again at the turn end.
1964
+ if (HIBERNATE_BUSY_REASONS.has(result.reason))
1965
+ throw new AitermError(`AGENT_BUSY: ${result.reason}: 席は作業中のため休止していません。`, 2);
1966
+ if (result.outcome === "unconfirmed")
1967
+ throw new AitermError(`AGENT_HIBERNATE_UNCONFIRMED: ${result.reason}: 停止を始めましたが休止の完了を確認できません。`, 2);
1968
+ throw new AitermError(`AGENT_HIBERNATE_UNAVAILABLE: ${result.reason}: 席は休止していません。`, 2);
1945
1969
  }
1946
1970
  /** One clock tick; native completion is refreshed even when no parent is waiting for the turn. */
1947
1971
  export async function serviceAgentIdleClock(expectedInput, token) {
@@ -3512,7 +3536,7 @@ function bindCompletedInitialPrompt(meta) {
3512
3536
  bindAgentHarnessSession(meta, scanned.event);
3513
3537
  setInitialPromptState(meta, "done");
3514
3538
  }
3515
- function latestAgentDoneEvent(meta, expectedOperationId = null) {
3539
+ function latestAgentDoneEvent(meta, expectedOperationId = null, expectedInputId = null) {
3516
3540
  if (meta.kind === "codex")
3517
3541
  return latestCodexCompletion(meta, readTranscriptLines);
3518
3542
  if (meta.kind === "cursor" && meta.completion_route === "cursor_transcript") {
@@ -3537,7 +3561,8 @@ function latestAgentDoneEvent(meta, expectedOperationId = null) {
3537
3561
  if (!line.trim() || Buffer.byteLength(line, "utf8") > 64 * 1024)
3538
3562
  continue;
3539
3563
  const parsed = parseAgentDoneEvent(line, meta);
3540
- if (parsed.event && (!expectedOperationId || parsed.event.operation_id === expectedOperationId))
3564
+ if (parsed.event && (!expectedOperationId || parsed.event.operation_id === expectedOperationId)
3565
+ && (!expectedInputId || parsed.event.input_id === expectedInputId))
3541
3566
  latest = parsed.event;
3542
3567
  }
3543
3568
  return latest;
@@ -3632,12 +3657,12 @@ function agentCompletionCursor(meta) {
3632
3657
  return transcript ? safeStatSize(transcript) : 0;
3633
3658
  }
3634
3659
  function transcriptUnavailable() {
3635
- throw new AitermError(`transcript がまだありません。ターン完了後に再取得してください。${agentWaitGuide()}`, 2);
3660
+ throw new AitermError(`TRANSCRIPT_UNAVAILABLE: transcript がまだありません。ターン完了後に再取得してください。${agentWaitGuide()}`, 2);
3636
3661
  }
3637
3662
  /** 完了したturnの回答が空だった時に、人とAIが読む表示へ出す文。機械はstructuredContentのanswer_emptyを見る。 */
3638
3663
  const AGENT_ANSWER_EMPTY_NOTICE = "このターンは完了しましたが、回答の本文は空でした。";
3639
3664
  function transcriptNotFound(vendor) {
3640
- throw new AitermError(`最終 assistant メッセージを特定できませんでした(harness=${agentHarness(vendor)}, vendor=${vendor})。screen で確認してください。`, 2);
3665
+ throw new AitermError(`TRANSCRIPT_NOT_FOUND: 最終 assistant メッセージを特定できませんでした(harness=${agentHarness(vendor)}, vendor=${vendor})。screen で確認してください。`, 2);
3641
3666
  }
3642
3667
  function readTranscriptLines(file) {
3643
3668
  try {
@@ -3805,22 +3830,34 @@ export async function readAgentTranscriptResult(name, o = {}) {
3805
3830
  if (operationId && meta.kind !== "claude") {
3806
3831
  throw new AitermError("operation_id付き回収はClaude agent sessionだけで使用できます", 2);
3807
3832
  }
3808
- if (meta.kind === "claude" && !o.completion) {
3833
+ const inputId = o.input_id ?? null;
3834
+ if (inputId !== null && (!/^[a-f0-9]{32}$/.test(inputId) || meta.kind !== "claude" || operationId || o.completion)) {
3835
+ throw new AitermError("input_id付き回収はClaude agent sessionだけで、operation_idと併用せず32桁の小文字16進で指定してください", 2);
3836
+ }
3837
+ const inputPending = () => {
3838
+ throw new AitermError(`AITERM_TRANSCRIPT_INPUT_PENDING: input ${inputId} の番はまだ完了していません。同じinput_idで後から再取得してください。${agentWaitGuide(name)}`, 2);
3839
+ };
3840
+ // 入力に束縛した回収は、その入力の完了だけを読む。後の番のmarkerはこの回収と無関係。
3841
+ if (meta.kind === "claude" && !o.completion && inputId === null) {
3809
3842
  let active = readClaudeOperationMarker(meta);
3810
3843
  if (active)
3811
3844
  active = await settlePublishedClaudeCompletionMarker(meta, active);
3812
3845
  if (active) {
3813
3846
  const label = active.operationId ? `operation ${active.operationId}` : "operation_idなしのClaude turn";
3814
- throw new AitermError(`${label} はまだ完了していません。Stop完了後に同じsessionから再取得してください。${agentWaitGuide(name)}`, 2);
3847
+ throw new AitermError(`TRANSCRIPT_TURN_ACTIVE: ${label} はまだ完了していません。Stop完了後に同じsessionから再取得してください。${agentWaitGuide(name)}`, 2);
3815
3848
  }
3816
3849
  }
3817
3850
  // wait timeout は「失敗」ではなく状態不明。後着した同一launchの完了eventから
3818
3851
  // harness session をbindし、promptを再送せず結果だけ回収できるようにする。
3819
3852
  recoverAgentHarnessSession(meta);
3820
3853
  if (!meta.vendor_session_id) {
3854
+ if (inputId)
3855
+ inputPending();
3821
3856
  throw new AitermError(`agent session '${name}' はまだターンが完了していません。agent_done 完了後に再取得してください。${agentWaitGuide(name)}`, 2);
3822
3857
  }
3823
- const done = latestAgentDoneEvent(meta, operationId);
3858
+ const done = latestAgentDoneEvent(meta, operationId, inputId);
3859
+ if (inputId && !done)
3860
+ inputPending();
3824
3861
  if (o.completion && meta.kind !== "codex" && meta.kind !== "grok"
3825
3862
  && (!done || done.turn_id !== o.completion.turn_id || done.operation_id !== o.completion.operation_id)) {
3826
3863
  throw new AitermError("回収対象の完了情報が置換されました。別の回答は配送しません", 2);
@@ -3834,7 +3871,9 @@ export async function readAgentTranscriptResult(name, o = {}) {
3834
3871
  if (meta.kind === "claude") {
3835
3872
  if (!done)
3836
3873
  transcriptUnavailable();
3837
- text = readClaudeResultText(meta, done, operationId, transcriptUnavailable);
3874
+ text = readClaudeResultText(meta, done, operationId, transcriptUnavailable, inputId ? () => {
3875
+ throw new AitermError(`AITERM_TRANSCRIPT_INPUT_REPLACED: input ${inputId} の回答は後の番の結果で置き換わりました。この入力の本文はもう読めません。`, 2);
3876
+ } : undefined);
3838
3877
  }
3839
3878
  else if (meta.kind === "antigravity") {
3840
3879
  if (!done || done.done_status !== "turn_done")
@@ -4798,7 +4837,9 @@ function loadAuthMetadata(name, kind) {
4798
4837
  throw new AitermError("AGENT_AUTH_HARNESS_MISMATCH: 認証sessionのharnessが一致しません。", 2);
4799
4838
  if (typeof value.bin !== "string" || typeof value.cwd !== "string" || !path.isAbsolute(value.cwd)
4800
4839
  || !["login", "onboarding"].includes(value.phase) || !Array.isArray(value.env_vars)
4801
- || value.env_vars.some(key => typeof key !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))) {
4840
+ || value.env_vars.some(key => typeof key !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
4841
+ || (value.claude_root !== undefined && (kind !== "claude" || typeof value.claude_root?.root !== "string" || !path.isAbsolute(value.claude_root.root)
4842
+ || (value.claude_root.selector !== null && value.claude_root.selector !== value.claude_root.root)))) {
4802
4843
  throw new AitermError("AGENT_AUTH_STATE_INVALID: 認証sessionの記録が不正です。", 2);
4803
4844
  }
4804
4845
  return value;
@@ -4978,7 +5019,9 @@ async function respondAgentAuth(kind, options) {
4978
5019
  }
4979
5020
  function launchAuthProcess(name, meta) {
4980
5021
  const plan = authPlan(meta.kind, meta.phase);
4981
- const env = plan.env.map(([key, value]) => shq(`${key}=${value}`));
5022
+ const root = meta.claude_root;
5023
+ const env = [...(!root ? [] : root.selector === null ? ["-u", "CLAUDE_CONFIG_DIR"] : [shq(`CLAUDE_CONFIG_DIR=${root.selector}`)]),
5024
+ ...plan.env.map(([key, value]) => shq(`${key}=${value}`))];
4982
5025
  const cmd = ["exec", "env", ...env, shq(agentBinForPaneShell(meta.bin)), ...plan.args.map(shq)].join(" ");
4983
5026
  send(name, `cd ${shq(paneCwdArgument(meta.cwd))} && ${cmd}`, { enter: true, force: true, raw: true });
4984
5027
  }
@@ -4990,10 +5033,21 @@ function launchAuthProcess(name, meta) {
4990
5033
  export async function authenticateAgent(kind, options) {
4991
5034
  if (options.action !== "status" || options.session_id !== undefined)
4992
5035
  assertExecutionContext(options.session_id);
4993
- const result = (status, session, message, pane) => {
5036
+ if (options.configuration_root !== undefined && kind !== "claude")
5037
+ throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: configuration_rootはclaude-code harnessだけで使えます。", 2);
5038
+ const claudeRoot = options.configuration_root === undefined ? undefined : resolveClaudeConfigurationRoot(options.configuration_root);
5039
+ if (claudeRoot && options.session_id !== undefined && options.action !== "start") {
5040
+ const saved = loadAuthMetadata(options.session_id, kind);
5041
+ if (saved && (saved.claude_root?.root !== claudeRoot.root || saved.claude_root.selector !== claudeRoot.selector))
5042
+ throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: 認証sessionは別のconfiguration_rootで始まっています。", 2);
5043
+ }
5044
+ const rootEnv = (env, root = claudeRoot) => root ? withClaudeConfigRoot(env, root) : env;
5045
+ const sessionEnv = (session, saved) => rootEnv(authSessionEnvironment(session, saved.env_vars), saved.claude_root);
5046
+ const result = (status, session, message, pane, label) => {
4994
5047
  const receipt = { schema: "aiterm.agent-auth-result.v1", harness: agentHarness(kind), status,
4995
5048
  session_id: session, url: pane?.url ?? null, user_code: pane?.user_code ?? null,
4996
- input_required: pane?.input_required ?? false, message: message ?? pane?.message ?? null };
5049
+ input_required: pane?.input_required ?? false, message: message ?? pane?.message ?? null,
5050
+ ...(kind === "claude" && status === "authenticated" ? { account_label: label ?? null } : {}) };
4997
5051
  receipt.auth_ui = authUi(receipt, pane, session ? readAuthBinding(session, kind) : null);
4998
5052
  if (isWin && receipt.auth_ui.input !== null)
4999
5053
  receipt.auth_ui = { ...receipt.auth_ui, stage: "unavailable", input: null, choices: [],
@@ -5028,15 +5082,17 @@ export async function authenticateAgent(kind, options) {
5028
5082
  if (kind === "antigravity" && options.relogin)
5029
5083
  return result("failed", null, "AGENT_AUTH_RELOGIN_UNSUPPORTED: Antigravityの再認証は公式TUIの /logout が必要で、共有の資格情報とcacheを消します。Aitermからは開始していません。");
5030
5084
  // reloginは今の状態を聞かない。状態を確認できない時(failed)でも、入り直しは始められる。
5031
- const before = options.relogin ? { status: "unauthenticated", message: null } : await authStatus(kind, bin, cwd);
5085
+ const envVars = options.env_vars ?? [];
5086
+ if (claudeRoot && envVars.includes("CLAUDE_CONFIG_DIR"))
5087
+ throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: env_varsのCLAUDE_CONFIG_DIRとconfiguration_rootは同時に指定できません。", 2);
5088
+ const before = options.relogin ? { status: "unauthenticated", message: null } : await authStatus(kind, bin, cwd, rootEnv(process.env));
5032
5089
  if (before.status === "failed")
5033
5090
  return result("failed", null, before.message);
5034
5091
  if (before.status === "authenticated" && !before.verify_onboarding)
5035
- return result("authenticated", null, null);
5036
- const envVars = options.env_vars ?? [];
5092
+ return result("authenticated", null, null, undefined, before.account_label);
5037
5093
  [name] = openSession(name, "bash", envVars);
5038
5094
  meta = { kind, bin, cwd, phase: before.status === "authenticated" ? "onboarding" : "login",
5039
- env_vars: envVars.filter(key => process.env[key] !== undefined) };
5095
+ env_vars: envVars.filter(key => process.env[key] !== undefined), ...(claudeRoot ? { claude_root: claudeRoot } : {}) };
5040
5096
  try {
5041
5097
  const kept = tmux("set-option", "-t", name, "remain-on-exit", "on");
5042
5098
  if (kept.code !== 0)
@@ -5066,8 +5122,8 @@ export async function authenticateAgent(kind, options) {
5066
5122
  const bin = resolveAgentBin(kind);
5067
5123
  if (!bin)
5068
5124
  return result("failed", null, `${agentLabel(kind)}の公式CLIが見つかりません。`);
5069
- const checked = await authStatus(kind, bin, cwd);
5070
- return result(checked.status === "authenticated" ? "authenticated" : checked.status === "failed" ? "failed" : "blocked", null, checked.message ?? (checked.status === "unauthenticated" ? "公式CLIの認証が必要です。agent_authのstartで開始してください。" : null));
5125
+ const checked = await authStatus(kind, bin, cwd, rootEnv(process.env));
5126
+ return result(checked.status === "authenticated" ? "authenticated" : checked.status === "failed" ? "failed" : "blocked", null, checked.message ?? (checked.status === "unauthenticated" ? "公式CLIの認証が必要です。agent_authのstartで開始してください。" : null), undefined, checked.account_label);
5071
5127
  }
5072
5128
  else {
5073
5129
  const loaded = loadAuthMetadata(name, kind);
@@ -5120,7 +5176,7 @@ export async function authenticateAgent(kind, options) {
5120
5176
  return result("failed", session, `公式認証processがsignalで終了しました(signal=${/^[A-Z0-9]+$/.test(signal) ? signal : "unknown"})。`);
5121
5177
  if (exit !== "0")
5122
5178
  return result("failed", session, `公式認証processが失敗しました(exit=${/^\d+$/.test(exit ?? "") ? exit : "unknown"})。`);
5123
- const checked = await authStatus(kind, meta.bin, meta.cwd, authSessionEnvironment(session, meta.env_vars));
5179
+ const checked = await authStatus(kind, meta.bin, meta.cwd, sessionEnv(session, meta));
5124
5180
  const afterOfficialStatus = pendingExitRefusal();
5125
5181
  if (afterOfficialStatus)
5126
5182
  return afterOfficialStatus;
@@ -5129,7 +5185,7 @@ export async function authenticateAgent(kind, options) {
5129
5185
  if (checked.status === "unauthenticated")
5130
5186
  return result("failed", session, "公式認証processは終了しましたが、公式statusは未認証です。");
5131
5187
  if (!checked.verify_onboarding)
5132
- return result("authenticated", session, null);
5188
+ return result("authenticated", session, null, undefined, checked.account_label);
5133
5189
  if (meta.phase === "onboarding")
5134
5190
  return result("blocked", session, "公式CLIの初回案内の完了を確認できません。");
5135
5191
  withExecutionPreparation(session, () => {
@@ -5147,9 +5203,9 @@ export async function authenticateAgent(kind, options) {
5147
5203
  if (pane.failed)
5148
5204
  return result("failed", session, null, pane);
5149
5205
  if (pane.onboarding_complete) {
5150
- const checked = await authStatus(kind, meta.bin, meta.cwd, authSessionEnvironment(session, meta.env_vars));
5206
+ const checked = await authStatus(kind, meta.bin, meta.cwd, sessionEnv(session, meta));
5151
5207
  if (checked.status === "authenticated")
5152
- return result("authenticated", session, null);
5208
+ return result("authenticated", session, null, undefined, checked.account_label);
5153
5209
  return result("failed", session, checked.message ?? "公式CLIのstatusが未認証です。");
5154
5210
  }
5155
5211
  if (pane.input_required)
@@ -6663,7 +6719,7 @@ function adoptVanishedAgentNative(meta) {
6663
6719
  "文字列は送信していません。agent_launchで起動し直してください。", 2);
6664
6720
  }
6665
6721
  }
6666
- async function resumeAgentInLock(name, readyTimeout) {
6722
+ async function resumeAgentInLock(name, readyTimeout, claudeRoot) {
6667
6723
  const previous = loadAgentMetadata(name);
6668
6724
  readyTimeout ??= previous.kind === "codex" ? AGENT_TUI_FIRST_DRAW_TIMEOUT_MS : AGENT_TUI_READY_TIMEOUT_MS;
6669
6725
  let lifecycle = readAgentLifecycle(previous);
@@ -6712,7 +6768,10 @@ async function resumeAgentInLock(name, readyTimeout) {
6712
6768
  };
6713
6769
  try {
6714
6770
  assertExecutionResumeSupported();
6715
- const recipe = confirmedAgentResumeRecipe(previous, lifecycle);
6771
+ const confirmed = confirmedAgentResumeRecipe(previous, lifecycle);
6772
+ // Same vendor session under another Claude root; the caller proved the transcript is there.
6773
+ const recipe = claudeRoot && confirmed.kind === "claude" ? { ...confirmed, configuration_root: claudeRoot.root,
6774
+ environment: { ...confirmed.environment, CLAUDE_CONFIG_DIR: claudeRoot.selector } } : confirmed;
6716
6775
  if (sessionExists(name))
6717
6776
  throw uncertain();
6718
6777
  const controlEnv = { ...process.env };
@@ -7578,8 +7637,13 @@ function prepareAgentLaunch(kind, opts = {}) {
7578
7637
  requireMatchingClaudeLaunch(opts.session_name, launchOperationId, launchRequestDigest);
7579
7638
  return () => existingAgentLaunchResult("claude", opts.session_name, model, effort);
7580
7639
  }
7640
+ const claudeRoot = kind === "claude" ? opts.claude_root : undefined;
7641
+ if (claudeRoot && envVars.includes("CLAUDE_CONFIG_DIR"))
7642
+ throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: env_varsのCLAUDE_CONFIG_DIRとconfiguration_rootは同時に指定できません。", 2);
7643
+ const claudeEnv = claudeRoot ? withClaudeConfigRoot(process.env, claudeRoot) : process.env;
7644
+ const claudeRootEntries = claudeRoot ? [["CLAUDE_CONFIG_DIR", claudeRoot.selector]] : [];
7581
7645
  if (kind === "claude")
7582
- assertClaudeAuthenticationReady(bin);
7646
+ assertClaudeAuthenticationReady(bin, claudeEnv);
7583
7647
  if (kind === "cursor")
7584
7648
  assertCursorAuthenticationReady(bin);
7585
7649
  if (kind === "antigravity") {
@@ -7645,7 +7709,7 @@ function prepareAgentLaunch(kind, opts = {}) {
7645
7709
  const meta = withExecutionPreparation(sid, () => {
7646
7710
  const meta = agentDone
7647
7711
  ? kind === "claude"
7648
- ? createClaudeAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", launchOperationId, launchRequestDigest, lineageContext, model, effort)
7712
+ ? createClaudeAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", launchOperationId, launchRequestDigest, lineageContext, model, effort, claudeRoot?.root)
7649
7713
  : kind === "codex"
7650
7714
  ? createCodexAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", { model, effort }, writeScope, lineageContext)
7651
7715
  : kind === "antigravity"
@@ -7679,7 +7743,7 @@ function prepareAgentLaunch(kind, opts = {}) {
7679
7743
  initialProof = proof;
7680
7744
  }
7681
7745
  try {
7682
- captureAgentResumeTemplate(meta, effort, envVars, kind === "claude" ? meta.claude_home : meta.codex_home);
7746
+ captureAgentResumeTemplate(meta, effort, envVars, kind === "claude" ? meta.claude_home : meta.codex_home, claudeEnv);
7683
7747
  }
7684
7748
  catch {
7685
7749
  process.stderr.write("aiterm: resume_template_unconfirmed\n");
@@ -7700,12 +7764,13 @@ function prepareAgentLaunch(kind, opts = {}) {
7700
7764
  : kind === "antigravity" ? antigravityAgentArgv(bin, model, effort, prompt)
7701
7765
  : grokAgentArgv(kind, bin, model, effort, prompt, meta);
7702
7766
  full = windowsAgentLaunchLine(cwd, [
7703
- ...(meta?.kind === "grok" ? grokEnvEntries(meta) : []), ...agentEnvEntries(meta, sid, envVars),
7767
+ ...claudeRootEntries, ...(meta?.kind === "grok" ? grokEnvEntries(meta) : []), ...agentEnvEntries(meta, sid, envVars),
7704
7768
  ], windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), meta?.windows_launch_exit_tracked ? { file: agentMetadataPath(sid, meta.launch_id) + ".launch-exited", launch_id: meta.launch_id } : undefined);
7705
7769
  }
7706
7770
  else {
7707
7771
  const cmd = buildAgentCmd(kind, binForCmd, model, effort, opts.prompt ?? null, meta, cursorFast);
7708
- const envPrefix = agentEnvPrefix(meta, sid, envVars);
7772
+ const envPrefix = (!claudeRoot ? "" : claudeRoot.selector === null ? "unset CLAUDE_CONFIG_DIR && "
7773
+ : `CLAUDE_CONFIG_DIR=${shq(claudeRoot.selector)} `) + agentEnvPrefix(meta, sid, envVars);
7709
7774
  const command = cwdForCmd ? `cd ${shq(cwdForCmd)} && ${envPrefix}${cmd}` : `${envPrefix}${cmd}`;
7710
7775
  // このpaneのbashはAitermが自分で選んだ。sub-agent instructionのLFを含む起動commandは、
7711
7776
  // 利用者のshell送信と同じknown-shell適合で1物理行にしてから打つ(sanitizeはしない)。
@@ -7808,6 +7873,9 @@ export class AgentLaunchPromptError extends AitermError {
7808
7873
  }
7809
7874
  }
7810
7875
  export async function openAgentWithInitialPrompt(kind, opts = {}) {
7876
+ if (opts.configuration_root != null && kind !== "claude")
7877
+ throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: configuration_rootはclaude-code harnessだけで使えます。", 2);
7878
+ const claudeRoot = opts.configuration_root == null ? undefined : resolveClaudeConfigurationRoot(opts.configuration_root);
7811
7879
  if (opts.session_name)
7812
7880
  await withExecutionNativeAdmission(opts.session_name, () => assertExecutionContext(opts.session_name));
7813
7881
  else
@@ -7868,12 +7936,17 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
7868
7936
  || (opts.write_scope !== undefined && opts.write_scope !== previous.write_scope)
7869
7937
  || (opts.env_vars !== undefined && !isDeepStrictEqual([...new Set(opts.env_vars)].sort(), Object.keys(recipe.environment).sort())))
7870
7938
  throw opts.require_existing_resume ? new AgentResumeUnavailableError(name) : new AitermError("AGENT_RESUME_CONFLICT: 同名の休止席は保存したharness・設定・project・明示envで再開します。変更は再開後に行ってください。", 2);
7939
+ // The only setting a resume may change: the Claude root, when it holds this conversation's transcript.
7940
+ const rootChange = claudeRoot && (claudeRoot.root !== recipe.configuration_root
7941
+ || (recipe.environment.CLAUDE_CONFIG_DIR ?? null) !== claudeRoot.selector) ? claudeRoot : undefined;
7942
+ if (rootChange && !fs.existsSync(path.join(rootChange.root, "projects", claudeProjectSlug(recipe.cwd), `${recipe.vendor_session_id}.jsonl`)))
7943
+ throw opts.require_existing_resume ? new AgentResumeUnavailableError(name) : new AitermError("AGENT_RESUME_CONFLICT: 指定したconfiguration_rootにこの会話の記録がありません。", 2);
7871
7944
  if (opts.launch_operation_id != null)
7872
7945
  requireMatchingClaudeLaunch(name, validateOperationId(opts.launch_operation_id), claudeLaunchRequestDigest({ sessionName: name, model: opts.model ?? null, effort: opts.reasoning_effort ?? null,
7873
7946
  cwd: opts.cwd ?? null, agentDone: true }));
7874
7947
  if (preparedLifecycle)
7875
7948
  commitWorkingAgentResume(previous, preparedLifecycle);
7876
- const resumed = await resumeAgentInLock(name, opts.ready_timeout ?? undefined);
7949
+ const resumed = await resumeAgentInLock(name, opts.ready_timeout ?? undefined, rootChange);
7877
7950
  return withAgentResumeTarget(resumed, async () => {
7878
7951
  const hint = `${agentLabel(kind)} を保存した同じ会話へ再開した。\n${attachHint(name)}`;
7879
7952
  const fastState = { fast: resumed.fast === true, fast_error: null };
@@ -7916,6 +7989,7 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
7916
7989
  cursor_fast: fastPlan.cursor_fast,
7917
7990
  fast_state: fastPlan.state,
7918
7991
  base_model: requestedModel,
7992
+ claude_root: claudeRoot,
7919
7993
  };
7920
7994
  // GrokとCursorは、起動の --model の値を利用者の既定へ書く(Cursorは版による)。起動の前後で、直前の値へ戻す。
7921
7995
  const launch = () => {
@@ -97,7 +97,7 @@ export function validateOperationId(operationId) {
97
97
  }
98
98
  return operationId;
99
99
  }
100
- export function readClaudeResultText(meta, done, operationId, transcriptUnavailable) {
100
+ export function readClaudeResultText(meta, done, operationId, transcriptUnavailable, mismatch = () => { throw new AitermError("TRANSCRIPT_RESULT_MISMATCH: Claude result file が完了eventと一致しません", 2); }) {
101
101
  if (meta.kind !== "claude" || !meta.result_file || !done.result_digest || done.result_bytes == null) {
102
102
  transcriptUnavailable();
103
103
  }
@@ -134,7 +134,7 @@ export function readClaudeResultText(meta, done, operationId, transcriptUnavaila
134
134
  typeof result.text !== "string" ||
135
135
  Buffer.byteLength(result.text, "utf8") !== done.result_bytes ||
136
136
  createHash("sha256").update(result.text, "utf8").digest("hex") !== done.result_digest) {
137
- throw new AitermError("Claude result file が完了eventと一致しません", 2);
137
+ mismatch();
138
138
  }
139
139
  return result.text;
140
140
  }
@@ -264,8 +264,9 @@ export function claudeCatalogFromInitialize(stdout, requestId, summary = "") {
264
264
  fast_unavailable: claudeFastUnavailable(response.response.response?.fast_mode_disabled_reason),
265
265
  });
266
266
  }
267
- export function assertClaudeAuthenticationReady(bin) {
267
+ export function assertClaudeAuthenticationReady(bin, env = process.env) {
268
268
  const result = spawnAgentControlCommand(bin, ["auth", "status", "--json"], process.cwd(), {
269
+ env,
269
270
  encoding: "utf8",
270
271
  timeout: CLAUDE_AUTH_STATUS_TIMEOUT_MS,
271
272
  maxBuffer: 64 * 1024,
@@ -608,7 +609,7 @@ export function claudeStartupAction(screen, trustProject) {
608
609
  }
609
610
  // submit座礁観測のcomposer領域マーカー(ready判定と同じ記号を行頭基準で探す)。
610
611
  export const CLAUDE_COMPOSER_MARKER_RE = /^\s*❯/;
611
- export function createClaudeAgentMetadata(name, cwd, initialPrompt, launchOperationId, launchRequestDigest, lineageContext, model, effort) {
612
+ export function createClaudeAgentMetadata(name, cwd, initialPrompt, launchOperationId, launchRequestDigest, lineageContext, model, effort, claudeHome = claudeConfigDir()) {
612
613
  // Claude Codeはリンクを解決したcwdでproject slugを作る。起動時に固定し、記録の監視時に再解決しない。
613
614
  const transcriptCwd = cwd === null ? null : fs.realpathSync(cwd);
614
615
  const launchId = randomBytes(16).toString("hex");
@@ -632,7 +633,7 @@ export function createClaudeAgentMetadata(name, cwd, initialPrompt, launchOperat
632
633
  ...agentLineageFields(lineageContext),
633
634
  node_platform: process.platform,
634
635
  claude_settings: claudeSettings,
635
- claude_home: path.resolve(cwd ?? process.cwd(), claudeConfigDir()),
636
+ claude_home: path.resolve(cwd ?? process.cwd(), claudeHome),
636
637
  result_file: resultFile,
637
638
  };
638
639
  writeAgentMetadata(meta);
@@ -685,7 +686,7 @@ export function claudeApiErrorFromLine(line) {
685
686
  };
686
687
  }
687
688
  export function claudeFailureCategory(error) {
688
- if (error.status === 429 || /^You've (?:reached your [^.\r\n]{1,80} limit\.|hit your (?:usage|session) limit\b)/i.test(error.text))
689
+ if (error.status === 429 || /^You've (?:reached your [^.\r\n]{1,80} limit\.|hit your (?:[a-z0-9-]+ ){0,3}limit\b)/i.test(error.text))
689
690
  return "rate_limited";
690
691
  if (error.status === 529)
691
692
  return "capacity";
@@ -724,8 +725,10 @@ export function claudeAuthStatus(bin, cwd, env = process.env) {
724
725
  catch {
725
726
  return { status: "failed", message: "Claude Codeの公式認証状態を読めません。" };
726
727
  }
728
+ // The e-mail is display text for which account this root holds, not a credential.
727
729
  if (!result.error && result.status === 0 && status?.loggedIn === true)
728
- return { status: "authenticated", verify_onboarding: true, message: null };
730
+ return { status: "authenticated", verify_onboarding: true, message: null,
731
+ account_label: typeof status.email === "string" && status.email ? status.email : null };
729
732
  if (!result.error && status?.loggedIn === false)
730
733
  return { status: "unauthenticated", message: null };
731
734
  return { status: "failed", message: "Claude Codeの公式認証状態の確認に失敗しました。" };
package/dist/index.js CHANGED
@@ -634,6 +634,11 @@ export function createAitermServer(options = {}) {
634
634
  .regex(/^sha256:[0-9a-f]{64}$/)
635
635
  .nullish()
636
636
  .describe("Claude operationの期待ID。agent_transcript:true時だけ指定し、古い別operationの結果を拒否する"),
637
+ input_id: z
638
+ .string()
639
+ .regex(/^[a-f0-9]{32}$/)
640
+ .nullish()
641
+ .describe("Claudeのpty_send dispatch receiptのinput_id。agent_transcript:true時だけ指定し、その入力の番の回答を読む。後の番が動いていても拒否しない。未完了はAITERM_TRANSCRIPT_INPUT_PENDING、後の番の結果で置換済みはAITERM_TRANSCRIPT_INPUT_REPLACED"),
637
642
  },
638
643
  outputSchema: {
639
644
  schema: z.literal("aiterm.pty-read-result.v1"),
@@ -651,7 +656,7 @@ export function createAitermServer(options = {}) {
651
656
  .optional()
652
657
  .describe("agent_transcriptで、完了したturnの回答が空だった時だけtrue(textは空文字列)。回答を読めなかった時は誤りを返す。terminalではnull"),
653
658
  },
654
- }, async ({ session_id, wait, until, until_regex, timeout, screen, full, lines, line_range, raw, rtk, agent_transcript, operation_id }) => {
659
+ }, async ({ session_id, wait, until, until_regex, timeout, screen, full, lines, line_range, raw, rtk, agent_transcript, operation_id, input_id }) => {
655
660
  try {
656
661
  if (agent_transcript) {
657
662
  if (screen || full || rtk || wait || line_range != null) {
@@ -661,6 +666,7 @@ export function createAitermServer(options = {}) {
661
666
  const result = await core.readAgentTranscriptResult(session_id, {
662
667
  lines: lines ?? null,
663
668
  operation_id: operation_id ?? null,
669
+ input_id: input_id ?? null,
664
670
  raw,
665
671
  });
666
672
  return {
@@ -680,6 +686,8 @@ export function createAitermServer(options = {}) {
680
686
  }
681
687
  if (operation_id != null)
682
688
  throw new Error("operation_idはagent_transcript:true時だけ指定できます");
689
+ if (input_id != null)
690
+ throw new Error("input_idはagent_transcript:true時だけ指定できます");
683
691
  let range = null;
684
692
  if (line_range) {
685
693
  const idx = line_range.indexOf(":");
@@ -745,15 +753,26 @@ export function createAitermServer(options = {}) {
745
753
  });
746
754
  registerRemoteAwareTool("pty_close", {
747
755
  description: "セッションを閉じ、ログ/読取位置を破棄する。同じsession_idへの再試行は安全で、" +
748
- "closed/already_closedのstructured receiptを返す。",
749
- inputSchema: { session_id: z.string() },
756
+ "closed/already_closedのstructured receiptを返す。" +
757
+ "hibernate:trueはClaude・Codexのagent席を今すぐ休止し(idle時計と同じ手順)、会話と再開情報を残してhibernatedを返す。" +
758
+ "次のagent_launch(session_name)が同じ会話へ再開する。turn・子process・子への配送が動いている間はAGENT_BUSYで断る(終わってから呼び直す)。" +
759
+ "Claudeの席が利用上限でturnを終えている時(最後の入力の後の会話記録がrate_limited)は、上限の待ち画面のままでも休止できる。" +
760
+ "他の理由で休止できない時はAGENT_HIBERNATE_UNAVAILABLE、席は触らない。",
761
+ inputSchema: {
762
+ session_id: z.string(),
763
+ hibernate: z.boolean().optional().describe("trueで閉じずに休止する(会話と再開情報を残す)。既定false"),
764
+ },
750
765
  outputSchema: {
751
766
  schema: z.literal("aiterm.pty-close-result.v1"),
752
767
  session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),
753
- outcome: z.enum(["closed", "already_closed"]),
768
+ outcome: z.enum(["closed", "already_closed", "hibernated"]),
754
769
  },
755
- }, async ({ session_id }) => {
770
+ }, async ({ session_id, hibernate }) => {
756
771
  try {
772
+ if (hibernate) {
773
+ const result = await core.hibernateAgentSession(session_id);
774
+ return { content: [{ type: "text", text: `hibernated ${session_id}` }], structuredContent: { ...result } };
775
+ }
757
776
  await parentDelivery?.beforeChange(session_id);
758
777
  const result = core.closeSessionResult(session_id);
759
778
  return {
@@ -993,6 +1012,7 @@ export function createAitermServer(options = {}) {
993
1012
  cwd: z.string().optional().describe("公式CLIを実行する作業ディレクトリの絶対パス"),
994
1013
  env_vars: z.array(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).optional().describe("startで認証PTYへ引き継ぐ環境変数名。値はreceiptへ返さない"),
995
1014
  relogin: z.boolean().optional().describe("startで、公式の状態が認証済みでも公式ログインを開始する。既定false。trueの時、authenticatedかつsession_idがnullの結果は返さない"),
1015
+ configuration_root: z.string().min(1).optional().describe("claude-code harnessだけ。認証する設定root(CLAUDE_CONFIG_DIR)。受ける範囲はagent_launchと同じ。startで決めたrootと違う指定はAGENT_CONFIGURATION_ROOT_REJECTED"),
996
1016
  },
997
1017
  outputSchema: {
998
1018
  schema: z.literal("aiterm.agent-auth-result.v1"),
@@ -1004,6 +1024,7 @@ export function createAitermServer(options = {}) {
1004
1024
  user_code: z.string().nullable(),
1005
1025
  input_required: z.boolean(),
1006
1026
  message: z.string().nullable(),
1027
+ account_label: z.string().nullable().optional().describe("claude-code harnessでauthenticatedの時だけ。公式statusのe-mail(表示用、資格情報ではない)。読めない時はnull"),
1007
1028
  },
1008
1029
  }, async ({ harness, ...options }) => {
1009
1030
  try {
@@ -1195,7 +1216,7 @@ export function createAitermServer(options = {}) {
1195
1216
  }
1196
1217
  async function launchAgent(kind, args, extra) {
1197
1218
  const supportsWriteScope = kind !== "claude";
1198
- const { prompt, image, throughline_source_session, throughline_supplement_file, model, reasoning_effort, fast, env_vars, cwd, session_name, launch_operation_id, write_scope, trust_project, require_existing_resume } = args;
1219
+ const { prompt, image, throughline_source_session, throughline_supplement_file, model, reasoning_effort, fast, env_vars, cwd, session_name, launch_operation_id, write_scope, trust_project, require_existing_resume, configuration_root } = args;
1199
1220
  let delivery = null;
1200
1221
  try {
1201
1222
  if (!supportsWriteScope && write_scope !== undefined) {
@@ -1222,6 +1243,7 @@ export function createAitermServer(options = {}) {
1222
1243
  cwd: cwd ?? undefined,
1223
1244
  session_name: session_name ?? undefined,
1224
1245
  require_existing_resume,
1246
+ configuration_root,
1225
1247
  launch_operation_id: launch_operation_id ?? undefined,
1226
1248
  ...(supportsWriteScope ? { write_scope } : {}),
1227
1249
  });
@@ -1292,6 +1314,7 @@ export function createAitermServer(options = {}) {
1292
1314
  }
1293
1315
  : {};
1294
1316
  if (kind === "claude") {
1317
+ correlatedLaunchSchema.configuration_root = z.string().min(1).optional().describe("Claude Codeの設定root(CLAUDE_CONFIG_DIR)の絶対パス。既定のroot(~/.claude、CLAUDE_CONFIG_DIRなし)か、AITERM_CLAUDE_CONFIG_ROOTSに並べた親の直下だけ。他はAGENT_CONFIGURATION_ROOT_REJECTED。休止席の再開では、新しいrootに同じ会話の記録がある時だけ替えられる");
1295
1318
  correlatedLaunchSchema.launch_operation_id = z
1296
1319
  .string()
1297
1320
  .regex(/^sha256:[0-9a-f]{64}$/)
@@ -1355,6 +1378,7 @@ export function createAitermServer(options = {}) {
1355
1378
  agentEnvironmentDesc + agentCompletionDesc,
1356
1379
  inputSchema: {
1357
1380
  require_existing_resume: z.boolean().optional().describe("Resume an existing saved conversation only; missing or unsupported target never creates a new session. Requires session_name and no prompt; local-only."),
1381
+ configuration_root: z.string().min(1).optional().describe("Claude Codeの設定root(CLAUDE_CONFIG_DIR)の絶対パス。既定のroot(~/.claude、CLAUDE_CONFIG_DIRなし)か、AITERM_CLAUDE_CONFIG_ROOTSに並べた親の直下だけ。他はAGENT_CONFIGURATION_ROOT_REJECTED。休止席の再開では、新しいrootに同じ会話の記録がある時だけ替えられる" + "。claude-code harnessだけ"),
1358
1382
  harness: z.enum(["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"]).describe("agent loop・session・hook・transcript・認証を所有する実行基盤"),
1359
1383
  prompt: z.string().nullish().describe("起動時に渡す初手プロンプト(任意)。送信後は待たずに即返る"),
1360
1384
  image: z.array(z.string()).optional().describe("初手プロンプトへ添付する画像ファイルの絶対パス(png/jpg/jpeg/gif/webp)"),
@@ -629,7 +629,8 @@ export function sessionEnvironmentLaunch(shell, environment, version) {
629
629
  return { shell: `exec /usr/bin/env ${environment.map(quote).join(" ")} ${quote(shell)}`, args: [], register_after_start: true };
630
630
  }
631
631
  // Aiterm が端末ごとに付け直す名札と、呼んだ側の pane を指す値。新しい端末へは継がせない。
632
- const SESSION_OWN_ENV = /^(?:AITERM_SESSION_ID|AITERM_AGENT_[A-Z0-9_]+|TMUX|TMUX_PANE)$/;
632
+ // AITERM_CLAUDE_CONFIG_ROOTS stays with the serving process: a seat's own Aiterm must not select other Claude roots.
633
+ const SESSION_OWN_ENV = /^(?:AITERM_SESSION_ID|AITERM_AGENT_[A-Z0-9_]+|AITERM_CLAUDE_CONFIG_ROOTS|TMUX|TMUX_PANE)$/;
633
634
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
634
635
  export function sessionCallerEnvironment(base = tmuxSpawnEnv() ?? process.env) {
635
636
  const env = {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.63.17",
3
+ "version": "0.64.0",
4
4
  "mcpName": "io.github.kitepon/aiterm-mcp",
5
5
  "description": "Persistent terminal MCP with one harness-based launcher for Claude Code, Codex CLI, Grok CLI, Cursor Agent CLI, and Antigravity CLI, plus durable PTYs for SSH, containers, and REPLs.",
6
6
  "keywords": [