aiterm-mcp 0.70.25 → 0.70.27

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,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.70.27] - 2026-11-11
11
+
12
+ - `pty_list` now lists a Claude agent seat whose terminal is gone with no lifecycle record (for example, it vanished with a container restart) as `current_command: "vanished"`, with its `last_input_at` and `limit_end`. Before, such a seat had no row until the next send adopted it, so a restart dropped a limit-held seat's record. Seat turns read it as idle. The next send still adopts and resumes it as before.
13
+
14
+ ## [0.70.26] - 2026-11-11
15
+
16
+ - A Claude turn that ends on a usage limit now has a terminal outcome. Claude Code 2.1.322 holds such a turn ("Usage limit reached · continuing automatically at 7pm · esc to cancel") and runs no Stop hook, so its operation stayed pending, `pty_key` refused every key but C-c, and the seat's span kept running. Now, from the transcript and Aiterm's activity record only: `pty_list` rows of Claude agent sessions carry `last_input_at` and `limit_end {at, reset_at, continued, hold: armed|cancelled|null}`; the Claude wait returns `rate_limited` (exit 6) with the record text and `reset_at` (it was `error` with failure category `rate_limited`); seat turns close the span; and an operation whose turn ended on an API error or an interrupt record no longer counts as pending. `pty_key` now refuses keys other than C-c only while an operation is pending (before, on every correlated Claude seat), so Escape cancels an armed hold, and `hold` turns `cancelled`.
17
+ - `aiterm-update` now keeps the reason when the new version's `aiterm-setup` does not end `ready`. The result already carried `setup_status` and `setup_reason_code`, but the setup's own message (for example which probe step failed and why) was dropped, so reading it meant running setup again on that host. The last lines of the setup's error output now go into the result's `message`.
18
+
10
19
  ## [0.70.25] - 2026-11-11
11
20
 
12
21
  - `pty_list` with seat turns is faster on a host with many seats. Checking whether one seat exists listed every seat with its agent metadata, and each metadata read scanned the whole agents folder, so one call grew with the number of seats squared (10-27 s for about 140 members). The check now reads only the session names, with the same tmux call, retry and failures. On the production state, reading the turns of 48 seats went from 4.6 s to 2.3 s. What `pty_list` returns is unchanged.
@@ -3305,7 +3314,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3305
3314
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3306
3315
  provenance.
3307
3316
 
3308
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.25...HEAD
3317
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.27...HEAD
3318
+ [0.70.27]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.26...v0.70.27
3319
+ [0.70.26]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.25...v0.70.26
3309
3320
  [0.70.25]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.24...v0.70.25
3310
3321
  [0.70.24]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.23...v0.70.24
