aiterm-mcp 0.63.3 → 0.63.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.63.6] - 2026-11-03
11
+
12
+ - Make the existing read-only diagnostics PTY probe finite and socket-exact: share a 5000 ms subprocess budget across backend resolution and one listing, and stop treating broad connection errors as absence. Opt-in `format:"v2"` adds safe PTY reason codes and the timeout budget; default v1 fields and the parent-hook text stay unchanged. No PTY warming or provider calls.
13
+
14
+ ## [0.63.5] - 2026-11-03
15
+
16
+ - Add opt-in request-bound `agent_configure` receipts and read-only reconciliation. Persist the original UUID, expected launch and normalized settings digest before native input; never reapply an existing ID. Missing, corrupt or unfinished records remain unknown. Native issuance stays `later_effect: unconfirmed` even after a successful handler; current settings inspection remains unsupported. Durable tracked apply is POSIX-only; existing configuration remains available on Windows.
17
+ - Keep legacy configure results unchanged and describe their existing typed errors in the output schema so SDK validation can retain them. Tracked remote forwarding is refused before connection because old servers may strip the new fields.
18
+
10
19
  ## [0.63.3] - 2026-11-03
11
20
 
12
21
  ### Fixed
@@ -3023,7 +3032,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3023
3032
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3024
3033
  provenance.
3025
3034
 
3026
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.3...HEAD
3035
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.6...HEAD
3036
+ [0.63.6]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.5...v0.63.6
3037
+ [0.63.5]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.3...v0.63.5
3027
3038
  [0.63.3]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.2...v0.63.3
3028
3039
  [0.63.2]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.1...v0.63.2
3029
3040
  [0.63.1]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.0...v0.63.1
