aiterm-mcp 0.70.18 → 0.70.20

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,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.70.20] - 2026-11-11
11
+
12
+ - `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.
13
+
14
+ ## [0.70.19] - 2026-11-11
15
+
16
+ - 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.
17
+ - Seat `env_vars` values (for example a seat MCP token) are no longer put on the terminal multiplexer's command line (`new-session -e`), where any process on the machine could read them from the process list (the psmux server keeps them in its argv on Windows). They reach the CLI only through the launch line's 0600 file, as before.
18
+ - A message sent to a terminal seat while its turn was running (`pty_send` taken as `agent_steer`) now returns a `wait_process` that waits over ssh for the end of the turn that took it (`aiterm-wait --cursor C --steer <id>` on the terminal). Before, the relay passed the terminal's own `wait_process` through: its Node path and files do not exist on the controlling host, so the wait failed and BellTeam recorded the accepted message as failed. A steer the relay cannot follow now answers `event_cursor`/`wait_process` null without the `aiterm/steer` meta.
19
+
10
20
  ## [0.70.18] - 2026-11-11
11
21
 
12
22
  - A seat relaunched on a terminal right after its last seat closed (for example `restart_session`) no longer gets a seat MCP port with no forward behind it (`ECONNREFUSED` at Claude start, and Claude Code never retries a failed MCP). The forward keeper stopped once no seat was bound, but the binding kept its port, and the next launch received that port at once. A launch in another Aiterm process was also invisible to the keeper. Now the keeper's remote command prints a mark once the forward's listener is up; a launch receives the port only when a live keeper reported that mark for it. A launch in any process keeps the forward needed until its seat is bound, and a stopped keeper hands over its lock at once, so the relaunch's process starts a new forward without the 15 s restart delay.
@@ -3273,7 +3283,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3273
3283
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3274
3284
  provenance.
3275
3285
 
3276
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.18...HEAD
3286
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.20...HEAD
3287
+ [0.70.20]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.19...v0.70.20
3288
+ [0.70.19]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.18...v0.70.19
3277
3289
  [0.70.18]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.17...v0.70.18
3278
3290
  [0.70.17]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.16...v0.70.17
3279
3291
  [0.70.16]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.15...v0.70.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.70.18** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.70.20** · 動作対象は 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.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.70.20** · 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
 
@@ -262,6 +262,22 @@ export function runThroughlineHandoffContext(bin, sessionId, supplementFile = nu
262
262
  encoding: "utf8",
263
263
  });
264
264
  }
265
+ /** The .exe an npm cmd-shim runs (`"%dp0%\\...\\x.exe" %*`), when it exists; null for any other .cmd. */
266
+ // shortcut: only exe targets; a node-script shim still goes through cmd.exe, upgrade when a harness ships one with multi-line argv.
267
+ export function npmShimExecutable(shim) {
268
+ let text;
269
+ try {
270
+ text = fs.readFileSync(shim, "utf8");
271
+ }
272
+ catch {
273
+ return null;
274
+ }
275
+ const match = /^"%dp0%\\([^"%\r\n]+\.exe)"\s+%\*\s*$/im.exec(text);
276
+ if (!match)
277
+ return null;
278
+ const exe = path.join(path.dirname(shim), ...match[1].split("\\"));
279
+ return fs.existsSync(exe) ? exe : null;
280
+ }
265
281
  /** Owned Windows agent launch: PowerShell uses argv, without interactive MSYS input. */
266
282
  export function windowsAgentLaunchLine(cwd, env, argv, exited) {
267
283
  const psq = (value) => `'${value.replace(/'/g, "''")}'`;
