aiterm-mcp 0.63.18 → 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,14 @@ 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
+
10
18
  ## [0.63.18] - 2026-11-08
11
19
 
12
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.
@@ -3094,7 +3102,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3094
3102
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3095
3103
  provenance.
3096
3104
 
3097
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.18...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
3098
3107
  [0.63.18]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.17...v0.63.18
3099
3108
  [0.63.17]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.16...v0.63.17
3100
3109
  [0.63.16]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.15...v0.63.16
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.18** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.64.0** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
219
219
 
220
220
  ### 更新と巻き戻し
221
221
 
package/README.md CHANGED
@@ -227,7 +227,7 @@ collection is off by default and performs no network I/O. It ships via
227
227
  tag-triggered CI with npm provenance (OIDC Trusted Publishing); the GitHub
228
228
  Release re-registers the Official MCP Registry entry.
229
229
 
230
- **Status:** actively maintained · current public release **v0.63.18** · 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
 
@@ -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) {
@@ -4813,7 +4837,9 @@ function loadAuthMetadata(name, kind) {
4813
4837
  throw new AitermError("AGENT_AUTH_HARNESS_MISMATCH: 認証sessionのharnessが一致しません。", 2);
4814
4838
  if (typeof value.bin !== "string" || typeof value.cwd !== "string" || !path.isAbsolute(value.cwd)
4815
4839
  || !["login", "onboarding"].includes(value.phase) || !Array.isArray(value.env_vars)
4816
- || 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)))) {
4817
4843
  throw new AitermError("AGENT_AUTH_STATE_INVALID: 認証sessionの記録が不正です。", 2);
4818
4844
  }
4819
4845
  return value;
@@ -4993,7 +5019,9 @@ async function respondAgentAuth(kind, options) {
4993
5019
  }