package/README.ja.md CHANGED
@@ -209,7 +209,7 @@ runtime-error store は canonical dotagents config の `collection.enabled: true
209
209
  場合だけ収集し、既定OFF、network送信は行いません。tag起点CIのnpm provenance(OIDC Trusted
210
210
  Publishing)で公開し、GitHub Release が Official MCP Registry を再登録します。
211
211
 
212
- **状態:** 開発継続中 · 現行公開版 **v0.63.3** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
212
+ **状態:** 開発継続中 · 現行公開版 **v0.63.6** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
213
213
 
214
214
  ### 更新と巻き戻し
215
215
 
@@ -619,6 +619,8 @@ Claudeの相関済み承認は既存の`claude_approval`を使う。
619
619
 
620
620
  `diagnostics` は PTY やエージェントを起動しない。パッケージ版、MCP 呼出 readiness、read-only な PTY 一覧要約、bounded runtime-error-store status、任意 vendor launcher の可用性だけを返す。path・環境値・認証情報・コマンド本文・PTY 出力・raw log は意図的に返さない。通常未設定の任意依存は `not_applicable`、安全に確定できない状態は `unverified` と表す。
621
621
 
622
+ `diagnostics({format:"v2"})`は同じ2つのtextを保ち、第1textを`aiterm-mcp.factory-diagnostics.v2`にする。`pty_list`には固定`reason_code`(`listed`/`socket_absent`/`dependency_unavailable`/`permission_denied`/`timeout`/`output_limit`/`signal`/`native_failure`)と`timeout_ms:5000`を追加する。binary解決とread-only一覧1回で共通5000msのsubprocess予算・1MiB出力上限を使い、PTYは作らない。不在はexit1・空stdout・選択socketの完全一致した不在文言が揃う場合だけ。他socket・権限/接続拒否・相反出力・未知はunverifiedのまま、生文言は返さない。`{}`/`{format:"v1"}`は既存fieldとschemaを維持し、不在判定だけを厳密化する。v2使用前に同接続のtoolが`format`を宣言していることと返却v2 schemaを確認する。旧serverは未知引数を捨て得る。vendor解決とruntime storeは既存の別の有限期限を持ち、5000msはPTY subprocessの予算であってMCP全体又はOSのhard realtime保証ではない。
623
+
622
624
  結果のtextは2つある。1つ目は上の内容で、項目を固定したfactory向けのJSON(`aiterm-mcp.factory-diagnostics.v1`)。2つ目は親配送hookの状態(`aiterm-mcp.parent-delivery-diagnostics.v1`)で、Claude Code・Cursorそれぞれの`status`(`ready`/`setup_required`/`not_applicable`/`unverified`)と`reason_code`、呼出元のclientに当たる`caller_status`を返す。`caller_status`が`setup_required`なら、そのclientからのagent送信は拒否されるので`aiterm-setup`を実行する。hookの状態は1つ目の`overall`には含めない。
623
625
 
624
626
  ### ローカル runtime error snapshot
@@ -644,6 +646,8 @@ Aitermは、既定では実行時エラーをどこへも送らない。送る
644
646
 
645
647
  `agent_configure({ session_id, model?, reasoning_effort?, fast? })`はharness標準操作で起動中のClaude/Codex/Grok/Cursor/Antigravityを変更し、PTYと会話contextを維持する。
646
648
 
649
+ 新しいconsumerは初回前に原要求の`request`(UUID・期待launch・設定digest)を保存し、`action: "reconcile"`で保存結果だけを照会できる。発行前に同じ接続のtool schema対応を確認し、未提供なら未発行として止める。handler終端だけで発行済みnative入力の後発作用を除外せず、現在設定の観測も未対応と明示する。追跡付きapplyはPOSIX・対象へのlocal接続に限定する。原要求bindingが欠けた旧事故は救済しない。[原要求と照会の契約](docs/configure-reconcile.md)を参照。
650
+
647
651
  Codex v1のgoalがactiveの席では、`agent_configure`がgoalを一時停止し、現在の番の終了記録を最長30分待ってから設定を替え、同じgoalを再開します。番を待つ間も差し込みは通ります。途中で変更されたgoalは保持し、再開できなかった時は設定変更の結果とgoalの状態をエラー本文に残します。他のharnessでは通常の入力待ち上限を維持するため、番が続くgoalは停止または完了にしてから設定を替えてください。
648
652
 
649
653
  Codexでmodelだけを変更する場合は、標準の選択画面から現在のeffortを読み、同じ値を明示的に選びます。現在値を読めない場合や変更先で選べない場合は、別の値へ置き換えず失敗します。
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.3** · 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.6** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
231
231
 
232
232
  ### Update and rollback
233
233
 
@@ -661,6 +661,8 @@ continue to use `claude_approval`.
661
661
 
662
662
  `diagnostics` never starts a PTY or agent. It reports package version, MCP call readiness, a read-only PTY-list summary, bounded runtime-error-store status, and optional vendor-launcher availability. It deliberately excludes paths, environment values, credentials, command text, PTY output, and raw logs; normal unset optional dependencies are `not_applicable`, while an indeterminate probe is `unverified`.
663
663
 
664
+ `diagnostics({format:"v2"})` keeps the two text items and uses `aiterm-mcp.factory-diagnostics.v2` for the first. Its `pty_list` adds `reason_code` (`listed`, `socket_absent`, `dependency_unavailable`, `permission_denied`, `timeout`, `output_limit`, `signal`, or `native_failure`) and `timeout_ms:5000`. Binary resolution and one read-only native listing share that 5000 ms subprocess budget and a 1 MiB output limit; no PTY is created. An absent result requires exit 1, empty stdout, and the exact selected-socket absence diagnostic. Other sockets, permission/refused connections, conflicting output and unknown failures stay unverified. Unknown text is never echoed. `{}` or `{format:"v1"}` retains the existing fields and schema, with the corrected strict absence classification. Inspect the connected tool's advertised `format` before opting into v2 and require the returned v2 schema: older servers can discard unknown input fields. Vendor lookup and runtime-store checks retain their own finite deadlines; the 5000 ms field describes the PTY subprocess budget, not the entire MCP call or a hard real-time OS guarantee.
665
+
664
666
  The result carries two text items. The first is the factory JSON described above (`aiterm-mcp.factory-diagnostics.v1`), whose fields are fixed. The second reports the parent-delivery hooks (`aiterm-mcp.parent-delivery-diagnostics.v1`): a `status` (`ready` / `setup_required` / `not_applicable` / `unverified`) and `reason_code` for Claude Code and Cursor, plus `caller_status` for the calling client. When `caller_status` is `setup_required`, agent dispatch from that client is rejected; run `aiterm-setup`. Hook status is not folded into `overall` in the first item.
665
667
 
666
668
  ### Local runtime error snapshot
@@ -689,6 +691,8 @@ enables collection on that host.
689
691
 
690
692
  `agent_configure({ session_id, model?, reasoning_effort?, fast? })` changes a running Claude, Codex, Grok, or Cursor TUI through the harness's standard controls, preserving the PTY and conversation context.
691
693
 
694
+ New consumers can opt into an original `request` binding (UUID, expected launch, settings digest) and use `action: "reconcile"` to read the saved outcome without input or replay. Negotiate the exact tool schema before the first call. Handler completion does not prove that previously issued native input cannot act later; current settings inspection remains unsupported. Tracked apply is POSIX-only and uses a local target connection. Existing incidents without the original binding cannot be recovered this way. See the [request/reconcile contract](docs/configure-reconcile.md).
695
+
692
696
  For an active Codex v1 goal, `agent_configure` temporarily pauses the goal, waits for the current native turn to end (up to 30 minutes), applies settings through the same send queue, and resumes that goal. Steering remains available during the wait. A changed goal is preserved; a failed or uncertain restoration is reported with the configuration outcome. Other harnesses retain the normal readiness limit: stop or complete a continuously running goal before configuring them.
693
697
 
694
698
  Codex model-only changes explicitly preserve the current reasoning effort read from the native picker. Unreadable or unsupported current effort fails without selecting another value.
@@ -0,0 +1,38 @@
1
+ // Only tracked configuration requests use this local guard; no graph or admission is created.
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { AitermError } from "./errors.js";
4
+ const requests = new AsyncLocalStorage();
5
+ export function hasConfigurationEffects() { return requests.getStore() !== undefined; }
6
+ export function beforeConfigurationEffect() {
7
+ const request = requests.getStore();
8
+ if (!request)
9
+ return;
10
+ if (request.closed)
11
+ throw new AitermError("CONFIGURATION_REQUEST_TERMINAL: later input refused", 2);
12
+ if (request.failed)
13
+ throw request.failure;
14
+ try {
15
+ request.beforeEffect();
16
+ }
17
+ catch (error) {
18
+ request.failed = true;
19
+ request.failure = error;
20
+ throw error;
21
+ }
22
+ }
23
+ export async function withConfigurationEffects(beforeEffect, body) {
24
+ if (requests.getStore())
25
+ throw new AitermError("CONFIGURATION_REQUEST_NESTED", 2);
26
+ const request = { closed: false, failed: false, beforeEffect };
27
+ return requests.run(request, async () => {
28
+ try {
29
+ const value = await body();
30
+ if (request.failed)
31
+ throw request.failure;
32
+ return value;
33
+ }
34
+ finally {
35
+ request.closed = true;
36
+ }
37
+ });
38
+ }
@@ -0,0 +1,147 @@
1
+ // One receipt per opt-in configuration request. Reconciliation never starts work.
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ import { z } from "zod";
6
+ import { stateRoot, ensureStateRoot } from "./agent-shared.js";
7
+ import { writeExecutionCheckpoint } from "./execution-checkpoint.js";
8
+ import { withConfigurationEffects } from "./configuration-effect.js";
9
+ import { AitermError } from "./errors.js";
10
+ export const configurationRequestSchema = z.object({
11
+ id: z.uuid(), launch_id: z.string().regex(/^[a-f0-9]{32}$/), digest: z.string().regex(/^[a-f0-9]{64}$/),
12
+ }).strict();
13
+ const settingsSchema = z.object({ model: z.string().max(512).nullable(), reasoning_effort: z.string().max(512).nullable(), fast: z.boolean().nullable() }).strict();
14
+ export function configurationSettings(input) {
15
+ return settingsSchema.parse({ model: input.model?.trim() || null, reasoning_effort: input.reasoning_effort?.trim() || null, fast: input.fast ?? null });
16
+ }
17
+ export function configurationRequestDigest(input) {
18
+ return createHash("sha256").update(JSON.stringify(configurationSettings(input))).digest("hex");
19
+ }
20
+ export const configurationBindingSchema = configurationRequestSchema.extend({ session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/) }).strict();
21
+ const resultSchema = z.object({ schema: z.literal("aiterm.agent-configure-result.v1"), session_id: z.string(),
22
+ provider: z.enum(["claude", "codex", "grok", "cursor", "antigravity"]),
23
+ harness: z.enum(["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"]),
24
+ model: z.string().nullable(), reasoning_effort: z.string().nullable(), fast: z.boolean().nullable() }).strict();
25
+ const recordSchema = z.object({ schema: z.literal("aiterm.configuration-request.v1"), binding: configurationBindingSchema,
26
+ requested: settingsSchema, terminal_at: z.iso.datetime().nullable(), native_effect: z.enum(["not_issued", "possible"]),
27
+ outcome: z.enum(["applied", "not_applied", "outcome_unknown"]), result: resultSchema.nullable(),
28
+ }).strict().refine(value => configurationRequestDigest(value.requested) === value.binding.digest
29
+ && (value.result === null || value.result.session_id === value.binding.session_id)
30
+ && (value.terminal_at !== null || value.result === null && value.outcome === "outcome_unknown")
31
+ && (value.outcome !== "applied" || value.terminal_at !== null && value.result !== null));
32
+ export const configurationReceiptSchema = z.object({ schema: z.literal("aiterm.agent-configure-request-result.v1"),
33
+ binding: configurationBindingSchema, request_state: z.enum(["not_recorded", "unavailable", "pending_or_unknown", "terminal"]),
34
+ outcome: z.enum(["applied", "not_applied", "outcome_unknown"]), later_effect: z.enum(["excluded", "unconfirmed"]),
35
+ terminal_at: z.iso.datetime().nullable(), result: resultSchema.nullable(),
36
+ current: z.object({ availability: z.literal("unsupported") }).strict(), observed_at: z.iso.datetime(),
37
+ }).strict();
38
+ const failureSchema = z.object({ schema: z.literal("aiterm.agent-configure-error.v1"), session_id: z.string(),
39
+ outcome: z.enum(["not_applied", "outcome_unknown"]), effect: z.enum(["not_started", "possible"]) }).strict()
40
+ .refine(value => value.outcome === "not_applied" ? value.effect === "not_started" : value.effect === "possible");
41
+ export const configurationToolOutputSchema = z.object({ ...resultSchema.partial().shape, ...configurationReceiptSchema.partial().shape,
42
+ ...z.object(failureSchema.shape).partial().shape,
43
+ schema: z.enum(["aiterm.agent-configure-result.v1", "aiterm.agent-configure-error.v1", "aiterm.agent-configure-request-result.v1"]),
44
+ outcome: configurationReceiptSchema.shape.outcome.optional(),
45
+ }).strict().superRefine((value, context) => {
46
+ const schema = value.schema === "aiterm.agent-configure-result.v1" ? resultSchema
47
+ : value.schema === "aiterm.agent-configure-error.v1" ? failureSchema : configurationReceiptSchema;
48
+ if (!schema.safeParse(value).success)
49
+ context.addIssue({ code: "custom", message: "Invalid configuration result variant" });
50
+ });
51
+ function directory(binding) { return path.join(stateRoot(), "configuration-requests", binding.id); }
52
+ function sameBinding(a, b) {
53
+ return a.id === b.id && a.session_id === b.session_id && a.launch_id === b.launch_id && a.digest === b.digest;
54
+ }
55
+ function readRecord(binding) {
56
+ const file = path.join(directory(binding), "receipt.json");
57
+ const noFollow = fs.constants.O_NOFOLLOW ?? 0;
58
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | noFollow);
59
+ try {
60
+ const before = fs.fstatSync(fd);
61
+ if (!before.isFile() || before.size > 8192)
62
+ throw new Error("invalid receipt file");
63
+ const buffer = Buffer.alloc(8193);
64
+ const count = fs.readSync(fd, buffer, 0, buffer.length, 0), after = fs.fstatSync(fd), current = fs.lstatSync(file);
65
+ if (count !== before.size || count > 8192 || after.size !== before.size || after.mtimeMs !== before.mtimeMs
66
+ || current.isSymbolicLink() || current.dev !== after.dev || current.ino !== after.ino)
67
+ throw new Error("receipt changed");
68
+ const record = recordSchema.parse(JSON.parse(buffer.subarray(0, count).toString("utf8")));
69
+ if (!sameBinding(record.binding, binding))
70
+ throw new AitermError("CONFIGURATION_REQUEST_CONFLICT", 2);
71
+ return record;
72
+ }
73
+ finally {
74
+ fs.closeSync(fd);
75
+ }
76
+ }
77
+ function receipt(binding, record, missing = "unavailable") {
78
+ return { schema: "aiterm.agent-configure-request-result.v1", binding,
79
+ request_state: record ? record.terminal_at === null ? "pending_or_unknown" : "terminal" : missing,
80
+ outcome: record?.outcome ?? "outcome_unknown",
81
+ later_effect: record?.terminal_at !== null && record?.native_effect === "not_issued" ? "excluded" : "unconfirmed",
82
+ terminal_at: record?.terminal_at ?? null, result: record?.result ?? null,
83
+ current: { availability: "unsupported" }, observed_at: new Date().toISOString() };
84
+ }
85
+ export function reconcileConfigurationRequest(input) {
86
+ const binding = configurationBindingSchema.parse(input);
87
+ try {
88
+ return receipt(binding, readRecord(binding));
89
+ }
90
+ catch (error) {
91
+ if (error instanceof AitermError)
92
+ throw error;
93
+ // A missing receipt inside a claimed directory never permits a second apply.
94
+ try {
95
+ fs.lstatSync(directory(binding));
96
+ }
97
+ catch (missing) {
98
+ if (missing.code === "ENOENT")
99
+ return receipt(binding, null, "not_recorded");
100
+ }
101
+ return receipt(binding, null);
102
+ }
103
+ }
104
+ export async function applyConfigurationRequest(input, settings, apply) {
105
+ const binding = configurationBindingSchema.parse(input), requested = configurationSettings(settings);
106
+ if (configurationRequestDigest(requested) !== binding.digest)
107
+ throw new AitermError("CONFIGURATION_REQUEST_DIGEST_MISMATCH: not issued", 2);
108
+ if (process.platform === "win32")
109
+ throw new AitermError("CONFIGURATION_REQUEST_UNSUPPORTED: durable directory sync unavailable; not issued", 2);
110
+ const parent = path.join(ensureStateRoot(), "configuration-requests");
111
+ fs.mkdirSync(parent, { recursive: true, mode: 0o700 });
112
+ try {
113
+ fs.mkdirSync(directory(binding), { mode: 0o700 });
114
+ }
115
+ catch (error) {
116
+ if (error.code !== "EEXIST")
117
+ throw error;
118
+ return { receipt: reconcileConfigurationRequest(binding) };
119
+ }
120
+ const record = { schema: "aiterm.configuration-request.v1", binding, requested, terminal_at: null,
121
+ native_effect: "not_issued", outcome: "outcome_unknown", result: null };
122
+ const save = () => writeExecutionCheckpoint(path.join(directory(binding), "receipt.json"), recordSchema.parse(record));
123
+ save(); // A failed durable admission leaves a claimed, non-replayable request.
124
+ let failure;
125
+ try {
126
+ record.result = await withConfigurationEffects(() => {
127
+ if (record.native_effect === "possible")
128
+ return;
129
+ record.native_effect = "possible";
130
+ save(); // Mark before native input; a failed checkpoint refuses input.
131
+ }, apply);
132
+ record.outcome = "applied";
133
+ }
134
+ catch (error) {
135
+ failure = error instanceof Error ? error : new Error("configuration failed");
136
+ const detail = failure.configurationFailure;
137
+ record.outcome = detail?.outcome === "not_applied" ? "not_applied" : "outcome_unknown";
138
+ }
139
+ record.terminal_at = new Date().toISOString();
140
+ try {
141
+ save();
142
+ }
143
+ catch {
144
+ return { receipt: receipt(binding, null), error: new AitermError("CONFIGURATION_RECEIPT_UNAVAILABLE: do not replay", 2) };
145
+ }
146
+ return { receipt: receipt(binding, record), ...(failure ? { error: failure } : {}) };
147
+ }
package/dist/core.js CHANGED
@@ -51,7 +51,7 @@ import { unfinishedDeliveriesOwnedBy } from "./parent-delivery-owners.js";
51
51
  import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, signalRuntimeProcess, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, macKeepAwakeProcess, processElapsedSeconds } from "./process-runtime.js";
52
52
  import { liveNodeExecutable } from "./live-node.js";
53
53
  import { AitermError, AgentResumeError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
54
- import { isWin, SOCKDIR, SOCK, tmuxCommand, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, } from "./tmux-runtime.js";
54
+ import { isWin, SOCKDIR, SOCK, tmuxCommand, readOnlyTmuxList, PtyDiagnosticError, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, } from "./tmux-runtime.js";
55
55
  import { AGENT_DEFAULT_PREFACE, sleep, currentUid, runtimeStateBase, safeStatSize, readFileRange, writeJson0600, createEmpty0600, shq, LAUNCH_ID_RE, AGENT_LINEAGE_RE, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, publishAgentGeneration, agentMetadataPath, writeAgentMetadata, AGENT_EVENT_TAIL_BYTES, agentLabel, agentHarness, subagentInstruction, } from "./agent-shared.js";
56
56
  import { AuthResponseError, authUi, authPromptDigest, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
57
57
  import { processStartIdentity } from "./runtime-error-os.js";
@@ -2193,22 +2193,26 @@ export function agentSessionChildren() {
2193
2193
  * session 名・前面コマンド・PTY 出力を診断応答へ持ち出さないため、factory が安全に readiness を
2194
2194
  * 見られる。socket 不在は「セッション未設定」であって障害ではない。
2195
2195
  */
2196
- export function readOnlyPtyListDiagnostic(runTmux = tmux) {
2196
+ export function readOnlyPtyListDiagnostic(runTmux = readOnlyTmuxList, detailed = false) {
2197
+ const result = (status, session_count, reason_code) => detailed ? { status, session_count, reason_code } : { status, session_count };
2197
2198
  try {
2198
2199
  const r = runTmux("list-sessions", "-F", "#{session_name}");
2199
- if (r.code === 0) {
2200
- return { status: "ready", session_count: r.stdout.split(/\r?\n/).filter(Boolean).length };
2200
+ if (r.code === 0 && r.stderr.trim() === "") {
2201
+ return result("ready", r.stdout.split(/\r?\n/).filter(Boolean).length, "listed");
2201
2202
  }
2202
- // tmux は専用 socket に server がいない通常状態を exit 1 で返す。その他の失敗を「空」と
2203
- // 偽装しないため、メッセージを公開せず unverified に留める。
2204
- if (/no server running|failed to connect/i.test(r.stderr)) {
2205
- return { status: "not_applicable", session_count: null };
2203
+ if (absentExecutionServer(r)) {
2204
+ return result("not_applicable", null, "socket_absent");
2206
2205
  }
2206
+ if (r.code === 1 && r.stdout.trim() === "" && [
2207
+ `error connecting to ${SOCK} (Permission denied)`, `failed to connect to ${SOCK}: Permission denied`,
2208
+ `error connecting to ${SOCK} (Operation not permitted)`,
2209
+ ].includes(r.stderr.trim()))
2210
+ return result("unverified", null, "permission_denied");
2207
2211
  }
2208
- catch {
2209
- // tmux/psmux 未導入等。絶対 path や生 stderr を診断 JSON に出さない。
2212
+ catch (error) {
2213
+ return result("unverified", null, error instanceof PtyDiagnosticError ? error.reasonCode : "native_failure");
2210
2214
  }
2211
- return { status: "unverified", session_count: null };
2215
+ return result("unverified", null, "native_failure");
2212
2216
  }
2213
2217
  /** 別processが待機中・送信中のsessionは閉じない。閉じる前の操作(下のClaude Codeへの終了の鍵)より先に確かめる。 */
2214
2218
  function assertSessionClosable(name) {
@@ -5779,7 +5783,7 @@ export async function pauseAgentGoalForStop(target) {
5779
5783
  function agentConfigureNotReady(name) {
5780
5784
  return new AitermError(`agent session '${name}' は入力待ちではありません。番またはgoalが継続する場合はgoalを停止または完了にしてから agent_configure してください。設定は変えていません。`, 2);
5781
5785
  }
5782
- export async function configureAgent(name, opts) {
5786
+ export async function configureAgent(name, opts, expectedLaunchId) {
5783
5787
  let mayHaveChanged = false;
5784
5788
  const beforeChange = () => { mayHaveChanged = true; };
5785
5789
  try {
@@ -5799,6 +5803,8 @@ export async function configureAgent(name, opts) {
5799
5803
  // 設定替えは席の入力欄へ命令を打つので、送信と同じ行列(ADR 0088)に並ぶ。替えている間に届いた文は、替え終えてから席へ入る(ADR 0120)。
5800
5804
  // 番が動いている席では、行列を持ったまま番の終わりを待たない(待つ間も、その席への差し込みを通す)。
5801
5805
  const meta = loadAgentMetadata(name);
5806
+ if (expectedLaunchId !== undefined && meta.launch_id !== expectedLaunchId)
5807
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
5802
5808
  const checkGeneration = () => {
5803
5809
  assertExecutionContext(name);
5804
5810
  if (tryLoadAgentMetadata(name)?.launch_id !== meta.launch_id || observeSessionGeneration(name).launch_id !== meta.launch_id)
@@ -4,6 +4,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
4
4
  import { executionLaunchSchema, executionPointSchema } from "./execution-contract.js";
5
5
  import { isDeepStrictEqual } from "node:util";
6
6
  import { ExecutionError } from "./execution-wire.js";
7
+ import { beforeConfigurationEffect, hasConfigurationEffects } from "./configuration-effect.js";
7
8
  const scopes = new AsyncLocalStorage();
8
9
  let required = false; // unmounted legacy product remains unchanged
9
10
  export function requireExecutionEffectScope(value) { required = value; }
@@ -351,6 +352,7 @@ export function executionManagementCloseTarget(session) {
351
352
  return scope?.session === session ? scope.managementCloseTarget : undefined;
352
353
  }
353
354
  export function beforeExecutionEffect(session, verify) {
355
+ beforeConfigurationEffect();
354
356
  const scope = scopes.getStore();
355
357
  if (!scope) {
356
358
  if (required)
@@ -381,6 +383,13 @@ const targetCommands = new Set(["send-keys", "paste-buffer", "respawn-pane", "ki
381
383
  * into tmux's prefix-match for a different seat. Native IDs need a prior bind.
382
384
  */
383
385
  export function guardTmuxExecution(input) {
386
+ if (hasConfigurationEffects())
387
+ for (let start = 0; start < input.length;) {
388
+ if (!metadataOrRead.has(input[start]))
389
+ beforeConfigurationEffect();
390
+ const end = input.indexOf(";", start);
391
+ start = end < 0 ? input.length : end + 1;
392
+ }
384
393
  const scope = scopes.getStore();
385
394
  if (!scope && !required)
386
395
  return input;
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { remoteInputDescription, remoteInputSchema } from "./remote-contract.js";
3
3
  import { AuthResponseError, authUiSchema, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
4
+ import { configurationRequestSchema, configurationToolOutputSchema, applyConfigurationRequest, reconcileConfigurationRequest } from "./configure-request.js";
4
5
  import { AitermError, AgentAuthenticationPreflightError, AgentResumeError } from "./errors.js";
5
6
  /**
6
7
  * aiterm-mcp — AI が握るローカル永続端末を stdio MCP サーバとして公開する(Node/TS 版)。
@@ -203,8 +204,8 @@ export function createAitermServer(options = {}) {
203
204
  * Factory 向けの read-only 診断。JSON の field は意図的に allowlist 制で、絶対 path、環境変数、
204
205
  * token、コマンド本文、PTY 出力、raw log、認証状態を公開しない。
205
206
  */
206
- async function factoryDiagnostics() {
207
- const ptyList = core.readOnlyPtyListDiagnostic();
207
+ async function factoryDiagnostics(format = "v1") {
208
+ const ptyList = core.readOnlyPtyListDiagnostic(undefined, format === "v2");
208
209
  const claude = core.harnessLauncherDiagnostic("claude");
209
210
  const codex = core.harnessLauncherDiagnostic("codex");
210
211
  const grok = core.harnessLauncherDiagnostic("grok");
@@ -213,11 +214,11 @@ export function createAitermServer(options = {}) {
213
214
  const runtimeErrors = await runtimeErrorStoreDiagnostic();
214
215
  const overall = ptyList.status === "unverified" || runtimeErrors.status === "unverified" ? "unverified" : "ready";
215
216
  return JSON.stringify({
216
- diagnostic_schema: "aiterm-mcp.factory-diagnostics.v1",
217
+ diagnostic_schema: format === "v2" ? "aiterm-mcp.factory-diagnostics.v2" : "aiterm-mcp.factory-diagnostics.v1",
217
218
  version: pkg.version,
218
219
  overall,
219
220
  mcp: { transport: "stdio", initialize: "ready", tool_call: "ready" },
220
- pty_list: { access: "read_only", ...ptyList },
221
+ pty_list: { access: "read_only", ...ptyList, ...(format === "v2" ? { timeout_ms: 5000 } : {}) },
221
222
  runtime_error_store: runtimeErrors,
222
223
  vendor_dependencies: {
223
224
  claude: {
@@ -279,6 +280,12 @@ export function createAitermServer(options = {}) {
279
280
  /** 配送の登録や事前確保が要るtoolだけ専用の中継にし、他は同じtoolをそのまま現地へ呼ぶ。 */
280
281
  function remoteToolHandler(name) {
281
282
  switch (name) {
283
+ case "agent_configure": return async (target, args) => {
284
+ // Older remote servers strip unknown input fields and could apply without tracking.
285
+ if (args.request || args.action === "reconcile")
286
+ throw new Error("REMOTE_UNSUPPORTED: tracked configuration requires the exact local connection; not issued");
287
+ return forwardRemote(target, name, args);
288
+ };
282
289
  case "pty_send": return sendRemote;
283
290
  case "pty_close": return async (target, args) => {
284
291
  await remoteParentDelivery?.beforeChange(deliveryKey(args.session_id, target));
@@ -348,11 +355,11 @@ export function createAitermServer(options = {}) {
348
355
  server.registerTool("diagnostics", {
349
356
  description: "Factory 向け read-only 診断。安全な状態語彙だけを機械可読 JSON で返す(PTY 内容・認証情報・path・環境値は返さない)。" +
350
357
  "2つ目のtextは親配送hook(Claude Code・Cursor)の登録状態で、caller_status が setup_required なら呼出元からのagent送信は拒否される。aiterm-setup を実行する。",
351
- inputSchema: {},
358
+ inputSchema: { format: z.enum(["v1", "v2"]).optional().describe("既定v1は既存の固定fieldを維持。v2はPTY診断の安全なreason_codeを含む。") },
352
359
  },
353
360
  // 1つ目は項目を固定したfactory向けの契約。親配送hookの状態は別のtextに分け、既存の読み手の形を変えない。
354
- async () => ({ content: [
355
- { type: "text", text: await factoryDiagnostics() },
361
+ async ({ format }) => ({ content: [
362
+ { type: "text", text: await factoryDiagnostics(format) },
356
363
  { type: "text", text: JSON.stringify(parentDeliveryDiagnostic(deliveryParentKind(server.server.getClientVersion()?.name))) },
357
364
  ] }));
358
365
  const DEFAULT_PTY_SHELL = process.platform === "win32" ? "pwsh" : "bash";
@@ -993,22 +1000,27 @@ export function createAitermServer(options = {}) {
993
1000
  "その選び方が無い版、選ぶ画面に無いmodel、そのmodelで選べないeffortは、何も変えずに断る。" +
994
1001
  "fastだけの指定も受ける。" + fastModeDesc,
995
1002
  inputSchema: {
1003
+ action: z.enum(["apply", "reconcile"]).optional().describe("省略は従来apply。reconcileはrequestへ固定した保存結果だけを読み、入力や再適用を行わない"),
1004
+ request: configurationRequestSchema.optional().describe("追跡する新規apply/reconcileの原要求。idは初回発行前に保存するUUID、launch_idは期待世代、digestは正規化した要求値のSHA256。旧事故への後付け不可"),
996
1005
  session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),
997
1006
  model: z.string().min(1).nullish().describe("変更後のmodel。省略時はmodelを変更しない"),
998
1007
  reasoning_effort: z.string().min(1).nullish().describe("変更後のreasoning effort。省略時はeffortを変更しない"),
999
1008
  fast: z.boolean().nullish().describe("変更後のfast。省略時は、その席の今の状態を変えない"),
1000
1009
  },
1001
- outputSchema: {
1002
- schema: z.literal("aiterm.agent-configure-result.v1"),
1003
- session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),
1004
- provider: z.enum(["claude", "codex", "grok", "cursor", "antigravity"]),
1005
- harness: z.enum(["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"]),
1006
- model: z.string().nullable(),
1007
- reasoning_effort: z.string().nullable(),
1008
- fast: z.boolean().nullable().optional().describe("切り替えた後の、席のfastの状態。Aitermが確かめた事の無い席(前の版が起こした席)はnull"),
1009
- },
1010
- }, async ({ session_id, model, reasoning_effort, fast }) => {
1010
+ outputSchema: configurationToolOutputSchema,
1011
+ }, async ({ action, request, session_id, model, reasoning_effort, fast }) => {
1011
1012
  try {
1013
+ if (action === "reconcile") {
1014
+ if (!request || model != null || reasoning_effort != null || fast != null)
1015
+ throw new Error("CONFIGURATION_RECONCILE_INVALID: request required; settings forbidden");
1016
+ const result = reconcileConfigurationRequest({ ...request, session_id });
1017
+ return { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: { ...result } };
1018
+ }
1019
+ if (request) {
1020
+ const tracked = await applyConfigurationRequest({ ...request, session_id }, { model, reasoning_effort, fast }, () => core.configureAgent(session_id, { model, reasoning_effort, fast }, request.launch_id));
1021
+ return { content: [{ type: "text", text: tracked.error?.message ?? JSON.stringify(tracked.receipt) }],
1022
+ structuredContent: { ...tracked.receipt }, ...(tracked.error ? { isError: true } : {}) };
1023
+ }
1012
1024
  const result = await core.configureAgent(session_id, { model, reasoning_effort, fast });
1013
1025
  return {
1014
1026
  content: [{ type: "text", text: JSON.stringify(result) }],
@@ -156,10 +156,37 @@ export function psmuxVersionSupported(output) {
156
156
  }
157
157
  let winPsmuxOk = false;
158
158
  let winPsmuxVersion = null;
159
- export function ensureWinPsmux(observe = true) {
159
+ export const PTY_DIAGNOSTIC_TIMEOUT_MS = 5000;
160
+ export class PtyDiagnosticError extends Error {
161
+ reasonCode;
162
+ constructor(reasonCode) {
163
+ super("PTY diagnostic unavailable");
164
+ this.reasonCode = reasonCode;
165
+ }
166
+ }
167
+ function diagnosticSpawnOptions(deadline) {
168
+ if (deadline === undefined)
169
+ return {};
170
+ const remaining = Math.ceil(deadline - performance.now());
171
+ if (remaining <= 0)
172
+ throw new PtyDiagnosticError("timeout");
173
+ return { timeout: remaining, killSignal: "SIGKILL", maxBuffer: 1024 * 1024 };
174
+ }
175
+ function diagnosticSpawnFailure(result, deadline, dependency = false) {
176
+ if (deadline === undefined)
177
+ return;
178
+ const code = result.error?.code;
179
+ const reason = code === "ETIMEDOUT" ? "timeout" : code === "ENOBUFS" ? "output_limit"
180
+ : code === "EACCES" || code === "EPERM" ? "permission_denied" : code === "ENOENT" ? "dependency_unavailable"
181
+ : result.error ? "native_failure" : result.signal ? "signal" : dependency && result.status !== 0 ? "dependency_unavailable" : null;
182
+ if (reason)
183
+ throw new PtyDiagnosticError(reason);
184
+ }
185
+ export function ensureWinPsmux(observe = true, deadline) {
160
186
  if (winPsmuxOk)
161
187
  return;
162
- const r = spawnSync(psmuxBin(), ["-V"], { encoding: "utf8", timeout: 10000 });
188
+ const r = spawnSync(psmuxBin(), ["-V"], { encoding: "utf8", timeout: 10000, ...diagnosticSpawnOptions(deadline) });
189
+ diagnosticSpawnFailure(r, deadline, true);
163
190
  if (r.error) {
164
191
  const code = r.error.code;
165
192
  if (code === "ENOENT")
@@ -168,8 +195,11 @@ export function ensureWinPsmux(observe = true) {
168
195
  }
169
196
  if (r.status !== 0)
170
197
  ptyDependencyError("psmux -V が失敗しました。`psmux -V` が通るか確認してください。", observe);
171
- if (!psmuxVersionSupported(r.stdout ?? ""))
198
+ if (!psmuxVersionSupported(r.stdout ?? "")) {
199
+ if (deadline !== undefined)
200
+ throw new PtyDiagnosticError("dependency_unavailable");
172
201
  ptyDependencyError("psmux 3.3.8以上が必要です。winget upgrade --id marlocarlo.psmux --source winget で更新してください。", observe);
202
+ }
173
203
  winPsmuxVersion = /^psmux (\d+\.\d+\.\d+)(?:\s|$)/mu.exec(r.stdout ?? "")?.[1] ?? null;
174
204
  winPsmuxOk = true;
175
205
  }
@@ -304,18 +334,21 @@ function tmuxMissingMessage() {
304
334
  // 解決順: AITERM_TMUX(明示指定)→ PATH 上の tmux → Homebrew 既定パス。一度だけ実行しキャッシュする。
305
335
  // 見つからなければ tmuxMissingMessage で投げる(黙ってフォールバックせず、原因が見えるようにする)。
306
336
  let tmuxBin = null;
307
- export function resolveTmux(observe = true) {
337
+ export function resolveTmux(observe = true, deadline) {
308
338
  if (tmuxBin)
309
339
  return tmuxBin;
310
340
  const override = process.env.AITERM_TMUX;
311
341
  if (override) {
312
- const r = spawnSync(override, ["-V"], { encoding: "utf8", timeout: 5000 });
342
+ const r = spawnSync(override, ["-V"], { encoding: "utf8", timeout: 5000, ...diagnosticSpawnOptions(deadline) });
343
+ diagnosticSpawnFailure(r, deadline, true);
313
344
  if (!r.error && r.status === 0)
314
345
  return (tmuxBin = override);
315
346
  ptyDependencyError(`AITERM_TMUX に指定された tmux を起動できません: ${override}(\`${override} -V\` が通りません)`, observe);