@@ -293,6 +309,10 @@ export function windowsLaunchIndirection(file) {
293
309
  * separate Git Bash window whose process outlives the pane (fox, 2026-10-14).
294
310
  */
295
311
  export function windowsAgentArgv(argv, scriptShell) {
312
+ // cmd.exe ends %* at the first newline, so a multi-line --append-system-prompt dropped every later argument (fox 2026-11-11).
313
+ const npmExe = /\.cmd$/i.test(argv[0]) ? npmShimExecutable(argv[0]) : null;
314
+ if (npmExe)
315
+ return [npmExe, ...argv.slice(1)];
296
316
  if (/\.(?:exe|com|cmd|bat|ps1)$/i.test(argv[0]))
297
317
  return argv;
298
318
  return [scriptShell(), argv[0].replace(/\\/g, "/"), ...argv.slice(1)];
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)
@@ -7822,7 +7872,9 @@ function prepareAgentLaunch(kind, opts = {}) {
7822
7872
  // command through MSYS interactive select/console-master input handling.
7823
7873
  const paneShell = isWin ? "pwsh" : "bash";
7824
7874
  try {
7825
- [sid, hint] = openSession(opts.session_name ?? null, paneShell, envVars);
7875
+ // env_vars values go only by the launch line's 0600 file: session -e would put them in the multiplexer's argv,
7876
+ // which any process can list (psmux server on Windows, fox 2026-11-11).
7877
+ [sid, hint] = openSession(opts.session_name ?? null, paneShell, []);
7826
7878
  }
7827
7879
  catch (error) {
7828
7880
  if (launchOperationId !== null && sessionExists(opts.session_name)) {
@@ -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
@@ -394,6 +394,8 @@ export function createAitermServer(options = {}) {
394
394
  await remoteParentDelivery.beforeChange(key);
395
395
  const result = await callRemoteTool(target, "pty_send", args, undefined, undefined, extra?._meta);
396
396
  const structured = result.structuredContent;
397
+ if (structured?.wait_process && (structured.mode === "agent_steer" || result.isError))
398
+ return relaySteerWait(target, result);
397
399
  if (result.isError || !structured || structured.mode !== "agent_dispatch")
398
400
  return remoteResult(target, result);
399
401
  try {
@@ -411,6 +413,17 @@ export function createAitermServer(options = {}) {
411
413
  const relayed = remoteResult(target, result, { ...structured, wait_process: waited.wait_process, ...(delivery?.result() ? { parent_delivery: delivery.result() } : {}) });
412
414
  return { ...relayed, content: [...relayed.content, { type: "text", text: deliveryIdLine(delivery).trim() || "completion=wait_process" }] };
413
415
  }
416
+ /** 現地の差し込みの返りのwait_processは現地のNodeとpathなので、ここで走らない。同じ差し込みの番の終わりをssh越しに待つものへ替える。 */
417
+ async function relaySteerWait(target, result) {
418
+ const structured = result.structuredContent;
419
+ const steerId = structured.steer_id ?? result._meta?.[STEER_RESULT_META_KEY]?.steer_id;
420
+ // 番を特定できない待ちは返さない。呼び手は追えない差し込みとして扱う(steer-refも外す)。
421
+ if (structured.event_cursor === null || typeof steerId !== "string") {
422
+ const { [STEER_RESULT_META_KEY]: _dropped, ...meta } = (result._meta ?? {});
423
+ return remoteResult(target, { ...result, _meta: Object.keys(meta).length ? meta : undefined }, { ...structured, event_cursor: null, wait_process: null });
424
+ }
425
+ return remoteResult(target, result, { ...structured, wait_process: await remoteWaitProcess(target, structured.session_id, structured.event_cursor, undefined, steerId) });
426
+ }
414
427
  /** 別端末の子の依頼を、この端末の親への配送に登録する。launch_idは現地の完了観測から取る。 */
415
428
  async function registerRemoteDelivery(delivery, target, sessionId, eventCursor, operationId = null, inputId) {
416
429
  const probe = await observeRemoteAgentDone(target, sessionId, { cursor: eventCursor, operation_id: operationId, timeout: 0, input_id: inputId });
@@ -1065,6 +1078,9 @@ export function createAitermServer(options = {}) {
1065
1078
  env_vars: z.array(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).optional().describe("startで認証PTYへ引き継ぐ環境変数名。値はreceiptへ返さない"),
1066
1079
  relogin: z.boolean().optional().describe("startで、公式の状態が認証済みでも公式ログインを開始する。既定false。trueの時、authenticatedかつsession_idがnullの結果は返さない"),
1067
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(開始しない)"),
1068
1084
  },
1069
1085
  outputSchema: {
1070
1086
  schema: z.literal("aiterm.agent-auth-result.v1"),
@@ -1077,6 +1093,7 @@ export function createAitermServer(options = {}) {
1077
1093
  input_required: z.boolean(),
1078
1094
  message: z.string().nullable(),
1079
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を知らない"),
1080
1097
  },
1081
1098
  }, async ({ harness, ...options }) => {
1082
1099
  try {
package/dist/remote.js CHANGED
@@ -269,13 +269,15 @@ export async function callRemoteTool(target, name, args, timeoutMs = 600_000, pr
269
269
  }
270
270
  const SESSION_RE = /^[A-Za-z0-9_-]{1,64}$/;
271
271
  const OPERATION_RE = /^sha256:[0-9a-f]{64}$/;
272
- export function remoteWaitCommand(shell, session, cursor, operationId, timeout, inputId, trusted = false) {
272
+ export function remoteWaitCommand(shell, session, cursor, operationId, timeout, inputId, trusted = false, steerId) {
273
273
  if (!SESSION_RE.test(session))
274
274
  throw new AitermError("REMOTE_SESSION_INVALID: session名が不正です", 2);
275
275
  if (operationId !== null && !OPERATION_RE.test(operationId))
276
276
  throw new AitermError("REMOTE_OPERATION_INVALID: operation_idが不正です", 2);
277
277
  if (inputId !== undefined && (!/^[a-f0-9]{32}$/.test(inputId) || cursor === null))
278
278
  throw new AitermError("REMOTE_INPUT_INVALID: input_id requires its original cursor", 2);
279
+ if (steerId !== undefined && (!/^[0-9a-f]{16}$/.test(steerId) || cursor === null || inputId !== undefined || operationId !== null))
280
+ throw new AitermError("REMOTE_STEER_INVALID: steer_id requires its cursor alone", 2);
279
281
  const parts = ["--session", session, "--timeout", String(timeout)];
280
282
  if (cursor !== null)
281
283
  parts.push("--cursor", String(cursor));
@@ -283,6 +285,8 @@ export function remoteWaitCommand(shell, session, cursor, operationId, timeout,
283
285
  parts.push("--operation", operationId);
284
286
  if (inputId !== undefined)
285
287
  parts.push("--input", inputId);
288
+ if (steerId !== undefined)
289
+ parts.push("--steer", steerId);
286
290
  if (trusted)
287
291
  return terminalCommand(shell, terminalProgram(["aiterm-wait", ...parts]));
288
292
  if (shell !== "posix")
@@ -290,9 +294,9 @@ export function remoteWaitCommand(shell, session, cursor, operationId, timeout,
290
294
  return posixCommand(terminalProgram(["aiterm-wait", ...parts]).posix);
291
295
  }
292
296
  /** 親が別processで起動する完了待ち。ssh越しのaiterm-waitで、exit codeは現地のaiterm-waitをそのまま返す。 */
293
- export async function remoteWaitProcess(target, session, cursor, inputId) {
297
+ export async function remoteWaitProcess(target, session, cursor, inputId, steerId) {
294
298
  // 別processには鍵のパスフレーズを渡せない。ssh-agentか、張ってあるControlMasterの接続に相乗りする。
295
- const { args } = sshInvocation(target, remoteWaitCommand(await remoteShell(target), session, cursor, null, 600, inputId, !!target.trusted_ref), { passphrase: false });
299
+ const { args } = sshInvocation(target, remoteWaitCommand(await remoteShell(target), session, cursor, null, 600, inputId, !!target.trusted_ref, steerId), { passphrase: false });
296
300
  return { executable: "ssh", args, windows_start_process_argument_list: process.platform === "win32" ? windowsStartProcessArgumentList(args) : null };
297
301
  }
298
302
  function runSsh(target, command, signal) {
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.18",
3
+ "version": "0.70.20",
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": [