aiterm-mcp 0.61.20 → 0.61.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,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.61.21] - 2026-10-26
11
+
12
+ - Distinguish tmux PTY EOF from a confirmed authentication process exit: observe missing exit status/signal for a bounded interval, preserve signals and nonzero exits as failures, and reject replaced generations without restarting login.
13
+ - Re-read the current Grok rate-limit panel once after an error event when waiting; preserve ordinary errors, one-shot reads, new turns and closed launches without replaying input.
14
+ - Observe authorization-code redraws for up to three seconds after a single native submission. Preserve unknown outcomes at the deadline or on generation replacement, without resubmitting or claiming authentication success.
15
+ - Recognize a current Cursor `prepaid_balance_exhausted` provider refusal without a new transcript user record as typed error only from a complete current error JSON object. Quoted diagnostic codes, malformed JSON, resumed composers and Codex 429 retries remain nonterminal; do not retry, close, or change credentials.
16
+
10
17
  ## [0.61.20] - 2026-10-26
11
18
 
12
19
  - Clear an existing UserPaused/Idle Grok goal on the original worker through one user-origin native command, with fresh durable acknowledgement and authoritative no-goal readback. Refuse busy input, drafts and replaced bindings; preserve unknown effects without retry.
@@ -2900,7 +2907,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
2900
2907
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
2901
2908
  provenance.
2902
2909
 
2903
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.61.20...HEAD
2910
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.61.21...HEAD
2911
+ [0.61.21]: https://github.com/kitepon/aiterm-mcp/compare/v0.61.20...v0.61.21
2904
2912
  [0.61.20]: https://github.com/kitepon/aiterm-mcp/compare/v0.61.19...v0.61.20
2905
2913
  [0.61.19]: https://github.com/kitepon/aiterm-mcp/compare/v0.61.18...v0.61.19
2906
2914
  [0.61.18]: https://github.com/kitepon/aiterm-mcp/compare/v0.61.17...v0.61.18