316
347
  }
317
348
  // CLI/開発時は PATH 上の tmux をそのまま使う(最優先)。
318
- const onPath = spawnSync("tmux", ["-V"], { encoding: "utf8", timeout: 5000 });
349
+ const onPath = spawnSync("tmux", ["-V"], { encoding: "utf8", timeout: 5000, ...diagnosticSpawnOptions(deadline) });
350
+ if (onPath.signal || ["ETIMEDOUT", "ENOBUFS"].includes(onPath.error?.code ?? ""))
351
+ diagnosticSpawnFailure(onPath, deadline);
319
352
  if (!onPath.error && onPath.status === 0)
320
353
  return (tmuxBin = "tmux");
321
354
  // GUI 起動などで PATH に Homebrew の bin が無い場合、既定の場所を探す。
@@ -323,13 +356,15 @@ export function resolveTmux(observe = true) {
323
356
  for (const cand of ["/opt/homebrew/bin/tmux", "/usr/local/bin/tmux"]) {
324
357
  try {
325
358
  fs.accessSync(cand, fs.constants.X_OK);
326
- console.error(`aiterm: tmux が PATH 上に無いため ${cand} を使用します`);
359
+ if (deadline === undefined)
360
+ console.error(`aiterm: tmux が PATH 上に無いため ${cand} を使用します`);
327
361
  return (tmuxBin = cand);
328
362
  }
329
363
  catch {
330
364
  /* 次の候補へ */
331
365
  }
332
366
  }
367
+ diagnosticSpawnFailure(onPath, deadline, true);
333
368
  ptyDependencyError(tmuxMissingMessage(), observe);
334
369
  }