3311
3322
  [0.70.23]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.22...v0.70.23
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.25** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.70.27** · 動作対象は 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.25** · 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.27** · 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
@@ -11,7 +11,7 @@ import { inspectIdleSettings, inspectCodexResumeSettings, codexRecoveryComposer
11
11
  import { AGENT_TUI_READY_TIMEOUT_MS, AGENT_TUI_FIRST_DRAW_TIMEOUT_MS, AGENT_TUI_READY_POLL_MS, isAgentTuiReady, isAgentTuiBusy, isAgentTuiIdleReady, agentPaneObservation, parentPaneEvidence, waitAgentTuiReadyImpl, detectAgentSubmitResidueImpl, waitCursorPromptVisibleImpl, settleAgentDoneScreenImpl } from "./agent-screen-observation.js";
12
12
  export { launchEchoIsLastOnScreen, __testSetAgentTuiReadyStableSamples } from "./agent-screen-observation.js";
13
13
  import { parseClaudeOperationMarker } from "./claude-operation-marker.js";
14
- import { withManagedSpan, observeManagedSpan, SPAN_HELD } from "./managed-seat-turn.js";
14
+ import { withManagedSpan, observeManagedSpan, closeManagedSpan, SPAN_HELD } from "./managed-seat-turn.js";
15
15
  /**
16
16
  * core — CLI/MCP が共有する端末操作とharness進行(Node/TS 版)。
17
17
  *
@@ -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, claudeOauthTokenFile, claudeSetupTokenPlan, claudeOauthToken, claudeOauthTokenPresent, writeClaudeOauthToken, OPERATION_ID_RE, CLAUDE_RESULT_MAX_BYTES, CLAUDE_EFFORTS, agentClaudeOperationPath, agentClaudeApprovalReceiptPath, agentClaudeDispatchReceiptPath, validateOperationId, readClaudeResultText, 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, claudeModelChoices, claudeConfigDir, claudeProjectSlug, claudeFastIndicatorShown, claudeFastResult, buildClaudeAgentCmd, claudeAgentArgv, claudeResumeArgv, claudeLaunchNote, claudePaneObservation, CLAUDE_INTERRUPT_KEY, claudeUsageLimit, claudeLiveSelectMenu, claudeStartupAction, createClaudeAgentMetadata, writeClaudeCallerFiles, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, claudeLimitEnd, claudeInterruptedAfter, claudeLimitResetAt, 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";
@@ -1008,8 +1008,10 @@ export function sendKeyResult(name, key, o = {}) {
1008
1008
  assertExecutionContext(name);
1009
1009
  assertSessionName(name);
1010
1010
  const k = KEYMAP[key.toLowerCase()] ?? key;
1011
- if (!o.preserveAgentOperation && k !== "C-c" && isAgentSession(name) && managedClaudeOperation(name) !== undefined) {
1012
- throw new AitermError("aiterm相関付きClaude agent sessionではturn相関を壊さないC-cだけをpty_keyで送れます。" +
1011
+ // Protects a pending operation: another key (Enter, history, a menu choice) could submit other input whose Stop the hook would
1012
+ // file under that operation. Exits on its own at the turn's Stop, its API-error/limit record, or its interrupt record; close too.
1013
+ if (!o.preserveAgentOperation && k !== "C-c" && isAgentSession(name) && managedClaudeOperation(name)) {
1014
+ throw new AitermError("aiterm相関付きClaude agent sessionのturnが終わるまでは、turn相関を壊さないC-cだけをpty_keyで送れます。" +
1013
1015
  "他の対話操作はpty_send(自動dispatch)、終了はpty_closeを使ってください。", 2);
1014
1016
  }
1015
1017
  return withAgentNativeOperation(name, true, () => sendKeyResultInNative(name, key, o));
@@ -1493,6 +1495,24 @@ async function readOutputInNative(name, o) {
1493
1495
  return body + "\n" + meta + agentMeta + completionSuffix(status);
1494
1496
  return body + "\n" + meta + agentMeta;
1495
1497
  }
1498
+ /** The usage limit that ended the turn after this launch's last input, or null. Transcript and activity only, no screen. */
1499
+ function claudeSeatLimitEnd(meta) {
1500
+ const input = Date.parse(readAgentActivity(meta).last_input_at ?? "");
1501
+ return Number.isFinite(input) ? claudeLimitEnd(meta, input) : null;
1502
+ }
1503
+ /** pty_list fields of a Claude agent row. */
1504
+ function claudeListedFields(meta) {
1505
+ if (meta?.kind !== "claude")
1506
+ return {};
1507
+ try {
1508
+ const end = claudeSeatLimitEnd(meta);
1509
+ return { last_input_at: readAgentActivity(meta).last_input_at,
1510
+ limit_end: end && { at: end.at, reset_at: end.reset_at, continued: end.continued, hold: end.hold } };
1511
+ }
1512
+ catch {
1513
+ return { last_input_at: null, limit_end: null };
1514
+ }
1515
+ }
1496
1516
  function decodeActivityCursor(cursor, name) {
1497
1517
  let value;
1498
1518
  try {
@@ -2211,11 +2231,12 @@ function listNativeSessionsResult(envKeys = [], runTmux = tmux) {
2211
2231
  sessions.push({ session_id: name, current_command: normalizePaneCommand(command), attached: Number(attached) > 0,
2212
2232
  width: Number(width), height: Number(height), harness: meta ? agentHarness(meta.kind) : null,
2213
2233
  launch_id: meta?.launch_id ?? null,
2214
- vendor_session_id: meta?.vendor_session_id ?? null, environment });
2234
+ vendor_session_id: meta?.vendor_session_id ?? null, environment, ...claudeListedFields(meta) });
2215
2235
  }
2216
2236
  return { schema: "aiterm.pty-list-result.v1", observed_at: new Date().toISOString(), sessions };
2217
2237
  }
