aiterm-mcp 0.70.19 → 0.70.21

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.70.21] - 2026-11-11
11
+
12
+ - A terminal's seat MCP forward no longer goes down a few seconds after a launch. The `ssh -R` keeper ran inside the MCP process that handled the launch; BellTeam launches through a one-shot Aiterm, so the forward died when that process ended and stayed refused until another process's 60-second check (about 45 s in a lab run). A seat whose Claude was still connecting its MCP servers then, or that started in that window, lost its tools for good. The forward is now held by a detached keeper process (`aiterm-remote-terminal forward-keeper --ref R`) that lives while the forward is needed; MCP processes only start it when no live keeper holds the lock.
13
+
14
+ ## [0.70.20] - 2026-11-11
15
+
16
+ - `agent_auth` (claude-code) takes `login: "oauth_token"` with `token_file` (only `<HOME>/.bellteam-accounts/claude/<slot>/oauth-token`; any other path is `AGENT_AUTH_TOKEN_FILE_REJECTED` before anything starts). `start` always runs `claude setup-token` (under `configuration_root`, same `auth_ui` stages, binding and `respond`), and Aiterm writes the printed token to `token_file` as the seat user, 0600, through a temp file, fsync and rename; the pane's history and screen are then cleared. The token is never in a receipt, `auth_ui`, a log, env or argv. Failure or cancel writes nothing. `status` in this mode reports `authenticated` only for a non-empty 0600 regular file of the user and never reads `.credentials.json`. Receipts echo `login: "oauth_token"`, so a caller can refuse an older Aiterm that would run `claude auth login` instead.
17
+
10
18
  ## [0.70.19] - 2026-11-11
11
19
 
12
20
  - Windows: a Claude Code installed by npm (`claude.cmd`) now gets every launch argument. The `.cmd` shim passes `%*` through `cmd.exe`, which ends the arguments at the first newline, so everything after the multi-line `--append-system-prompt` (`--mcp-config`, `--model`, `--effort`) was lost and the seat ran without its MCP servers on the default model. Aiterm now runs the shim's `.exe` directly.
@@ -3279,7 +3287,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3279
3287
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3280
3288
  provenance.
3281
3289
 
3282
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.19...HEAD
3290
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.21...HEAD
3291
+ [0.70.21]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.20...v0.70.21
3292
+ [0.70.20]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.19...v0.70.20
3283
3293
  [0.70.19]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.18...v0.70.19
3284
3294
  [0.70.18]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.17...v0.70.18
3285
3295
  [0.70.17]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.16...v0.70.17
