aiterm-mcp 0.62.6 → 0.63.1

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,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.63.1] - 2026-11-02
11
+
12
+ ### Added
13
+ - Add `npm run test:dev` and a Testgate wrapper declaration for development test selection while preserving the Windows test runner and the full `npm test` entry.
14
+
15
+ ### Fixed
16
+ - Preserve printed output and correlated completion marks when ConPTY emits carriage return followed by cursor visibility controls.
17
+ - Keep native Windows Codex catalog fixtures until the test run ends so per-test cleanup does not race executable handle release after session shutdown.
18
+
19
+ ## [0.63.0] - 2026-11-01
20
+
21
+ - Preserve Windows registry protection before native identity checks, batch exact process births, and confirm native shutdown before cleaning a closed seat.
22
+ ### Added
23
+ - Hibernate managed Claude and Codex conversations after 30 idle minutes on Linux, macOS and Windows; resume the same vendor conversation and saved settings on the next send. Preserve logical listings and explicit environment values while dormant.
24
+ - Add `aiterm-idle-check` and native per-launch sleep clocks. Keep active turns, approvals, attachments, pending deliveries, working descendants and unconfirmed generations alive; exclude unverified harnesses and mounted execution graphs.
25
+ - Bind launch, resume, input and close to the actual native creation identity and preserve predecessor history and uncertain effects without replay.
26
+
27
+ ### Fixed
28
+ - Pause an active Codex v1 goal for session configuration, wait for its native turn end, and restore the owned pause while reporting partial or uncertain failures.
29
+ - Preserve Claude configuration selection across resume and refuse onboarding screens as composer readiness.
30
+ - Preserve unset Windows environment values, use exact session targets for native close, and retain literal POSIX environment values ending in a semicolon.
31
+ - Read the explicit `Fast off` preview in Codex 0.162 and distinguish Claude's native macOS keep-awake helper from user work.
32
+
10
33
  ## [0.62.6] - 2026-11-01
11
34
 
12
35
  ### Fixed
@@ -2975,7 +2998,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
2975
2998
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
2976
2999
  provenance.
2977
3000
 