4994
5020
  function launchAuthProcess(name, meta) {
4995
5021
  const plan = authPlan(meta.kind, meta.phase);
4996
- 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}`))];
4997
5025
  const cmd = ["exec", "env", ...env, shq(agentBinForPaneShell(meta.bin)), ...plan.args.map(shq)].join(" ");
4998
5026
  send(name, `cd ${shq(paneCwdArgument(meta.cwd))} && ${cmd}`, { enter: true, force: true, raw: true });
4999
5027
  }
@@ -5005,10 +5033,21 @@ function launchAuthProcess(name, meta) {
5005
5033
  export async function authenticateAgent(kind, options) {
5006
5034
  if (options.action !== "status" || options.session_id !== undefined)
5007
5035
  assertExecutionContext(options.session_id);
5008
- 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) => {
5009
5047
  const receipt = { schema: "aiterm.agent-auth-result.v1", harness: agentHarness(kind), status,
5010
5048
  session_id: session, url: pane?.url ?? null, user_code: pane?.user_code ?? null,
5011
- 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 } : {}) };
5012
5051
  receipt.auth_ui = authUi(receipt, pane, session ? readAuthBinding(session, kind) : null);
5013
5052
  if (isWin && receipt.auth_ui.input !== null)
5014
5053
  receipt.auth_ui = { ...receipt.auth_ui, stage: "unavailable", input: null, choices: [],
@@ -5043,15 +5082,17 @@ export async function authenticateAgent(kind, options) {
5043
5082
  if (kind === "antigravity" && options.relogin)
5044
5083
  return result("failed", null, "AGENT_AUTH_RELOGIN_UNSUPPORTED: Antigravityの再認証は公式TUIの /logout が必要で、共有の資格情報とcacheを消します。Aitermからは開始していません。");
5045
5084
  // reloginは今の状態を聞かない。状態を確認できない時(failed)でも、入り直しは始められる。
5046
- 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));
5047
5089
  if (before.status === "failed")
5048
5090
  return result("failed", null, before.message);
5049
5091
  if (before.status === "authenticated" && !before.verify_onboarding)
5050
- return result("authenticated", null, null);
5051
- const envVars = options.env_vars ?? [];
5092
+ return result("authenticated", null, null, undefined, before.account_label);
5052
5093
  [name] = openSession(name, "bash", envVars);
5053
5094
  meta = { kind, bin, cwd, phase: before.status === "authenticated" ? "onboarding" : "login",
5054
- env_vars: envVars.filter(key => process.env[key] !== undefined) };
5095
+ env_vars: envVars.filter(key => process.env[key] !== undefined), ...(claudeRoot ? { claude_root: claudeRoot } : {}) };
5055
5096
  try {
5056
5097
  const kept = tmux("set-option", "-t", name, "remain-on-exit", "on");
5057
5098
  if (kept.code !== 0)
@@ -5081,8 +5122,8 @@ export async function authenticateAgent(kind, options) {
5081
5122
  const bin = resolveAgentBin(kind);
5082
5123
  if (!bin)
5083
5124
  return result("failed", null, `${agentLabel(kind)}の公式CLIが見つかりません。`);
5084
- const checked = await authStatus(kind, bin, cwd);
5085
- 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);
5086
5127
  }
5087
5128
  else {
5088
5129
  const loaded = loadAuthMetadata(name, kind);
@@ -5135,7 +5176,7 @@ export async function authenticateAgent(kind, options) {
5135
5176
  return result("failed", session, `公式認証processがsignalで終了しました(signal=${/^[A-Z0-9]+$/.test(signal) ? signal : "unknown"})。`);
5136
5177
  if (exit !== "0")
5137
5178
  return result("failed", session, `公式認証processが失敗しました(exit=${/^\d+$/.test(exit ?? "") ? exit : "unknown"})。`);
5138
- 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));
5139
5180
  const afterOfficialStatus = pendingExitRefusal();
5140
5181
  if (afterOfficialStatus)
5141
5182
  return afterOfficialStatus;
@@ -5144,7 +5185,7 @@ export async function authenticateAgent(kind, options) {
5144
5185
  if (checked.status === "unauthenticated")
5145
5186
  return result("failed", session, "公式認証processは終了しましたが、公式statusは未認証です。");
5146
5187
  if (!checked.verify_onboarding)
5147
- return result("authenticated", session, null);
5188
+ return result("authenticated", session, null, undefined, checked.account_label);
5148
5189
  if (meta.phase === "onboarding")
5149
5190
  return result("blocked", session, "公式CLIの初回案内の完了を確認できません。");
5150
5191
  withExecutionPreparation(session, () => {
@@ -5162,9 +5203,9 @@ export async function authenticateAgent(kind, options) {
5162
5203
  if (pane.failed)
5163
5204
  return result("failed", session, null, pane);
5164
5205
  if (pane.onboarding_complete) {
5165
- 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));
5166
5207
  if (checked.status === "authenticated")
5167
- return result("authenticated", session, null);
5208
+ return result("authenticated", session, null, undefined, checked.account_label);
5168
5209
  return result("failed", session, checked.message ?? "公式CLIのstatusが未認証です。");
5169
5210
  }
5170
5211
  if (pane.input_required)
@@ -6678,7 +6719,7 @@ function adoptVanishedAgentNative(meta) {
6678
6719
  "文字列は送信していません。agent_launchで起動し直してください。", 2);
6679
6720
  }
6680
6721
  }
6681
- async function resumeAgentInLock(name, readyTimeout) {
6722
+ async function resumeAgentInLock(name, readyTimeout, claudeRoot) {
6682
6723
  const previous = loadAgentMetadata(name);
6683
6724
  readyTimeout ??= previous.kind === "codex" ? AGENT_TUI_FIRST_DRAW_TIMEOUT_MS : AGENT_TUI_READY_TIMEOUT_MS;
6684
6725
  let lifecycle = readAgentLifecycle(previous);
@@ -6727,7 +6768,10 @@ async function resumeAgentInLock(name, readyTimeout) {
6727
6768
  };
6728
6769
  try {
6729
6770
  assertExecutionResumeSupported();
6730
- 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;
6731
6775
  if (sessionExists(name))
6732
6776
  throw uncertain();
6733
6777
  const controlEnv = { ...process.env };
@@ -7593,8 +7637,13 @@ function prepareAgentLaunch(kind, opts = {}) {
7593
7637
  requireMatchingClaudeLaunch(opts.session_name, launchOperationId, launchRequestDigest);
7594
7638
  return () => existingAgentLaunchResult("claude", opts.session_name, model, effort);
7595
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]] : [];
7596
7645
  if (kind === "claude")
7597
- assertClaudeAuthenticationReady(bin);
7646
+ assertClaudeAuthenticationReady(bin, claudeEnv);
7598
7647
  if (kind === "cursor")
7599
7648
  assertCursorAuthenticationReady(bin);
7600
7649
  if (kind === "antigravity") {
@@ -7660,7 +7709,7 @@ function prepareAgentLaunch(kind, opts = {}) {
7660
7709
  const meta = withExecutionPreparation(sid, () => {
7661
7710
  const meta = agentDone
7662
7711
  ? kind === "claude"
7663
- ? 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)
7664
7713
  : kind === "codex"
7665
7714
  ? createCodexAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", { model, effort }, writeScope, lineageContext)
7666
7715
  : kind === "antigravity"
@@ -7694,7 +7743,7 @@ function prepareAgentLaunch(kind, opts = {}) {
7694
7743
  initialProof = proof;
7695
7744
  }
7696
7745
  try {
7697
- 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);
7698
7747
  }
7699
7748
  catch {
7700
7749
  process.stderr.write("aiterm: resume_template_unconfirmed\n");
@@ -7715,12 +7764,13 @@ function prepareAgentLaunch(kind, opts = {}) {
7715
7764
  : kind === "antigravity" ? antigravityAgentArgv(bin, model, effort, prompt)
7716
7765
  : grokAgentArgv(kind, bin, model, effort, prompt, meta);
7717
7766
  full = windowsAgentLaunchLine(cwd, [
7718
- ...(meta?.kind === "grok" ? grokEnvEntries(meta) : []), ...agentEnvEntries(meta, sid, envVars),
7767
+ ...claudeRootEntries, ...(meta?.kind === "grok" ? grokEnvEntries(meta) : []), ...agentEnvEntries(meta, sid, envVars),
7719
7768
  ], windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), meta?.windows_launch_exit_tracked ? { file: agentMetadataPath(sid, meta.launch_id) + ".launch-exited", launch_id: meta.launch_id } : undefined);
7720
7769
  }
7721
7770
  else {
7722
7771
  const cmd = buildAgentCmd(kind, binForCmd, model, effort, opts.prompt ?? null, meta, cursorFast);
7723
- 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);
7724
7774
  const command = cwdForCmd ? `cd ${shq(cwdForCmd)} && ${envPrefix}${cmd}` : `${envPrefix}${cmd}`;
7725
7775
  // このpaneのbashはAitermが自分で選んだ。sub-agent instructionのLFを含む起動commandは、
7726
7776
  // 利用者のshell送信と同じknown-shell適合で1物理行にしてから打つ(sanitizeはしない)。
@@ -7823,6 +7873,9 @@ export class AgentLaunchPromptError extends AitermError {
7823
7873
  }
7824
7874
  }
7825
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);
7826
7879
  if (opts.session_name)
7827
7880
  await withExecutionNativeAdmission(opts.session_name, () => assertExecutionContext(opts.session_name));
7828
7881
  else
@@ -7883,12 +7936,17 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
7883
7936
  || (opts.write_scope !== undefined && opts.write_scope !== previous.write_scope)
7884
7937
  || (opts.env_vars !== undefined && !isDeepStrictEqual([...new Set(opts.env_vars)].sort(), Object.keys(recipe.environment).sort())))
7885
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);
7886
7944
  if (opts.launch_operation_id != null)
7887
7945
  requireMatchingClaudeLaunch(name, validateOperationId(opts.launch_operation_id), claudeLaunchRequestDigest({ sessionName: name, model: opts.model ?? null, effort: opts.reasoning_effort ?? null,
7888
7946
  cwd: opts.cwd ?? null, agentDone: true }));
7889
7947
  if (preparedLifecycle)
7890
7948
  commitWorkingAgentResume(previous, preparedLifecycle);
7891
- const resumed = await resumeAgentInLock(name, opts.ready_timeout ?? undefined);
7949
+ const resumed = await resumeAgentInLock(name, opts.ready_timeout ?? undefined, rootChange);
7892
7950
  return withAgentResumeTarget(resumed, async () => {
7893
7951
  const hint = `${agentLabel(kind)} を保存した同じ会話へ再開した。\n${attachHint(name)}`;
7894
7952
  const fastState = { fast: resumed.fast === true, fast_error: null };
@@ -7931,6 +7989,7 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
7931
7989
  cursor_fast: fastPlan.cursor_fast,
7932
7990
  fast_state: fastPlan.state,
7933
7991
  base_model: requestedModel,
7992
+ claude_root: claudeRoot,
7934
7993
  };
7935
7994
  // GrokとCursorは、起動の --model の値を利用者の既定へ書く(Cursorは版による)。起動の前後で、直前の値へ戻す。
7936
7995
  const launch = () => {
@@ -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
@@ -753,15 +753,26 @@ export function createAitermServer(options = {}) {
753
753
  });
754
754
  registerRemoteAwareTool("pty_close", {
755
755
  description: "セッションを閉じ、ログ/読取位置を破棄する。同じsession_idへの再試行は安全で、" +
756
- "closed/already_closedのstructured receiptを返す。",
757
- 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
+ },
758
765
  outputSchema: {
759
766
  schema: z.literal("aiterm.pty-close-result.v1"),
760
767
  session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),
761
- outcome: z.enum(["closed", "already_closed"]),
768
+ outcome: z.enum(["closed", "already_closed", "hibernated"]),
762
769
  },
763
- }, async ({ session_id }) => {
770
+ }, async ({ session_id, hibernate }) => {
764
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
+ }
765
776
  await parentDelivery?.beforeChange(session_id);
766
777
  const result = core.closeSessionResult(session_id);
767
778
  return {
@@ -1001,6 +1012,7 @@ export function createAitermServer(options = {}) {
1001
1012
  cwd: z.string().optional().describe("公式CLIを実行する作業ディレクトリの絶対パス"),
1002
1013
  env_vars: z.array(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).optional().describe("startで認証PTYへ引き継ぐ環境変数名。値はreceiptへ返さない"),
1003
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"),
1004
1016
  },
1005
1017
  outputSchema: {
1006
1018
  schema: z.literal("aiterm.agent-auth-result.v1"),
@@ -1012,6 +1024,7 @@ export function createAitermServer(options = {}) {
1012
1024
  user_code: z.string().nullable(),
1013
1025
  input_required: z.boolean(),
1014
1026
  message: z.string().nullable(),
1027
+ account_label: z.string().nullable().optional().describe("claude-code harnessでauthenticatedの時だけ。公式statusのe-mail(表示用、資格情報ではない)。読めない時はnull"),
1015
1028
  },
1016
1029
  }, async ({ harness, ...options }) => {
1017
1030
  try {
@@ -1203,7 +1216,7 @@ export function createAitermServer(options = {}) {
1203
1216
  }
1204
1217
  async function launchAgent(kind, args, extra) {
1205
1218
  const supportsWriteScope = kind !== "claude";
1206
- 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;
1207
1220
  let delivery = null;
1208
1221
  try {
1209
1222
  if (!supportsWriteScope && write_scope !== undefined) {
@@ -1230,6 +1243,7 @@ export function createAitermServer(options = {}) {
1230
1243
  cwd: cwd ?? undefined,
1231
1244
  session_name: session_name ?? undefined,
1232
1245
  require_existing_resume,
1246
+ configuration_root,
1233
1247
  launch_operation_id: launch_operation_id ?? undefined,
1234
1248
  ...(supportsWriteScope ? { write_scope } : {}),
1235
1249
  });
@@ -1300,6 +1314,7 @@ export function createAitermServer(options = {}) {
1300
1314
  }
1301
1315
  : {};
1302
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に同じ会話の記録がある時だけ替えられる");
1303
1318
  correlatedLaunchSchema.launch_operation_id = z
1304
1319
  .string()
1305
1320
  .regex(/^sha256:[0-9a-f]{64}$/)
@@ -1363,6 +1378,7 @@ export function createAitermServer(options = {}) {
1363
1378
  agentEnvironmentDesc + agentCompletionDesc,
1364
1379
  inputSchema: {
1365
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だけ"),
1366
1382
  harness: z.enum(["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"]).describe("agent loop・session・hook・transcript・認証を所有する実行基盤"),
1367
1383
  prompt: z.string().nullish().describe("起動時に渡す初手プロンプト(任意)。送信後は待たずに即返る"),
1368
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.18",
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": [