package/README.ja.md CHANGED
@@ -215,7 +215,7 @@ runtime-error store は canonical dotagents config の `collection.enabled: true
215
215
  場合だけ収集し、既定OFF、network送信は行いません。tag起点CIのnpm provenance(OIDC Trusted
216
216
  Publishing)で公開し、GitHub Release が Official MCP Registry を再登録します。
217
217
 
218
- **状態:** 開発継続中 · 現行公開版 **v0.70.19** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.70.21** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
219
219
 
220
220
  ### 更新と巻き戻し
221
221
 
package/README.md CHANGED
@@ -227,7 +227,7 @@ collection is off by default and performs no network I/O. It ships via
227
227
  tag-triggered CI with npm provenance (OIDC Trusted Publishing); the GitHub
228
228
  Release re-registers the Official MCP Registry entry.
229
229
 
230
- **Status:** actively maintained · current public release **v0.70.19** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
230
+ **Status:** actively maintained · current public release **v0.70.21** · 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
 
package/dist/core.js CHANGED
@@ -67,7 +67,7 @@ import { readFileOrNull, restoreJsonSetting, withUserConfigLock, restoreUserDefa
67
67
  import { isDeepStrictEqual } from "node:util";
68
68
  import { grokAuthPlan, grokAuthStatus, grokAuthPane, GROK_MODEL_DEFAULTS, realGrokHome, resolveAndValidateGrokAuth, assertGrokModelAvailable, grokModelChoices, grokModelFromFooter, grokFooterModelName, grokModelDefaultsFromBody, restoreGrokModelDefaults, grokEventsTranscript, grokSessionDirectory, latestGrokCompletion, grokTurnSettled, observeGrokDone, buildGrokAgentCmd, grokAgentArgv, writeGrokCallerFiles, checkGrokCallerInput, grokLaunchNote, grokEnvTokens, grokEnvEntries, grokTuiReady, grokPaneObservation, GROK_INTERRUPT_KEY, grokRateLimitDialog, grokPromptAwaitingAccept, grokUnacceptedPromptRestored, grokStartupAction, grokFooterHasConfiguration, grokTranscriptText, createGrokAgentMetadata, } from "./harnesses/grok.js";
69
69
  import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexCompletedTurnId, codexWorkingResumeConfiguration, captureCodexRecoveryProof, captureCodexResumeProof, readCodexResumeProof, codexResumeProofDigest, codexRootTranscript, codexRolloutSessionId, codexRunningTurn, codexInterruptionRecord, observeCodexDone, buildCodexAgentCmd, codexAgentArgv, codexResumeArgv, writeCodexCallerFiles, refuseCodexCallerInput, codexLaunchNote, codexPaneObservation, CODEX_INTERRUPT_KEY, codexHelperProcess, codexRateLimitModelSwitchDialog, codexApprovalDialog, codexStartupAction, codexModelChoice, codexEffortChoice, codexMoreReasoningChoice, codexTranscriptText, createCodexAgentMetadata, codexModelChoices, codexFastCommandOffered, codexFooterShowsFast, codexServiceTierNotices, restoreCodexDefaults, restoreCodexDefaultInFile, } from "./harnesses/codex.js";
70
- 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, writeClaudeCallerFiles, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, claudeApiErrorEndingTurn, claudeFailureCategory, } from "./harnesses/claude.js";
70
+ import { claudeAuthPlan, claudeAuthStatus, claudeAuthPane, claudeOauthTokenFile, claudeSetupTokenPlan, claudeOauthToken, claudeOauthTokenPresent, writeClaudeOauthToken, 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, writeClaudeCallerFiles, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, claudeApiErrorEndingTurn, claudeFailureCategory, } from "./harnesses/claude.js";
71
71
  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, cursorLineagePreface, writeCursorCallerFiles, checkCursorCallerInput, createCursorAgentMetadata, cursorLaunchNote, cursorEffortNavigation, cursorTuiReady, cursorPaneObservation, CURSOR_INTERRUPT_KEY, cursorPromptHooksRunning, cursorUsageLimit, CURSOR_SUBMIT_SEQUENCE, validateCursorModelEffort, } from "./harnesses/cursor.js";
72
72
  import { interimFromNow, interimFromToken, readInterimWords, recordInterimBoundary } from "./interim-words.js";
73
73
  import { codexSeatAwaitingRollout, codexSeatTurn, grokSteerAcceptance, observeSteerDone, readSteerEntry, recordSteer } from "./steer-follow.js";
@@ -4876,7 +4876,9 @@ function authMetadataPath(name) {
4876
4876
  assertSessionName(name);
4877
4877
  return path.join(agentsDir(), `${name}.auth.json`);
4878
4878
  }
4879
- function authPlan(kind, phase) {
4879
+ function authPlan(kind, phase, login) {
4880
+ if (login === "oauth_token")
4881
+ return claudeSetupTokenPlan();
4880
4882
  switch (kind) {
4881
4883
  case "claude": return claudeAuthPlan(phase === "onboarding");
4882
4884
  case "codex": return codexAuthPlan();
@@ -4930,7 +4932,9 @@ function loadAuthMetadata(name, kind) {
4930
4932
  || !["login", "onboarding"].includes(value.phase) || !Array.isArray(value.env_vars)
4931
4933
  || value.env_vars.some(key => typeof key !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
4932
4934
  || (value.claude_root !== undefined && (kind !== "claude" || typeof value.claude_root?.root !== "string" || !path.isAbsolute(value.claude_root.root)
4933
- || (value.claude_root.selector !== null && value.claude_root.selector !== value.claude_root.root)))) {
4935
+ || (value.claude_root.selector !== null && value.claude_root.selector !== value.claude_root.root)))
4936
+ || (value.login !== undefined && (kind !== "claude" || value.login !== "oauth_token" || typeof value.token_file !== "string"))
4937
+ || (value.login === undefined && (value.token_file !== undefined || value.token_written !== undefined))) {
4934
4938
  throw new AitermError("AGENT_AUTH_STATE_INVALID: 認証sessionの記録が不正です。", 2);
4935
4939
  }
4936
4940
  return value;
@@ -5109,7 +5113,7 @@ async function respondAgentAuth(kind, options) {
5109
5113
  }
5110
5114
  }
5111
5115
  function launchAuthProcess(name, meta) {
5112
- const plan = authPlan(meta.kind, meta.phase);
5116
+ const plan = authPlan(meta.kind, meta.phase, meta.login);
5113
5117
  const root = meta.claude_root;
5114
5118
  const env = [...(!root ? [] : root.selector === null ? ["-u", "CLAUDE_CONFIG_DIR"] : [shq(`CLAUDE_CONFIG_DIR=${root.selector}`)]),
5115
5119
  ...plan.env.map(([key, value]) => shq(`${key}=${value}`))];
@@ -5127,6 +5131,20 @@ export async function authenticateAgent(kind, options) {
5127
5131
  if (options.configuration_root !== undefined && kind !== "claude")
5128
5132
  throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: configuration_rootはclaude-code harnessだけで使えます。", 2);
5129
5133
  const claudeRoot = options.configuration_root === undefined ? undefined : resolveClaudeConfigurationRoot(options.configuration_root);
5134
+ if ((options.login !== undefined || options.token_file !== undefined) && (kind !== "claude" || options.login !== "oauth_token" || options.token_file === undefined))
5135
+ throw new AitermError("AGENT_AUTH_LOGIN_REJECTED: login:\"oauth_token\"はclaude-code harnessだけで、token_fileと組で使えます。開始していません。", 2);
5136
+ const tokenFile = options.token_file === undefined ? undefined : claudeOauthTokenFile(options.token_file);
5137
+ // The mode of an existing session is its own; a request naming another mode or file is refused like another root.
5138
+ // A broken or foreign record fails later at its usual place, in the usual order.
5139
+ let savedAuth = null;
5140
+ try {
5141
+ if (options.session_id !== undefined && options.action !== "start")
5142
+ savedAuth = loadAuthMetadata(options.session_id, kind);
5143
+ }
5144
+ catch { /* below */ }
5145
+ if (savedAuth && tokenFile !== undefined && savedAuth.token_file !== tokenFile)
5146
+ throw new AitermError("AGENT_AUTH_LOGIN_REJECTED: 認証sessionは別のloginかtoken_fileで始まっています。", 2);
5147
+ const login = options.action === "start" || !savedAuth ? options.login : savedAuth.login;
5130
5148
  if (claudeRoot && options.session_id !== undefined && options.action !== "start") {
5131
5149
  const saved = loadAuthMetadata(options.session_id, kind);
5132
5150
  if (saved && (saved.claude_root?.root !== claudeRoot.root || saved.claude_root.selector !== claudeRoot.selector))
@@ -5138,7 +5156,8 @@ export async function authenticateAgent(kind, options) {
5138
5156
  const receipt = { schema: "aiterm.agent-auth-result.v1", harness: agentHarness(kind), status,
5139
5157
  session_id: session, url: pane?.url ?? null, user_code: pane?.user_code ?? null,
5140
5158
  input_required: pane?.input_required ?? false, message: message ?? pane?.message ?? null,
5141
- ...(kind === "claude" && status === "authenticated" ? { account_label: label ?? null } : {}) };
5159
+ ...(kind === "claude" && status === "authenticated" && !login ? { account_label: label ?? null } : {}),
5160
+ ...(login ? { login } : {}) };
5142
5161
  receipt.auth_ui = authUi(receipt, pane, session ? readAuthBinding(session, kind) : null);
5143
5162
  if (isWin && receipt.auth_ui.input !== null)
5144
5163
  receipt.auth_ui = { ...receipt.auth_ui, stage: "unavailable", input: null, choices: [],
@@ -5176,14 +5195,15 @@ export async function authenticateAgent(kind, options) {
5176
5195
  const envVars = options.env_vars ?? [];
5177
5196
  if (claudeRoot && envVars.includes("CLAUDE_CONFIG_DIR"))
5178
5197
  throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: env_varsのCLAUDE_CONFIG_DIRとconfiguration_rootは同時に指定できません。", 2);
5179
- const before = options.relogin ? { status: "unauthenticated", message: null } : await authStatus(kind, bin, cwd, rootEnv(process.env));
5198
+ const before = options.relogin || login ? { status: "unauthenticated", message: null } : await authStatus(kind, bin, cwd, rootEnv(process.env));
5180
5199
  if (before.status === "failed")
5181
5200
  return result("failed", null, before.message);
5182
5201
  if (before.status === "authenticated" && !before.verify_onboarding)
5183
5202
  return result("authenticated", null, null, undefined, before.account_label);
5184
5203
  [name] = openSession(name, "bash", envVars);
5185
5204
  meta = { kind, bin, cwd, phase: before.status === "authenticated" ? "onboarding" : "login",
5186
- env_vars: envVars.filter(key => process.env[key] !== undefined), ...(claudeRoot ? { claude_root: claudeRoot } : {}) };
5205
+ env_vars: envVars.filter(key => process.env[key] !== undefined), ...(claudeRoot ? { claude_root: claudeRoot } : {}),
5206
+ ...(login ? { login, token_file: tokenFile } : {}) };
5187
5207
  try {
5188
5208
  const kept = tmux("set-option", "-t", name, "remain-on-exit", "on");
5189
5209
  if (kept.code !== 0)
@@ -5192,6 +5212,9 @@ export async function authenticateAgent(kind, options) {
5192
5212
  // shortcut: AGY 1.4.12 hides its OAuth code field at 80x24; revisit if its auth layout grows.
5193
5213
  if (kind === "antigravity" && tmux("resize-window", "-t", name, "-x", "120", "-y", "60").code !== 0)
5194
5214
  throw new AitermError("AGENT_AUTH_PANE_CONFIG_FAILED: Antigravityの認証画面サイズを設定できません。", 2);
5215
+ // The ~110-character token must not be wrapped into separate lines by the CLI's own layout.
5216
+ if (login && tmux("resize-window", "-t", name, "-x", "400", "-y", "50").code !== 0)
5217
+ throw new AitermError("AGENT_AUTH_PANE_CONFIG_FAILED: 認証画面サイズを設定できません。", 2);
5195
5218
  meta.launch_id = randomBytes(16).toString("hex");
5196
5219
  if (hasExecutionCreationScope()) {
5197
5220
  meta.execution_native = executionCreatedNativeBinding(name);
@@ -5213,6 +5236,9 @@ export async function authenticateAgent(kind, options) {
5213
5236
  const bin = resolveAgentBin(kind);
5214
5237
  if (!bin)
5215
5238
  return result("failed", null, `${agentLabel(kind)}の公式CLIが見つかりません。`);
5239
+ if (tokenFile)
5240
+ return claudeOauthTokenPresent(tokenFile) ? result("authenticated", null, null)
5241
+ : result("blocked", null, "token_fileがありません。agent_authのstartで開始してください。");
5216
5242
  const checked = await authStatus(kind, bin, cwd, rootEnv(process.env));
5217
5243
  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);
5218
5244
  }
@@ -5250,7 +5276,28 @@ export async function authenticateAgent(kind, options) {
5250
5276
  if (observed.code !== 0)
5251
5277
  return result("failed", session, "認証processの終了状態を取得できません。");
5252
5278
  const [dead, exit, signal] = observed.stdout.trim().split("\t");
5253
- const pane = authPane(meta, stripControl(captureScreen(session, 0)));
5279
+ const screen = stripControl(captureScreen(session, 0));
5280
+ const pane = authPane(meta, screen);
5281
+ let token = meta.login ? claudeOauthToken(screen) : null;
5282
+ // While the CLI still runs, take the token only when a second look shows the same one (no half-drawn line).
5283
+ if (token && dead === "0") {
5284
+ await sleep(200);
5285
+ if (claudeOauthToken(stripControl(captureScreen(session, 0))) !== token)
5286
+ token = null;
5287
+ }
5288
+ if (token) {
5289
+ const tokenRefusal = pendingExitRefusal();
5290
+ if (tokenRefusal)
5291
+ return tokenRefusal;
5292
+ writeClaudeOauthToken(meta.token_file, token);
5293
+ withExecutionPreparation(session, () => { meta.token_written = true; writeJson0600(authMetadataPath(session), meta); });
5294
+ // The token was only on this pane: clear its history and screen, leaving a dead pane that exited 0.
5295
+ const wiped = tmux("clear-history", "-t", session).code === 0
5296
+ && tmux("respawn-pane", "-k", "-t", session, ...(isWin ? ["cmd.exe", "/d", "/c", "exit 0"] : ["/bin/sh", "-c", "exit 0"])).code === 0;
5297
+ if (!wiped)
5298
+ closeSession(session);
5299
+ return result("authenticated", wiped ? session : null, null);
5300
+ }
5254
5301
  const afterExitRead = pendingExitRefusal();
5255
5302
  if (afterExitRead)
5256
5303
  return afterExitRead;
@@ -5267,6 +5314,9 @@ export async function authenticateAgent(kind, options) {
5267
5314
  return result("failed", session, `公式認証processがsignalで終了しました(signal=${/^[A-Z0-9]+$/.test(signal) ? signal : "unknown"})。`);
5268
5315
  if (exit !== "0")
5269
5316
  return result("failed", session, `公式認証processが失敗しました(exit=${/^\d+$/.test(exit ?? "") ? exit : "unknown"})。`);
5317
+ if (meta.login)
5318
+ return meta.token_written && claudeOauthTokenPresent(meta.token_file) ? result("authenticated", session, null)
5319
+ : result("failed", session, "公式CLIは終了しましたが、tokenを確認できません。token_fileは変えていません。");
5270
5320
  const checked = await authStatus(kind, meta.bin, meta.cwd, sessionEnv(session, meta));
5271
5321
  const afterOfficialStatus = pendingExitRefusal();
5272
5322
  if (afterOfficialStatus)
@@ -839,6 +839,73 @@ export function claudeApiErrorAfter(meta, startedAtMs) {
839
839
  }
840
840
  return null;
841
841
  }
842
+ // ---- login "oauth_token" (BellTeam Claude 2nd slot, Owner ruling 2026-11-09): `claude setup-token` prints a 1-year token once;
843
+ // Aiterm, as the PTY owner, writes it to the slot's token file. The CLI keeps no copy, so the file is the credential.
844
+ const OAUTH_TOKEN_RE = /sk-ant-oat01-[A-Za-z0-9_-]{20,}/g;
845
+ /** The only accepted token file: `<HOME>/.bellteam-accounts/claude/<slot>/oauth-token`. Anything else is refused before any start. */
846
+ export function claudeOauthTokenFile(file) {
847
+ const home = process.env.HOME ?? os.homedir();
848
+ const slot = typeof file === "string" && path.isAbsolute(file) && path.basename(file) === "oauth-token" ? path.basename(path.dirname(file)) : "";
849
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(slot) || file !== path.join(home, ".bellteam-accounts", "claude", slot, "oauth-token"))
850
+ throw new AitermError("AGENT_AUTH_TOKEN_FILE_REJECTED: token_fileは<HOME>/.bellteam-accounts/claude/<slot>/oauth-tokenだけを受けます。開始していません。", 2);
851
+ return file;
852
+ }
853
+ export function claudeSetupTokenPlan() { return { args: ["setup-token"], env: [] }; }
854
+ /** The token on the setup-token screen, only when exactly one distinct token is shown. */
855
+ export function claudeOauthToken(screen) {
856
+ const found = new Set(screen.match(OAUTH_TOKEN_RE) ?? []);
857
+ return found.size === 1 ? [...found][0] : null;
858
+ }
859
+ /** Authenticated iff the token file is this user's non-empty regular 0600 file (POSIX; Windows has no such mode bits). */
860
+ export function claudeOauthTokenPresent(file) {
861
+ let stat;
862
+ try {
863
+ stat = fs.lstatSync(file);
864
+ }
865
+ catch {
866
+ return false;
867
+ }
868
+ if (!stat.isFile() || stat.size === 0)
869
+ return false;
870
+ return process.platform === "win32" || ((stat.mode & 0o777) === 0o600 && stat.uid === process.getuid());
871
+ }
872
+ /** tmp + fsync + rename in the same directory, then fsync the directory. An older token is replaced (the Owner's relogin). */
873
+ export function writeClaudeOauthToken(file, token) {
874
+ const dir = path.dirname(file);
875
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
876
+ const tmp = path.join(dir, `.oauth-token.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
877
+ const bytes = Buffer.from(token, "utf8");
878
+ try {
879
+ const fd = fs.openSync(tmp, "wx", 0o600);
880
+ try {
881
+ fs.writeSync(fd, bytes);
882
+ fs.fsyncSync(fd);
883
+ }
884
+ finally {
885
+ fs.closeSync(fd);
886
+ }
887
+ fs.renameSync(tmp, file);
888
+ }
889
+ catch (error) {
890
+ try {
891
+ fs.unlinkSync(tmp);
892
+ }
893
+ catch { /* not created */ }
894
+ throw error;
895
+ }
896
+ finally {
897
+ bytes.fill(0);
898
+ }
899
+ if (process.platform !== "win32") {
900
+ const fd = fs.openSync(dir, "r");
901
+ try {
902
+ fs.fsyncSync(fd);
903
+ }
904
+ finally {
905
+ fs.closeSync(fd);
906
+ }
907
+ }
908
+ }
842
909
  export function claudeAuthPlan(onboarding = false) { return { args: onboarding ? [] : ["auth", "login"], env: [] }; }