package/README.ja.md CHANGED
@@ -209,7 +209,7 @@ runtime-error store は canonical dotagents config の `collection.enabled: true
209
209
  場合だけ収集し、既定OFF、network送信は行いません。tag起点CIのnpm provenance(OIDC Trusted
210
210
  Publishing)で公開し、GitHub Release が Official MCP Registry を再登録します。
211
211
 
212
- **状態:** 開発継続中 · 現行公開版 **v0.61.20** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
212
+ **状態:** 開発継続中 · 現行公開版 **v0.61.21** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
213
213
 
214
214
  ### 更新と巻き戻し
215
215
 
@@ -263,6 +263,7 @@ ClaudeがAPIエラーや安全判定の拒否で終了した時は、Stop hook
263
263
 
264
264
  Codexがサービスの誤りや通信の失敗でturnを打ち切った時は、完了待ちが`done`ではなく`error`を返す(`aiterm-wait`はexit 7、親への配送は`outcome=error`)。`error`は応答の本文とURLを落とした1行の文で、Codexが記録した種類(`internal_server_error`・`http_connection_failed`など)は`error_kind`に載る。利用上限は今までどおり`rate_limited`。誤りで終わった後の席は、次の`pty_send`を新しいturnとして受ける。
265
265
  Cursorが誤りでturnを終えた時(記録の`turn_ended`が`status: "error"`)も同じで、完了待ちは`error`を返し、文の頭の角括弧の名前(`unavailable`など)を`error_kind`に載せる。利用上限の文は`rate_limited`、席で止めたturn(`User aborted request`)は今までどおり`done`。
266
+ 現在の`Error:`以降が完全なJSONで、`error.code`が`prepaid_balance_exhausted`なら、新しいuser記録が無くても同じ種類の`error`を返す。説明文中のcode、壊れたJSON、後続の入力欄や実行中表示がある旧エラーでは終端にしない。自動再送や席の閉鎖は行わない。
266
267
 
267
268
  agent配送だけを期待する連携では、`pty_send`に`require_agent:true`を指定する。agent登録が無ければ、打鍵前に`AGENT_SESSION_REQUIRED`と「文字列は送信していません」を返す。省略時は通常PTY送信を維持する。`force:true`との併用は未送信で拒否する。
268
269
 
@@ -280,6 +281,8 @@ Grokの無人起動は公式`--trust`で指定された作業フォルダを信
280
281
 
281
282
  Grokで終了済みターンのweekly-limitパネルが残っている場合、次の通常`pty_send`が`Shift+X`で一度閉じ、入力受付を確認して今回の本文を送る。同じsessionと会話を保ち、receiptの`pane_input_recovery`に`grok_rate_limit_dialog_dismissed`を記録する。ターン未終了・harness不在は`GROK_RATE_LIMIT_RECOVERY_BLOCKED`、解除後の入力受付失敗は`GROK_RATE_LIMIT_RECOVERY_FAILED`となり、本文は未送信。上限の継続は`rate_limited`として返し、過去promptは再送しない。Grokの上限観測には現在の画面だけを使う。Claude Codeの上限は現在の画面の入力欄の下に出る知らせで、Codexの上限はturnを終えた記録(`task_complete`の`codex_error_info: "usage_limit_exceeded"`)で見分ける。pane logや道具の出力に残る上限の文字では判定しない。
282
283
 
284
+ Grokの待機中にerror eventが先に現れた場合は、見回り一回分後に現在の上限panelを読み直す。上限が無ければ元のerrorを返し、次turnや消失したlaunchへ古いerrorを結び付けない。timeout=0の即時照会は待たず、入力やAPI要求は再送しない。
285
+
283
286
  Cursorの送信前hook(`beforeSubmitPrompt`と、互換読込するClaude Codeの`UserPromptSubmit`)がpromptを拒否すると、Cursorはpromptを捨て、turnも完了も起きない。Aitermはこの拒否の表示を見分け、起動時promptは`initial_prompt=failed`、`pty_send`は成功receiptを返さず、どちらも`USER_HOOK_BLOCKED`とhookの出力を返す。確認時間(3秒)より後の拒否は、完了待ちが`outcome=error`(`aiterm-wait`はexit 7)で返す。
284
287
 
285
288
  Grokがread-only sandboxの適用を拒否した場合、prompt送信時に`GROK_SANDBOX_STARTUP_FAILED`とCLIの原因を返す。例えばhookのパスにシンボリックリンクがあるとGrok CLIは起動を拒否する。設定の管理元で原因を修正し、対象sessionを`pty_close`して起動し直す。Aitermはsandboxを解除したりhookをコピーしたりしない。
@@ -640,6 +643,10 @@ Aitermは、既定では実行時エラーをどこへも送らない。送る
640
643
 
641
644
  認証UIは追加の`auth_ui`を使う。`stage`は`open_url` / `device_code` / `paste_code` / `select` / `waiting` / `complete` / `failed` / `unavailable`。公式URL・表示code・具体的な選択ラベル・入力種別をNativeが返し、`input_required`だけから入力内容や端末キーを推測しない。`respond`は直近の`auth_ui.binding`を`expected_binding`へ渡し、`expected_prompt_digest`には同じ`auth_ui.prompt_digest`を渡す。`response:{kind:"authorization_code",value}`または`{kind:"choice",id}`を同じ認証flowへ送る。認証コードを`pty_send`へ渡さない。専用入力はlastcmd・通常turn・paneログ・argv・一時fileへコードを保存せず、CLIの画面echoもpaneログへ保存しない。未発行と入力後不明は構造化errorの`effect:not_issued|unknown`で区別し、自動再送しない。legacy flowの`launch_id:null`は実native識別情報で照合し、UUIDを補わない。Windowsの専用入力は前面所有確認が未受入のため`not_issued`で拒否する。
642
645
 
646
+ コード入力後は同じ認証世代の状態を最大3秒確認する。画面更新後のwaitingは処理待ちで、認証成功を意味しない。入力待ちが変わらない・世代が変わる・状態を読めない場合はunknownを保ち、入力を再送しない。
647
+
648
+ 認証processの端末切断が終了コード確定に先行した時は、同じ世代の終了コード・signalを3秒の期限付きで確認する。signal終了や非0は失敗を保ち、0でも公式statusを確認する。期限まで不明、session消失・交代は成功にせず、ログインの再起動や入力再送は行わない。
649
+
643
650
 
644
651
  `start`は、公式の状態が認証済みなら何も起こさず`authenticated`(`session_id:null`)を返す。`relogin:true`を付けると、認証済みに見えても公式ログインを開始し、`session_id`付きの結果を返す。別のアカウントへ入り直す時と、ログインの期限切れを状態から見抜けない時に使う。Aitermは資格情報を消さず、置き換えは公式CLIが行う。ただし、公式CLIがログインを始めた時点で元のログインを消す事がある(Codex 0.160.0の`codex login --device-auth`は、始めた時点で`auth.json`を消す。途中で`cancel`しても戻らない)。Claude CodeとCursorは、途中で`cancel`すれば元の資格情報が残る(無効な資格情報で確認)。
645
652
 
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.61.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).
230
+ **Status:** actively maintained · current public release **v0.61.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
 
@@ -305,8 +305,12 @@ Grokの無人起動は公式`--trust`で指定された作業フォルダを信
305
305
 
306
306
  Grokで終了済みターンのweekly-limitパネルが残っている場合、次の通常`pty_send`が`Shift+X`で一度閉じ、入力受付を確認して今回の本文を送る。同じsessionと会話を保ち、receiptの`pane_input_recovery`に`grok_rate_limit_dialog_dismissed`を記録する。ターン未終了・harness不在は`GROK_RATE_LIMIT_RECOVERY_BLOCKED`、解除後の入力受付失敗は`GROK_RATE_LIMIT_RECOVERY_FAILED`となり、本文は未送信。上限の継続は`rate_limited`として返し、過去promptは再送しない。Grokの上限観測には現在の画面だけを使う。Claude Codeの上限は現在の画面の入力欄の下に出る知らせで、Codexの上限はturnを終えた記録(`task_complete`の`codex_error_info: "usage_limit_exceeded"`)で見分ける。pane logや道具の出力に残る上限の文字では判定しない。
307
307
 
308
+ Grokの待機中にerror eventが先に現れた場合は、見回り一回分後に現在の上限panelを読み直す。上限が無ければ元のerrorを返し、次turnや消失したlaunchへ古いerrorを結び付けない。timeout=0の即時照会は待たず、入力やAPI要求は再送しない。
309
+
308
310
  When a Cursor pre-submit hook (`beforeSubmitPrompt`, or a Claude Code `UserPromptSubmit` hook that Cursor loads for compatibility) rejects the prompt, Cursor drops it and no turn or completion follows. Aiterm recognizes the rejection: an initial prompt returns `initial_prompt=failed`, and `pty_send` returns an error instead of a success receipt, both with `USER_HOOK_BLOCKED` and the hook's output. A rejection that comes after the 3-second start check is reported by the completion wait as `outcome=error` (`aiterm-wait` exit 7).
309
311
 
312
+ A current Cursor `Error:` containing a complete JSON object with `error.code` equal to `prepaid_balance_exhausted` ends the wait as `outcome=error` with that `error_kind`, even without a new user record. Quoted diagnostic codes, malformed JSON and old errors followed by a composer or busy display do not establish this terminal. Aiterm does not resend or close the session.
313
+
310
314
  Grokがread-only sandboxの適用を拒否した場合、prompt送信時に`GROK_SANDBOX_STARTUP_FAILED`とCLIの原因を返す。hookパスのシンボリックリンクなど、CLIが示した原因を設定の管理元で修正し、対象sessionを`pty_close`して起動し直す。Aitermはsandboxを解除したりhookをコピーしたりしない。
311
315
 
312
316
  この判定はGrok専用アダプターが所有する。初回prompt付きの`agent_launch`と通常の`pty_send`で、入力受付待ち中に拒否を検出すると未送信のエラーを返す。promptなし・`trust_project`指定なしの起動応答は入力受付を保証しない。`trust_project:true`では入力受付まで確認し、`startup.status`を返す。Grokのprivacy notice起動設定も同アダプターが所有する。実装の責務分担は[DESIGN](docs/DESIGN.md#failure-and-recovery)を参照。
@@ -684,6 +688,10 @@ Claude Codeの席では、`/model`の選ぶ画面の`s`(use this session only
684
688
 
685
689
  認証UIは追加の`auth_ui`を使う。`stage`は`open_url` / `device_code` / `paste_code` / `select` / `waiting` / `complete` / `failed` / `unavailable`。公式URL・表示code・具体的な選択ラベル・入力種別をNativeが返し、`input_required`だけから入力内容や端末キーを推測しない。`respond`は直近の`auth_ui.binding`を`expected_binding`へ渡し、`expected_prompt_digest`には同じ`auth_ui.prompt_digest`を渡す。`response:{kind:"authorization_code",value}`または`{kind:"choice",id}`を同じ認証flowへ送る。認証コードを`pty_send`へ渡さない。専用入力はlastcmd・通常turn・paneログ・argv・一時fileへコードを保存せず、CLIの画面echoもpaneログへ保存しない。未発行と入力後不明は構造化errorの`effect:not_issued|unknown`で区別し、自動再送しない。legacy flowの`launch_id:null`は実native識別情報で照合し、UUIDを補わない。Windowsの専用入力は前面所有確認が未受入のため`not_issued`で拒否する。
686
690
 
691
+ コード入力後は同じ認証世代の状態を最大3秒確認する。画面更新後のwaitingは処理待ちで、認証成功を意味しない。入力待ちが変わらない・世代が変わる・状態を読めない場合はunknownを保ち、入力を再送しない。
692
+
693
+ 認証processの端末切断が終了コード確定に先行した時は、同じ世代の終了コード・signalを3秒の期限付きで確認する。signal終了や非0は失敗を保ち、0でも公式statusを確認する。期限まで不明、session消失・交代は成功にせず、ログインの再起動や入力再送は行わない。
694
+
687
695
 
688
696
  `start`は、公式の状態が認証済みなら何も起こさず`authenticated`(`session_id:null`)を返す。`relogin:true`を付けると、認証済みに見えても公式ログインを開始し、`session_id`付きの結果を返す。別のアカウントへ入り直す時と、ログインの期限切れを状態から見抜けない時に使う。Aitermは資格情報を消さず、置き換えは公式CLIが行う。ただし、公式CLIがログインを始めた時点で元のログインを消す事がある(Codex 0.160.0の`codex login --device-auth`は、始めた時点で`auth.json`を消す。途中で`cancel`しても戻らない)。Claude CodeとCursorは、途中で`cancel`すれば元の資格情報が残る(無効な資格情報で確認)。
689
697
 
package/dist/core.js CHANGED
@@ -4512,12 +4512,28 @@ async function respondAgentAuth(kind, options) {
4512
4512
  finally {
4513
4513
  release();
4514
4514
  }
4515
- await sleep(100);
4516
4515
  try {
4517
- const result = await authenticateAgent(kind, { action: "status", session_id: name });
4518
- if (result.auth_ui?.input === "authorization_code" && response.data.kind === "authorization_code")
4519
- throw new Error("native input consumption unconfirmed");
4520
- return result;
4516
+ const initialMeta = loadAuthMetadata(name, kind);
4517
+ const checkReadbackGeneration = (result) => {
4518
+ const current = loadAuthMetadata(name, kind);
4519
+ const stat = fs.lstatSync(authMetadataPath(name));
4520
+ const sameOnboardingLaunch = expected.data.launch_id !== null && initialMeta?.phase === "login" && current?.phase === "onboarding"
4521
+ && result?.status === "waiting" && result.auth_ui?.binding?.launch_id === expected.data.launch_id;
4522
+ if (!current || (current.launch_id ?? null) !== expected.data.launch_id
4523
+ || !sameOnboardingLaunch && !expected.data.metadata_identity.startsWith(`${stat.dev}:${stat.ino}:${stat.birthtimeMs}:`))
4524
+ throw new Error("native authentication generation changed");
4525
+ };
4526
+ const deadline = performance.now() + 3000;
4527
+ do {
4528
+ await sleep(100);
4529
+ checkReadbackGeneration();
4530
+ const result = await authenticateAgent(kind, { action: "status", session_id: name });
4531
+ checkReadbackGeneration(result);
4532
+ if (result.auth_ui?.input !== "authorization_code" || response.data.kind !== "authorization_code")
4533
+ return result;
4534
+ // Native input and its redraw are asynchronous; observe without submitting again.
4535
+ } while (performance.now() < deadline);
4536
+ throw new Error("native input consumption unconfirmed");
4521
4537
  }
4522
4538
  catch {
4523
4539
  throw new AuthResponseError("AGENT_AUTH_RESPONSE_UNKNOWN", "unknown", "入力後の状態を確認できません。自動再送しないでください。");
@@ -4620,19 +4636,52 @@ export async function authenticateAgent(kind, options) {
4620
4636
  meta = loaded;
4621
4637
  }
4622
4638
  const session = name;
4623
- const deadline = performance.now() + (options.action === "start" ? 3000 : 0);
4639
+ const exitDeadline = performance.now() + 3000;
4640
+ const deadline = options.action === "start" ? exitDeadline : performance.now();
4641
+ const originalStat = fs.lstatSync(authMetadataPath(session));
4642
+ let pendingExit = false;
4643
+ const pendingExitRefusal = () => {
4644
+ if (!pendingExit)
4645
+ return null;
4646
+ if (!authSessionExists(session))
4647
+ return result("failed", null, "認証sessionが失われました。元の終了状態は未確認です。");
4648
+ const current = loadAuthMetadata(session, kind);
4649
+ const stat = current && fs.lstatSync(authMetadataPath(session));
4650
+ return !current || !stat || (current.launch_id ?? null) !== (meta.launch_id ?? null)
4651
+ || stat.dev !== originalStat.dev || stat.ino !== originalStat.ino || stat.birthtimeMs !== originalStat.birthtimeMs
4652
+ ? result("failed", null, "認証sessionの世代が変わりました。元の終了状態は未確認です。") : null;
4653
+ };
4624
4654
  for (;;) {
4625
4655
  if (!authSessionExists(session))
4626
4656
  return result("failed", null, "認証sessionが失われました。agent_authのstartで開始してください。");
4627
- const observed = tmux("display-message", "-p", "-t", session, "#{pane_dead}\t#{pane_dead_status}");
4657
+ const beforeExitRead = pendingExitRefusal();
4658
+ if (beforeExitRead)
4659
+ return beforeExitRead;
4660
+ const observed = tmux("display-message", "-p", "-t", session, "#{pane_dead}\t#{pane_dead_status}\t#{pane_dead_signal}");
4628
4661
  if (observed.code !== 0)
4629
4662
  return result("failed", session, "認証processの終了状態を取得できません。");
4630
- const [dead, exit] = observed.stdout.trim().split("\t");
4663
+ const [dead, exit, signal] = observed.stdout.trim().split("\t");
4631
4664
  const pane = authPane(meta, stripControl(captureScreen(session, 0)));
4665
+ const afterExitRead = pendingExitRefusal();
4666
+ if (afterExitRead)
4667
+ return afterExitRead;
4668
+ if (pendingExit && dead === "0")
4669
+ return result("failed", null, "認証processが終了観測中に交代しました。元の終了状態は未確認です。");
4632
4670
  if (dead === "1") {
4671
+ // tmux can close the PTY before waitpid publishes either status or signal.
4672
+ if (!exit && !signal && performance.now() < exitDeadline) {
4673
+ pendingExit = true;
4674
+ await sleep(100);
4675
+ continue;
4676
+ }
4677
+ if (signal)
4678
+ return result("failed", session, `公式認証processがsignalで終了しました(signal=${/^[A-Z0-9]+$/.test(signal) ? signal : "unknown"})。`);
4633
4679
  if (exit !== "0")
4634
4680
  return result("failed", session, `公式認証processが失敗しました(exit=${/^\d+$/.test(exit ?? "") ? exit : "unknown"})。`);
4635
4681
  const checked = await authStatus(kind, meta.bin, meta.cwd, authSessionEnvironment(session, meta.env_vars));
4682
+ const afterOfficialStatus = pendingExitRefusal();
4683
+ if (afterOfficialStatus)
4684
+ return afterOfficialStatus;
4636
4685
  if (checked.status === "failed")
4637
4686
  return result("failed", session, checked.message);
4638
4687
  if (checked.status === "unauthenticated")
@@ -256,6 +256,9 @@ export async function observeCursorDone(meta, timeout, requestedCursor, readScre
256
256
  // 最初の周回では必ず読む(timeout=0の照会も1回は読む)。
257
257
  if (screenDue()) {
258
258
  const screen = readScreen(meta.aiterm_session);
259
+ const providerFailure = cursorProviderFailure(screen);
260
+ if (providerFailure)
261
+ return observation("error", null, null, providerFailure.message, providerFailure.kind);
259
262
  const limited = cursorUsageLimit(screen)?.message ?? null;
260
263
  if (limited)
261
264
  return observation("rate_limited", null, limited);
@@ -566,6 +569,27 @@ export function cursorTuiReady(screen) {
566
569
  return true;
567
570
  return /Cursor Agent/i.test(screen) && CURSOR_COMPOSER_MARKER_RE.test(screen);
568
571
  }
572
+ /** Current official billing refusal, not an idle/completed turn or an authentication error. */
573
+ export function cursorProviderFailure(screen) {
574
+ const clean = screen.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "");
575
+ const heading = [...clean.matchAll(/^[ \t]*Error:[ \t]*[^\n]*/gim)].at(-1);
576
+ if (!heading)
577
+ return null;
578
+ const current = clean.slice(heading.index);
579
+ const after = clean.slice(heading.index + heading[0].length);
580
+ if (cursorTuiBusy(after) || CURSOR_FOLLOWUP_MARKER_RE.test(after) || CURSOR_START_PROMPT_MARKER_RE.test(after)
581
+ || after.split("\n").some(line => CURSOR_COMPOSER_CONTENT_MARKER_RE.test(line)))
582
+ return null;
583
+ try {
584
+ const payload = JSON.parse(current.slice(current.indexOf(":") + 1).trim());
585
+ if (payload?.error?.code !== "prepaid_balance_exhausted")
586
+ return null;
587
+ }
588
+ catch {
589
+ return null;
590
+ }
591
+ return { kind: "prepaid_balance_exhausted", message: "Cursor: prepaid_balance_exhausted" };
592
+ }
569
593
  // 利用上限に達したCursorは、入力欄も戻さずに説明を出して止まる(2026.09.26-dd393fe、macOSで実測)。
570
594
  // transcriptには、user turnを残さずにturn_ended(status "error")だけを書く事がある(実記録で8件)。その時は完了の条件
571
595
  // (user turnが増えている)に当たらないので、画面で見る。user turnがある時は、完了待ちが記録から読む(cursorTurnError)。
@@ -623,6 +647,9 @@ export function cursorPromptHooksRunning(screen) {
623
647
  }
624
648
  export function cursorPaneObservation(screen) {
625
649
  const tail = screen.split("\n").slice(-32).join("\n");
650
+ const providerFailure = cursorProviderFailure(tail);
651
+ if (providerFailure)
652
+ return { state: "blocked", reason: providerFailure.kind, detail: providerFailure.message };
626
653
  if (cursorUsageLimit(tail))
627
654
  return { state: "blocked", reason: "rate_limited" };
628
655
  const hookBlocked = cursorHookBlocked(tail);
@@ -284,6 +284,7 @@ export async function observeGrokDone(meta, timeout, requestedCursor, detectRate
284
284
  let initializedBoundary = false;
285
285
  let turnStarted = false;
286
286
  let unacceptedSeen = 0;
287
+ let pendingError = null;
287
288
  const deadline = performance.now() + timeout * 1000;
288
289
  const rateLimitDue = pollGate(AGENT_RATE_LIMIT_POLL_MS);
289
290
  const observation = (outcome, ev = null, rateLimit = null, error = null) => ({
@@ -339,13 +340,18 @@ export async function observeGrokDone(meta, timeout, requestedCursor, detectRate
339
340
  }
340
341
  try {
341
342
  const record = JSON.parse(line);
342
- if (record?.type === "turn_started")
343
+ if (record?.type === "turn_started") {
343
344
  turnStarted = true;
345
+ pendingError = null;
346
+ }
344
347
  const done = grokCompletionEvent(meta, record);
345
348
  if (done) {
346
349
  const limited = done.done_status === "turn_error"
347
350
  ? detectRateLimit(meta.kind, meta.aiterm_session) : null;
348
- return observation(limited ? "rate_limited" : done.done_status === "turn_error" ? "error" : "done", done, limited);
351
+ if (done.done_status === "turn_error" && !limited && timeout > 0 && performance.now() < deadline)
352
+ pendingError = { event: done, until: Math.min(deadline, performance.now() + AGENT_DONE_POLL_MS) };
353
+ else
354
+ return observation(limited ? "rate_limited" : done.done_status === "turn_error" ? "error" : "done", done, limited);
349
355
  }
350
356
  }
351
357
  catch {
@@ -354,6 +360,23 @@ export async function observeGrokDone(meta, timeout, requestedCursor, detectRate
354
360
  }
355
361
  }
356
362
  }
363
+ if (pendingError) {
364
+ const remaining = pendingError.until - performance.now();
365
+ // shortcut: settle one existing poll after the error event; extend only with evidence of a longer native redraw.
366
+ if (remaining > 0) {
367
+ await sleep(remaining);
368
+ continue;
369
+ }
370
+ const limited = detectRateLimit(meta.kind, meta.aiterm_session);
371
+ if (!fs.existsSync(metadataFile))
372
+ return observation("closed");
373
+ if (safeStatSize(transcript) !== cursor) {
374
+ if (performance.now() >= deadline)
375
+ return observation("timeout");
376
+ continue;
377
+ }
378
+ return observation(limited ? "rate_limited" : "error", pendingError.event, limited);
379
+ }
357
380
  // 質問カードの確認は画面を読む(tmuxを起動する)。完了の見回りより間隔を空け、最初の周回では必ず見る。
358
381
  if (rateLimitDue()) {
359
382
  const limited = detectRateLimit(meta.kind, meta.aiterm_session);
package/docs/DESIGN.md CHANGED
@@ -440,6 +440,7 @@ Codexが書いた種類は`error_kind`で返す。失敗を空の回答の完了
440
440
  Cursorは、誤りで終わったturnを、記録の`turn_ended`へ`status: "error"`と文で書く。完了待ちは、利用上限の文を`rate_limited`、
441
441
  席で止めたturn(`User aborted request`)を今までどおり`done`、ほかを`error`で返す。`error`は1行の文、文の頭の角括弧の名前は
442
442
  `error_kind`で返す(ADR 0106)。判定と文の整え方は`src/harnesses/cursor.ts`が所有する。
443
+ Cursorの現在Error表示も同じharnessで解析し、完全なJSONの`error.code`が`prepaid_balance_exhausted`ならuser記録を待たずerrorへ進める。説明文のcodeや壊れたJSON、後続composer/busyを持つ旧表示は採用しない。stopの非busy保全は変更しない。
443
444
 
444
445
  Grokのread-only sandbox起動拒否は、`src/harnesses/grok.ts`の
445
446
  `assertGrokSandboxNotRejected`がCLIのエラー表示から検出する。`src/core.ts`の共通入力受付待機は
@@ -466,6 +467,7 @@ Grokの終了済みerrorターンにweekly-limit質問カードが残る場合
466
467
  `grokRateLimitDialog`が見出しと操作footerの組を所有し、過去logや後続UIのあるカードは採用しない。
467
468
  privacy案内は現在の枠付きcomposerとmodel footerが見える場合だけ入力受付を妨げない。
468
469
  完了観測は成功eventを優先し、今回のerror eventと現在のカードが揃えばturn情報付きの`rate_limited`を返す。
470
+ Grokのerror eventが先に見え、上限panelがまだ無い場合、待機呼出しは既存の見回り一回分だけ後に現在panelを再確認する。上限が無ければ元のerrorを保ち、途中の次turn開始や元launch消失を再検査する。timeout=0の即時照会は待たない。遅い全描画の成功を保証せず、入力・provider要求を再送しない。
469
471
  完了の見回りは100msで、画面を読む確認(利用上限の知らせ、Cursorのhook拒否の表示)は別の間隔で行う。画面を読むたびにtmuxを1回起動するため。
470
472
  Claude・Grokは2秒、Cursorは1秒に1回で、待ちに入った最初の周回では必ず読む(ADR 0085)。
471
473
  新turnの完了前に古いlogだけで上限を返さない。購入・再認証・過去prompt再送・定期再試行は行わない。
@@ -511,6 +513,10 @@ respondは既session send lock内で現在の空欄/段階と世代を再検証
511
513
 
512
514
  Claude authのcurrent menuはharnessの単一parseがphase/rows/selected/入力占有を所有する。古いthemeと新loginが同viewportに残っても最後の現在phaseだけを採り、coreはそのselected_idでnavigateする。code欄が現在phaseならoccupied状態から古いmenu UIへ戻さない。cursor欠測/複数cursor/未知row/後続の未知promptは入力前拒否。Native内部の入力観測は公開auth_uiへ直接返さず、公開schemaを拡張しない。
513
515
 
516
+ Authorization-code readback observes the same metadata generation for up to three seconds after one submission. A later redraw may establish a waiting or other recognized stage; it does not establish authenticated status by itself. An unchanged code prompt, replaced metadata generation or failed readback retains unknown without another input.
517
+
518
+ Authentication process exit observation reads the native exit status and signal independently of PTY EOF. If EOF is visible before either terminal field is ready, the same metadata generation is observed for a three-second window; missing status at the deadline remains unconfirmed failure. Signals and nonzero exits stay failures. Exit0 still requires the official authentication status, with a generation recheck after that call. A disappeared or replaced session, including a pane returning live after EOF, is not adopted. Observation never restarts login or repeats input.
519
+
514
520
  ## CLI-owned goal adapter
515
521
 
516
522
  `agent-goal.ts` owns typed I/O, operation preconditions, host provenance, and result/readback distinctions. `harnesses/codex-goal.ts` maps these operations to the official goal protocol and verifies the loaded thread. `codex-goal-connection.ts` owns the POSIX native rendezvous alias checks; `codex-relay-client.ts` supplies the existing WebSocket request transport with explicit experimental opt-in. `core.agentGoal` binds the original session/launch/harness process and shares existing send admission. No goal state or continuation loop is stored by Aiterm.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.61.20",
3
+ "version": "0.61.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, and Cursor Agent CLI, plus durable PTYs for SSH, containers, and REPLs.",
6
6
  "keywords": [