aiterm-mcp 0.62.5 → 0.63.0
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 +23 -1
- package/README.ja.md +8 -2
- package/README.md +8 -2
- package/dist/agent-activity.js +69 -0
- package/dist/agent-goal.js +3 -1
- package/dist/agent-idle-cli.js +36 -0
- package/dist/agent-idle-clock.js +100 -0
- package/dist/agent-idle.js +92 -0
- package/dist/agent-lifecycle.js +182 -0
- package/dist/agent-resolver.js +1 -1
- package/dist/agent-shared.js +61 -0
- package/dist/aiterm-wait-cli.js +11 -4
- package/dist/claude-stop-hook.js +12 -1
- package/dist/configure-goal.js +63 -0
- package/dist/core.js +1261 -304
- package/dist/errors.js +1 -0
- package/dist/execution-effect.js +8 -0
- package/dist/harnesses/claude.js +20 -5
- package/dist/harnesses/codex.js +170 -10
- package/dist/harnesses/grok.js +21 -0
- package/dist/harnesses/idle-settings.js +109 -0
- package/dist/index.js +14 -7
- package/dist/interim-words.js +18 -3
- package/dist/native-session.js +22 -0
- package/dist/process-runtime.js +83 -9
- package/dist/process-start.js +26 -7
- package/dist/process-tree-stop.js +91 -0
- package/dist/psmux-send-worker.js +7 -1
- package/dist/steer-follow.js +88 -3
- package/dist/tmux-runtime.js +157 -8
- package/docs/DESIGN.md +13 -1
- package/package.json +3 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.63.0] - 2026-11-01
|
|
11
|
+
|
|
12
|
+
- Preserve Windows registry protection before native identity checks, batch exact process births, and confirm native shutdown before cleaning a closed seat.
|
|
13
|
+
### Added
|
|
14
|
+
- 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.
|
|
15
|
+
- 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.
|
|
16
|
+
- Bind launch, resume, input and close to the actual native creation identity and preserve predecessor history and uncertain effects without replay.
|
|
17
|
+
|
|
18
|
+
### Fixed
|
|
19
|
+
- 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.
|
|
20
|
+
- Preserve Claude configuration selection across resume and refuse onboarding screens as composer readiness.
|
|
21
|
+
- Preserve unset Windows environment values, use exact session targets for native close, and retain literal POSIX environment values ending in a semicolon.
|
|
22
|
+
- Read the explicit `Fast off` preview in Codex 0.162 and distinguish Claude's native macOS keep-awake helper from user work.
|
|
23
|
+
|
|
24
|
+
## [0.62.6] - 2026-11-01
|
|
25
|
+
|
|
26
|
+
### Fixed
|
|
27
|
+
- Correlate Grok input with its accepted native turn when the preceding turn ends during submission; never substitute the preceding completion or resend the input.
|
|
28
|
+
- Preserve `STEER_NOT_QUEUED` / `STEER_STILL_QUEUED` errors with typed unknown-effect receipts and a launch-bound Grok observation handle when available.
|
|
29
|
+
|
|
10
30
|
## [0.62.5] - 2026-11-01
|
|
11
31
|
|
|
12
32
|
### Added
|
|
@@ -2969,7 +2989,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
|
|
|
2969
2989
|
`ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
|
|
2970
2990
|
provenance.
|
|
2971
2991
|
|
|
2972
|
-
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.
|
|
2992
|
+
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.0...HEAD
|
|
2993
|
+
[0.63.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.6...v0.63.0
|
|
2994
|
+
[0.62.6]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.5...v0.62.6
|
|
2973
2995
|
[0.62.5]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.4...v0.62.5
|
|
2974
2996
|
[0.62.4]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.3...v0.62.4
|
|
2975
2997
|
[0.62.3]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.2...v0.62.3
|
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.
|
|
212
|
+
**状態:** 開発継続中 · 現行公開版 **v0.63.0** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
|
|
213
213
|
|
|
214
214
|
### 更新と巻き戻し
|
|
215
215
|
|
|
@@ -238,6 +238,8 @@ MCP clientが起動し直すまで旧版のcodeで動き(`running_servers`)
|
|
|
238
238
|
|
|
239
239
|
## 2 つの使い方
|
|
240
240
|
|
|
241
|
+
Grokへの`pty_send`中に前のturnが終わった場合、送信後の本文全体とnative turn番号を照合し、新turnでの受理を確認できれば`agent_dispatch`を返す。本文は再送しない。`STEER_NOT_QUEUED`・`STEER_STILL_QUEUED`は既存の`isError:true`と本文prefixを保ち、`structuredContent`に`aiterm.agent-send-error.v1`、文字列の`code`、`outcome:"outcome_unknown"`、`effect:"possible"`、元session/launchを返す。Grokの送信前記録を保存できた場合だけ観測用の手がかりを付け、取得不能はnullとする。不明の本文は再送しない。観測は本文のnative受理を確認するまで未完了を保ち、前のturnの完了を流用しない。Cursorの成否不明エラーでは、native受理を確定する観測経路が未対応のため手がかりはnull。
|
|
242
|
+
|
|
241
243
|
### 1. SSH・コンテナ・REPL を 1 本の永続端末で操作する — 土台
|
|
242
244
|
|
|
243
245
|
これが土台で、platform backend(POSIXのtmux/Windows nativeのpsmux)だけで動く——他の CLI は要らない。`pty_open` がローカル端末を 1 個握り、`ssh host`・`docker exec -it x bash`・REPL は、その中へ `pty_send` で打ち込む「ただのテキスト」——**一度だけ**。以降のコマンドは同じ認証済みセッションを通る。セッション種別をツールで区別しない。
|
|
@@ -532,7 +534,7 @@ sessionへ登録する名前の配列で、`pty_list({ env_keys: ["JOB_OWNER"] }
|
|
|
532
534
|
最後のsessionを閉じた直後は、終了中のserverの一覧を最長500msで再観測する場合がある。管理されたnative操作は、正常一覧または同socketの厳密な不在を確認できなければunknownを保つ。closeや送信は再実行しない。
|
|
533
535
|
|
|
534
536
|
`pty_observe({ session_id, cursor? })`は`aiterm.pty-observe-result.v1`で`exists`、`observed_at`、
|
|
535
|
-
`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`を返す。
|
|
536
538
|
Windowsで新しく起動するClaude・Codex・Grok・Antigravityは、本人processが不在でも、同じ起動のCLIからshellへ戻った記録がなければ未確認を返す。送信は既存の準備待ちの期限を使い、貼付直前とEnter直前にも本人を確認する。旧版で起動したsessionの扱いは維持する。
|
|
537
539
|
`pane_process`と`harness_process`は別のidentityで、`process_identity`はagentならharness、通常PTYなら
|
|
538
540
|
一意な子process group leader、子がなければpaneを指す。identityは`pid`、`process_group_id`、
|
|
@@ -545,6 +547,8 @@ Windowsで新しく起動するClaude・Codex・Grok・Antigravityは、本人pr
|
|
|
545
547
|
`background_cpu_delta_complete`はpane開始から60秒以降に生成された子孫だけの同じ観測で、起動時MCPを除外する。
|
|
546
548
|
`token_hint`は画面の直近token表示値またはnull。画面本文や生argvを解析する必要はない。
|
|
547
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
|
+
|
|
548
552
|
agent sessionを閉じると失うものは、次の2項目で分かる。`activity.post_startup_process_count`は、`agent_launch`の起動準備が
|
|
549
553
|
完了した時点(初手を送る前)に居なかったprocessの数。起動直後の1分に始めた裏の作業も数える。数えないものは2つ。Codex自身の
|
|
550
554
|
補助process(`codex-code-mode-host`)と、中継`mcp-lazy`の直接の子(初めて使う時に起こすMCPの本体と、先行起動の判定)。
|
|
@@ -637,6 +641,8 @@ Aitermは、既定では実行時エラーをどこへも送らない。送る
|
|
|
637
641
|
|
|
638
642
|
`agent_configure({ session_id, model?, reasoning_effort?, fast? })`はharness標準操作で起動中のClaude/Codex/Grok/Cursor/Antigravityを変更し、PTYと会話contextを維持する。
|
|
639
643
|
|
|
644
|
+
Codex v1のgoalがactiveの席では、`agent_configure`がgoalを一時停止し、現在の番の終了記録を最長30分待ってから設定を替え、同じgoalを再開します。番を待つ間も差し込みは通ります。途中で変更されたgoalは保持し、再開できなかった時は設定変更の結果とgoalの状態をエラー本文に残します。他のharnessでは通常の入力待ち上限を維持するため、番が続くgoalは停止または完了にしてから設定を替えてください。
|
|
645
|
+
|
|
640
646
|
Codexでmodelだけを変更する場合は、標準の選択画面から現在のeffortを読み、同じ値を明示的に選びます。現在値を読めない場合や変更先で選べない場合は、別の値へ置き換えず失敗します。
|
|
641
647
|
|
|
642
648
|
長寿命Codexでは状態footerの空白入りモデル表示名も認識し、起動headerが画面外へ流れた後も入力欄の受付を維持する。
|
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.
|
|
230
|
+
**Status:** actively maintained · current public release **v0.63.0** · 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
|
|
|
@@ -268,6 +268,8 @@ Cursorが誤りでturnを終えた時(記録の`turn_ended`が`status: "error"
|
|
|
268
268
|
|
|
269
269
|
## Two ways to use it
|
|
270
270
|
|
|
271
|
+
Grok can finish its current turn while `pty_send` is submitting input. Aiterm correlates the newly appended full user message with the native turn number and returns `agent_dispatch` for a proven new turn, without sending again. `STEER_NOT_QUEUED` and `STEER_STILL_QUEUED` preserve `isError:true` and their existing text prefix; `structuredContent` adds `aiterm.agent-send-error.v1`, a string `code`, `outcome:"outcome_unknown"`, `effect:"possible"`, and the original session/launch. A Grok observation handle is returned only when its pre-input record was saved; unavailable handles are null. Do not resend unknown input. Its waiter remains pending until the input's native acceptance is proven and cannot use the preceding turn's completion. Cursor errors retain null recovery handles until native acceptance can be proven.
|
|
272
|
+
|
|
271
273
|
### 1. Drive SSH, containers, and REPLs in one persistent terminal — the primitive
|
|
272
274
|
|
|
273
275
|
This is the base, and it works with just the platform backend — tmux on POSIX or psmux on native Windows. `pty_open` grabs one local terminal; `ssh host`, `docker exec -it x bash`, or a REPL are just text you `pty_send` into it — **once**. Every command after that rides the same already-authenticated session. Session kind is never a tool-level distinction.
|
|
@@ -565,7 +567,7 @@ Its `aiterm.pty-list-result.v1` receipt contains `observed_at` and `sessions`, w
|
|
|
565
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.
|
|
566
568
|
|
|
567
569
|
`pty_observe({ session_id, cursor? })` returns `aiterm.pty-observe-result.v1` with `exists`, `observed_at`, `state`
|
|
568
|
-
(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`
|
|
569
571
|
are separate identities. `process_identity` selects the harness for agents, or the unique child process-group leader
|
|
570
572
|
for an ordinary terminal, using the pane when no child leader exists. An identity contains `pid`, `process_group_id`,
|
|
571
573
|
`started_identity`, and `argv_digest`; unresolved identities are null. Windows PIDs are native and its process-group field
|
|
@@ -580,6 +582,8 @@ between observations, the delta covers only observed increments and `cpu_delta_c
|
|
|
580
582
|
only to descendants created at least 60 seconds after the pane, excluding startup MCP processes. `token_hint` is the latest
|
|
581
583
|
displayed token count or null. Callers do not need raw argv or pane-text parsing.
|
|
582
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
|
+
|
|
583
587
|
Two fields tell a caller what closing an agent session would lose. `activity.post_startup_process_count` is the number of
|
|
584
588
|
processes in the session that did not exist when `agent_launch` finished startup (before the first prompt), so background work
|
|
585
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
|
|
@@ -682,6 +686,8 @@ enables collection on that host.
|
|
|
682
686
|
|
|
683
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.
|
|
684
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
|
+
|
|
685
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.
|
|
686
692
|
|
|
687
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.
|
|
@@ -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
|
+
}
|
package/dist/agent-goal.js
CHANGED
|
@@ -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
|
+
}
|