335
370
  // tmux は locale が C/POSIX/未設定だと UTF-8 を扱えない: server は send-keys/paste のマルチバイト
@@ -352,7 +387,7 @@ export function tmuxCommandWithInput(observe, input, ...args) {
352
387
  }
353
388
  // session は、新しい session を作る呼び出しの時だけ渡す client の環境(POSIX のみ)。server を起こし得るのは
354
389
  // この呼び出しだけなので、空 config の指定と macOS の gui domain での起動もここに限る。
355
- function runTmux(observe, input, args, session) {
390
+ function runTmux(observe, input, args, session, deadline) {
356
391
  // Authorize the logical/native session before routing it to its pinned pane.
357
392
  args = nativeSessionArgs(guardTmuxExecution(args));
358
393
  args = nativeConditionalArgs(args);
@@ -360,19 +395,20 @@ function runTmux(observe, input, args, session) {
360
395
  // 頭打ちになり stdout が切れる/空になる。Python の subprocess.run は無制限だったので 64MiB へ広げる。
361
396
  // Windows は tmux CLI 互換の native psmux を -L namespace 隔離で叩く(WSL 非依存)。
362
397
  let r;
363
- const spawnOpts = { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, input, env: session ?? tmuxSpawnEnv() };
398
+ const spawnOpts = () => ({ encoding: "utf8", maxBuffer: 64 * 1024 * 1024, input, env: session ?? tmuxSpawnEnv(), ...diagnosticSpawnOptions(deadline) });
364
399
  if (isWin) {
365
- ensureWinPsmux(observe);
366
- r = spawnSync(psmuxBin(), ["-L", WIN_NS, ...args], spawnOpts);
400
+ ensureWinPsmux(observe, deadline);
401
+ r = spawnSync(psmuxBin(), ["-L", WIN_NS, ...args], spawnOpts());
367
402
  }
368
403
  else {
369
404
  // resolveTmux() は tmux を解決できなければ明確な AitermError を投げる(POSIX 版の事前確認)。
370
- const bin = resolveTmux(observe);
405
+ const bin = resolveTmux(observe, deadline);
371
406
  // -f は tmux 本体の引数で、server を起こす時にだけ読まれる(new-session の -f は別物で、config を指さない)。
372
407
  const argv = session ? ["-f", TMUX_EMPTY_CONFIG, "-S", SOCK, ...args] : ["-S", SOCK, ...args];
373
408
  r = (session && macGuiServerWanted(bin) && startTmuxInMacGui(bin, argv, session))
374
- || spawnSync(bin, argv, spawnOpts);
409
+ || spawnSync(bin, argv, spawnOpts());
375
410
  }
411
+ diagnosticSpawnFailure(r, deadline);
376
412
  // ENOBUFS(出力が 64MiB 超)を「code=1 の失敗」へ握り潰すと部分/空 stdout を正常扱いしてしまう。区別して投げる。
377
413
  // EXPECTED-FAILURE: 外部システム境界(tmux 出力過大)
378
414
  if (r.error && r.error.code === "ENOBUFS") {
@@ -391,6 +427,10 @@ function runTmux(observe, input, args, session) {
391
427
  verifyNativeTarget(native);
392
428
  return { code: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
393
429
  }
430
+ /** One read-only probe; resolution and listing consume the same subprocess budget. */
431
+ export function readOnlyTmuxList() {
432
+ return runTmux(false, undefined, ["list-sessions", "-F", "#{session_name}"], undefined, performance.now() + PTY_DIAGNOSTIC_TIMEOUT_MS);
433
+ }
394
434
  // macOS の login keychain は GUI(Aqua)の security session からしか読めない。SSH 等から立てた
395
435
  // tmux server の pane では Claude Code・Cursor CLI がログイン済みでも未ログイン扱いになる。
396
436
  // server が無く、自分が Aqua の外にいて、同じ利用者が画面にログインしている時だけ、最初の
package/docs/DESIGN.md CHANGED
@@ -184,6 +184,8 @@ Codex model-only configuration reads the native current effort before navigating
184
184
 
185
185
  4harness共通の`agent_configure`は、変更を発行し得る境界に達したかを要求内で保持する。失敗は`aiterm.agent-configure-error.v1`の`not_applied/not_started`又は`outcome_unknown/possible`で返し、後者には部分適用を含む。これは要求単位の保守的な分類で、以前の実設定や他要求の状態は証明しない。成功型は維持し、Codexの完了は指定ID・effortに一致する新規native通知を確認する。別modelの通知や残画面では成功にしない。
186
186
 
187
+ opt-inの原要求receiptと読取専用reconcileは[公開契約](configure-reconcile.md)・[設定図](https://github.com/kitepon/aiterm-mcp/blob/main/docs/architecture/model-configuration.md)へ接続する。初回のUUID/期待launch/digestを耐久保存し、同IDを再適用しない。handlerとfinallyの終端、native作用発行、現在設定観測は別に返す。native入力発行後は成功してもlater_effect=unconfirmed、現在設定はunsupported。この局所記録を全execution graphへ結合しない。directory sync未対応のWindowsとtracked remoteは作用前拒否、legacy configureは維持。
188
+
187
189
  Codex v1のactive goalは設定替えの間だけ一時停止する。`configure-goal.ts`がpause→nativeの番終了待ち→既存の設定替え→resumeを持つ。coreは同じlaunch/threadへの束縛と番終了記録を供給し、待機中は送信lockを持たない。pause/resumeは既存のCLI goal adapterで一度だけ発行し、mutation直前のnative readbackが比較元から変われば発行しない。設定替え失敗でも自分のpauseの復元を試み、別goalや変更されたgoalは再開しない。公開schemaは維持し、設定とgoalの不確定な結果はエラー本文で併記する(ADR 0137)。
188
190
 
189
191
  無活動判定用の時刻は、起動世代ごとのactivity.jsonlに追記する。agent-activity.tsがlast_input_atとlast_turn_end_atを返し、metadata全体を書き戻す処理とは独立する。親からの初手・dispatch・steerのPTY書込み境界と、Claude Stop/既存のnative完了観測だけが記録する。同じ番の完了を繰り返し読んでも起点を更新せず、途中出力・画面描画・設定命令では更新しない。履歴欠測と破損は未知として扱い、時刻記録失敗で既に得た完了結果を失わせない。Claude/Codexの3OS実会話復帰・公開論理席とconsumer受入に基づき、通常起動では自動休止を有効にする(ADR 0138)。node:testのfixtureはcontrollerを明示駆動し、無人timerを作らない。
@@ -585,3 +587,5 @@ Grok clear uses the existing host-origin contract and only a fresh UserPaused/Id
585
587
  休止の直前には、保存templateではなく元nativeのmodel/effort/fast表示を、同じ送信admissionとcreate receiptで確認する。harnesses/idle-settings.tsが保存しないnative表示の確認/取消しを所有し、coreは既存の入力とready確認を供給する。確認後の画面やattach履歴が最初のsignal前に変われば停止しない。未対応表示や現在設定の欠測はskipし、native表示用の命令を活動時刻へ数えない。詳細と現時点の受入限界はADR0138。
586
588
 
587
589
  Claude resume preserves the original CLAUDE_CONFIG_DIR selector (including unset) separately from its resolved path; incomplete old selectors remain unavailable. Security notes block startup even when an older shell marker remains above them.
590
+
591
+ Factory diagnostics keep the v1 default projection and the separate parent-hook text. Optional format v2 adds fixed PTY reason codes and the 5000ms subprocess budget. Native resolution and the single scoped listing consume one deadline; unknown/permission/timeout failures do not prove absence. This uses ordinary native reads and no execution graph, PTY creation or credentials. The subprocess budget is not a hard real-time bound on OS filesystem calls or the complete diagnostics response.
@@ -0,0 +1,61 @@
1
+ # Request-bound configuration and reconciliation
2
+
3
+ This contract applies only when the new request fields are supplied to `agent_configure`. Existing calls keep their existing result and error shapes. It cannot recover an old request whose original ID or launch was not retained.
4
+
5
+ Before the **first** call, the consumer durably saves the original settings, a UUID `id`, the observed target `launch_id`, and the request `digest`. It must first inspect the exact connected server's tool schema: `agent_configure` must advertise `action` with `apply`/`reconcile`, the `request` object below, and output schema `aiterm.agent-configure-request-result.v1`. Check the approved package/version on that same connection. Do not send a tracked apply to an older server: older schemas can silently discard unknown fields and apply without tracking. Missing capability means local not-issued; never fall back to an untracked call. The ID is not an authorization credential; existing management access remains required.
6
+
7
+ ```json
8
+ {
9
+ "action": "apply",
10
+ "session_id": "original-seat",
11
+ "request": {
12
+ "id": "ea1dbfa0-c370-4dd7-a209-21325b1be447",
13
+ "launch_id": "11111111111111111111111111111111",
14
+ "digest": "<64 lowercase hexadecimal characters>"
15
+ },
16
+ "model": "requested-model",
17
+ "reasoning_effort": "high",
18
+ "fast": false
19
+ }
20
+ ```
21
+
22
+ The digest is SHA256 of UTF-8 `JSON.stringify({model,reasoning_effort,fast})`, with keys in that order. Model/effort are trimmed strings or null for missing/null/empty; fast is boolean or null for missing/null. Values are limited to 512 characters. `configurationRequestDigest` in `dist/configure-request.js` implements this exact canonicalization. Persist this binding before issuing the RPC; do not replace it after a timeout. JSON-RPC IDs alone do not identify a request across connections.
23
+
24
+ Tracked apply exclusively claims `configuration-requests/<id>/receipt.json` in the product state root, then uses the existing file-and-directory-sync checkpoint before invoking the original configuration handler. Each first native mutation marks possible and syncs before input. Failure poisons that local request; neither subsequent cleanup nor a late continuation can issue native input through it. The completed handler, including its finally/goal restoration, is recorded before returning. An existing ID only reads the original record and never invokes configuration again; a changed session/launch/digest is a conflict. A partially created claim is unavailable and cannot replay. Receipts remain until the product state is explicitly disposed; retaining them prevents late duplicate requests from becoming new work. They contain settings and safe result fields, not prompts, credentials, screen output or raw exception text. No general execution graph is created.
25
+
26
+ Tracked apply currently requires POSIX file/directory sync. Native Windows returns unsupported before applying; legacy `agent_configure` is unchanged. Tracked remote calls are refused before any SSH connection, since forwarding to an old server could silently remove the request binding. Use the exact local consumer connection on the target runtime. This limitation does not authorize replacing a running consumer or changing its connection.
27
+
28
+ To reconcile, send only the original binding:
29
+
30
+ ```json
31
+ {
32
+ "action": "reconcile",
33
+ "session_id": "original-seat",
34
+ "request": {"id":"ea1dbfa0-c370-4dd7-a209-21325b1be447","launch_id":"11111111111111111111111111111111","digest":"<original digest>"}
35
+ }
36
+ ```
37
+
38
+ Model, effort and fast are forbidden in reconcile. The reader does not create a state root, resume work, send UI keys, invoke vendor commands, register a participant or modify a receipt. It may read across a new MCP connection to the same approved state scope. It returns `aiterm.agent-configure-request-result.v1`:
39
+
40
+ | Field | Meaning |
41
+ | --- | --- |
42
+ | `binding` | Exact original ID, session, launch and digest; never a current/latest guess |
43
+ | `request_state` | `terminal`, `pending_or_unknown`, `not_recorded`, or `unavailable` |
44
+ | `outcome` | Historical `applied`, `not_applied`, or `outcome_unknown`; not a current settings snapshot |
45
+ | `terminal_at` | Saved handler/finally completion time, otherwise null |
46
+ | `result` | Original successful configure result, otherwise null; its model/effort retain their existing requested-value semantics |
47
+ | `later_effect` | `excluded` only for saved terminal requests with no native mutation issued; otherwise `unconfirmed` |
48
+ | `current` | `{ "availability": "unsupported" }`; no UI preview is performed |
49
+ | `observed_at` | Time this receipt was read |
50
+
51
+ Any native mutation, including menu preparation, keeps `later_effect=unconfirmed` even if the handler succeeds or the visible model matches. A native send acknowledgment does not prove input consumption. Pending records remain uncertain after process exit or restart. Missing/corrupt records are not proof of non-admission: an original packet could still arrive. Receipt loss, elapsed time, a completed goal/turn or a new current launch must not authorize replay or uncertainty removal. The local terminal guard prevents new Aiterm continuations; it cannot retract already issued native input. Removing product state also removes duplicate protection and must never be presented as reconciliation.
52
+
53
+ For a consumer to consider its own fence, the local uncertainty/version and original binding must still match, and native `request_state=terminal` plus `later_effect=excluded` must both be present. Keep the outcome and desired/current differences separate. This product receipt does not itself delete consumer flags or authorize a message, restart, stop or reconfiguration. `later_effect=unconfirmed` is not a request to retry.
54
+
55
+ ## Existing incidents and explicit recovery
56
+
57
+ There is no existing public read-only operation that recovers a configuration request whose ID/launch were never retained. This feature does not assign retrospective IDs or infer them from current settings. A consumer's `BOT_SESSION_UNCONFIRMED` remains its own safety fence.
58
+
59
+ If the original operation cannot be conclusively recovered, replacing the session is a separate explicit operation: the owner must first decide when active work/goal may be interrupted, which transcript/worktree/metadata to retain, who controls the old CLI and late requests, and how a new CLI resumes saved work. A close/restart can interrupt a live goal and lose uncommitted in-memory CLI context. `pty_close` is destructive to product session state and ordinary log/read positions; it is not a log-preserving recovery and must not be proposed as if it retained everything. A normal vendor quit can preserve vendor history but ends the running CLI; it also does not, by itself, fence an uncertain management request or repair consumer bookkeeping. An owner-approved recovery must confirm old request/connection quiescence and respect the consumer's own recovery contract before reusing a name. No such real-seat operation is part of this release.
60
+
61
+ The implementation/ownership diagram is [model configuration](https://github.com/kitepon/aiterm-mcp/blob/main/docs/architecture/model-configuration.md). Direct tests cover original binding, pre-input durable admission, duplicate/late requests, corrupt/missing receipts, process exit, checkpoint refusal, post-terminal continuation refusal, ordinary MCP errors and a fake Codex on an isolated native PTY. They do not prove real provider behavior or recovery of an existing incident.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.63.3",
3
+ "version": "0.63.6",
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": [
@@ -58,6 +58,7 @@
58
58
  "docs/00_overview.md",
59
59
  "docs/DESIGN.md",
60
60
  "docs/RELEASE.md",
61
+ "docs/configure-reconcile.md",
61
62
  "LICENSE"
62
63
  ],
63
64
  "engines": {