aiterm-mcp 0.63.16 → 0.63.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.63.17] - 2026-11-08
11
+
12
+ - 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.
13
+ - 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.
14
+ - 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.
15
+ - 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.
16
+ - 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.
17
+
10
18
  ## [0.63.16] - 2026-11-07
11
19
 
12
20
  - `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 +3088,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3080
3088
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3081
3089
  provenance.
3082
3090
 
3083
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.16...HEAD
3091
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.17...HEAD
3092
+ [0.63.17]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.16...v0.63.17
3084
3093
  [0.63.16]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.15...v0.63.16
3085
3094
  [0.63.15]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.14...v0.63.15
3086
3095
  [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.16** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.63.17** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
219
219
 
220
220
  ### 更新と巻き戻し
221
221
 
package/README.md CHANGED
@@ -227,7 +227,7 @@ collection is off by default and performs no network I/O. It ships via
227
227
  tag-triggered CI with npm provenance (OIDC Trusted Publishing); the GitHub
228
228
  Release re-registers the Official MCP Registry entry.
229
229
 
230
- **Status:** actively maintained · current public release **v0.63.16** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
230
+ **Status:** actively maintained · current public release **v0.63.17** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
231
231
 
232
232
  ### Update and rollback
233
233
 
package/dist/core.js CHANGED
@@ -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();
@@ -6342,13 +6351,17 @@ function verifyCreatedNative(native, allowExitedPane = false) {
6342
6351
  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
6352
  const fields = pane.stdout.trim().split("\t");
6344
6353
  const exited = allowExitedPane && fields[5] === "1";
6345
- const [serverStarted, paneStarted] = processStartIdentities(exited ? [native.server_pid] : [native.server_pid, native.pane_pid], process.platform);
6346
6354
  // macOS tmux clears pane_pid after exit; only the explicit dead-pane close admits that absence.
6347
6355
  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
6356
  || (fields[4] !== String(native.pane_pid) && !(exited && fields[4] === ""))
6349
- || !["0", "1"].includes(fields[5]) || serverStarted !== native.server_started_identity
6350
- || (!exited && paneStarted !== native.pane_started_identity))
6357
+ || !["0", "1"].includes(fields[5]))
6358
+ throw unavailable();
6359
+ const [serverStarted, paneStarted] = processStartIdentities(exited ? [native.server_pid] : [native.server_pid, native.pane_pid], process.platform);
6360
+ if ((serverStarted !== null && serverStarted !== native.server_started_identity)
6361
+ || (!exited && paneStarted !== null && paneStarted !== native.pane_started_identity))
6351
6362
  throw unavailable();
6363
+ if (!serverStarted || (!exited && !paneStarted))
6364
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 作成したnative本人性を取得できません。", 2);
6352
6365
  }
6353
6366
  function withAgentResumeTarget(meta, body, allowExitedPane = false) {
6354
6367
  if (hasVerifiedNativeSessionTarget(meta.aiterm_session))
@@ -6624,6 +6637,32 @@ function prepareWorkingAgentResume(meta) {
6624
6637
  throw unavailable();
6625
6638
  return lifecycle;
6626
6639
  }
6640
+ /** Write a prepared restart lifecycle after rechecking native absence and unchanged metadata under the caller's lock. */
6641
+ function commitWorkingAgentResume(previous, lifecycle) {
6642
+ const name = previous.aiterm_session, native = observeExecutionNativeSessions();
6643
+ if (native.state !== "known" || native.sessions.some(row => row.session_id === name)
6644
+ || !isDeepStrictEqual(loadAgentMetadata(name), previous) || readAgentLifecycle(previous))
6645
+ throw new AgentResumeUnavailableError(name);
6646
+ withExecutionPreparation(name, () => writeAgentLifecycle(previous, lifecycle));
6647
+ }
6648
+ /** A current generation with no lifecycle/attempt state whose native is confirmed absent. */
6649
+ function vanishedAgentNative(meta) {
6650
+ if (agentDormantState(meta) !== null)
6651
+ return false;
6652
+ const native = observeExecutionNativeSessions();
6653
+ return native.state === "known" && !native.sessions.some(row => row.session_id === meta.aiterm_session);
6654
+ }
6655
+ function adoptVanishedAgentNative(meta) {
6656
+ try {
6657
+ commitWorkingAgentResume(meta, prepareWorkingAgentResume(meta));
6658
+ }
6659
+ catch (error) {
6660
+ if (error instanceof ExecutionError)
6661
+ throw error;
6662
+ throw new AitermError(`AGENT_SESSION_REQUIRED: session '${meta.aiterm_session}' のnative端末が無く、保存した会話へ再開できません。` +
6663
+ "文字列は送信していません。agent_launchで起動し直してください。", 2);
6664
+ }
6665
+ }
6627
6666
  async function resumeAgentInLock(name, readyTimeout) {
6628
6667
  const previous = loadAgentMetadata(name);
6629
6668
  readyTimeout ??= previous.kind === "codex" ? AGENT_TUI_FIRST_DRAW_TIMEOUT_MS : AGENT_TUI_READY_TIMEOUT_MS;
@@ -7832,13 +7871,8 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
7832
7871
  if (opts.launch_operation_id != null)
7833
7872
  requireMatchingClaudeLaunch(name, validateOperationId(opts.launch_operation_id), claudeLaunchRequestDigest({ sessionName: name, model: opts.model ?? null, effort: opts.reasoning_effort ?? null,
7834
7873
  cwd: opts.cwd ?? null, agentDone: true }));
7835
- if (preparedLifecycle) {
7836
- const native = observeExecutionNativeSessions();
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
- }
7874
+ if (preparedLifecycle)
7875
+ commitWorkingAgentResume(previous, preparedLifecycle);
7842
7876
  const resumed = await resumeAgentInLock(name, opts.ready_timeout ?? undefined);
7843
7877
  return withAgentResumeTarget(resumed, async () => {
7844
7878
  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
- return { mode: values.mode, codexHome: values["codex-home"], hookDirectory: values["hook-directory"], expectedScope: { state_root: values["state-root"], multiplexer: { kind: "socket", key: values.socket } },
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/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 pkg = createRequire(import.meta.url)("../package.json");
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;
@@ -1383,9 +1429,8 @@ export function createAitermServer(options = {}) {
1383
1429
  // 親ホストを initialize の clientInfo.name から確定させ、receipt の完了待ちコマンドを
1384
1430
  // そのホストの実際の起動形で名指しする(実測: claude-code は initialize → notifications/initialized
1385
1431
  // → tools/list の順で送るため、どの tool 呼び出しより先に確定する)。取れない時は汎用文へ落ちるだけ。
1386
- server.server.oninitialized = () => {
1432
+ const startParentManagers = () => {
1387
1433
  const name = server.server.getClientVersion()?.name;
1388
- core.setParentClient(name ?? null);
1389
1434
  if (name === "codex-mcp-client" || name === "claude-code" || isCursorMcpClient(name)) {
1390
1435
  parentDelivery ??= new ParentDeliveryManager({ parent_kind: deliveryParentKind(name),
1391
1436
  ...(execution ? { execution: execution.parentExecution, dependencies: execution.parentDependencies,
@@ -1394,10 +1439,27 @@ export function createAitermServer(options = {}) {
1394
1439
  remoteParentDelivery ??= new ParentDeliveryManager({ parent_kind: deliveryParentKind(name), remote: true });
1395
1440
  }
1396
1441
  };
1442
+ server.server.oninitialized = () => {
1443
+ core.setParentClient(server.server.getClientVersion()?.name ?? null);
1444
+ // Standby must not start recovery/heartbeat timers or claim records; activation starts them.
1445
+ if (!adoption || adoption.state === "active")
1446
+ startParentManagers();
1447
+ };
1448
+ // One close per manager: retire awaits it, a later transport close reuses the same promise.
1449
+ let managersClosed = null;
1450
+ const closeParentManagers = () => managersClosed ??= Promise.all([parentDelivery?.close(), remoteParentDelivery?.close()]).then(() => undefined);
1397
1451
  server.server.onclose = () => {
1398
- void parentDelivery?.close().catch(() => process.stderr.write("aiterm: PARENT_DELIVERY_CLOSE_FAILED\n"));
1399
- void remoteParentDelivery?.close().catch(() => process.stderr.write("aiterm: PARENT_DELIVERY_CLOSE_FAILED\n"));
1452
+ void closeParentManagers().catch(() => process.stderr.write("aiterm: PARENT_DELIVERY_CLOSE_FAILED\n"));
1400
1453
  };
1454
+ if (options.runtimeAdoption) {
1455
+ adoption = createRuntimeAdoption(options.runtimeAdoption, {
1456
+ declaration: () => pkgRequire("../runtime-overlap.json"),
1457
+ onActivate: () => { if (server.server.getClientVersion())
1458
+ startParentManagers(); },
1459
+ onRetire: closeParentManagers,
1460
+ });
1461
+ registerRuntimeAdoptionTool(server, adoption);
1462
+ }
1401
1463
  return server;
1402
1464
  }
1403
1465
  async function main() {
@@ -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 === registration.command && isDeepStrictEqual(args, registration.args))
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 isDeepStrictEqual(args, direct) || (separator >= 0 && isDeepStrictEqual(args.slice(separator + 1), direct));
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
- if (previous.command !== registration.command && sameRegistration(previous.command, previous.args, registration))
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.16",
3
+ "version": "0.63.17",
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
+ }