843
910
  export function claudeAuthStatus(bin, cwd, env = process.env) {
844
911
  const result = spawnAgentControlCommand(bin, ["auth", "status", "--json"], cwd, { cwd, env, encoding: "utf8", timeout: 5000, maxBuffer: 64 * 1024 });
package/dist/index.js CHANGED
@@ -1078,6 +1078,9 @@ export function createAitermServer(options = {}) {
1078
1078
  env_vars: z.array(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).optional().describe("startで認証PTYへ引き継ぐ環境変数名。値はreceiptへ返さない"),
1079
1079
  relogin: z.boolean().optional().describe("startで、公式の状態が認証済みでも公式ログインを開始する。既定false。trueの時、authenticatedかつsession_idがnullの結果は返さない"),
1080
1080
  configuration_root: z.string().min(1).optional().describe("claude-code harnessだけ。認証する設定root(CLAUDE_CONFIG_DIR)。受ける範囲はagent_launchと同じ。startで決めたrootと違う指定はAGENT_CONFIGURATION_ROOT_REJECTED"),
1081
+ login: z.enum(["oauth_token"]).optional().describe("claude-code harnessだけ、token_fileと組。startは状態を聞かずに必ず `claude setup-token` を起こし、出たtokenをAitermがtoken_fileへ書く(本人・0600・置き換え)。" +
1082
+ "statusはtoken_fileが本人の0600の空でない通常fileの時だけauthenticated(.credentials.jsonは見ない)。失敗・取消では書かない。receiptはloginを返す"),
1083
+ token_file: z.string().min(1).optional().describe("login:\"oauth_token\"の書き先。HOME配下の決まった形のslotのoauth-tokenだけを受け、他はAGENT_AUTH_TOKEN_FILE_REJECTED(開始しない)"),
1081
1084
  },
1082
1085
  outputSchema: {
1083
1086
  schema: z.literal("aiterm.agent-auth-result.v1"),
@@ -1090,6 +1093,7 @@ export function createAitermServer(options = {}) {
1090
1093
  input_required: z.boolean(),
1091
1094
  message: z.string().nullable(),
1092
1095
  account_label: z.string().nullable().optional().describe("claude-code harnessでauthenticatedの時だけ。公式statusのe-mail(表示用、資格情報ではない)。読めない時はnull"),
1096
+ login: z.enum(["oauth_token"]).optional().describe("login:\"oauth_token\"で扱った時だけ。無ければ、このAitermはそのmodeを知らない"),
1093
1097
  },
1094
1098
  }, async ({ harness, ...options }) => {
1095
1099
  try {
@@ -12,7 +12,7 @@ import { createRequire } from "node:module";
12
12
  import { z } from "zod";
13
13
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
14
14
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
15
- import { REMOTE_COMMAND_OPS, RemoteTerminalConnection, RemoteTerminalError, bindingStatus, confirmHostKey, loadCredential, registerBinding } from "./remote-terminal.js";
15
+ import { REMOTE_COMMAND_OPS, RemoteTerminalConnection, RemoteTerminalError, bindingStatus, confirmHostKey, loadCredential, registerBinding, runForwardKeeper } from "./remote-terminal.js";
16
16
  import { readCompletedTranscript } from "./transcript-read.js";
17
17
  import { credentialHandleSchema, terminalOsSchema } from "./remote-contract.js";
18
18
  import { inspectPath, listDirectories, makeDirectory } from "./remote-path.js";
@@ -118,6 +118,9 @@ export function main(args) {
118
118
  const [command, ...rest] = args;
119
119
  if (command === "serve")
120
120
  return serve();
121
+ // Started detached by Aiterm itself (remote-terminal.md forward keeper); not an operator command.
122
+ if (command === "forward-keeper")
123
+ return runForwardKeeper(option(rest, "--ref") ?? "");
121
124
  if (command === "status")
122
125
  return oneShot(() => bindingStatus(option(rest, "--ref") ?? ""), "aiterm.remote-binding-error.v1");
123
126
  if (command === "register")
@@ -7,12 +7,14 @@ import * as os from "node:os";
7
7
  import * as path from "node:path";
8
8
  import { createHash, randomUUID } from "node:crypto";
9
9
  import { createRequire } from "node:module";
10
+ import { fileURLToPath } from "node:url";
10
11
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
11
12
  import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
12
13
  import { ensureStateRoot, writeJson0600 } from "./agent-shared.js";
13
14
  import { powershellForShell, remotePlatform, remoteShell, terminalCommand, terminalProgram } from "./remote.js";
14
15
  import { PRIVATE_ENV_SCHEMA } from "./private-env.js";
15
16
  import { checkRemotePath } from "./remote-path.js";
17
+ import { liveNodeExecutable } from "./live-node.js";
16
18
  const pkg = createRequire(import.meta.url)("../package.json");
17
19
  export class RemoteTerminalError extends Error {
18
20
  code;
@@ -927,7 +929,50 @@ function storedIngress(ref) {
927
929
  return undefined;
928
930
  }
929
931
  }
932
+ // Only the detached keeper process (`forward-keeper --ref R`) holds the ssh. BellTeam launches through a one-shot Aiterm,
933
+ // and a forward held there died with it right after the launch (lab 2026-11-11: ~45 s refused until a 60 s check).
934
+ let keeperProcess = false;
935
+ const startedKeepers = new Map();
936
+ const KEEPER_CLI = new URL("./remote-terminal-cli.js", import.meta.url);
937
+ function startForwardKeeper(ref) {
938
+ if (!forwardNeeded(ref)) {
939
+ releaseIdleCredential(ref);
940
+ return;
941
+ }
942
+ const owner = lockOwner(ref);
943
+ if (owner && ownerAlive(owner))
944
+ return;
945
+ const started = startedKeepers.get(ref); // one keeper per process at a time, while it takes the lock
946
+ if (started && started.exitCode === null && started.signalCode === null)
947
+ return;
948
+ const child = spawn(liveNodeExecutable(), [fileURLToPath(KEEPER_CLI), "forward-keeper", "--ref", ref], { detached: true, stdio: "ignore", env: process.env, windowsHide: true });
949
+ child.on("error", () => { /* exitCode stays null: clear it so the next check starts another */ startedKeepers.delete(ref); });
950
+ child.unref();
951
+ startedKeepers.set(ref, child);
952
+ }
953
+ /** `aiterm-remote-terminal forward-keeper --ref R`: hold R's forward while it is needed; exit when this process has nothing to hold. */
954
+ export function runForwardKeeper(ref) {
955
+ binding(ref);
956
+ keeperProcess = true;
957
+ keeperHold = setInterval(() => { keep(ref); settleKeeper(ref); }, 5_000);
958
+ keep(ref);
959
+ settleKeeper(ref);
960
+ }
961
+ let keeperHold = null;
962
+ /** The keeper process ends (its loop stops, nothing else holds it) once it has no forward, timer, probe or lock. */
963
+ function settleKeeper(ref) {
964
+ const keeper = keepers.get(ref);
965
+ if (!keeperHold || (keeper && (keeper.child || keeper.timer || keeper.starting || Number(lockOwner(ref)?.pid) === process.pid)))
966
+ return;
967
+ clearInterval(keeperHold);
968
+ keeperHold = null;
969
+ keepers.delete(ref);
970
+ }
930
971
  function keep(ref) {
972
+ if (!keeperProcess) {
973
+ startForwardKeeper(ref);
974
+ return;
975
+ }
931
976
  const keeper = keepers.get(ref) ?? { child: null, ingress: 0, refusals: 0, timer: null };
932
977
  keepers.set(ref, keeper);
933
978
  if (keeper.child) {
@@ -1022,6 +1067,7 @@ function keep(ref) {
1022
1067
  again();
1023
1068
  else
1024
1069
  keep(ref);
1070
+ settleKeeper(ref);
1025
1071
  });
1026
1072
  }, () => { keeper.starting = false; again(); });
1027
1073
  }
package/docs/DESIGN.md CHANGED
@@ -434,6 +434,7 @@ native/server stampと新しいauth世代を保存・結合する。通常agent
434
434
  BellTeamのrefなしpty_send/pty_keyは、この作成proofを保持するauth PTYにだけ許可し、通常Botの未登録本文には広げない。
435
435
  初回案内のrespawnも同じsession世代を保ち、phase保存は準備受付を通す。旧auth metadataの欠測を現nativeから補わず、
436
436
  不明な入力・世代・未返却RPCのslotをstatusだけで解除しない。credentialの保存・操作は公式CLIが所有する。
437
+ 例外は`login: "oauth_token"`(claude-codeだけ、0.70.20、BellTeam usageのClaude 2nd slot。指揮官氏の裁定 2026-11-09)。`token_file`は`<HOME>/.bellteam-accounts/claude/<slot>/oauth-token`だけを受け、他は開始前に`AGENT_AUTH_TOKEN_FILE_REJECTED`。startは状態を聞かずに必ず`claude setup-token`を起こす(configuration_root・auth_ui・binding・respondは従来どおり、paneは400桁でtokenを折らない)。画面に出た`sk-ant-oat01-…`がちょうど1つの時、Aitermがそのtokenを`token_file`へ書く(本人・0600・tmp+fsync+rename・親dirもfsync、古いtokenは置き換え)。書いた直後に`clear-history`と`respawn-pane -k`(`exit 0`)でpaneの画面と履歴を消し、metadataへ`token_written`を残す。tokenはreceipt・auth_ui・log(pipe-paneは開始時に外す)・env・argvに出ない。失敗・取消・tokenの無いexit 0は書かず、元のfileは触らない。statusは、このmodeでは`.credentials.json`を見ず、`token_file`が本人の0600の通常fileで空でない時だけauthenticated(sessionありは加えて`token_written`)。receiptは`login: "oauth_token"`を返し、知らない旧版(黙って`claude auth login`を起こす)を呼び手が見分ける。
437
438
 
438
439
 
439
440
  PTYが消失した場合は、相関記録の有無にかかわらず`status`が`failed`、`cancel`が既に終了・取消済みを示す`blocked`を返し、どちらも`session_id:null`となる。保存したsession IDを解除して`start`で再開始できる。生存中の通常PTYやharness不一致、記録の破損・読取り失敗はエラーを返す。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.70.19",
3
+ "version": "0.70.21",
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": [