2218
- export function listSessionsResult(envKeys = [], runTmux = tmux) {
2238
+ /** `vanished` is the public pty_list's view only: generation existence (observeSessionGeneration) and lineage keep native + dormant. */
2239
+ export function listSessionsResult(envKeys = [], runTmux = tmux, o = {}) {
2219
2240
  const result = listNativeSessionsResult(envKeys, runTmux);
2220
2241
  const present = new Set(result.sessions.map(row => row.session_id));
2221
2242
  for (const name of savedAgentSessionNames()) {
@@ -2224,10 +2245,12 @@ export function listSessionsResult(envKeys = [], runTmux = tmux) {
2224
2245
  if (!meta)
2225
2246
  continue;
2226
2247
  const state = agentDormantState(meta);
2227
- if (!state)
2248
+ // A Claude seat whose native session is gone with no lifecycle (e.g. it vanished with the container) stays listed as
2249
+ // "vanished": its last_input_at/limit_end survive, and the next dispatch adopts and resumes it (adoptVanishedAgentNative).
2250
+ if (!state && (!o.vanished || present.has(name) || meta.kind !== "claude"))
2228
2251
  continue;
2229
2252
  const environment = Object.fromEntries(envKeys.map(key => [key, null]));
2230
- let command = state;
2253
+ let command = state ?? "vanished";
2231
2254
  const recipe = readAgentResumeRecipe(meta);
2232
2255
  if (recipe?.kind === meta.kind && recipe.vendor_session_id === meta.vendor_session_id)
2233
2256
  for (const key of envKeys)
@@ -2245,7 +2268,7 @@ export function listSessionsResult(envKeys = [], runTmux = tmux) {
2245
2268
  continue;
2246
2269
  }
2247
2270
  result.sessions.push({ session_id: name, launch_id: meta.launch_id, current_command: command, attached: false, width: 0, height: 0,
2248
- harness: agentHarness(meta.kind), vendor_session_id: meta.vendor_session_id ?? null, environment });
2271
+ harness: agentHarness(meta.kind), vendor_session_id: meta.vendor_session_id ?? null, environment, ...claudeListedFields(meta) });
2249
2272
  }
2250
2273
  return result;
2251
2274
  }
@@ -2871,7 +2894,24 @@ function managedClaudeOperation(name) {
2871
2894
  }
2872
2895
  if (meta.kind !== "claude")
2873
2896
  return undefined;
2874
- return readClaudeOperationMarker(meta);
2897
+ return pendingClaudeOperation(meta);
2898
+ }
2899
+ /** The marker of a turn still pending. A turn its API error ended (a usage-limit hold included) or an interrupt ended may never
2900
+ * get a Stop: its marker is kept, so the original waiter can still bind its input and read that end, but it is not pending. */
2901
+ function pendingClaudeOperation(meta) {
2902
+ const marker = readClaudeOperationMarker(meta);
2903
+ if (!marker)
2904
+ return null;
2905
+ let at;
2906
+ try {
2907
+ at = fs.statSync(agentClaudeOperationPath(meta.aiterm_session, meta.launch_id)).mtimeMs;
2908
+ }
2909
+ catch (error) {
2910
+ if (error.code === "ENOENT")
2911
+ return null;
2912
+ throw error;
2913
+ }
2914
+ return claudeApiErrorAfter(meta, at) || claudeInterruptedAfter(meta, at) ? null : marker;
2875
2915
  }