2978
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.6...HEAD
3001
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.1...HEAD
3002
+ [0.63.1]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.0...v0.63.1
3003
+ [0.63.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.6...v0.63.0
2979
3004
  [0.62.6]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.5...v0.62.6
2980
3005
  [0.62.5]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.4...v0.62.5
2981
3006
  [0.62.4]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.3...v0.62.4
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.62.6** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
212
+ **状態:** 開発継続中 · 現行公開版 **v0.63.1** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
213
213
 
214
214
  ### 更新と巻き戻し
215
215
 
@@ -534,7 +534,7 @@ sessionへ登録する名前の配列で、`pty_list({ env_keys: ["JOB_OWNER"] }
534
534
  最後のsessionを閉じた直後は、終了中のserverの一覧を最長500msで再観測する場合がある。管理されたnative操作は、正常一覧または同socketの厳密な不在を確認できなければunknownを保つ。closeや送信は再実行しない。
535
535
 
536
536
  `pty_observe({ session_id, cursor? })`は`aiterm.pty-observe-result.v1`で`exists`、`observed_at`、
537
- `state`(busy/idle/blocked/dead/missing/unknown)、`reason`、`pane_alive`、`harness_alive`を返す。
537
+ `state`(busy/idle/blocked/dead/missing/unknown/hibernated)、`reason`、`pane_alive`、`harness_alive`を返す。
538
538
  Windowsで新しく起動するClaude・Codex・Grok・Antigravityは、本人processが不在でも、同じ起動のCLIからshellへ戻った記録がなければ未確認を返す。送信は既存の準備待ちの期限を使い、貼付直前とEnter直前にも本人を確認する。旧版で起動したsessionの扱いは維持する。
539
539
  `pane_process`と`harness_process`は別のidentityで、`process_identity`はagentならharness、通常PTYなら
540
540
  一意な子process group leader、子がなければpaneを指す。identityは`pid`、`process_group_id`、
@@ -547,6 +547,8 @@ Windowsで新しく起動するClaude・Codex・Grok・Antigravityは、本人pr
547
547
  `background_cpu_delta_complete`はpane開始から60秒以降に生成された子孫だけの同じ観測で、起動時MCPを除外する。
548
548
  `token_hint`は画面の直近token表示値またはnull。画面本文や生argvを解析する必要はない。
549
549
 
550
+ 休止を確定した会話席は、同じsession ID・harness・会話ID・明示登録envを`pty_list`に残す。`pty_observe`は`state=hibernated`、`reason=idle_timeout`、`exists=true`を返す。pane/harnessの生存はfalse、process本人性3項目とtoken_hintはnull。未配送数と起動後process数は0、CPU累積は0、cursorと活動差分はnull。停止途中・復帰途中・失敗・native世代の不一致はunknownとする。休止席のcloseはCLIを起こさず論理席を消す。同名を明示した`agent_launch`は保存した会話と設定で再開し、harness・設定・project・明示env名の矛盾は入力前に`AGENT_RESUME_CONFLICT`で断る。`pty_open`で休止会話席を上書きしない。通常の`pty_read`・制御キー・承認操作は、休止中や世代未確定では`AGENT_RESUME_UNCONFIRMED`で断る。履歴は既存のtranscriptオプションで読める。停止ボタンは確定休止席を起こさず閉じずidleで返し、途中や不整合は拒否する。全対応OSのmanaged Claude/Codex初回起動も実端末の作成本人性を保持し、証拠欠測では休止しない。自動採番は論理席の名前も避ける。休止直前には実CLIの現在設定も確認し、不一致や確認不能なら席を保持する。Linux・macOS・Windowsのmanaged Claude/Codex会話席は最後の番の終了から30分で休止し、次の送信で同じ会話へ戻る。正の有限値の`AITERM_IDLE_MINUTES`で分数を変更できる。応答中・承認待ち・attach中・未配送・作業中の子孫・作成証拠欠測・設定未確認の席は保持する。他のharness、通常PTY、mounted execution graphは対象外。`aiterm-idle-check --session <name> --launch <32hex>`で同じ保護付き判定を一度実行できる。
551
+
550
552
  agent sessionを閉じると失うものは、次の2項目で分かる。`activity.post_startup_process_count`は、`agent_launch`の起動準備が
551
553
  完了した時点(初手を送る前)に居なかったprocessの数。起動直後の1分に始めた裏の作業も数える。数えないものは2つ。Codex自身の
552
554
  補助process(`codex-code-mode-host`)と、中継`mcp-lazy`の直接の子(初めて使う時に起こすMCPの本体と、先行起動の判定)。
@@ -639,6 +641,8 @@ Aitermは、既定では実行時エラーをどこへも送らない。送る
639
641
 
640
642
  `agent_configure({ session_id, model?, reasoning_effort?, fast? })`はharness標準操作で起動中のClaude/Codex/Grok/Cursor/Antigravityを変更し、PTYと会話contextを維持する。
641
643
 
644
+ Codex v1のgoalがactiveの席では、`agent_configure`がgoalを一時停止し、現在の番の終了記録を最長30分待ってから設定を替え、同じgoalを再開します。番を待つ間も差し込みは通ります。途中で変更されたgoalは保持し、再開できなかった時は設定変更の結果とgoalの状態をエラー本文に残します。他のharnessでは通常の入力待ち上限を維持するため、番が続くgoalは停止または完了にしてから設定を替えてください。
645
+
642
646
  Codexでmodelだけを変更する場合は、標準の選択画面から現在のeffortを読み、同じ値を明示的に選びます。現在値を読めない場合や変更先で選べない場合は、別の値へ置き換えず失敗します。
643
647
 
644
648
  長寿命Codexでは状態footerの空白入りモデル表示名も認識し、起動headerが画面外へ流れた後も入力欄の受付を維持する。
@@ -761,6 +765,7 @@ agent_launch({ "harness": "codex-cli", "remote": { "host": "rabbit" }, "cwd": "/
761
765
  ### トークン削減
762
766
 
763
767
  - `pty_read` は既定で制御文字除去・連続重複圧縮・head+tail 折りたたみ(+復元ヒント・メタ併記)をかける。
768
+ - 復帰文字の後ろにカーソル表示の制御だけが続く場合も、既に印字された出力と完了印を保持する。
764
769
  - `pty_read({ rtk: true })` は直前に送ったコマンド別の reducer(`git status`/`git log`/`grep`/`pytest` ほか)で観測出力をさらに縮約する(rtk バイナリ非依存・自前実装)。
765
770
  - `pty_send({ rtk: true })` は既知コマンドを `rtk` 形に書き換えて送り、実行先に `rtk` があればソースで削減を効かせる(無ければ素通し)。
766
771
 
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.62.6** · 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.63.1** · 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
 
@@ -567,7 +567,7 @@ Its `aiterm.pty-list-result.v1` receipt contains `observed_at` and `sessions`, w
567
567
  After the last session closes, session listing may briefly re-observe an exiting server for up to 500 ms. Managed native operations retain unknown unless the listing or exact scoped absence can be confirmed; this never repeats a close or send.
568
568
 
569
569
  `pty_observe({ session_id, cursor? })` returns `aiterm.pty-observe-result.v1` with `exists`, `observed_at`, `state`
570
- (busy/idle/blocked/dead/missing/unknown), `reason`, `pane_alive`, and `harness_alive`. `pane_process` and `harness_process`
570
+ (busy/idle/blocked/dead/missing/unknown/hibernated), `reason`, `pane_alive`, and `harness_alive`. `pane_process` and `harness_process`
571
571
  are separate identities. `process_identity` selects the harness for agents, or the unique child process-group leader
572
572
  for an ordinary terminal, using the pane when no child leader exists. An identity contains `pid`, `process_group_id`,
573
573
  `started_identity`, and `argv_digest`; unresolved identities are null. Windows PIDs are native and its process-group field
@@ -582,6 +582,8 @@ between observations, the delta covers only observed increments and `cpu_delta_c
582
582
  only to descendants created at least 60 seconds after the pane, excluding startup MCP processes. `token_hint` is the latest
583
583
  displayed token count or null. Callers do not need raw argv or pane-text parsing.
584
584
 
585
+ A confirmed hibernation keeps the same logical session in `pty_list`, with the saved harness, conversation ID, and explicitly registered environment values. `pty_observe` returns `state: "hibernated"`, `reason: "idle_timeout"`, and `exists: true`, while both liveness fields are false and process identities and token hint are null. Pending child deliveries and post-startup process count are zero; CPU totals are zero and activity cursors and differences are null. Stopping, resuming, failed, or conflicting native generations remain unknown. Closing a hibernated seat removes it without restarting the CLI. An explicit same-name `agent_launch` resumes the saved conversation and settings; conflicting harness, settings, project, or registered environment names return `AGENT_RESUME_CONFLICT` before input. `pty_open` cannot replace a dormant agent seat. Native `pty_read`, control keys and approval actions refuse dormant or uncertain generations with `AGENT_RESUME_UNCONFIRMED`; transcript reads remain available through the existing transcript option. The stop button returns idle for a confirmed hibernated seat without waking or closing it, and refuses uncertain or conflicting generations. Initial managed Claude/Codex launches on all supported operating systems also retain the actual terminal creation identity; a missing proof prevents automatic hibernation, and automatic naming preserves logical seat names. Idle shutdown also requires confirmation of the running CLI’s settings; mismatched or unknown settings keep the seat alive. Managed Claude and Codex conversations on Linux, macOS and Windows hibernate after 30 minutes from their last completed turn and resume the same conversation on the next send. Set `AITERM_IDLE_MINUTES` to a positive finite duration to change the threshold. Busy or blocked turns, attached terminals, pending child deliveries, active descendants, missing native creation evidence and uncertain settings remain alive. Other harnesses, ordinary PTYs and mounted execution graphs are excluded. `aiterm-idle-check --session <name> --launch <32hex>` runs the same guarded check once.
586
+
585
587
  Two fields tell a caller what closing an agent session would lose. `activity.post_startup_process_count` is the number of
586
588
  processes in the session that did not exist when `agent_launch` finished startup (before the first prompt), so background work
587
589
  started in the first minute is counted too. Two kinds of process are not counted: Codex's own `codex-code-mode-host` helper, and
@@ -684,6 +686,8 @@ enables collection on that host.
684
686
 
685
687
  `agent_configure({ session_id, model?, reasoning_effort?, fast? })` changes a running Claude, Codex, Grok, or Cursor TUI through the harness's standard controls, preserving the PTY and conversation context.
686
688
 
689
+ For an active Codex v1 goal, `agent_configure` temporarily pauses the goal, waits for the current native turn to end (up to 30 minutes), applies settings through the same send queue, and resumes that goal. Steering remains available during the wait. A changed goal is preserved; a failed or uncertain restoration is reported with the configuration outcome. Other harnesses retain the normal readiness limit: stop or complete a continuously running goal before configuring them.
690
+
687
691
  Codex model-only changes explicitly preserve the current reasoning effort read from the native picker. Unreadable or unsupported current effort fails without selecting another value.
688
692
 
689
693
  Long-lived Codex sessions recognize native model display names containing spaces in the status footer, so a ready composer remains available after the launch header scrolls away.
@@ -819,6 +823,7 @@ agent_launch({ "harness": "codex-cli", "remote": { "host": "rabbit" }, "cwd": "/
819
823
  ### Token reduction
820
824
 
821
825
  - `pty_read` by default strips control characters, collapses repeated lines, and folds long output into head+tail (with a restore hint and a meta line).
826
+ - Carriage returns followed only by cursor visibility controls preserve printed output and completion marks.
822
827
  - `pty_read({ rtk: true })` further shrinks the observed output with a per-command reducer (`git status`/`git log`/`grep`/`pytest` and more) — a self-contained reimplementation that needs no `rtk` binary.
823
828
  - `pty_send({ rtk: true })` rewrites a known command into `rtk` form before sending, so reduction happens at the source if `rtk` exists there (passthrough otherwise).
824
829
 
@@ -0,0 +1,69 @@
1
+ import fs from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import { agentMetadataPath } from "./agent-shared.js";
4
+ import { AitermError } from "./errors.js";
5
+ const activityPath = (launch) => agentMetadataPath(launch.aiterm_session, launch.launch_id).replace(/\.agent\.json$/, ".activity.jsonl");
6
+ const validTime = (at) => typeof at === "string" && at.length <= 40 && Number.isFinite(Date.parse(at));
7
+ const unreadable = () => new AitermError("AGENT_ACTIVITY_UNCONFIRMED: 席の最終入力・番終了の記録を確認できません。", 2);
8
+ function read(launch) {
9
+ const activity = { tracked: false, last_input_at: null, last_turn_end_at: null };
10
+ const completed = new Set();
11
+ let text;
12
+ try {
13
+ text = fs.readFileSync(activityPath(launch), "utf8");
14
+ }
15
+ catch (error) {
16
+ if (error.code === "ENOENT")
17
+ return { activity, completed };
18
+ throw unreadable();
19
+ }
20
+ if (!text.endsWith("\n"))
21
+ throw unreadable();
22
+ for (const line of text.trimEnd().split("\n")) {
23
+ let record;
24
+ try {
25
+ record = JSON.parse(line);
26
+ }
27
+ catch {
28
+ throw unreadable();
29
+ }
30
+ if (!record || !["created", "input", "turn_end"].includes(record.kind) || !validTime(record.at)
31
+ || (record.kind === "turn_end" && (typeof record.key !== "string" || !/^[a-f0-9]{64}$/.test(record.key))))
32
+ throw unreadable();
33
+ activity.tracked = true;
34
+ if (record.kind === "created")
35
+ continue;
36
+ if (record.kind === "turn_end") {
37
+ if (completed.has(record.key))
38
+ continue;
39
+ completed.add(record.key);
40
+ }
41
+ const field = record.kind === "input" ? "last_input_at" : "last_turn_end_at";
42
+ if (activity[field] === null || Date.parse(record.at) > Date.parse(activity[field]))
43
+ activity[field] = record.at;
44
+ }
45
+ return { activity, completed };
46
+ }
47
+ export function readAgentActivity(launch) { return read(launch).activity; }
48
+ function append(launch, record) {
49
+ // Hook and sender must not overwrite each other's metadata snapshots.
50
+ fs.appendFileSync(activityPath(launch), JSON.stringify(record) + "\n", { mode: 0o600 });
51
+ }
52
+ export function initializeAgentActivity(meta) {
53
+ if (!validTime(meta.created_at))
54
+ throw unreadable();
55
+ fs.writeFileSync(activityPath(meta), JSON.stringify({ kind: "created", at: meta.created_at }) + "\n", { mode: 0o600, flag: "wx" });
56
+ }
57
+ export function recordAgentInput(launch, at = new Date().toISOString()) {
58
+ if (!validTime(at))
59
+ throw unreadable();
60
+ append(launch, { kind: "input", at });
61
+ }
62
+ export function recordAgentTurnEnd(launch, event) {
63
+ if (!validTime(event.at))
64
+ throw unreadable();
65
+ const key = createHash("sha256").update(JSON.stringify([event.vendor, event.vendor_session_id,
66
+ event.turn_id ?? event.operation_id ?? event.at])).digest("hex");
67
+ if (!read(launch).completed.has(key))
68
+ append(launch, { kind: "turn_end", at: event.at, key });
69
+ }
@@ -54,7 +54,7 @@ export const agentGoalResultSchema = z.object({
54
54
  export function sameGoalTarget(current, target) {
55
55
  return !!current && !!target && current.session_id === target.session_id && current.launch_id === target.launch_id
56
56
  && current.harness === target.harness && current.vendor_session_id === target.vendor_session_id
57
- && current.codex_home === target.codex_home && current.grok_home === target.grok_home && current.cwd === target.cwd && current.executable === target.executable
57
+ && current.codex_home === target.codex_home && current.claude_home === target.claude_home && current.grok_home === target.grok_home && current.cwd === target.cwd && current.executable === target.executable
58
58
  && JSON.stringify(current.native_process) === JSON.stringify(target.native_process);
59
59
  }
60
60
  export class AgentGoalConnectionError extends Error {
@@ -147,6 +147,8 @@ export async function manageAgentGoal(input, runtime, origin = "automatic") {
147
147
  return reject("resume_requires_paused_goal");
148
148
  if (input.action === "pause" && before?.status !== "active")
149
149
  return reject("pause_requires_active_goal");
150
+ if (runtime.beforeMutation && !runtime.beforeMutation(before))
151
+ return reject("goal_changed_before_mutation");
150
152
  if (!same())
151
153
  return { ...result, availability: "unavailable", outcome: "unavailable", reason: "generation_replaced" };
152
154
  const method = input.action === "clear" ? "thread/goal/clear" : "thread/goal/set";
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ import { fileURLToPath } from "node:url";
3
+ import { executionLaunchSchema } from "./execution-contract.js";
4
+ import { AitermError } from "./errors.js";
5
+ import { AGENT_IDLE_ENABLED } from "./agent-idle-clock.js";
6
+ import { serviceAgentIdleClock } from "./core.js";
7
+ export function parseIdleArgs(args) {
8
+ const fields = {};
9
+ for (let index = 0; index < args.length; index += 2) {
10
+ const key = args[index], value = args[index + 1];
11
+ if (!["--session", "--launch", "--clock"].includes(key) || value === undefined || fields[key] !== undefined)
12
+ throw new Error("usage: aiterm-idle-check --session <name> --launch <32hex> [--clock <32hex>]");
13
+ fields[key] = value;
14
+ }
15
+ const launch = executionLaunchSchema.parse({ session_id: fields["--session"], launch_id: fields["--launch"] });
16
+ if (fields["--clock"] !== undefined && !/^[a-f0-9]{32}$/.test(fields["--clock"]))
17
+ throw new Error("invalid idle clock token");
18
+ return { ...launch, ...(fields["--clock"] !== undefined ? { token: fields["--clock"] } : {}) };
19
+ }
20
+ export async function main(args = process.argv.slice(2)) {
21
+ try {
22
+ const { token, ...launch } = parseIdleArgs(args);
23
+ const result = AGENT_IDLE_ENABLED ? await serviceAgentIdleClock(launch, token)
24
+ : { outcome: "skipped", reason: "lifecycle_not_enabled" };
25
+ process.stdout.write(JSON.stringify(result) + "\n");
26
+ return result.outcome === "unconfirmed" ? 2 : 0;
27
+ }
28
+ catch (error) {
29
+ if (error instanceof AitermError && error.message.startsWith("AGENT_SEND_BUSY:"))
30
+ return 75;
31
+ process.stderr.write("aiterm: idle_check_unconfirmed\n");
32
+ return 2;
33
+ }
34
+ }
35
+ if (process.argv[1] === fileURLToPath(import.meta.url))
36
+ process.exitCode = await main();
@@ -0,0 +1,100 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { readProcessIdentities, idleClockCommand, signalRuntimeProcess } from "./process-runtime.js";
7
+ import { resolveWindowsPowerShell7 } from "./windows-powershell.js";
8
+ import { liveNodeExecutable } from "./live-node.js";
9
+ import { readAgentIdleClock, readAgentResumeNative, writeAgentIdleClock } from "./agent-lifecycle.js";
10
+ import { ensureStateRoot } from "./agent-shared.js";
11
+ // Test fixtures drive the controller explicitly, without arming unattended timers.
12
+ export const AGENT_IDLE_ENABLED = !process.env.NODE_TEST_CONTEXT;
13
+ const CLI = fileURLToPath(new URL("./agent-idle-cli.js", import.meta.url));
14
+ export function idleClockDeadline(result, now) {
15
+ if (result.outcome === "hibernated" || result.outcome === "unconfirmed" || ["dead", "missing"].includes(result.reason))
16
+ return null;
17
+ return result.due_at !== null && result.due_at > now ? result.due_at : now + 60_000;
18
+ }
19
+ async function detached(command) {
20
+ const env = { ...process.env };
21
+ for (const key of Object.keys(env))
22
+ if (key.startsWith("AITERM_AGENT_"))
23
+ delete env[key];
24
+ if (process.platform === "win32") {
25
+ // PowerShell needs CREATE_NO_WINDOW: DETACHED_PROCESS skips execution, inherited consoles die with the caller.
26
+ const quote = (value) => `'${value.replace(/'/g, "''")}'`;
27
+ const directory = mkdtempSync(join(ensureStateRoot(), "idle-start-")), receipt = join(directory, "owner.json");
28
+ try {
29
+ const script = `$ErrorActionPreference='Stop'; $s=[Diagnostics.ProcessStartInfo]::new(${quote(command.executable)}); $s.UseShellExecute=$false; $s.CreateNoWindow=$true; foreach($a in @(${command.args.map(quote).join(",")})){$s.ArgumentList.Add($a)}; $p=[Diagnostics.Process]::Start($s); try { $owner=[ordered]@{pid=$p.Id;started_identity=$p.StartTime.ToUniversalTime().ToString('o')} | ConvertTo-Json -Compress; [IO.File]::WriteAllText(${quote(receipt)},$owner) } catch { $p.Kill(); throw }`;
30
+ // The sleeper must inherit null handles, not pipes that keep this one-shot launcher waiting.
31
+ const result = spawnSync(resolveWindowsPowerShell7(), ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand",
32
+ Buffer.from(script, "utf16le").toString("base64")], { stdio: "ignore", env, windowsHide: true, timeout: 10_000 });
33
+ if (result.error || result.status !== 0)
34
+ throw new Error("idle_clock_start_failed");
35
+ const owner = JSON.parse(readFileSync(receipt, "utf8"));
36
+ if (!Number.isSafeInteger(owner?.pid) || owner.pid <= 1 || typeof owner.started_identity !== "string"
37
+ || !Number.isFinite(Date.parse(owner.started_identity)))
38
+ throw new Error("idle_clock_owner_unconfirmed");
39
+ return { pid: owner.pid, started_identity: new Date(owner.started_identity).toISOString() };
40
+ }
41
+ finally {
42
+ rmSync(directory, { recursive: true, force: true });
43
+ }
44
+ }
45
+ const child = spawn(command.executable, command.args, { stdio: "ignore", detached: true, env });
46
+ child.unref();
47
+ await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
48
+ const owner = child.pid === undefined ? undefined : readProcessIdentities([child.pid]).find(row => row.pid === child.pid);
49
+ if (!owner?.started_identity) {
50
+ if (child.exitCode === null)
51
+ child.kill();
52
+ throw new Error("idle_clock_owner_unconfirmed");
53
+ }
54
+ return { pid: owner.pid, started_identity: owner.started_identity };
55
+ }
56
+ export function isAgentIdleClockOwner(clock) {
57
+ return [process.pid, process.ppid].includes(clock.owner.pid) && readProcessIdentities([clock.owner.pid])
58
+ .some(row => row.started_identity === clock.owner.started_identity);
59
+ }
60
+ /** Called under the existing seat send lock; the record is not an independent admission. */
61
+ export async function armAgentIdleClock(meta, anchor, wakeAt, replaceToken) {
62
+ const previous = readAgentIdleClock(meta);
63
+ if (replaceToken !== undefined && previous?.token !== replaceToken)
64
+ return "superseded";
65
+ if (replaceToken === undefined && previous && readProcessIdentities([previous.owner.pid])
66
+ .some(row => row.started_identity === previous.owner.started_identity))
67
+ return "existing";
68
+ const token = randomBytes(16).toString("hex");
69
+ const owner = await detached(idleClockCommand(wakeAt - Date.now(), liveNodeExecutable(), [CLI,
70
+ "--session", meta.aiterm_session, "--launch", meta.launch_id, "--clock", token]));
71
+ try {
72
+ const clock = { schema: "aiterm.agent-idle-clock.v1", launch_id: meta.launch_id,
73
+ token, owner: { pid: owner.pid, started_identity: owner.started_identity }, anchor, wake_at: new Date(wakeAt).toISOString() };
74
+ writeAgentIdleClock(meta, clock);
75
+ return "armed";
76
+ }
77
+ catch (error) {
78
+ // Only this newly spawned sleeper is ours; an older or uncertain owner is never killed.
79
+ if (readProcessIdentities([owner.pid]).some(row => row.started_identity === owner.started_identity))
80
+ signalRuntimeProcess({ ...owner, process_group_id: null, argv_digest: "" }, "SIGKILL", false);
81
+ throw error;
82
+ }
83
+ }
84
+ export function requestAgentIdleClock(session, launchId) {
85
+ if (!AGENT_IDLE_ENABLED)
86
+ return;
87
+ try {
88
+ if (!readAgentResumeNative({ aiterm_session: session, launch_id: launchId }))
89
+ return;
90
+ const clock = readAgentIdleClock({ aiterm_session: session, launch_id: launchId });
91
+ if (clock && readProcessIdentities([clock.owner.pid]).some(row => row.started_identity === clock.owner.started_identity))
92
+ return;
93
+ }
94
+ catch {
95
+ process.stderr.write("aiterm: idle_clock_state_unconfirmed\n");
96
+ return;
97
+ }
98
+ void detached(idleClockCommand(0, liveNodeExecutable(), [CLI, "--session", session, "--launch", launchId]))
99
+ .catch(() => { process.stderr.write("aiterm: idle_clock_start_failed\n"); });
100
+ }
@@ -0,0 +1,92 @@
1
+ export function idleMinutes(value = process.env.AITERM_IDLE_MINUTES) {
2
+ if (value === undefined)
3
+ return 30;
4
+ const minutes = Number(value);
5
+ if (!value.trim() || !Number.isFinite(minutes * 60_000) || minutes <= 0)
6
+ throw new Error("AITERM_IDLE_MINUTES must be a positive finite duration");
7
+ return minutes;
8
+ }
9
+ export function decideIdleSeat(seat, now, minutes = 30, expectedAnchor) {
10
+ const result = { outcome: "skipped", reason: "observation_unconfirmed", anchor: null, due_at: null, stalled: false };
11
+ if (!Number.isFinite(now) || !Number.isFinite(minutes * 60_000) || minutes <= 0)
12
+ return result;
13
+ if (seat.state !== "idle" || seat.reason !== "composer_ready")
14
+ return { ...result, reason: seat.state === "busy" ? "turn_running" : seat.state,
15
+ stalled: seat.state === "busy" && seat.window_activity_at !== null && Number.isFinite(seat.window_activity_at)
16
+ && now - seat.window_activity_at >= 60 * 60_000 };
17
+ if (seat.attached !== false)
18
+ return { ...result, reason: seat.attached === true ? "attached" : "attachment_unconfirmed" };
19
+ if (seat.pending_child_deliveries !== 0)
20
+ return { ...result, reason: "child_delivery_pending_or_unknown" };
21
+ if (seat.post_startup_process_count !== 0)
22
+ return { ...result, reason: "background_work_or_unknown" };
23
+ if (!seat.vendor_session_id)
24
+ return { ...result, reason: "conversation_id_unavailable" };
25
+ if (!seat.resume_ready)
26
+ return { ...result, reason: "resume_unavailable" };
27
+ if (seat.turn_settled !== true)
28
+ return { ...result, reason: "turn_end_unconfirmed" };
29
+ const anchor = seat.activity.last_turn_end_at ?? (!seat.activity.tracked ? seat.created_at : null);
30
+ if (anchor === null || !Number.isFinite(Date.parse(anchor)))
31
+ return { ...result, reason: "turn_end_time_unavailable" };
32
+ const input = seat.activity.last_input_at;
33
+ if (input !== null && (!Number.isFinite(Date.parse(input)) || Date.parse(input) > Date.parse(anchor)))
34
+ return { ...result, reason: "input_without_turn_end" };
35
+ const due = Date.parse(anchor) + minutes * 60_000;
36
+ if (!Number.isFinite(due))
37
+ return result;
38
+ if (expectedAnchor !== undefined && expectedAnchor !== anchor)
39
+ return { ...result, reason: "superseded_timer", anchor, due_at: due };
40
+ if (now >= due && !seat.native_configuration_confirmed)
41
+ return { ...result, reason: "native_configuration_unconfirmed", anchor, due_at: due };
42
+ return { ...result, outcome: now < due ? "not_due" : "ready", reason: now < due ? "before_deadline" : "idle_timeout", anchor, due_at: due };
43
+ }
44
+ /** The owner supplies the same seat admission used by input; no independent queue is created. */
45
+ export async function checkIdleSeat(runtime, expectedLaunch, minutes = 30, expectedAnchor) {
46
+ return runtime.exclusive(async () => {
47
+ let issued = false;
48
+ let effectIssued = false;
49
+ let preparation = null;
50
+ let result;
51
+ try {
52
+ const before = runtime.snapshot();
53
+ const lastInputAt = before.activity.last_input_at;
54
+ result = before.launch_id !== expectedLaunch
55
+ ? { outcome: "skipped", reason: "generation_replaced", anchor: null, due_at: null, stalled: false }
56
+ : decideIdleSeat(before, runtime.now(), minutes, expectedAnchor);
57
+ if (result.outcome === "ready") {
58
+ const anchor = result.anchor;
59
+ const verify = () => {
60
+ const current = runtime.snapshot();
61
+ const decision = decideIdleSeat(current, runtime.now(), minutes, anchor);
62
+ if (current.launch_id !== expectedLaunch || current.activity.last_input_at !== lastInputAt
63
+ || (effectIssued ? current.attached === true || ["busy", "blocked"].includes(current.state) : decision.outcome !== "ready"))
64
+ throw new Error("idle_precondition_changed");
65
+ };
66
+ verify();
67
+ preparation = { seat: before, anchor };
68
+ issued = true;
69
+ runtime.begin(before, anchor);
70
+ const stopped = await runtime.stop(verify, () => { effectIssued = true; });
71
+ if (!stopped)
72
+ throw new Error("process_tree_exit_unconfirmed");
73
+ verify();
74
+ runtime.finish(before, anchor);
75
+ result = { ...result, outcome: "hibernated" };
76
+ }
77
+ }
78
+ catch {
79
+ if (issued && !effectIssued && preparation) {
80
+ try {
81
+ runtime.cancel(preparation.seat, preparation.anchor);
82
+ issued = false;
83
+ }
84
+ catch { /* Keep an uncertain stopping record. */ }
85
+ }
86
+ result = { outcome: issued ? "unconfirmed" : "skipped", reason: issued ? "stop_unconfirmed" : "observation_unconfirmed",
87
+ anchor: null, due_at: null, stalled: false };
88
+ }
89
+ runtime.record(result);
90
+ return result;
91
+ });
92
+ }
@@ -0,0 +1,182 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { z } from "zod";
5
+ import { agentMetadataPath, writeJson0600 } from "./agent-shared.js";
6
+ import { AitermError } from "./errors.js";
7
+ const launchId = z.string().regex(/^[a-f0-9]{32}$/);
8
+ const absolute = z.string().min(1).refine(value => path.isAbsolute(value) && !value.includes("\0"));
9
+ export const agentResumeRecipeSchema = z.object({
10
+ schema: z.literal("aiterm.agent-resume.v1"), launch_id: launchId,
11
+ kind: z.enum(["claude", "codex"]), vendor_session_id: z.string().regex(/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i),
12
+ executable: absolute, cwd: absolute, configuration_root: absolute, model: z.string().nullable(), reasoning_effort: z.string().nullable(), fast: z.boolean(),
13
+ environment: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), z.string().refine(value => !value.includes("\0")).nullable()),
14
+ }).strict();
15
+ const identity = z.object({ pid: z.number().int().positive(), process_group_id: z.number().int().positive().nullable(),
16
+ started_identity: z.string().min(1), argv_digest: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
17
+ export const agentLifecycleSchema = z.object({ schema: z.literal("aiterm.agent-lifecycle.v1"), launch_id: launchId,
18
+ state: z.enum(["stopping", "hibernated"]), socket: z.string().min(1).optional(), at: z.iso.datetime(), anchor: z.string().min(1),
19
+ native_id: z.string().regex(/^\$\d+$/), pane: identity, resume_proof_digest: z.string().regex(/^[a-f0-9]{64}$/).optional(), recipe_digest: z.string().regex(/^[a-f0-9]{64}$/),
20
+ }).strict();
21
+ const file = (meta, suffix) => agentMetadataPath(meta.aiterm_session, meta.launch_id).replace(/\.agent\.json$/, suffix);
22
+ const unavailable = () => new AitermError("AGENT_LIFECYCLE_UNCONFIRMED: 席の休止・復帰記録を確認できません。", 2);
23
+ function read(meta, suffix, schema) {
24
+ let body;
25
+ try {
26
+ const item = fs.lstatSync(file(meta, suffix));
27
+ if (!item.isFile() || item.isSymbolicLink() || item.size > 4 * 1024 * 1024)
28
+ throw unavailable();
29
+ body = fs.readFileSync(file(meta, suffix), "utf8");
30
+ }
31
+ catch (error) {
32
+ if (error.code === "ENOENT")
33
+ return null;
34
+ throw unavailable();
35
+ }
36
+ try {
37
+ return schema.parse(JSON.parse(body));
38
+ }
39
+ catch {
40
+ throw unavailable();
41
+ }
42
+ }
43
+ export function readAgentResumeRecipe(meta) {
44
+ const value = read(meta, ".resume.json", agentResumeRecipeSchema);
45
+ if (value && value.launch_id !== meta.launch_id)
46
+ throw unavailable();
47
+ return value;
48
+ }
49
+ export function writeAgentResumeRecipe(meta, input) {
50
+ const value = agentResumeRecipeSchema.parse(input);
51
+ if (value.launch_id !== meta.launch_id || value.vendor_session_id !== meta.vendor_session_id || value.kind !== meta.kind)
52
+ throw unavailable();
53
+ writeJson0600(file(meta, ".resume.json"), value);
54
+ }
55
+ export function agentResumeRecipeDigest(recipe) {
56
+ return createHash("sha256").update(JSON.stringify(agentResumeRecipeSchema.parse(recipe))).digest("hex");
57
+ }
58
+ export function readAgentLifecycle(meta) {
59
+ const value = read(meta, ".lifecycle.json", agentLifecycleSchema);
60
+ if (value && value.launch_id !== meta.launch_id)
61
+ throw unavailable();
62
+ return value;
63
+ }
64
+ export function writeAgentLifecycle(meta, input) {
65
+ const value = agentLifecycleSchema.parse(input);
66
+ if (value.launch_id !== meta.launch_id)
67
+ throw unavailable();
68
+ writeJson0600(file(meta, ".lifecycle.json"), value);
69
+ }
70
+ export function cancelAgentStopping(meta, anchor) {
71
+ const value = readAgentLifecycle(meta);
72
+ if (value === null)
73
+ return;
74
+ if (value.state !== "stopping" || value.anchor !== anchor)
75
+ throw unavailable();
76
+ fs.unlinkSync(file(meta, ".lifecycle.json"));
77
+ }
78
+ const resumeAttemptSchema = z.object({ schema: z.literal("aiterm.agent-resume-attempt.v1"), launch_id: launchId,
79
+ next_launch_id: launchId, state: z.enum(["resuming", "ready", "failed"]), at: z.iso.datetime(),
80
+ recipe_digest: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
81
+ export function readAgentResumeAttempt(meta) {
82
+ const value = read(meta, ".resume-attempt.json", resumeAttemptSchema);
83
+ if (value && value.launch_id !== meta.launch_id)
84
+ throw unavailable();
85
+ return value;
86
+ }
87
+ export function writeAgentResumeAttempt(meta, value) {
88
+ if (value.launch_id !== meta.launch_id || value.next_launch_id === meta.launch_id)
89
+ throw unavailable();
90
+ writeJson0600(file(meta, ".resume-attempt.json"), resumeAttemptSchema.parse(value));
91
+ }
92
+ const resumeNativeSchema = z.object({ schema: z.literal("aiterm.agent-resume-native.v1"), launch_id: launchId,
93
+ native_id: z.string().regex(/^\$\d+$/), session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),
94
+ server_pid: z.number().int().positive(), server_started_identity: z.string().min(1),
95
+ pane_id: z.string().regex(/^%\d+$/), pane_pid: z.number().int().positive(), pane_started_identity: z.string().min(1),
96
+ }).strict();
97
+ export function readAgentResumeNative(meta) {
98
+ const value = read(meta, ".resume-native.json", resumeNativeSchema);
99
+ if (value && (value.launch_id !== meta.launch_id || value.session_id !== meta.aiterm_session))
100
+ throw unavailable();
101
+ return value;
102
+ }
103
+ export function writeAgentResumeNative(meta, value) {
104
+ if (value.launch_id !== meta.launch_id || value.session_id !== meta.aiterm_session)
105
+ throw unavailable();
106
+ writeJson0600(file(meta, ".resume-native.json"), resumeNativeSchema.parse(value));
107
+ }
108
+ const idleClockSchema = z.object({ schema: z.literal("aiterm.agent-idle-clock.v1"), launch_id: launchId,
109
+ token: launchId, owner: z.object({ pid: z.number().int().positive(), started_identity: z.string().min(1) }).strict(),
110
+ anchor: z.string().nullable(), wake_at: z.iso.datetime() }).strict();
111
+ export function readAgentIdleClock(meta) {
112
+ const value = read(meta, ".idle-clock.json", idleClockSchema);
113
+ if (value && value.launch_id !== meta.launch_id)
114
+ throw unavailable();
115
+ return value;
116
+ }
117
+ export function writeAgentIdleClock(meta, input) {
118
+ const value = idleClockSchema.parse(input);
119
+ if (value.launch_id !== meta.launch_id)
120
+ throw unavailable();
121
+ writeJson0600(file(meta, ".idle-clock.json"), value);
122
+ }
123
+ export function retireAgentIdleClock(meta, token) {
124
+ const value = readAgentIdleClock(meta);
125
+ if (value === null || (token !== undefined && value.token !== token))
126
+ return;
127
+ fs.unlinkSync(file(meta, ".idle-clock.json"));
128
+ }
129
+ const resumeTemplateSchema = agentResumeRecipeSchema.omit({ vendor_session_id: true, fast: true }).extend({
130
+ schema: z.literal("aiterm.agent-resume-template.v1"), state: z.enum(["confirmed", "unconfirmed"]),
131
+ }).strict();
132
+ export function readAgentResumeTemplate(meta) {
133
+ const value = read(meta, ".resume-template.json", resumeTemplateSchema);
134
+ if (value && value.launch_id !== meta.launch_id)
135
+ throw unavailable();
136
+ return value;
137
+ }
138
+ export function writeAgentResumeTemplate(meta, input) {
139
+ const value = resumeTemplateSchema.parse(input);
140
+ if (value.launch_id !== meta.launch_id || value.kind !== meta.kind)
141
+ throw unavailable();
142
+ writeJson0600(file(meta, ".resume-template.json"), value);
143
+ }
144
+ export function captureAgentResumeTemplate(meta, effort, envNames, configurationRoot, env = process.env) {
145
+ if (meta.kind !== "claude" && meta.kind !== "codex")
146
+ return;
147
+ // Explicit credential variables cannot be persisted as a conversation recipe.
148
+ if (envNames.some(name => /(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIALS?|AUTH)$/i.test(name)))
149
+ return;
150
+ writeAgentResumeTemplate(meta, { schema: "aiterm.agent-resume-template.v1", launch_id: meta.launch_id, kind: meta.kind,
151
+ executable: meta.agent_executable, cwd: meta.cwd, configuration_root: configurationRoot, model: meta.model ?? null, reasoning_effort: effort,
152
+ environment: Object.fromEntries([...new Set([...envNames, ...(meta.kind === "claude" ? ["CLAUDE_CONFIG_DIR"] : [])])].map(name => [name, env[name] ?? null])), state: "confirmed" });
153
+ }
154
+ export function finishAgentResumeConfiguration(meta, before, model, effort) {
155
+ const complete = !!model && !!effort;
156
+ const known = before.state === "confirmed" && (!model || model === before.model || effort !== null);
157
+ writeAgentResumeTemplate(meta, { ...before, model: model ?? before.model, reasoning_effort: effort ?? before.reasoning_effort,
158
+ state: complete || known ? "confirmed" : "unconfirmed" });
159
+ }
160
+ export function refreshAgentResumeRecipe(meta) {
161
+ const template = readAgentResumeTemplate(meta);
162
+ if (!template) {
163
+ const recipe = readAgentResumeRecipe(meta);
164
+ return recipe?.model && recipe.reasoning_effort
165
+ && (meta.kind !== "claude" || Object.hasOwn(recipe.environment, "CLAUDE_CONFIG_DIR")) ? recipe : null;
166
+ }
167
+ if (template.state !== "confirmed" || !template.model || !template.reasoning_effort || template.model !== meta.model
168
+ || template.executable !== meta.agent_executable || template.cwd !== meta.cwd || typeof meta.fast !== "boolean")
169
+ return null;
170
+ if (meta.kind === "claude" && (!Object.hasOwn(template.environment, "CLAUDE_CONFIG_DIR")
171
+ || !["low", "medium", "high", "xhigh", "max"].includes(template.reasoning_effort)))
172
+ return null;
173
+ const { state, ...settings } = template;
174
+ const candidate = agentResumeRecipeSchema.safeParse({ ...settings, schema: "aiterm.agent-resume.v1",
175
+ vendor_session_id: meta.vendor_session_id, fast: meta.fast });
176
+ if (!candidate.success)
177
+ return null;
178
+ const previous = readAgentResumeRecipe(meta);
179
+ if (!previous || agentResumeRecipeDigest(previous) !== agentResumeRecipeDigest(candidate.data))
180
+ writeAgentResumeRecipe(meta, candidate.data);
181
+ return candidate.data;
182
+ }