aiterm-mcp 0.63.16 → 0.63.18
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 +17 -1
- package/README.ja.md +2 -2
- package/README.md +2 -2
- package/dist/core.js +67 -18
- package/dist/execution-native-server.js +19 -3
- package/dist/harnesses/claude.js +2 -2
- package/dist/index.js +77 -7
- package/dist/process-start.js +2 -2
- package/dist/runtime-adoption.js +160 -0
- package/dist/runtime-compatibility.js +75 -0
- package/dist/setup-integrations.js +40 -5
- package/package.json +2 -1
- package/runtime-overlap.json +12 -0
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.63.18] - 2026-11-08
|
|
11
|
+
|
|
12
|
+
- `pty_read(agent_transcript:true, input_id)` reads the Claude answer of the input that `pty_send` returned in its dispatch receipt. It selects that input's `agent_done` and does not refuse because a later turn is active, so a reply typed right after a turn ends no longer breaks the read of the previous answer. The answer is returned only while the per-launch result file still holds that event's digest and bytes. No completion yet answers `AITERM_TRANSCRIPT_INPUT_PENDING`; a result already replaced by a later turn answers `AITERM_TRANSCRIPT_INPUT_REPLACED`. `input_id` with a non-Claude session or with `operation_id` is an argument error. structuredContent is unchanged.
|
|
13
|
+
- Transcript read errors now start with a code token, rendered as `aiterm: <CODE>: <text>`: `TRANSCRIPT_TURN_ACTIVE` (an unbound Claude read while a turn is active), `TRANSCRIPT_UNAVAILABLE`, `TRANSCRIPT_NOT_FOUND` and `TRANSCRIPT_RESULT_MISMATCH`. Match the token, not the text.
|
|
14
|
+
- The macOS CI job removes Aiterm test tmux servers left by a cancelled or timed-out job before and after it runs.
|
|
15
|
+
|
|
16
|
+
## [0.63.17] - 2026-11-08
|
|
17
|
+
|
|
18
|
+
- A managed seat whose native terminal vanished while its records survived (for example after a container restart emptied tmux) is no longer refused with `AGENT_RESUME_UNCONFIRMED: 作成したnative端末が置き換わっています。` on every send. When the native list is known and the seat has no lifecycle or pending resume, an ordinary `pty_send`/dispatch records the existing `origin:restart` hibernation and cold-resumes the same Claude or Codex conversation, then delivers the body. A seat that cannot be resumed (other harnesses, missing vendor conversation, recipe or proof) answers `AGENT_SESSION_REQUIRED` with nothing sent and its records unchanged, so a fresh `agent_launch` under the same name reaches it. Unknown native state and live natives keep their existing checks.
|
|
19
|
+
- Add an opt-in runtime generation lifecycle for hosts that update Aiterm without restarting their body or seats. `execution-native-server.js --mode mcp --runtime-adoption standby|active --runtime-generation <id> --runtime-scope <id>` registers a host-only `runtime_adoption` tool (prepare/activate/status/retire, `aiterm.runtime-adoption.v1`). Standby refuses ordinary tools and starts no parent-delivery recovery; activate writes a durable record under `<state-root>/runtime-adoption/` before acknowledging; retire waits for running tool handlers and the parent-delivery manager close and never stops native seats. The package ships `runtime-overlap.json` (`aiterm.runtime-overlap.v1`) declaring the store formats it reads and writes, so a host can require overlap with every live generation. Default startup and the public tool list are unchanged.
|
|
20
|
+
- Setup now treats an updater-installed immutable installation capsule (`aiterm-capsule.json`, `aiterm.installation-capsule.v1`, listing `index.js`/`execution-native-server.js`) with the same Node as Aiterm's own registration, directly or behind `mcp-lazy`, and leaves it with its timeout/env fields in place. Unknown scripts and standby or hook-mode arguments are never treated as equivalent.
|
|
21
|
+
- Allow ten seconds by default for Windows process birth reads, preserving explicit caller deadlines, so PowerShell startup under load does not exhaust the former one-second budget. Created-native verification reports unreadable birth identities separately from a proven target replacement; neither sends input to an unproven target, and a later operation can read the original target afresh.
|
|
22
|
+
- Restore same-process exclusion for managed-agent native mutations (force `pty_send`, `pty_key`, approval respond): while another input owner in the same process holds the seat (idle inspection or a send), the operation is refused with the existing `AGENT_RESUME_UNCONFIRMED` text instead of taking over the owner. The 0.63.12 file-lock removal had dropped this refusal along with the cross-process lock. A verified creation/resume of a new native is not blocked by an older generation's owner. Cross-process serialization stays the caller's responsibility (0.63.12). Tests whose contract changed in 0.63.12/0.63.15 are updated.
|
|
23
|
+
|
|
10
24
|
## [0.63.16] - 2026-11-07
|
|
11
25
|
|
|
12
26
|
- `agent_configure` on a seat whose turn is running now refuses at once with the existing not-ready error instead of rechecking for 30 seconds (ADR 0120 amendment). The recheck protected nothing and held callers that configure before delivering input. Deferred settings are re-requested by the caller after the turn ends; the Codex goal pause / turn-end wait of ADR 0137 is kept because it orders the deferred setting before the goal's next turn.
|
|
@@ -3080,7 +3094,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
|
|
|
3080
3094
|
`ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
|
|
3081
3095
|
provenance.
|
|
3082
3096
|
|
|
3083
|
-
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.
|
|
3097
|
+
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.18...HEAD
|
|
3098
|
+
[0.63.18]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.17...v0.63.18
|
|
3099
|
+
[0.63.17]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.16...v0.63.17
|
|
3084
3100
|
[0.63.16]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.15...v0.63.16
|
|
3085
3101
|
[0.63.15]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.14...v0.63.15
|
|
3086
3102
|
[0.63.14]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.13...v0.63.14
|
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.63.
|
|
218
|
+
**状態:** 開発継続中 · 現行公開版 **v0.63.18** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
|
|
219
219
|
|
|
220
220
|
### 更新と巻き戻し
|
|
221
221
|
|
|
@@ -611,7 +611,7 @@ Claudeの相関済み承認は既存の`claude_approval`を使う。
|
|
|
611
611
|
| --- | --- | --- |
|
|
612
612
|
| `pty_open` | 端末を1個開き`session_id`を返す | `name?`, `shell?`, `env_vars?` |
|
|
613
613
|
| `pty_send` | テキストを送る。agent sessionでは子のturnが実行中なら現在のturnへ差し込み(`agent_steer`)、それ以外は非ブロックdispatchとして`event_cursor`を返す(`agent_dispatch`)。差し込みでGrokが待ち行列へ入れない時とCursorの入力欄に残った時は失敗する | `session_id`, `text`, `enter=true`, `mark`, `force`, `require_agent=false`, `preface`, `rtk`, `raw` |
|
|
614
|
-
| `pty_read` | 出力を削減して読む(既定は増分) | `session_id`, `wait`, `until`, `until_regex`, `timeout`, `screen`, `full`, `lines`, `line_range`, `raw`, `rtk`, `agent_transcript`, `operation_id` |
|
|
614
|
+
| `pty_read` | 出力を削減して読む(既定は増分) | `session_id`, `wait`, `until`, `until_regex`, `timeout`, `screen`, `full`, `lines`, `line_range`, `raw`, `rtk`, `agent_transcript`, `operation_id`, `input_id` |
|
|
615
615
|
| `pty_key` | 制御キーを送る | `session_id`, `key`(`C-c`/`Enter`/`Up`…) |
|
|
616
616
|
| `pty_close` | 冪等に閉じ、`closed` / `already_closed`を返す | `session_id` |
|
|
617
617
|
| `pty_list` | textと構造化したsession一覧。管理対象の起動ID `launch_id` は一覧取得時の値で、通常PTYやmetadata不明時はnull、旧remote版は省略。操作前の最新の紐付け確認は引き続き必要。明示した非秘密環境変数も照会できる | `env_keys?` |
|
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.63.
|
|
230
|
+
**Status:** actively maintained · current public release **v0.63.18** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
|
|
231
231
|
|
|
232
232
|
### Update and rollback
|
|
233
233
|
|
|
@@ -651,7 +651,7 @@ continue to use `claude_approval`.
|
|
|
651
651
|
| --- | --- | --- |
|
|
652
652
|
| `pty_open` | Open one terminal and return a `session_id` | `name?`, `shell?`, `env_vars?` |
|
|
653
653
|
| `pty_send` | Send text. On an agent session Aiterm picks the route when it sends: if the child's turn is running, it steers the text into that turn (`agent_steer`); otherwise it is a non-blocking **dispatch** returning an `event_cursor` (`agent_dispatch`). Steering fails when Grok does not queue the text or Cursor leaves it in the composer | `session_id`, `text`, `enter=true`, `mark`, `force`, `require_agent=false`, `preface`, `rtk`, `raw` |
|
|
654
|
-
| `pty_read` | Read output, token-reduced (incremental by default) | `session_id`, `wait`, `until`, `until_regex`, `timeout`, `screen`, `full`, `lines`, `line_range`, `raw`, `rtk`, `agent_transcript`, `operation_id` |
|
|
654
|
+
| `pty_read` | Read output, token-reduced (incremental by default) | `session_id`, `wait`, `until`, `until_regex`, `timeout`, `screen`, `full`, `lines`, `line_range`, `raw`, `rtk`, `agent_transcript`, `operation_id`, `input_id` |
|
|
655
655
|
| `pty_key` | Send a control key | `session_id`, `key` (`C-c`/`Enter`/`Up`…) |
|
|
656
656
|
| `pty_close` | Close idempotently; return `closed` / `already_closed` | `session_id` |
|
|
657
657
|
| `pty_list` | Text and structured session list (managed sessions include snapshot `launch_id` and harness conversation ID `vendor_session_id`; `launch_id` is null for ordinary/unmanaged PTYs and may be absent on older remote versions, so callers retain fresh binding checks before operations), with explicitly requested non-secret environment values | `env_keys?` |
|
package/dist/core.js
CHANGED
|
@@ -3231,6 +3231,10 @@ function withAgentNativeOperation(name, mutates, body) {
|
|
|
3231
3231
|
};
|
|
3232
3232
|
if (!mutates || owns)
|
|
3233
3233
|
return execute();
|
|
3234
|
+
// Another same-process input owner holds this seat (the file lock removed in 0.63.12 used to refuse this).
|
|
3235
|
+
// A verified creation/resume frame is pinned to its own new native, so an older generation's owner does not block it.
|
|
3236
|
+
if (owner !== undefined && !verified)
|
|
3237
|
+
throw unavailable();
|
|
3234
3238
|
const mine = Symbol(name);
|
|
3235
3239
|
agentSendHeld.add(name);
|
|
3236
3240
|
activeAgentSendOwner.set(name, mine);
|
|
@@ -3307,6 +3311,11 @@ async function withAgentSendLock(name, run, untouched = AGENT_SEND_UNSENT, pinRe
|
|
|
3307
3311
|
throw uncertain();
|
|
3308
3312
|
}
|
|
3309
3313
|
}
|
|
3314
|
+
// A vanished native (e.g. container restart) is not pinned: adopt it as a restart hibernation, then resume.
|
|
3315
|
+
if (vanishedAgentNative(meta)) {
|
|
3316
|
+
adoptVanishedAgentNative(meta);
|
|
3317
|
+
return await run();
|
|
3318
|
+
}
|
|
3310
3319
|
return await withAgentResumeTarget(meta, run);
|
|
3311
3320
|
}
|
|
3312
3321
|
return await run();
|
|
@@ -3503,7 +3512,7 @@ function bindCompletedInitialPrompt(meta) {
|
|
|
3503
3512
|
bindAgentHarnessSession(meta, scanned.event);
|
|
3504
3513
|
setInitialPromptState(meta, "done");
|
|
3505
3514
|
}
|
|
3506
|
-
function latestAgentDoneEvent(meta, expectedOperationId = null) {
|
|
3515
|
+
function latestAgentDoneEvent(meta, expectedOperationId = null, expectedInputId = null) {
|
|
3507
3516
|
if (meta.kind === "codex")
|
|
3508
3517
|
return latestCodexCompletion(meta, readTranscriptLines);
|
|
3509
3518
|
if (meta.kind === "cursor" && meta.completion_route === "cursor_transcript") {
|
|
@@ -3528,7 +3537,8 @@ function latestAgentDoneEvent(meta, expectedOperationId = null) {
|
|
|
3528
3537
|
if (!line.trim() || Buffer.byteLength(line, "utf8") > 64 * 1024)
|
|
3529
3538
|
continue;
|
|
3530
3539
|
const parsed = parseAgentDoneEvent(line, meta);
|
|
3531
|
-
if (parsed.event && (!expectedOperationId || parsed.event.operation_id === expectedOperationId)
|
|
3540
|
+
if (parsed.event && (!expectedOperationId || parsed.event.operation_id === expectedOperationId)
|
|
3541
|
+
&& (!expectedInputId || parsed.event.input_id === expectedInputId))
|
|
3532
3542
|
latest = parsed.event;
|
|
3533
3543
|
}
|
|
3534
3544
|
return latest;
|
|
@@ -3623,12 +3633,12 @@ function agentCompletionCursor(meta) {
|
|
|
3623
3633
|
return transcript ? safeStatSize(transcript) : 0;
|
|
3624
3634
|
}
|
|
3625
3635
|
function transcriptUnavailable() {
|
|
3626
|
-
throw new AitermError(`transcript がまだありません。ターン完了後に再取得してください。${agentWaitGuide()}`, 2);
|
|
3636
|
+
throw new AitermError(`TRANSCRIPT_UNAVAILABLE: transcript がまだありません。ターン完了後に再取得してください。${agentWaitGuide()}`, 2);
|
|
3627
3637
|
}
|
|
3628
3638
|
/** 完了したturnの回答が空だった時に、人とAIが読む表示へ出す文。機械はstructuredContentのanswer_emptyを見る。 */
|
|
3629
3639
|
const AGENT_ANSWER_EMPTY_NOTICE = "このターンは完了しましたが、回答の本文は空でした。";
|
|
3630
3640
|
function transcriptNotFound(vendor) {
|
|
3631
|
-
throw new AitermError(
|
|
3641
|
+
throw new AitermError(`TRANSCRIPT_NOT_FOUND: 最終 assistant メッセージを特定できませんでした(harness=${agentHarness(vendor)}, vendor=${vendor})。screen で確認してください。`, 2);
|
|
3632
3642
|
}
|
|
3633
3643
|
function readTranscriptLines(file) {
|
|
3634
3644
|
try {
|
|
@@ -3796,22 +3806,34 @@ export async function readAgentTranscriptResult(name, o = {}) {
|
|
|
3796
3806
|
if (operationId && meta.kind !== "claude") {
|
|
3797
3807
|
throw new AitermError("operation_id付き回収はClaude agent sessionだけで使用できます", 2);
|
|
3798
3808
|
}
|
|
3799
|
-
|
|
3809
|
+
const inputId = o.input_id ?? null;
|
|
3810
|
+
if (inputId !== null && (!/^[a-f0-9]{32}$/.test(inputId) || meta.kind !== "claude" || operationId || o.completion)) {
|
|
3811
|
+
throw new AitermError("input_id付き回収はClaude agent sessionだけで、operation_idと併用せず32桁の小文字16進で指定してください", 2);
|
|
3812
|
+
}
|
|
3813
|
+
const inputPending = () => {
|
|
3814
|
+
throw new AitermError(`AITERM_TRANSCRIPT_INPUT_PENDING: input ${inputId} の番はまだ完了していません。同じinput_idで後から再取得してください。${agentWaitGuide(name)}`, 2);
|
|
3815
|
+
};
|
|
3816
|
+
// 入力に束縛した回収は、その入力の完了だけを読む。後の番のmarkerはこの回収と無関係。
|
|
3817
|
+
if (meta.kind === "claude" && !o.completion && inputId === null) {
|
|
3800
3818
|
let active = readClaudeOperationMarker(meta);
|
|
3801
3819
|
if (active)
|
|
3802
3820
|
active = await settlePublishedClaudeCompletionMarker(meta, active);
|
|
3803
3821
|
if (active) {
|
|
3804
3822
|
const label = active.operationId ? `operation ${active.operationId}` : "operation_idなしのClaude turn";
|
|
3805
|
-
throw new AitermError(
|
|
3823
|
+
throw new AitermError(`TRANSCRIPT_TURN_ACTIVE: ${label} はまだ完了していません。Stop完了後に同じsessionから再取得してください。${agentWaitGuide(name)}`, 2);
|
|
3806
3824
|
}
|
|
3807
3825
|
}
|
|
3808
3826
|
// wait timeout は「失敗」ではなく状態不明。後着した同一launchの完了eventから
|
|
3809
3827
|
// harness session をbindし、promptを再送せず結果だけ回収できるようにする。
|
|
3810
3828
|
recoverAgentHarnessSession(meta);
|
|
3811
3829
|
if (!meta.vendor_session_id) {
|
|
3830
|
+
if (inputId)
|
|
3831
|
+
inputPending();
|
|
3812
3832
|
throw new AitermError(`agent session '${name}' はまだターンが完了していません。agent_done 完了後に再取得してください。${agentWaitGuide(name)}`, 2);
|
|
3813
3833
|
}
|
|
3814
|
-
const done = latestAgentDoneEvent(meta, operationId);
|
|
3834
|
+
const done = latestAgentDoneEvent(meta, operationId, inputId);
|
|
3835
|
+
if (inputId && !done)
|
|
3836
|
+
inputPending();
|
|
3815
3837
|
if (o.completion && meta.kind !== "codex" && meta.kind !== "grok"
|
|
3816
3838
|
&& (!done || done.turn_id !== o.completion.turn_id || done.operation_id !== o.completion.operation_id)) {
|
|
3817
3839
|
throw new AitermError("回収対象の完了情報が置換されました。別の回答は配送しません", 2);
|
|
@@ -3825,7 +3847,9 @@ export async function readAgentTranscriptResult(name, o = {}) {
|
|
|
3825
3847
|
if (meta.kind === "claude") {
|
|
3826
3848
|
if (!done)
|
|
3827
3849
|
transcriptUnavailable();
|
|
3828
|
-
text = readClaudeResultText(meta, done, operationId, transcriptUnavailable)
|
|
3850
|
+
text = readClaudeResultText(meta, done, operationId, transcriptUnavailable, inputId ? () => {
|
|
3851
|
+
throw new AitermError(`AITERM_TRANSCRIPT_INPUT_REPLACED: input ${inputId} の回答は後の番の結果で置き換わりました。この入力の本文はもう読めません。`, 2);
|
|
3852
|
+
} : undefined);
|
|
3829
3853
|
}
|
|
3830
3854
|
else if (meta.kind === "antigravity") {
|
|
3831
3855
|
if (!done || done.done_status !== "turn_done")
|
|
@@ -6342,13 +6366,17 @@ function verifyCreatedNative(native, allowExitedPane = false) {
|
|
|
6342
6366
|
const pane = tmux("display-message", "-p", "-t", nativePaneTarget(native), "#{session_id}\t#{session_name}\t#{pid}\t#{pane_id}\t#{pane_pid}\t#{pane_dead}");
|
|
6343
6367
|
const fields = pane.stdout.trim().split("\t");
|
|
6344
6368
|
const exited = allowExitedPane && fields[5] === "1";
|
|
6345
|
-
const [serverStarted, paneStarted] = processStartIdentities(exited ? [native.server_pid] : [native.server_pid, native.pane_pid], process.platform);
|
|
6346
6369
|
// macOS tmux clears pane_pid after exit; only the explicit dead-pane close admits that absence.
|
|
6347
6370
|
if (pane.code !== 0 || fields.length !== 6 || fields.slice(0, 4).join("\t") !== [native.native_id, native.session_id, native.server_pid, native.pane_id].join("\t")
|
|
6348
6371
|
|| (fields[4] !== String(native.pane_pid) && !(exited && fields[4] === ""))
|
|
6349
|
-
|| !["0", "1"].includes(fields[5])
|
|
6350
|
-
|| (!exited && paneStarted !== native.pane_started_identity))
|
|
6372
|
+
|| !["0", "1"].includes(fields[5]))
|
|
6351
6373
|
throw unavailable();
|
|
6374
|
+
const [serverStarted, paneStarted] = processStartIdentities(exited ? [native.server_pid] : [native.server_pid, native.pane_pid], process.platform);
|
|
6375
|
+
if ((serverStarted !== null && serverStarted !== native.server_started_identity)
|
|
6376
|
+
|| (!exited && paneStarted !== null && paneStarted !== native.pane_started_identity))
|
|
6377
|
+
throw unavailable();
|
|
6378
|
+
if (!serverStarted || (!exited && !paneStarted))
|
|
6379
|
+
throw new AitermError("AGENT_RESUME_UNCONFIRMED: 作成したnative本人性を取得できません。", 2);
|
|
6352
6380
|
}
|
|
6353
6381
|
function withAgentResumeTarget(meta, body, allowExitedPane = false) {
|
|
6354
6382
|
if (hasVerifiedNativeSessionTarget(meta.aiterm_session))
|
|
@@ -6624,6 +6652,32 @@ function prepareWorkingAgentResume(meta) {
|
|
|
6624
6652
|
throw unavailable();
|
|
6625
6653
|
return lifecycle;
|
|
6626
6654
|
}
|
|
6655
|
+
/** Write a prepared restart lifecycle after rechecking native absence and unchanged metadata under the caller's lock. */
|
|
6656
|
+
function commitWorkingAgentResume(previous, lifecycle) {
|
|
6657
|
+
const name = previous.aiterm_session, native = observeExecutionNativeSessions();
|
|
6658
|
+
if (native.state !== "known" || native.sessions.some(row => row.session_id === name)
|
|
6659
|
+
|| !isDeepStrictEqual(loadAgentMetadata(name), previous) || readAgentLifecycle(previous))
|
|
6660
|
+
throw new AgentResumeUnavailableError(name);
|
|
6661
|
+
withExecutionPreparation(name, () => writeAgentLifecycle(previous, lifecycle));
|
|
6662
|
+
}
|
|
6663
|
+
/** A current generation with no lifecycle/attempt state whose native is confirmed absent. */
|
|
6664
|
+
function vanishedAgentNative(meta) {
|
|
6665
|
+
if (agentDormantState(meta) !== null)
|
|
6666
|
+
return false;
|
|
6667
|
+
const native = observeExecutionNativeSessions();
|
|
6668
|
+
return native.state === "known" && !native.sessions.some(row => row.session_id === meta.aiterm_session);
|
|
6669
|
+
}
|
|
6670
|
+
function adoptVanishedAgentNative(meta) {
|
|
6671
|
+
try {
|
|
6672
|
+
commitWorkingAgentResume(meta, prepareWorkingAgentResume(meta));
|
|
6673
|
+
}
|
|
6674
|
+
catch (error) {
|
|
6675
|
+
if (error instanceof ExecutionError)
|
|
6676
|
+
throw error;
|
|
6677
|
+
throw new AitermError(`AGENT_SESSION_REQUIRED: session '${meta.aiterm_session}' のnative端末が無く、保存した会話へ再開できません。` +
|
|
6678
|
+
"文字列は送信していません。agent_launchで起動し直してください。", 2);
|
|
6679
|
+
}
|
|
6680
|
+
}
|
|
6627
6681
|
async function resumeAgentInLock(name, readyTimeout) {
|
|
6628
6682
|
const previous = loadAgentMetadata(name);
|
|
6629
6683
|
readyTimeout ??= previous.kind === "codex" ? AGENT_TUI_FIRST_DRAW_TIMEOUT_MS : AGENT_TUI_READY_TIMEOUT_MS;
|
|
@@ -7832,13 +7886,8 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
|
|
|
7832
7886
|
if (opts.launch_operation_id != null)
|
|
7833
7887
|
requireMatchingClaudeLaunch(name, validateOperationId(opts.launch_operation_id), claudeLaunchRequestDigest({ sessionName: name, model: opts.model ?? null, effort: opts.reasoning_effort ?? null,
|
|
7834
7888
|
cwd: opts.cwd ?? null, agentDone: true }));
|
|
7835
|
-
if (preparedLifecycle)
|
|
7836
|
-
|
|
7837
|
-
if (native.state !== "known" || native.sessions.some(row => row.session_id === name)
|
|
7838
|
-
|| !isDeepStrictEqual(loadAgentMetadata(name), previous) || readAgentLifecycle(previous))
|
|
7839
|
-
throw new AgentResumeUnavailableError(name);
|
|
7840
|
-
withExecutionPreparation(name, () => writeAgentLifecycle(previous, preparedLifecycle));
|
|
7841
|
-
}
|
|
7889
|
+
if (preparedLifecycle)
|
|
7890
|
+
commitWorkingAgentResume(previous, preparedLifecycle);
|
|
7842
7891
|
const resumed = await resumeAgentInLock(name, opts.ready_timeout ?? undefined);
|
|
7843
7892
|
return withAgentResumeTarget(resumed, async () => {
|
|
7844
7893
|
const hint = `${agentLabel(kind)} を保存した同じ会話へ再開した。\n${attachHint(name)}`;
|
|
@@ -17,10 +17,11 @@ import { observeExecutionActor } from "./process-runtime.js";
|
|
|
17
17
|
import { ExecutionError } from "./execution-wire.js";
|
|
18
18
|
import { createAitermServer } from "./index.js";
|
|
19
19
|
import { immediateStopInputSchema, immediateStopResultSchema } from "./execution-immediate-stop.js";
|
|
20
|
+
import { parseRuntimeAdoptionConfig } from "./runtime-adoption.js";
|
|
20
21
|
/** Ordinary delivery and leaf-first cancel keys have no execution-store
|
|
21
22
|
* registration, participant gate, shared transaction or graph write. */
|
|
22
23
|
export function createNativeDeliveryServer(dependencies = {}) {
|
|
23
|
-
const server = createAitermServer({ goalOrigin: dependencies.goalOrigin });
|
|
24
|
+
const server = createAitermServer({ goalOrigin: dependencies.goalOrigin, runtimeAdoption: dependencies.runtimeAdoption });
|
|
24
25
|
server.registerTool("agent_stop", {
|
|
25
26
|
description: "指定sessionとその呼出先へ末端から通常の停止キーを送る。sentはキー送信結果であり終了の証明ではない。",
|
|
26
27
|
inputSchema: immediateStopInputSchema.shape,
|
|
@@ -130,6 +131,8 @@ export function parseNativeExecutionArguments(args) {
|
|
|
130
131
|
"execution-interrupt": { type: "boolean" }, "state-root": { type: "string" },
|
|
131
132
|
socket: { type: "string" }, "steer-provider": { type: "string" },
|
|
132
133
|
mode: { type: "string", default: "mcp" }, "codex-home": { type: "string" }, "hook-directory": { type: "string" },
|
|
134
|
+
// Opt-in lifecycle; argv (not env) so it never leaks into seats/hooks spawned by this MCP.
|
|
135
|
+
"runtime-adoption": { type: "string" }, "runtime-generation": { type: "string" }, "runtime-scope": { type: "string" },
|
|
133
136
|
} });
|
|
134
137
|
if (values["execution-interrupt"] !== true || !values["state-root"] || !values.socket || !values["steer-provider"]
|
|
135
138
|
|| [values["state-root"], values.socket, values["steer-provider"]].some(value => !path.isAbsolute(value) || /[\r\n\0]/.test(value)))
|
|
@@ -138,13 +141,26 @@ export function parseNativeExecutionArguments(args) {
|
|
|
138
141
|
|| (values.mode === "codex-hook" && (!values["codex-home"] || !values["hook-directory"]))
|
|
139
142
|
|| [values["codex-home"], values["hook-directory"]].some(value => value !== undefined && (!path.isAbsolute(value) || /[\r\n\0]/.test(value))))
|
|
140
143
|
throw new ExecutionError("EXECUTION_INVALID");
|
|
141
|
-
|
|
144
|
+
const lifecycle = ["runtime-adoption", "runtime-generation", "runtime-scope"];
|
|
145
|
+
const lifecycleCount = lifecycle.filter(name => values[name] !== undefined).length;
|
|
146
|
+
if (lifecycleCount && (lifecycleCount !== lifecycle.length || values.mode !== "mcp"))
|
|
147
|
+
throw new ExecutionError("EXECUTION_INVALID");
|
|
148
|
+
let runtimeAdoption;
|
|
149
|
+
if (lifecycleCount)
|
|
150
|
+
try {
|
|
151
|
+
runtimeAdoption = parseRuntimeAdoptionConfig({ mode: values["runtime-adoption"], generation: values["runtime-generation"],
|
|
152
|
+
scope: values["runtime-scope"], stateRoot: values["state-root"] });
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
throw new ExecutionError("EXECUTION_INVALID");
|
|
156
|
+
}
|
|
157
|
+
return { ...(runtimeAdoption ? { runtimeAdoption } : {}), mode: values.mode, codexHome: values["codex-home"], hookDirectory: values["hook-directory"], expectedScope: { state_root: values["state-root"], multiplexer: { kind: "socket", key: values.socket } },
|
|
142
158
|
providerFile: values["steer-provider"] };
|
|
143
159
|
}
|
|
144
160
|
async function main() {
|
|
145
161
|
const options = parseNativeExecutionArguments(process.argv.slice(2));
|
|
146
162
|
if (options.mode === "mcp") {
|
|
147
|
-
await createNativeDeliveryServer().connect(new StdioServerTransport());
|
|
163
|
+
await createNativeDeliveryServer({ runtimeAdoption: options.runtimeAdoption }).connect(new StdioServerTransport());
|
|
148
164
|
}
|
|
149
165
|
else {
|
|
150
166
|
const provider = await import(pathToFileURL(options.providerFile).href);
|
package/dist/harnesses/claude.js
CHANGED
|
@@ -97,7 +97,7 @@ export function validateOperationId(operationId) {
|
|
|
97
97
|
}
|
|
98
98
|
return operationId;
|
|
99
99
|
}
|
|
100
|
-
export function readClaudeResultText(meta, done, operationId, transcriptUnavailable) {
|
|
100
|
+
export function readClaudeResultText(meta, done, operationId, transcriptUnavailable, mismatch = () => { throw new AitermError("TRANSCRIPT_RESULT_MISMATCH: Claude result file が完了eventと一致しません", 2); }) {
|
|
101
101
|
if (meta.kind !== "claude" || !meta.result_file || !done.result_digest || done.result_bytes == null) {
|
|
102
102
|
transcriptUnavailable();
|
|
103
103
|
}
|
|
@@ -134,7 +134,7 @@ export function readClaudeResultText(meta, done, operationId, transcriptUnavaila
|
|
|
134
134
|
typeof result.text !== "string" ||
|
|
135
135
|
Buffer.byteLength(result.text, "utf8") !== done.result_bytes ||
|
|
136
136
|
createHash("sha256").update(result.text, "utf8").digest("hex") !== done.result_digest) {
|
|
137
|
-
|
|
137
|
+
mismatch();
|
|
138
138
|
}
|
|
139
139
|
return result.text;
|
|
140
140
|
}
|
package/dist/index.js
CHANGED
|
@@ -34,6 +34,7 @@ import { acceptRemote, callRemoteTool, observeRemoteAgentDone, remoteLabel, remo
|
|
|
34
34
|
import { codexParentFromRequest } from "./codex-parent-receiver.js";
|
|
35
35
|
import { claudeParentFromRequest, discardClaudeHookRequest } from "./claude-parent-receiver.js";
|
|
36
36
|
import { parentDeliveryDiagnostic } from "./parent-hook-diagnostic.js";
|
|
37
|
+
import { createRuntimeAdoption, RuntimeAdoptionError } from "./runtime-adoption.js";
|
|
37
38
|
import { cursorParentFromRequest, isCursorMcpClient } from "./cursor-parent-receiver.js";
|
|
38
39
|
import { waitProcessCommandLine } from "./cursor-parent-receive.js";
|
|
39
40
|
import { INTERIM_RESULT_META_KEY, interimCallerFromMeta, interimRequestFromMeta } from "./interim-words.js";
|
|
@@ -42,13 +43,45 @@ import { SEAT_TURNS_RESULT_META_KEY, STEER_RESULT_META_KEY } from "./steer-follo
|
|
|
42
43
|
// createRequire を使うのは、import 属性 `with { type: "json" }` が Node 18.20+ 限定で
|
|
43
44
|
// engines "node >=18"(18.0〜18.19)を SyntaxError で壊し、旧 `assert` 構文は逆に Node 22 で
|
|
44
45
|
// 除去済み=どちらの静的構文も 18〜22 全域を満たせないため(実行時 require が唯一全域で動く)。
|
|
45
|
-
const
|
|
46
|
+
const pkgRequire = createRequire(import.meta.url);
|
|
47
|
+
const pkg = pkgRequire("../package.json");
|
|
48
|
+
export const RUNTIME_ADOPTION_TOOL = "runtime_adoption";
|
|
49
|
+
// Ordinary tools declare outputSchema and SDK clients validate structuredContent even
|
|
50
|
+
// on isError, so their refusal is text-only; the control tool (no outputSchema) adds it.
|
|
51
|
+
function runtimeAdoptionFailure(e, structured = false) {
|
|
52
|
+
const code = e instanceof RuntimeAdoptionError ? e.code : "RUNTIME_ADOPTION_UNAVAILABLE";
|
|
53
|
+
return { content: [{ type: "text", text: JSON.stringify({ error_code: code }) }], isError: true,
|
|
54
|
+
...(structured ? { structuredContent: { error_code: code } } : {}) };
|
|
55
|
+
}
|
|
56
|
+
/** Opt-in lifecycle control; absent from default tools/list. Generation/scope come from composition. */
|
|
57
|
+
function registerRuntimeAdoptionTool(server, adoption) {
|
|
58
|
+
server.registerTool(RUNTIME_ADOPTION_TOOL, {
|
|
59
|
+
description: "Host-only runtime generation lifecycle (aiterm.runtime-adoption.v1). Never stops seats.",
|
|
60
|
+
inputSchema: {
|
|
61
|
+
action: z.enum(["prepare", "activate", "status", "retire"]),
|
|
62
|
+
job_id: z.string().optional(), expected: z.string().optional(),
|
|
63
|
+
live: z.array(z.unknown()).max(32).optional(),
|
|
64
|
+
},
|
|
65
|
+
}, async (args) => {
|
|
66
|
+
try {
|
|
67
|
+
const result = args.action === "prepare" ? await adoption.prepare(args)
|
|
68
|
+
: args.action === "activate" ? await adoption.activate(args)
|
|
69
|
+
: args.action === "status" ? adoption.status(args) : await adoption.retire();
|
|
70
|
+
return { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result };
|
|
71
|
+
}
|
|
72
|
+
catch (e) {
|
|
73
|
+
return runtimeAdoptionFailure(e, true);
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
}
|
|
46
77
|
/** Constructor for isolated transport acceptance. main never supplies the
|
|
47
78
|
* private execution factory until runtime/participant coverage is complete.
|
|
48
79
|
* Importing this module neither connects stdio nor runs diagnostics/reporters.
|
|
49
80
|
*/
|
|
50
81
|
export function createAitermServer(options = {}) {
|
|
51
82
|
const server = new McpServer({ name: "aiterm", version: pkg.version });
|
|
83
|
+
// Assigned below once manager closure exists; the request wrapper only reads it.
|
|
84
|
+
let adoption = null;
|
|
52
85
|
const goalOrigin = options.goalOrigin;
|
|
53
86
|
if (goalOrigin !== undefined && typeof goalOrigin !== "function")
|
|
54
87
|
throw new Error("Invalid trusted goal provenance adapter");
|
|
@@ -66,6 +99,19 @@ export function createAitermServer(options = {}) {
|
|
|
66
99
|
// toolごとのhandlerではなくtools/callの返りを見る。McpServerがそのhandlerを置くのは最初のtool登録の時で、その前に包む。
|
|
67
100
|
const setRequestHandler = server.server.setRequestHandler.bind(server.server);
|
|
68
101
|
server.server.setRequestHandler = ((schema, handler) => setRequestHandler(schema, schema !== CallToolRequestSchema ? handler : async (request, extra) => {
|
|
102
|
+
// Lifecycle control is not counted in its own drain; every other tool needs an active generation.
|
|
103
|
+
if (adoption && request?.params?.name !== RUNTIME_ADOPTION_TOOL) {
|
|
104
|
+
try {
|
|
105
|
+
adoption.admit();
|
|
106
|
+
}
|
|
107
|
+
catch (e) {
|
|
108
|
+
return runtimeAdoptionFailure(e);
|
|
109
|
+
}
|
|
110
|
+
return await adoption.track(handleTool(handler, request, extra));
|
|
111
|
+
}
|
|
112
|
+
return await handleTool(handler, request, extra);
|
|
113
|
+
}));
|
|
114
|
+
async function handleTool(handler, request, extra) {
|
|
69
115
|
let result;
|
|
70
116
|
let cleanupExtra = extra;
|
|
71
117
|
if (execution) {
|
|
@@ -94,7 +140,7 @@ export function createAitermServer(options = {}) {
|
|
|
94
140
|
}
|
|
95
141
|
catch { /* 見回りへ回す */ }
|
|
96
142
|
return result;
|
|
97
|
-
}
|
|
143
|
+
}
|
|
98
144
|
let parentDelivery = null;
|
|
99
145
|
// 別端末の子の配送。記録の保存場所を分けるため、この端末の子とは別のmanagerにする。
|
|
100
146
|
let remoteParentDelivery = null;
|
|
@@ -588,6 +634,11 @@ export function createAitermServer(options = {}) {
|
|
|
588
634
|
.regex(/^sha256:[0-9a-f]{64}$/)
|
|
589
635
|
.nullish()
|
|
590
636
|
.describe("Claude operationの期待ID。agent_transcript:true時だけ指定し、古い別operationの結果を拒否する"),
|
|
637
|
+
input_id: z
|
|
638
|
+
.string()
|
|
639
|
+
.regex(/^[a-f0-9]{32}$/)
|
|
640
|
+
.nullish()
|
|
641
|
+
.describe("Claudeのpty_send dispatch receiptのinput_id。agent_transcript:true時だけ指定し、その入力の番の回答を読む。後の番が動いていても拒否しない。未完了はAITERM_TRANSCRIPT_INPUT_PENDING、後の番の結果で置換済みはAITERM_TRANSCRIPT_INPUT_REPLACED"),
|
|
591
642
|
},
|
|
592
643
|
outputSchema: {
|
|
593
644
|
schema: z.literal("aiterm.pty-read-result.v1"),
|
|
@@ -605,7 +656,7 @@ export function createAitermServer(options = {}) {
|
|
|
605
656
|
.optional()
|
|
606
657
|
.describe("agent_transcriptで、完了したturnの回答が空だった時だけtrue(textは空文字列)。回答を読めなかった時は誤りを返す。terminalではnull"),
|
|
607
658
|
},
|
|
608
|
-
}, async ({ session_id, wait, until, until_regex, timeout, screen, full, lines, line_range, raw, rtk, agent_transcript, operation_id }) => {
|
|
659
|
+
}, async ({ session_id, wait, until, until_regex, timeout, screen, full, lines, line_range, raw, rtk, agent_transcript, operation_id, input_id }) => {
|
|
609
660
|
try {
|
|
610
661
|
if (agent_transcript) {
|
|
611
662
|
if (screen || full || rtk || wait || line_range != null) {
|
|
@@ -615,6 +666,7 @@ export function createAitermServer(options = {}) {
|
|
|
615
666
|
const result = await core.readAgentTranscriptResult(session_id, {
|
|
616
667
|
lines: lines ?? null,
|
|
617
668
|
operation_id: operation_id ?? null,
|
|
669
|
+
input_id: input_id ?? null,
|
|
618
670
|
raw,
|
|
619
671
|
});
|
|
620
672
|
return {
|
|
@@ -634,6 +686,8 @@ export function createAitermServer(options = {}) {
|
|
|
634
686
|
}
|
|
635
687
|
if (operation_id != null)
|
|
636
688
|
throw new Error("operation_idはagent_transcript:true時だけ指定できます");
|
|
689
|
+
if (input_id != null)
|
|
690
|
+
throw new Error("input_idはagent_transcript:true時だけ指定できます");
|
|
637
691
|
let range = null;
|
|
638
692
|
if (line_range) {
|
|
639
693
|
const idx = line_range.indexOf(":");
|
|
@@ -1383,9 +1437,8 @@ export function createAitermServer(options = {}) {
|
|
|
1383
1437
|
// 親ホストを initialize の clientInfo.name から確定させ、receipt の完了待ちコマンドを
|
|
1384
1438
|
// そのホストの実際の起動形で名指しする(実測: claude-code は initialize → notifications/initialized
|
|
1385
1439
|
// → tools/list の順で送るため、どの tool 呼び出しより先に確定する)。取れない時は汎用文へ落ちるだけ。
|
|
1386
|
-
|
|
1440
|
+
const startParentManagers = () => {
|
|
1387
1441
|
const name = server.server.getClientVersion()?.name;
|
|
1388
|
-
core.setParentClient(name ?? null);
|
|
1389
1442
|
if (name === "codex-mcp-client" || name === "claude-code" || isCursorMcpClient(name)) {
|
|
1390
1443
|
parentDelivery ??= new ParentDeliveryManager({ parent_kind: deliveryParentKind(name),
|
|
1391
1444
|
...(execution ? { execution: execution.parentExecution, dependencies: execution.parentDependencies,
|
|
@@ -1394,10 +1447,27 @@ export function createAitermServer(options = {}) {
|
|
|
1394
1447
|
remoteParentDelivery ??= new ParentDeliveryManager({ parent_kind: deliveryParentKind(name), remote: true });
|
|
1395
1448
|
}
|
|
1396
1449
|
};
|
|
1450
|
+
server.server.oninitialized = () => {
|
|
1451
|
+
core.setParentClient(server.server.getClientVersion()?.name ?? null);
|
|
1452
|
+
// Standby must not start recovery/heartbeat timers or claim records; activation starts them.
|
|
1453
|
+
if (!adoption || adoption.state === "active")
|
|
1454
|
+
startParentManagers();
|
|
1455
|
+
};
|
|
1456
|
+
// One close per manager: retire awaits it, a later transport close reuses the same promise.
|
|
1457
|
+
let managersClosed = null;
|
|
1458
|
+
const closeParentManagers = () => managersClosed ??= Promise.all([parentDelivery?.close(), remoteParentDelivery?.close()]).then(() => undefined);
|
|
1397
1459
|
server.server.onclose = () => {
|
|
1398
|
-
void
|
|
1399
|
-
void remoteParentDelivery?.close().catch(() => process.stderr.write("aiterm: PARENT_DELIVERY_CLOSE_FAILED\n"));
|
|
1460
|
+
void closeParentManagers().catch(() => process.stderr.write("aiterm: PARENT_DELIVERY_CLOSE_FAILED\n"));
|
|
1400
1461
|
};
|
|
1462
|
+
if (options.runtimeAdoption) {
|
|
1463
|
+
adoption = createRuntimeAdoption(options.runtimeAdoption, {
|
|
1464
|
+
declaration: () => pkgRequire("../runtime-overlap.json"),
|
|
1465
|
+
onActivate: () => { if (server.server.getClientVersion())
|
|
1466
|
+
startParentManagers(); },
|
|
1467
|
+
onRetire: closeParentManagers,
|
|
1468
|
+
});
|
|
1469
|
+
registerRuntimeAdoptionTool(server, adoption);
|
|
1470
|
+
}
|
|
1401
1471
|
return server;
|
|
1402
1472
|
}
|
|
1403
1473
|
async function main() {
|
package/dist/process-start.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import { spawnSync } from "node:child_process";
|
|
4
4
|
import { resolveWindowsPowerShell7 } from "./windows-powershell.js";
|
|
5
|
-
export function processStartIdentities(pids, platform, timeoutMs = 1000) {
|
|
5
|
+
export function processStartIdentities(pids, platform, timeoutMs = platform === "win32" ? 10000 : 1000) {
|
|
6
6
|
if (platform !== "win32")
|
|
7
7
|
return pids.map(pid => processStartIdentity(pid, platform, timeoutMs));
|
|
8
8
|
const wanted = [...new Set(pids.filter(pid => Number.isSafeInteger(pid) && pid > 0))];
|
|
@@ -27,7 +27,7 @@ export function processStartIdentities(pids, platform, timeoutMs = 1000) {
|
|
|
27
27
|
const starts = new Map(rows.map(row => [row.pid, row.start === null ? null : `win32:${row.start}`]));
|
|
28
28
|
return pids.map(pid => starts.get(pid) ?? null);
|
|
29
29
|
}
|
|
30
|
-
export function processStartIdentity(pid, platform, timeoutMs = 1000) {
|
|
30
|
+
export function processStartIdentity(pid, platform, timeoutMs = platform === "win32" ? 10000 : 1000) {
|
|
31
31
|
if (!Number.isInteger(pid) || pid < 1)
|
|
32
32
|
return null;
|
|
33
33
|
if (platform === "linux") {
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// Opt-in runtime lifecycle (aiterm.runtime-adoption.v1). Only a trusted host
|
|
2
|
+
// composition creates it; default startup never registers the control tool.
|
|
3
|
+
// It never stops tmux/native/vendor processes, resumes a CLI or resets state.
|
|
4
|
+
import * as fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { writeExecutionCheckpoint } from "./execution-checkpoint.js";
|
|
7
|
+
import { RUNTIME_ADOPTION_ABI, decideRuntimeOverlap } from "./runtime-compatibility.js";
|
|
8
|
+
export const RUNTIME_ADOPTION_SCHEMA = RUNTIME_ADOPTION_ABI;
|
|
9
|
+
export class RuntimeAdoptionError extends Error {
|
|
10
|
+
code;
|
|
11
|
+
constructor(code) {
|
|
12
|
+
super(code);
|
|
13
|
+
this.code = code;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const TOKEN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
17
|
+
const token = (value) => {
|
|
18
|
+
if (typeof value !== "string" || !TOKEN.test(value))
|
|
19
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_INVALID");
|
|
20
|
+
return value;
|
|
21
|
+
};
|
|
22
|
+
export function parseRuntimeAdoptionConfig(value) {
|
|
23
|
+
if (value.mode !== "standby" && value.mode !== "active")
|
|
24
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_INVALID");
|
|
25
|
+
if (typeof value.stateRoot !== "string" || !path.isAbsolute(value.stateRoot) || /[\r\n\0]/.test(value.stateRoot))
|
|
26
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_INVALID");
|
|
27
|
+
return { mode: value.mode, generation: token(value.generation), scope: token(value.scope), stateRoot: value.stateRoot };
|
|
28
|
+
}
|
|
29
|
+
export function activationRecordPath(config, jobId) {
|
|
30
|
+
return path.join(config.stateRoot, "runtime-adoption", token(config.scope), `${token(jobId)}.json`);
|
|
31
|
+
}
|
|
32
|
+
/** Read-only; ENOENT is "absent", any other failure is unavailable (never absent). */
|
|
33
|
+
export function readActivationRecord(config, jobId) {
|
|
34
|
+
let text;
|
|
35
|
+
try {
|
|
36
|
+
text = fs.readFileSync(activationRecordPath(config, jobId), "utf8");
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (error.code === "ENOENT")
|
|
40
|
+
return null;
|
|
41
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_UNAVAILABLE");
|
|
42
|
+
}
|
|
43
|
+
let record;
|
|
44
|
+
try {
|
|
45
|
+
record = JSON.parse(text);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_UNAVAILABLE");
|
|
49
|
+
}
|
|
50
|
+
if (!record || record.schema !== RUNTIME_ADOPTION_SCHEMA || record.phase !== "activated" || record.job_id !== jobId
|
|
51
|
+
|| record.scope !== config.scope || typeof record.expected !== "string" || typeof record.candidate !== "string")
|
|
52
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_UNAVAILABLE");
|
|
53
|
+
return record;
|
|
54
|
+
}
|
|
55
|
+
export function createRuntimeAdoption(config, hooks) {
|
|
56
|
+
let state = config.mode;
|
|
57
|
+
let prepared = null;
|
|
58
|
+
let retirement = null;
|
|
59
|
+
let serial = Promise.resolve();
|
|
60
|
+
const inflight = new Set();
|
|
61
|
+
const identity = () => ({ schema: RUNTIME_ADOPTION_SCHEMA, generation: config.generation, scope: config.scope, state });
|
|
62
|
+
const serialize = (work) => {
|
|
63
|
+
const next = serial.then(work, work);
|
|
64
|
+
serial = next.catch(() => undefined);
|
|
65
|
+
return next;
|
|
66
|
+
};
|
|
67
|
+
function prepare(input) {
|
|
68
|
+
return serialize(() => {
|
|
69
|
+
if (state !== "standby")
|
|
70
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_STATE");
|
|
71
|
+
const expected = token(input.expected);
|
|
72
|
+
let decision;
|
|
73
|
+
try {
|
|
74
|
+
decision = decideRuntimeOverlap(hooks.declaration(), input.live);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_INVALID");
|
|
78
|
+
}
|
|
79
|
+
prepared = decision.supported ? { expected, decision } : null;
|
|
80
|
+
return { ...identity(), action: "prepare", expected, overlap: decision };
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
function activate(input) {
|
|
84
|
+
return serialize(() => {
|
|
85
|
+
const jobId = token(input.job_id), expected = token(input.expected);
|
|
86
|
+
const existing = readActivationRecord(config, jobId);
|
|
87
|
+
if (existing) {
|
|
88
|
+
if (existing.candidate !== config.generation || existing.expected !== expected)
|
|
89
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_CONFLICT");
|
|
90
|
+
if (state === "standby") {
|
|
91
|
+
state = "active";
|
|
92
|
+
try {
|
|
93
|
+
hooks.onActivate?.();
|
|
94
|
+
}
|
|
95
|
+
catch { /* lazy per request */ }
|
|
96
|
+
}
|
|
97
|
+
if (state !== "active")
|
|
98
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_STATE");
|
|
99
|
+
return { ...identity(), action: "activate", disposition: "activated", record: existing };
|
|
100
|
+
}
|
|
101
|
+
if (state !== "standby")
|
|
102
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_STATE");
|
|
103
|
+
if (!prepared || prepared.expected !== expected)
|
|
104
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_UNSUPPORTED");
|
|
105
|
+
const record = { schema: RUNTIME_ADOPTION_SCHEMA, job_id: jobId, scope: config.scope,
|
|
106
|
+
expected, candidate: config.generation, common_formats: prepared.decision.common_formats, phase: "activated" };
|
|
107
|
+
const file = activationRecordPath(config, jobId);
|
|
108
|
+
try {
|
|
109
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_UNAVAILABLE");
|
|
113
|
+
}
|
|
114
|
+
// Durable before ACK. A failed directory flush may still leave the record visible: status decides.
|
|
115
|
+
try {
|
|
116
|
+
writeExecutionCheckpoint(file, record);
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_UNAVAILABLE");
|
|
120
|
+
}
|
|
121
|
+
state = "active";
|
|
122
|
+
try {
|
|
123
|
+
hooks.onActivate?.();
|
|
124
|
+
}
|
|
125
|
+
catch { /* lazy per request */ }
|
|
126
|
+
return { ...identity(), action: "activate", disposition: "activated", record };
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
function status(input) {
|
|
130
|
+
const jobId = token(input.job_id);
|
|
131
|
+
const record = readActivationRecord(config, jobId);
|
|
132
|
+
return { ...identity(), action: "status", disposition: record ? "activated" : "absent",
|
|
133
|
+
...(record ? { record } : {}) };
|
|
134
|
+
}
|
|
135
|
+
function retire() {
|
|
136
|
+
retirement ??= serialize(async () => {
|
|
137
|
+
state = "retiring";
|
|
138
|
+
// Real handler completion, not client cancellation. New ordinary requests are refused meanwhile.
|
|
139
|
+
while (inflight.size)
|
|
140
|
+
await Promise.allSettled([...inflight]);
|
|
141
|
+
await hooks.onRetire();
|
|
142
|
+
state = "retired";
|
|
143
|
+
}).catch(error => { retirement = null; throw error; });
|
|
144
|
+
return retirement.then(() => ({ ...identity(), action: "retire", owner_closed: true }));
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
get state() { return state; },
|
|
148
|
+
config: Object.freeze({ ...config }),
|
|
149
|
+
/** Ordinary tools only while active. Standby/retiring never mutate production state. */
|
|
150
|
+
admit() { if (state !== "active")
|
|
151
|
+
throw new RuntimeAdoptionError("RUNTIME_ADOPTION_NOT_SERVING"); },
|
|
152
|
+
track(work) {
|
|
153
|
+
inflight.add(work);
|
|
154
|
+
const done = () => { inflight.delete(work); };
|
|
155
|
+
work.then(done, done);
|
|
156
|
+
return work;
|
|
157
|
+
},
|
|
158
|
+
prepare, activate, status, retire,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// A1 overlap validation. Pure data: no package execution, file or process access.
|
|
2
|
+
// The caller binds each declaration to its verified signed archive; this module
|
|
3
|
+
// only decides whether a candidate and EVERY live/recovery generation share formats.
|
|
4
|
+
export const RUNTIME_OVERLAP_SCHEMA = "aiterm.runtime-overlap.v1";
|
|
5
|
+
export const RUNTIME_ADOPTION_ABI = "aiterm.runtime-adoption.v1";
|
|
6
|
+
export const LEGACY_RUNTIME_IDENTITY = "legacy-v1";
|
|
7
|
+
// Every store with its own on-disk reader. A store missing from either side is unsupported.
|
|
8
|
+
export const RUNTIME_OVERLAP_STORES = ["agent-metadata", "execution-metadata", "parent-delivery",
|
|
9
|
+
"provider-hooks", "events", "runtime-errors"];
|
|
10
|
+
// Releases shipped before the declaration existed all write/read the strict v1
|
|
11
|
+
// shapes and steer-v1 provider records. A live peer may name it explicitly.
|
|
12
|
+
export const LEGACY_RUNTIME_DECLARATION = Object.freeze({
|
|
13
|
+
schema: RUNTIME_OVERLAP_SCHEMA,
|
|
14
|
+
stores: Object.freeze(Object.fromEntries(RUNTIME_OVERLAP_STORES.map(store => [store, Object.freeze({ writes: store === "provider-hooks" ? "steer-v1" : "v1",
|
|
15
|
+
reads: Object.freeze([store === "provider-hooks" ? "steer-v1" : "v1"]) })]))),
|
|
16
|
+
});
|
|
17
|
+
const TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;
|
|
18
|
+
export function parseRuntimeOverlapDeclaration(value) {
|
|
19
|
+
if (value === LEGACY_RUNTIME_IDENTITY)
|
|
20
|
+
return LEGACY_RUNTIME_DECLARATION;
|
|
21
|
+
const fail = () => { throw new Error("RUNTIME_OVERLAP_INVALID"); };
|
|
22
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
23
|
+
fail();
|
|
24
|
+
const input = value;
|
|
25
|
+
if (Object.keys(input).some(key => !["schema", "manager_abi", "stores"].includes(key)))
|
|
26
|
+
fail();
|
|
27
|
+
if (input.schema !== RUNTIME_OVERLAP_SCHEMA)
|
|
28
|
+
fail();
|
|
29
|
+
if (input.manager_abi !== undefined && (typeof input.manager_abi !== "string" || !TOKEN.test(input.manager_abi)))
|
|
30
|
+
fail();
|
|
31
|
+
const stores = input.stores;
|
|
32
|
+
if (!stores || typeof stores !== "object" || Array.isArray(stores))
|
|
33
|
+
fail();
|
|
34
|
+
const parsed = {};
|
|
35
|
+
for (const [store, entry] of Object.entries(stores)) {
|
|
36
|
+
if (!TOKEN.test(store) || !entry || typeof entry !== "object" || Array.isArray(entry))
|
|
37
|
+
fail();
|
|
38
|
+
const { writes, reads, ...rest } = entry;
|
|
39
|
+
if (Object.keys(rest).length || typeof writes !== "string" || !TOKEN.test(writes) || !Array.isArray(reads)
|
|
40
|
+
|| reads.length === 0 || reads.length > 16 || reads.some(format => typeof format !== "string" || !TOKEN.test(format))
|
|
41
|
+
|| !reads.includes(writes))
|
|
42
|
+
fail();
|
|
43
|
+
parsed[store] = { writes: writes, reads: [...new Set(reads)] };
|
|
44
|
+
}
|
|
45
|
+
return { schema: RUNTIME_OVERLAP_SCHEMA, ...(input.manager_abi ? { manager_abi: input.manager_abi } : {}), stores: parsed };
|
|
46
|
+
}
|
|
47
|
+
/** Candidate writes must be readable by every live peer and every peer write by
|
|
48
|
+
* the candidate. Pairwise-against-latest is never enough: pass ALL live peers. */
|
|
49
|
+
export function decideRuntimeOverlap(candidateInput, liveInput) {
|
|
50
|
+
const candidate = parseRuntimeOverlapDeclaration(candidateInput);
|
|
51
|
+
if (!Array.isArray(liveInput) || liveInput.length === 0 || liveInput.length > 32)
|
|
52
|
+
throw new Error("RUNTIME_OVERLAP_INVALID");
|
|
53
|
+
const live = liveInput.map(parseRuntimeOverlapDeclaration);
|
|
54
|
+
const conflicts = [];
|
|
55
|
+
const common = {};
|
|
56
|
+
for (const store of RUNTIME_OVERLAP_STORES) {
|
|
57
|
+
const own = candidate.stores[store];
|
|
58
|
+
live.forEach((peer, index) => {
|
|
59
|
+
const theirs = peer.stores[store];
|
|
60
|
+
if (!own || !theirs)
|
|
61
|
+
conflicts.push({ peer: index, store, reason: "missing" });
|
|
62
|
+
else {
|
|
63
|
+
if (!theirs.reads.includes(own.writes))
|
|
64
|
+
conflicts.push({ peer: index, store, reason: "candidate_unreadable_by_peer" });
|
|
65
|
+
if (!own.reads.includes(theirs.writes))
|
|
66
|
+
conflicts.push({ peer: index, store, reason: "peer_unreadable_by_candidate" });
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
if (own)
|
|
70
|
+
common[store] = own.writes;
|
|
71
|
+
}
|
|
72
|
+
if (candidate.manager_abi !== RUNTIME_ADOPTION_ABI)
|
|
73
|
+
conflicts.push({ peer: -1, store: "manager_abi", reason: "missing" });
|
|
74
|
+
return { supported: conflicts.length === 0, common_formats: conflicts.length ? {} : common, conflicts };
|
|
75
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { mergeAntigravityHooks, antigravityHookFile } from "./harnesses/antigravity.js";
|
|
2
2
|
// AI clientごとの登録形式をここに閉じ込め、setup共通処理へ漏らさない。
|
|
3
3
|
import { copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
|
-
import { dirname, join } from "node:path";
|
|
4
|
+
import { basename, dirname, isAbsolute, join } from "node:path";
|
|
5
5
|
import { randomUUID } from "node:crypto";
|
|
6
6
|
import { isDeepStrictEqual } from "node:util";
|
|
7
7
|
import * as steer from "aiterm-steer-delivery";
|
|
@@ -24,13 +24,47 @@ const record = (value) => typeof value === "object" && value !== null && !Array.
|
|
|
24
24
|
export function sameRegistration(command, args, registration) {
|
|
25
25
|
if (typeof command !== "string" || !Array.isArray(args))
|
|
26
26
|
return false;
|
|
27
|
-
if (command
|
|
27
|
+
if (sameDirect(command, args, registration))
|
|
28
28
|
return true;
|
|
29
29
|
if (!lazyRelayExecutable(command))
|
|
30
30
|
return false;
|
|
31
|
-
const direct = [registration.command, ...registration.args];
|
|
32
31
|
const separator = args.indexOf("--");
|
|
33
|
-
return
|
|
32
|
+
return [args, separator >= 0 ? args.slice(separator + 1) : []]
|
|
33
|
+
.some(inner => inner.length > 0 && sameDirect(inner[0], inner.slice(1), registration));
|
|
34
|
+
}
|
|
35
|
+
function sameDirect(command, args, registration) {
|
|
36
|
+
return command === registration.command && (isDeepStrictEqual(args, registration.args) || installationCapsuleEntry(args));
|
|
37
|
+
}
|
|
38
|
+
// Updater-installed immutable capsule (BellTeam RUNTIME_ROOT/dispatch/aiterm/v<N>/): Aiterm entry basenames
|
|
39
|
+
// plus this marker. Same node + marker-listed entry = Aiterm's own registration, so setup keeps it (and
|
|
40
|
+
// its timeout/env) instead of rewriting it to a disposable package dist. Unknown scripts never match.
|
|
41
|
+
export const INSTALLATION_CAPSULE_FILE = "aiterm-capsule.json";
|
|
42
|
+
export const INSTALLATION_CAPSULE_SCHEMA = "aiterm.installation-capsule.v1";
|
|
43
|
+
export function installationCapsuleEntry(args) {
|
|
44
|
+
const [entry, ...rest] = args;
|
|
45
|
+
if (typeof entry !== "string" || !isAbsolute(entry))
|
|
46
|
+
return false;
|
|
47
|
+
const name = basename(entry);
|
|
48
|
+
if (name === "index.js") {
|
|
49
|
+
if (rest.length)
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
else if (name === "execution-native-server.js") {
|
|
53
|
+
// Persistent registrations are ordinary MCP; lifecycle standby is never written to HOME.
|
|
54
|
+
const mode = rest.indexOf("--mode");
|
|
55
|
+
if (rest[0] !== "--execution-interrupt" || rest.includes("--runtime-adoption") || (mode >= 0 && rest[mode + 1] !== "mcp"))
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
else
|
|
59
|
+
return false;
|
|
60
|
+
try {
|
|
61
|
+
const marker = JSON.parse(readFileSync(join(dirname(entry), INSTALLATION_CAPSULE_FILE), "utf8"));
|
|
62
|
+
return record(marker) && marker.schema === INSTALLATION_CAPSULE_SCHEMA && marker.package === "aiterm-mcp"
|
|
63
|
+
&& Array.isArray(marker.entries) && marker.entries.includes(name);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
34
68
|
}
|
|
35
69
|
export function mergeJsonMcp(file, registration) {
|
|
36
70
|
let current = {};
|
|
@@ -61,7 +95,8 @@ export function mergeJsonMcp(file, registration) {
|
|
|
61
95
|
const servers = (current.mcpServers ?? {});
|
|
62
96
|
const previous = record(servers.aiterm) ? servers.aiterm : {};
|
|
63
97
|
// 中継で包んだ同じ登録は、そのまま残す(直結へ書き戻さない)。
|
|
64
|
-
|
|
98
|
+
const exact = previous.command === registration.command && isDeepStrictEqual(previous.args, registration.args);
|
|
99
|
+
if (!exact && sameRegistration(previous.command, previous.args, registration))
|
|
65
100
|
return "unchanged";
|
|
66
101
|
const updated = { ...previous, ...registration };
|
|
67
102
|
if (isDeepStrictEqual(servers.aiterm, updated))
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiterm-mcp",
|
|
3
|
-
"version": "0.63.
|
|
3
|
+
"version": "0.63.18",
|
|
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": [
|
|
@@ -53,6 +53,7 @@
|
|
|
53
53
|
"files": [
|
|
54
54
|
"dist/*.js",
|
|
55
55
|
"dist/harnesses/*.js",
|
|
56
|
+
"runtime-overlap.json",
|
|
56
57
|
"README.md",
|
|
57
58
|
"CHANGELOG.md",
|
|
58
59
|
"docs/00_overview.md",
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema": "aiterm.runtime-overlap.v1",
|
|
3
|
+
"manager_abi": "aiterm.runtime-adoption.v1",
|
|
4
|
+
"stores": {
|
|
5
|
+
"agent-metadata": { "writes": "v1", "reads": ["v1"] },
|
|
6
|
+
"execution-metadata": { "writes": "v1", "reads": ["v1"] },
|
|
7
|
+
"parent-delivery": { "writes": "v1", "reads": ["v1"] },
|
|
8
|
+
"provider-hooks": { "writes": "steer-v1", "reads": ["steer-v1"] },
|
|
9
|
+
"events": { "writes": "v1", "reads": ["v1"] },
|
|
10
|
+
"runtime-errors": { "writes": "v1", "reads": ["v1"] }
|
|
11
|
+
}
|
|
12
|
+
}
|