2876
2916
  function clearClaudeApiErrorOperation(meta) {
2877
2917
  const file = agentClaudeOperationPath(meta.aiterm_session, meta.launch_id);
@@ -3788,6 +3828,9 @@ export function readSessionInterimWords(name, after, from = null) {
3788
3828
  export function readSeatTurns(sessionIds) {
3789
3829
  const seats = [], unread = [];
3790
3830
  const observedAt = new Map();
3831
+ let native = null;
3832
+ // One listing for the call: a Claude seat with no native session and no lifecycle vanished (pty_list "vanished") and runs no turn.
3833
+ const vanished = (name) => !(native ??= new Set(listNativeSessionRows().map(([listed]) => listed))).has(name);
3791
3834
  for (const name of sessionIds) {
3792
3835
  const meta = tryLoadAgentMetadata(name);
3793
3836
  if (!meta)
@@ -3796,7 +3839,8 @@ export function readSeatTurns(sessionIds) {
3796
3839
  try {
3797
3840
  const state = agentDormantState(meta);
3798
3841
  turn = state ? (state === "hibernated" && observeSession(name).state === "hibernated" ? { state: "idle" } : null)
3799
- : meta.kind === "codex" ? codexSeatTurn(meta) ?? freshCodexSeatTurn(meta) : readManagedSeatTurn(meta);
3842
+ : meta.kind === "codex" ? codexSeatTurn(meta) ?? freshCodexSeatTurn(meta)
3843
+ : meta.kind === "claude" && vanished(name) ? { state: "idle" } : readManagedSeatTurn(meta);
3800
3844
  }
3801
3845
  catch { /* 読めない席は、分からないまま返す */ }
3802
3846
  if (turn === SPAN_HELD) {
@@ -3913,6 +3957,11 @@ function readManagedSeatTurn(meta) {
3913
3957
  || performance.now() - started >= 15_000)
3914
3958
  return null;
3915
3959
  const binding = JSON.stringify([meta.aiterm_session, meta.launch_id, meta.kind, conversation, proof, live.pane_process, live.harness_process]);
3960
+ // Claude holds a limit-ended turn with no Stop and a busy-looking footer; its transcript says the turn ended.
3961
+ const limited = meta.kind === "claude" ? claudeSeatLimitEnd(meta) : null;
3962
+ if (limited && !limited.continued) {
3963
+ return closeManagedSpan(file, binding, `limit:${limited.at}`, () => managedSpanStart(meta));
3964
+ }
3916
3965
  return observeManagedSpan(file, binding, evidence, terminal, new Date().toISOString(), () => managedSpanStart(meta));
3917
3966
  });
3918
3967
  return performance.now() - started < 15_000 ? result : null;
@@ -4195,7 +4244,8 @@ export async function observeAgentDone(name, o = {}) {
4195
4244
  if (o.expected_launch_id && !fs.existsSync(agentMetadataPath(name, o.expected_launch_id)))
4196
4245
  throw new ExecutionError("EXECUTION_STALE_GENERATION");
4197
4246
  const result = await observeAgentDoneInternal(name, o);
4198
- if ((result.outcome === "done" || result.outcome === "error") && result.at !== null) {
4247
+ // A rate_limited with `at` is a recorded end (Claude's limit record, Antigravity's quota Stop); a screen-read limit has none.
4248
+ if ((result.outcome === "done" || result.outcome === "error" || result.outcome === "rate_limited") && result.at !== null) {
4199
4249
  try {
4200
4250
  recordAgentTurnEnd({ aiterm_session: name, launch_id: result.launch_id }, {
4201
4251
  ...result, at: Number.isFinite(Date.parse(result.at)) ? result.at : new Date().toISOString(),
@@ -4295,8 +4345,9 @@ async function observeAgentDoneInternal(name, o = {}) {
4295
4345
  turn_id: ev?.turn_id ?? null,
4296
4346
  malformed_events: malformedEvents,
4297
4347
  at: ev?.at ?? apiError?.at ?? null,
4298
- rate_limit: rateLimit,
4299
- error: apiError?.text ?? null,
4348
+ rate_limit: rateLimit ?? (outcome === "rate_limited" ? apiError?.text ?? null : null),
4349
+ ...(outcome === "rate_limited" && apiError?.at ? { reset_at: claudeLimitResetAt(apiError.text, Date.parse(apiError.at)) } : {}),
4350
+ error: outcome === "rate_limited" ? null : apiError?.text ?? null,
4300
4351
  error_kind: apiError?.status ? `http_${apiError.status}` : null,
4301
4352
  ...(apiError ? { failure: { category: claudeFailureCategory(apiError), execution: sawExecution ? "started" : "unknown",
4302
4353
  boundary: transcriptBound && sawUser && apiError.session_id === meta.vendor_session_id && parentUuid !== null && apiError.parent_uuid === parentUuid && apiError.uuid !== null ? {
@@ -4343,7 +4394,7 @@ async function observeAgentDoneInternal(name, o = {}) {
4343
4394
  // 利用上限ではStopも走る。その番の最後の記録がAPIエラーなら、doneでなく誤りとして返す。
4344
4395
  const ended = scanned.event && meta.kind === "claude" ? claudeApiErrorEndingTurn(meta, scanned.event.at) : null;
4345
4396
  if (ended)
4346
- return observation("error", null, null, ended);
4397
+ return observation(claudeFailureCategory(ended) === "rate_limited" ? "rate_limited" : "error", null, null, ended);
4347
4398
  if (scanned.event?.done_status === "turn_error") {
4348
4399
  // agy ends a quota-stopped turn with ERROR; its Stop error names the limit (RESOURCE_EXHAUSTED, code 429).
4349
4400
  const limited = antigravityQuotaLimit(scanned.event.error);
@@ -4400,7 +4451,7 @@ async function observeAgentDoneInternal(name, o = {}) {
4400
4451
  for (const line of lines) {
4401
4452
  const apiError = claudeApiErrorFromLine(line);
4402
4453
  if (apiError && (apiError.session_id === null || apiError.session_id === meta.vendor_session_id))
4403
- return observation("error", null, null, apiError);
4454
+ return observation(claudeFailureCategory(apiError) === "rate_limited" ? "rate_limited" : "error", null, null, apiError);
4404
4455
  let record;
4405
4456
  try {
4406
4457
  record = JSON.parse(line);
@@ -40,7 +40,7 @@ const waitSchema = z.object({
40
40
  schema: z.literal("aiterm.agent-wait-result.v1"), session_id: executionLaunchSchema.shape.session_id,
41
41
  launch_id: executionLaunchSchema.shape.launch_id,
42
42
  outcome: z.enum(["done", "running", "timeout", "closed", "rate_limited", "error", "not_taken"]),
43
- operation_id: z.string().nullable(), turn_id: z.string().nullable(),
43
+ operation_id: z.string().nullable(), turn_id: z.string().nullable(), at: z.string().nullable().optional(),
44
44
  steer: z.object({ placement: z.enum(["same_turn", "next_turn", "unknown"]) }).optional(),
45
45
  });
46
46
  const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
@@ -158,7 +158,8 @@ export function createExecutionRuntime(bindings) {
158
158
  return unknown;
159
159
  // core's typed error means the harness recorded a terminal turn error;
160
160
  // generic MCP/RPC errors do not satisfy waitSchema and cannot get here.
161
- if (result.outcome !== "done" && result.outcome !== "error")
161
+ // rate_limited with `at` is a recorded terminal end (Claude limit record, Antigravity quota Stop); a screen-read limit is not.
162
+ if (result.outcome !== "done" && result.outcome !== "error" && !(result.outcome === "rate_limited" && result.at))
162
163
  return unknown;
163
164
  const evidence = await bindings.invocationFence?.(structuredClone(point)).catch(() => "unknown") ?? "unknown";
164
165
  const final = await observe(point.launch.session_id);
@@ -806,6 +806,130 @@ export function claudeApiErrorAfter(meta, startedAtMs) {
806
806
  }
807
807
  return null;
808
808
  }
809
+ /** Claude wrote its interrupt record ("[Request interrupted by user…]") at or after `sinceMs`: the turn was interrupted. */
810
+ export function claudeInterruptedAfter(meta, sinceMs) {
811
+ const file = claudeSessionTranscriptPath(meta);
812
+ if (!file)
813
+ return false;
814
+ let size;
815
+ try {
816
+ size = fs.statSync(file).size;
817
+ }
818
+ catch (error) {
819
+ if (error.code === "ENOENT")
820
+ return false;
821
+ throw error;
822
+ }
823
+ const lines = readFileRange(file, Math.max(0, size - AGENT_EVENT_TAIL_BYTES), size).toString("utf8").split("\n");
824
+ lines.pop();
825
+ return lines.some(line => {
826
+ if (!line.includes("[Request interrupted by user"))
827
+ return false;
828
+ try {
829
+ const record = JSON.parse(line), content = record?.message?.content;
830
+ const text = typeof content === "string" ? content : Array.isArray(content) ? content.map((part) => part?.text ?? "").join("") : "";
831
+ return record?.type === "user" && record.isSidechain !== true && (!record.sessionId || record.sessionId === meta.vendor_session_id)
832
+ && Date.parse(record.timestamp) >= sinceMs && /^\[Request interrupted by user\b/u.test(text.trim());
833
+ }
834
+ catch {
835
+ return false;
836
+ }
837
+ });
838
+ }
839
+ const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
840
+ const zoneOffset = (ms, zone) => {
841
+ const parts = Object.fromEntries(new Intl.DateTimeFormat("en-US", { timeZone: zone, hourCycle: "h23", year: "numeric", month: "numeric",
842
+ day: "numeric", hour: "numeric", minute: "numeric", second: "numeric" }).formatToParts(ms).map(part => [part.type, part.value]));
843
+ return Date.UTC(+parts.year, +parts.month - 1, +parts.day, +parts.hour, +parts.minute, +parts.second) - Math.floor(ms / 1000) * 1000;
844
+ };
845
+ /** "… resets 7pm (UTC)" / "resets Nov 14, 4:30am (Asia/Tokyo)": the first such wall-clock instant after `atMs`. Null when it does not parse. */
846
+ export function claudeLimitResetAt(text, atMs) {
847
+ const hit = /\bresets\s+(?:([A-Za-z]{3})[a-z]*\s+(\d{1,2}),?\s+)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)\s*\(([^)\s]+)\)/i.exec(text);
848
+ if (!hit || !Number.isFinite(atMs))
849
+ return null;
850
+ const [, mon, day, hour, minute = "0", meridiem, zone] = hit;
851
+ const month = mon ? MONTHS.indexOf(mon.toLowerCase()) : -1;
852
+ if (mon && month < 0)
853
+ return null;
854
+ const h = (+hour % 12) + (meridiem.toLowerCase() === "pm" ? 12 : 0);
855
+ try {
856
+ const local = new Date(atMs + zoneOffset(atMs, zone));
857
+ const toUtc = (y, m, d) => {
858
+ const wall = Date.UTC(y, m, d, h, +minute);
859
+ const first = wall - zoneOffset(wall, zone);
860
+ return wall - zoneOffset(first, zone);
861
+ };
862
+ let y = local.getUTCFullYear(), m = mon ? month : local.getUTCMonth(), d = mon ? +day : local.getUTCDate();
863
+ let result = toUtc(y, m, d);
864
+ // Not after the limit itself: the named time is the next one (tomorrow, or next year for a dated reset).
865
+ if (result <= atMs)
866
+ result = mon ? toUtc(++y, m, d) : toUtc(y, m, d + 1);
867
+ return Number.isFinite(result) ? new Date(result).toISOString() : null;
868
+ }
869
+ catch {
870
+ return null;
871
+ }
872
+ }
873
+ /**
874
+ * The rate_limited API error that ended the turn after `sinceMs` (the last input), with what Claude Code recorded after it.
875
+ * Claude Code 2.1.322 holds such a turn without a Stop hook ("Usage limit reached · continuing automatically at 7pm · esc to cancel")
876
+ * and continues it at the reset by itself; only its transcript shows the hold. Null when no such error follows the input.
877
+ */
878
+ export function claudeLimitEnd(meta, sinceMs) {
879
+ const file = claudeSessionTranscriptPath(meta);
880
+ if (!file || !Number.isFinite(sinceMs))
881
+ return null;
882
+ let size;
883
+ try {
884
+ size = fs.statSync(file).size;
885
+ }
886
+ catch (error) {
887
+ if (error.code === "ENOENT")
888
+ return null;
889
+ throw error;
890
+ }
891
+ const lines = readFileRange(file, Math.max(0, size - AGENT_EVENT_TAIL_BYTES), size).toString("utf8").split("\n");
892
+ lines.pop();
893
+ let end = null;
894
+ for (const line of lines) {
895
+ const error = claudeApiErrorFromLine(line);
896
+ if (error) {
897
+ if (error.at && Date.parse(error.at) >= sinceMs && (error.session_id === null || error.session_id === meta.vendor_session_id)
898
+ && claudeFailureCategory(error) === "rate_limited")
899
+ end = { at: error.at, reset_at: claudeLimitResetAt(error.text, Date.parse(error.at)), continued: false, hold: null, text: error.text };
900
+ else if (end)
901
+ end.continued = true;
902
+ continue;
903
+ }
904
+ if (!end)
905
+ continue;
906
+ let record;
907
+ try {
908
+ record = JSON.parse(line);
909
+ }
910
+ catch {
911
+ continue;
912
+ }
913
+ if (record?.isSidechain === true || (record?.sessionId && record.sessionId !== meta.vendor_session_id))
914
+ continue;
915
+ if (record?.type === "system" && record.subtype === "informational" && typeof record.content === "string") {
916
+ if (/^Usage limit reached\b.*\bcontinuing automatically\b/i.test(record.content))
917
+ end.hold = "armed";
918
+ else if (/^Automatic continue cancelled\b/i.test(record.content))
919
+ end.hold = "cancelled";
920
+ }
921
+ else if ((record?.type === "user" || record?.type === "assistant") && record.isMeta !== true) {
922
+ const content = record.message?.content;
923
+ // Slash commands typed on the seat (/rate-limit-options to re-arm) are not conversation work.
924
+ if (typeof content === "string" && /^\s*<(?:command-|local-command-)/u.test(content))
925
+ continue;
926
+ end.continued = true;
927
+ }
928
+ }
929
+ if (end?.continued)
930
+ end.hold = null;
931
+ return end;
932
+ }
809
933
  // ---- login "oauth_token" (BellTeam Claude 2nd slot, Owner ruling 2026-11-09): `claude setup-token` prints a 1-year token once;
810
934
  // Aiterm, as the PTY owner, writes it to the slot's token file. The CLI keeps no copy, so the file is the credential.
811
935
  const OAUTH_TOKEN_RE = /sk-ant-oat01-[A-Za-z0-9_-]{20,}/g;
package/dist/index.js CHANGED
@@ -821,7 +821,8 @@ export function createAitermServer(options = {}) {
821
821
  schema: z.literal("aiterm.pty-list-result.v1"),
822
822
  observed_at: z.string(),
823
823
  sessions: z.array(z.object({
824
- session_id: z.string(), current_command: z.string(), attached: z.boolean(),
824
+ session_id: z.string(), current_command: z.string().describe("前面コマンド。休止などの席は状態名(hibernated等)、端末が消えたClaudeの席(コンテナ再起動等)は\"vanished\"。次の送信で再開する"),
825
+ attached: z.boolean(),
825
826
  width: z.number(), height: z.number(),
826
827
  harness: z.enum(["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"]).nullable(),
827
828
  launch_id: z.string().nullable().optional().describe("一覧取得時のmanaged起動ID。通常PTYやmetadata不明時はnull、旧remote版は省略。操作時のfresh binding検証の代わりにはしない"),
@@ -829,12 +830,18 @@ export function createAitermServer(options = {}) {
829
830
  vendor_session_id: z.string().nullable().optional().describe("agent sessionのharness側の会話ID。Claude CodeとGrokは起動時に--session-idで渡した値(席の中で会話を移した後は追わない)、" +
830
831
  "CodexとCursorは分かった後の値。通常PTYと、まだ分からない席はnull"),
831
832
  environment: z.record(z.string(), z.string().nullable()),
833
+ // Claude agent rows only (0.70.26). Transcript and Aiterm's activity record, no screen; other rows omit both.
834
+ last_input_at: z.string().nullable().optional().describe("Claude agent rows: the last input Aiterm typed into this launch"),
835
+ limit_end: z.object({
836
+ at: z.string(), reset_at: z.string().nullable(), continued: z.boolean(), hold: z.enum(["armed", "cancelled"]).nullable(),
837
+ }).nullable().optional().describe("Claude agent rows: the usage limit that ended the turn after last_input_at (that turn is over; no Stop follows). " +
838
+ "continued: Claude recorded work after it. hold: Claude's automatic continue is armed, or was cancelled (pty_key Escape cancels an armed hold)"),
832
839
  })),
833
840
  },
834
841
  }, async ({ env_keys }, extra) => {
835
842
  try {
836
843
  await core.maintainAgentIdleClocks();
837
- const result = core.listSessionsResult(env_keys);
844
+ const result = core.listSessionsResult(env_keys, undefined, { vanished: true });
838
845
  return { ...ok(core.listSessions(result)), structuredContent: { ...result }, ...await seatTurnsMeta(result.sessions, extra._meta) };
839
846
  }
840
847
  catch (e) {
@@ -118,3 +118,15 @@ export function observeManagedSpan(file, binding, evidence, terminal, at, positi
118
118
  }
119
119
  return { state: "idle" };
120
120
  }
121
+ /** A turn the harness's own record ended without a completion hook (Claude's usage-limit hold): close its span now.
122
+ * `terminal` names that end, so a later busy frame opens a new span and only a newer terminal settles it. */
123
+ export function closeManagedSpan(file, binding, terminal, position = () => null) {
124
+ let record = null;
125
+ try {
126
+ record = recordSchema.parse(JSON.parse(fs.readFileSync(file, "utf8")));
127
+ }
128
+ catch { /* absent or unreadable: write a closed one */ }
129
+ if (record?.binding !== binding || record.span || record.terminal !== terminal)
130
+ writeJson0600(file, { binding, span: null, terminal, ready: null, settled_from: position() });
131
+ return { state: "idle" };
132
+ }
package/dist/update.js CHANGED
@@ -151,6 +151,9 @@ export function updateLocal(options) {
151
151
  base.setup_status = typeof setupResult?.status === "string" ? setupResult.status : null;
152
152
  if (typeof setupResult?.reason_code === "string")
153
153
  base.setup_reason_code = setupResult.reason_code;
154
+ // setupの失敗理由はstderrにしか出ない。残さないと読むために現地でsetupを流し直すことになる。
155
+ if (base.setup_status && base.setup_status !== "ready" && tail(setup.stderr))
156
+ base.message = `aiterm-setup: ${tail(setup.stderr)}`;
154
157
  if (!base.setup_status) {
155
158
  return { ...base, status, reason_code: "setup_failed", message: `aiterm-setup --json が結果を返しません: ${tail(setup.stderr) || setup.error || `exit ${setup.status}`}` };
156
159
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.70.25",
3
+ "version": "0.70.27",
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": [