aiterm-mcp 0.63.5 → 0.63.7
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 +11 -1
- package/README.ja.md +9 -1
- package/README.md +7 -1
- package/dist/aiterm-wait-cli.js +13 -4
- package/dist/claude-operation-marker.js +16 -2
- package/dist/claude-stop-hook.js +4 -3
- package/dist/core.js +163 -39
- package/dist/execution-interruption.js +1 -1
- package/dist/harnesses/claude.js +13 -2
- package/dist/harnesses/codex.js +29 -2
- package/dist/index.js +29 -21
- package/dist/parent-delivery-record.js +18 -1
- package/dist/parent-delivery.js +14 -1
- package/dist/remote.js +8 -4
- package/dist/steer-follow.js +11 -6
- package/dist/tmux-runtime.js +53 -13
- package/docs/DESIGN.md +2 -0
- package/package.json +1 -1
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.7] - 2026-11-03
|
|
11
|
+
|
|
12
|
+
- Preserve capacity, usage-limit and transient failure classifications through wait, steer and parent delivery without treating an error as permission to replay input. Claude dispatches retain an input ID and the pre-submit transcript boundary so failures written before the waiter starts are observed. Bound waiters reject another input's completion; legacy outcomes and exit codes are unchanged.
|
|
13
|
+
|
|
14
|
+
## [0.63.6] - 2026-11-03
|
|
15
|
+
|
|
16
|
+
- 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.
|
|
17
|
+
|
|
10
18
|
## [0.63.5] - 2026-11-03
|
|
11
19
|
|
|
12
20
|
- 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.
|
|
@@ -3028,7 +3036,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
|
|
|
3028
3036
|
`ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
|
|
3029
3037
|
provenance.
|
|
3030
3038
|
|
|
3031
|
-
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.
|
|
3039
|
+
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.7...HEAD
|
|
3040
|
+
[0.63.7]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.6...v0.63.7
|
|
3041
|
+
[0.63.6]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.5...v0.63.6
|
|
3032
3042
|
[0.63.5]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.3...v0.63.5
|
|
3033
3043
|
[0.63.3]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.2...v0.63.3
|
|
3034
3044
|
[0.63.2]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.1...v0.63.2
|
package/README.ja.md
CHANGED
|
@@ -8,6 +8,12 @@
|
|
|
8
8
|
|
|
9
9
|
# Aiterm
|
|
10
10
|
|
|
11
|
+
Codex・Claudeの失敗した番では、既存の待機結果へ`failure`を追加します。`category`は`capacity`/`rate_limited`/`transient`/`other`、`execution`は記録に作業があれば`started`、分からなければ`unknown`です。providerの拒否だけで、それ以前の道具が未実行だったとは判断しません。`terminal`は観測した番の終了だけを示し、`future_effects:"unknown"`は待ち行列・自動再試行・ほかの送信元の作用を未確認のまま残します。
|
|
12
|
+
|
|
13
|
+
Claudeの送信・初手つき起動の返りには`input_id`が付きます。返りの`wait_process`を保持するか、元のsession・launch・cursorと一緒に`aiterm-wait --input <id>`へ渡してください。APIエラー直後は匿名入力のcursorが同じになることがありますが、古い入力を次の番の成功へ結び直しません。送信前の会話記録の位置から読むため、待機開始前のAPIエラーも拾います。この境界はAitermの入力観測との対応であり、nativeによる本文受理の証明ではありません。旧記録や欠測を新しい証拠へ変換しません。
|
|
14
|
+
|
|
15
|
+
分類は親配送の保存・返りにも残ります。Aitermは元本文を自動再送しません。呼出元は通常の停止・設定の条件を守り、残された会話や保存した引継ぎから未了の仕事を続けられます。
|
|
16
|
+
|
|
11
17
|
[](https://github.com/kitepon/aiterm-mcp/actions/workflows/ci.yml)
|
|
12
18
|
[](https://www.npmjs.com/package/aiterm-mcp)
|
|
13
19
|
[](https://www.npmjs.com/package/aiterm-mcp)
|
|
@@ -209,7 +215,7 @@ runtime-error store は canonical dotagents config の `collection.enabled: true
|
|
|
209
215
|
場合だけ収集し、既定OFF、network送信は行いません。tag起点CIのnpm provenance(OIDC Trusted
|
|
210
216
|
Publishing)で公開し、GitHub Release が Official MCP Registry を再登録します。
|
|
211
217
|
|
|
212
|
-
**状態:** 開発継続中 · 現行公開版 **v0.63.
|
|
218
|
+
**状態:** 開発継続中 · 現行公開版 **v0.63.7** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
|
|
213
219
|
|
|
214
220
|
### 更新と巻き戻し
|
|
215
221
|
|
|
@@ -619,6 +625,8 @@ Claudeの相関済み承認は既存の`claude_approval`を使う。
|
|
|
619
625
|
|
|
620
626
|
`diagnostics` は PTY やエージェントを起動しない。パッケージ版、MCP 呼出 readiness、read-only な PTY 一覧要約、bounded runtime-error-store status、任意 vendor launcher の可用性だけを返す。path・環境値・認証情報・コマンド本文・PTY 出力・raw log は意図的に返さない。通常未設定の任意依存は `not_applicable`、安全に確定できない状態は `unverified` と表す。
|
|
621
627
|
|
|
628
|
+
`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保証ではない。
|
|
629
|
+
|
|
622
630
|
結果の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
631
|
|
|
624
632
|
### ローカル runtime error snapshot
|
package/README.md
CHANGED
|
@@ -227,7 +227,7 @@ collection is off by default and performs no network I/O. It ships via
|
|
|
227
227
|
tag-triggered CI with npm provenance (OIDC Trusted Publishing); the GitHub
|
|
228
228
|
Release re-registers the Official MCP Registry entry.
|
|
229
229
|
|
|
230
|
-
**Status:** actively maintained · current public release **v0.63.
|
|
230
|
+
**Status:** actively maintained · current public release **v0.63.7** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
|
|
231
231
|
|
|
232
232
|
### Update and rollback
|
|
233
233
|
|
|
@@ -268,6 +268,10 @@ Cursorが誤りでturnを終えた時(記録の`turn_ended`が`status: "error"
|
|
|
268
268
|
|
|
269
269
|
## Two ways to use it
|
|
270
270
|
|
|
271
|
+
Failed Codex and Claude turns may add `failure` to the existing wait result. Its `category` is `capacity`, `rate_limited`, `transient` or `other`; `execution` reports observed work as `started` or leaves it `unknown`. A provider rejection never proves that earlier tools did not run. `terminal` refers only to the observed turn; `future_effects:"unknown"` preserves uncertainty about queued input, retries and other producers. No input is automatically replayed by Aiterm.
|
|
272
|
+
|
|
273
|
+
Claude dispatch and prompt-launch receipts include `input_id`. Keep the receipt's `wait_process`, or pass that ID to `aiterm-wait --input <id> --cursor <original cursor>` with the original session and launch. This prevents a later anonymous turn at the same event cursor from becoming the old request's result. Its saved transcript boundary also catches an API error written before the waiter starts. The failure boundary identifies the Aiterm input observation, not native input acceptance. Missing or legacy evidence is not upgraded. Parent receipts and notices preserve the classification. A caller can continue unfinished work from the retained conversation or saved handoff after applying its normal stop and configuration conditions; replaying the original message is a separate decision.
|
|
274
|
+
|
|
271
275
|
Grok can finish its current turn while `pty_send` is submitting input. Aiterm correlates the newly appended full user message with the native turn number and returns `agent_dispatch` for a proven new turn, without sending again. `STEER_NOT_QUEUED` and `STEER_STILL_QUEUED` preserve `isError:true` and their existing text prefix; `structuredContent` adds `aiterm.agent-send-error.v1`, a string `code`, `outcome:"outcome_unknown"`, `effect:"possible"`, and the original session/launch. A Grok observation handle is returned only when its pre-input record was saved; unavailable handles are null. Do not resend unknown input. Its waiter remains pending until the input's native acceptance is proven and cannot use the preceding turn's completion. Cursor errors retain null recovery handles until native acceptance can be proven.
|
|
272
276
|
|
|
273
277
|
### 1. Drive SSH, containers, and REPLs in one persistent terminal — the primitive
|
|
@@ -661,6 +665,8 @@ continue to use `claude_approval`.
|
|
|
661
665
|
|
|
662
666
|
`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
667
|
|
|
668
|
+
`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.
|
|
669
|
+
|
|
664
670
|
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
671
|
|
|
666
672
|
### Local runtime error snapshot
|
package/dist/aiterm-wait-cli.js
CHANGED
|
@@ -12,7 +12,7 @@ import { AitermError, detectAgentRateLimit, observeAgentDone } from "./core.js";
|
|
|
12
12
|
const SESSION_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
13
13
|
const OPERATION_RE = /^sha256:[0-9a-f]{64}$/;
|
|
14
14
|
const STEER_RE = /^[0-9a-f]{16}$/;
|
|
15
|
-
const USAGE = "usage: aiterm-wait --session <name> [--cursor <event_cursor>] [--operation sha256:<64hex>] [--timeout <sec>]" +
|
|
15
|
+
const USAGE = "usage: aiterm-wait --session <name> [--cursor <event_cursor>] [--input <32hex>] [--operation sha256:<64hex>] [--timeout <sec>]" +
|
|
16
16
|
"(--timeout 0 は待たずに一度だけ観測する照会で、未完了は outcome=running / exit 5)";
|
|
17
17
|
export function parseArgs(argv) {
|
|
18
18
|
let session = null;
|
|
@@ -21,14 +21,20 @@ export function parseArgs(argv) {
|
|
|
21
21
|
let cursor = null;
|
|
22
22
|
let steer = null;
|
|
23
23
|
let expectedLaunchId;
|
|
24
|
+
let inputId;
|
|
24
25
|
for (let i = 0; i < argv.length; i++) {
|
|
25
26
|
const a = argv[i];
|
|
26
|
-
if (a === "--session" || a === "--operation" || a === "--timeout" || a === "--cursor" || a === "--steer" || a === "--launch") {
|
|
27
|
+
if (a === "--session" || a === "--operation" || a === "--timeout" || a === "--cursor" || a === "--steer" || a === "--launch" || a === "--input") {
|
|
27
28
|
const v = argv[i + 1];
|
|
28
29
|
if (v === undefined)
|
|
29
30
|
throw new Error(`${a} に値がありません。${USAGE}`);
|
|
30
31
|
i++;
|
|
31
|
-
if (a === "--
|
|
32
|
+
if (a === "--input") {
|
|
33
|
+
if (inputId !== undefined || !/^[0-9a-f]{32}$/.test(v))
|
|
34
|
+
throw new Error(`--input が不正又は重複しています。${USAGE}`);
|
|
35
|
+
inputId = v;
|
|
36
|
+
}
|
|
37
|
+
else if (a === "--launch") {
|
|
32
38
|
if (expectedLaunchId !== undefined || !/^[0-9a-f]{32}$/.test(v))
|
|
33
39
|
throw new Error(`--launch が不正又は重複しています。${USAGE}`);
|
|
34
40
|
expectedLaunchId = v;
|
|
@@ -79,7 +85,9 @@ export function parseArgs(argv) {
|
|
|
79
85
|
throw new Error(`--session は必須です。${USAGE}`);
|
|
80
86
|
if (steer !== null && operationId !== null)
|
|
81
87
|
throw new Error(`--steer は --operation と併用できません。${USAGE}`);
|
|
82
|
-
|
|
88
|
+
if (inputId && (steer !== null || cursor === null))
|
|
89
|
+
throw new Error(`--input requires --cursor without --steer. ${USAGE}`);
|
|
90
|
+
return { session, operationId, timeout: timeout ?? 600, cursor, steer, ...(expectedLaunchId ? { expectedLaunchId } : {}), ...(inputId ? { inputId } : {}) };
|
|
83
91
|
}
|
|
84
92
|
function emit(value) {
|
|
85
93
|
process.stdout.write(JSON.stringify(value) + "\n");
|
|
@@ -106,6 +114,7 @@ export async function main(argv) {
|
|
|
106
114
|
cursor: cmd.cursor,
|
|
107
115
|
steer: cmd.steer,
|
|
108
116
|
expected_launch_id: cmd.expectedLaunchId,
|
|
117
|
+
input_id: cmd.inputId,
|
|
109
118
|
});
|
|
110
119
|
}
|
|
111
120
|
catch (e) {
|
|
@@ -4,8 +4,22 @@ export function parseClaudeOperationMarker(value) {
|
|
|
4
4
|
const legacy = keys === "operation_id,schema" && row.schema === "aiterm.claude-operation-marker.v1";
|
|
5
5
|
const bound = keys === "event_cursor,operation_id,schema" && row.schema === "aiterm.claude-operation-marker.v2"
|
|
6
6
|
&& Number.isSafeInteger(row.event_cursor) && row.event_cursor >= 0;
|
|
7
|
-
|
|
7
|
+
const captured = keys === "event_cursor,input_id,operation_id,schema,transcript" && row.schema === "aiterm.claude-operation-marker.v3"
|
|
8
|
+
&& Number.isSafeInteger(row.event_cursor) && row.event_cursor >= 0
|
|
9
|
+
&& typeof row.input_id === "string" && /^[a-f0-9]{32}$/.test(row.input_id);
|
|
10
|
+
if (captured && row.transcript !== null) {
|
|
11
|
+
const value = row.transcript;
|
|
12
|
+
if (!value || typeof value !== "object" || Array.isArray(value)
|
|
13
|
+
|| Object.keys(value).sort().join(",") !== "cursor,device,inode,session_id"
|
|
14
|
+
|| typeof value.session_id !== "string" || !/^[A-Za-z0-9_-]{1,256}$/.test(value.session_id)
|
|
15
|
+
|| !Number.isSafeInteger(value.cursor) || value.cursor < 0
|
|
16
|
+
|| ![value.device, value.inode].every(n => n === null || (typeof n === "string" && /^\d{1,30}$/.test(n)))
|
|
17
|
+
|| ((value.device === null) !== (value.inode === null)) || (value.device === null && value.cursor !== 0))
|
|
18
|
+
throw new Error("Claude transcript boundaryが不正です");
|
|
19
|
+
}
|
|
20
|
+
if ((!legacy && !bound && !captured) || (row.operation_id !== null
|
|
8
21
|
&& (typeof row.operation_id !== "string" || !/^sha256:[0-9a-f]{64}$/.test(row.operation_id))))
|
|
9
22
|
throw new Error("Claude operation markerが不正です");
|
|
10
|
-
return { operationId: row.operation_id, eventCursor: bound ? row.event_cursor : null
|
|
23
|
+
return { operationId: row.operation_id, eventCursor: bound || captured ? row.event_cursor : null,
|
|
24
|
+
...(captured ? { inputId: row.input_id, transcript: row.transcript } : {}) };
|
|
11
25
|
}
|
package/dist/claude-stop-hook.js
CHANGED
|
@@ -109,10 +109,10 @@ function readOperationMarker(file) {
|
|
|
109
109
|
}
|
|
110
110
|
const body = fs.readFileSync(fd, "utf8");
|
|
111
111
|
const value = JSON.parse(body);
|
|
112
|
-
//
|
|
113
|
-
//
|
|
112
|
+
// v1/v2 remain readable. The v3 input ID correlates this reservation;
|
|
113
|
+
// none of these markers proves native interruption or a producer fence.
|
|
114
114
|
const marker = parseClaudeOperationMarker(value);
|
|
115
|
-
return { operationId: marker.operationId, dev: st.dev, ino: st.ino };
|
|
115
|
+
return { operationId: marker.operationId, ...(marker.inputId ? { inputId: marker.inputId } : {}), dev: st.dev, ino: st.ino };
|
|
116
116
|
}
|
|
117
117
|
catch (error) {
|
|
118
118
|
fail(error instanceof Error ? error.message : String(error));
|
|
@@ -212,6 +212,7 @@ async function main() {
|
|
|
212
212
|
operation_id: operationId,
|
|
213
213
|
reason: "Stop",
|
|
214
214
|
done_status: "turn_done",
|
|
215
|
+
...(operationMarker?.inputId ? { input_id: operationMarker.inputId } : {}),
|
|
215
216
|
stop_hook_active: !!payload.stop_hook_active,
|
|
216
217
|
result_digest: resultDigest,
|
|
217
218
|
result_bytes: resultBytes,
|
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";
|
|
@@ -62,7 +62,7 @@ import { readFileOrNull, restoreJsonSetting, withUserConfigLock, restoreUserDefa
|
|
|
62
62
|
import { isDeepStrictEqual } from "node:util";
|
|
63
63
|
import { grokAuthPlan, grokAuthStatus, grokAuthPane, GROK_MODEL_DEFAULTS, realGrokHome, resolveAndValidateGrokAuth, assertGrokModelAvailable, grokModelChoices, grokModelFromFooter, grokFooterModelName, grokModelDefaultsFromBody, restoreGrokModelDefaults, grokEventsTranscript, grokSessionDirectory, latestGrokCompletion, grokTurnSettled, observeGrokDone, buildGrokAgentCmd, grokAgentArgv, grokLaunchNote, grokEnvTokens, grokEnvEntries, grokTuiReady, grokPaneObservation, GROK_INTERRUPT_KEY, grokRateLimitDialog, grokPromptAwaitingAccept, grokUnacceptedPromptRestored, grokStartupAction, grokFooterHasConfiguration, grokTranscriptText, createGrokAgentMetadata, } from "./harnesses/grok.js";
|
|
64
64
|
import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexCompletedTurnId, captureCodexRecoveryProof, captureCodexResumeProof, readCodexResumeProof, codexResumeProofDigest, codexRootTranscript, codexRunningTurn, codexInterruptionRecord, observeCodexDone, buildCodexAgentCmd, codexAgentArgv, codexResumeArgv, codexLaunchNote, codexPaneObservation, CODEX_INTERRUPT_KEY, codexHelperProcess, codexRateLimitModelSwitchDialog, codexApprovalDialog, codexStartupAction, codexModelChoice, codexEffortChoice, codexMoreReasoningChoice, codexTranscriptText, createCodexAgentMetadata, codexModelChoices, codexFastCommandOffered, codexFooterShowsFast, codexServiceTierNotices, restoreCodexDefaults, restoreCodexDefaultInFile, } from "./harnesses/codex.js";
|
|
65
|
-
import { claudeAuthPlan, claudeAuthStatus, claudeAuthPane, OPERATION_ID_RE, CLAUDE_RESULT_MAX_BYTES, CLAUDE_EFFORTS, agentClaudeOperationPath, agentClaudeApprovalReceiptPath, agentClaudeDispatchReceiptPath, validateOperationId, readClaudeResultText, assertClaudeAuthenticationReady, claudeModelChoices, claudeConfigDir, claudeFastIndicatorShown, claudeFastResult, buildClaudeAgentCmd, claudeAgentArgv, claudeResumeArgv, claudeLaunchNote, claudePaneObservation, CLAUDE_INTERRUPT_KEY, claudeUsageLimit, claudeLiveSelectMenu, claudeStartupAction, createClaudeAgentMetadata, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, } from "./harnesses/claude.js";
|
|
65
|
+
import { claudeAuthPlan, claudeAuthStatus, claudeAuthPane, OPERATION_ID_RE, CLAUDE_RESULT_MAX_BYTES, CLAUDE_EFFORTS, agentClaudeOperationPath, agentClaudeApprovalReceiptPath, agentClaudeDispatchReceiptPath, validateOperationId, readClaudeResultText, assertClaudeAuthenticationReady, claudeModelChoices, claudeConfigDir, claudeFastIndicatorShown, claudeFastResult, buildClaudeAgentCmd, claudeAgentArgv, claudeResumeArgv, claudeLaunchNote, claudePaneObservation, CLAUDE_INTERRUPT_KEY, claudeUsageLimit, claudeLiveSelectMenu, claudeStartupAction, createClaudeAgentMetadata, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, claudeFailureCategory, } from "./harnesses/claude.js";
|
|
66
66
|
import { cursorAuthPlan, cursorAuthStatus, cursorAuthPane, bindCursorTranscriptSession, cursorTurnBoundary, latestCursorCompletion, observeCursorDone, cursorTranscriptText, assertCursorAuthenticationReady, assertCursorModelAvailable, cursorModelChoices, cursorModelIsFastVariant, cursorFastParameter, cursorHeaderShowsFast, cursorPickerView, cursorEffortSelected, cursorParameterRows, cursorUserConfigPath, CURSOR_DEFAULT_MODEL_KEYS, realCursorHome, buildCursorAgentCmd, cursorAgentArgv, cursorPromptWithLineage, createCursorAgentMetadata, cursorLaunchNote, cursorEffortNavigation, cursorTuiReady, cursorPaneObservation, CURSOR_INTERRUPT_KEY, cursorPromptHooksRunning, cursorUsageLimit, CURSOR_SUBMIT_SEQUENCE, validateCursorModelEffort, } from "./harnesses/cursor.js";
|
|
67
67
|
import { interimFromNow, readInterimWords, recordInterimBoundary } from "./interim-words.js";
|
|
68
68
|
import { codexSeatTurn, grokSteerAcceptance, observeSteerDone, readSteerEntry, recordSteer } from "./steer-follow.js";
|
|
@@ -1210,12 +1210,13 @@ function observeManagedClaudeInterruption(point) {
|
|
|
1210
1210
|
};
|
|
1211
1211
|
try {
|
|
1212
1212
|
const before = { marker: identity(marker, false), receipt: receipt ? identity(receipt, true) : null };
|
|
1213
|
-
|
|
1213
|
+
const parsed = readClaudeOperationMarker(meta);
|
|
1214
|
+
if (!matchesClaudeInterruptionMarker(parsed, point))
|
|
1214
1215
|
throw new ExecutionError("EXECUTION_UNSUPPORTED");
|
|
1215
1216
|
const after = { marker: identity(marker, false), receipt: receipt ? identity(receipt, true) : null };
|
|
1216
1217
|
if (!isDeepStrictEqual(before, after))
|
|
1217
1218
|
throw new ExecutionError("EXECUTION_CONFLICT");
|
|
1218
|
-
return after;
|
|
1219
|
+
return { ...after, protocol: parsed?.inputId ? "aiterm.claude-operation-marker.v3" : "aiterm.claude-operation-marker.v2" };
|
|
1219
1220
|
}
|
|
1220
1221
|
catch (error) {
|
|
1221
1222
|
if (error instanceof ExecutionError)
|
|
@@ -1255,7 +1256,7 @@ function observeManagedClaudeInterruption(point) {
|
|
|
1255
1256
|
return { ...common, schema: "aiterm.claude-anonymous-interruption-observation.v1",
|
|
1256
1257
|
endpoint: { session_id: null, operation_marker: reference(after.files.marker), dispatch_receipt: null },
|
|
1257
1258
|
native_boundary: { type: "anonymous_turn_reserved", event_cursor: point.boundary.event_cursor },
|
|
1258
|
-
marker_protocol:
|
|
1259
|
+
marker_protocol: after.files.protocol, loaded_hook: "unconfirmed" };
|
|
1259
1260
|
return { ...common, schema: "aiterm.claude-managed-interruption-observation.v1",
|
|
1260
1261
|
endpoint: { session_id: null, operation_marker: reference(after.files.marker), dispatch_receipt: reference(after.files.receipt) },
|
|
1261
1262
|
native_boundary: { type: "managed_operation_reserved", operation_id: operation } };
|
|
@@ -2193,22 +2194,26 @@ export function agentSessionChildren() {
|
|
|
2193
2194
|
* session 名・前面コマンド・PTY 出力を診断応答へ持ち出さないため、factory が安全に readiness を
|
|
2194
2195
|
* 見られる。socket 不在は「セッション未設定」であって障害ではない。
|
|
2195
2196
|
*/
|
|
2196
|
-
export function readOnlyPtyListDiagnostic(runTmux =
|
|
2197
|
+
export function readOnlyPtyListDiagnostic(runTmux = readOnlyTmuxList, detailed = false) {
|
|
2198
|
+
const result = (status, session_count, reason_code) => detailed ? { status, session_count, reason_code } : { status, session_count };
|
|
2197
2199
|
try {
|
|
2198
2200
|
const r = runTmux("list-sessions", "-F", "#{session_name}");
|
|
2199
|
-
if (r.code === 0) {
|
|
2200
|
-
return
|
|
2201
|
+
if (r.code === 0 && r.stderr.trim() === "") {
|
|
2202
|
+
return result("ready", r.stdout.split(/\r?\n/).filter(Boolean).length, "listed");
|
|
2201
2203
|
}
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
if (/no server running|failed to connect/i.test(r.stderr)) {
|
|
2205
|
-
return { status: "not_applicable", session_count: null };
|
|
2204
|
+
if (absentExecutionServer(r)) {
|
|
2205
|
+
return result("not_applicable", null, "socket_absent");
|
|
2206
2206
|
}
|
|
2207
|
+
if (r.code === 1 && r.stdout.trim() === "" && [
|
|
2208
|
+
`error connecting to ${SOCK} (Permission denied)`, `failed to connect to ${SOCK}: Permission denied`,
|
|
2209
|
+
`error connecting to ${SOCK} (Operation not permitted)`,
|
|
2210
|
+
].includes(r.stderr.trim()))
|
|
2211
|
+
return result("unverified", null, "permission_denied");
|
|
2207
2212
|
}
|
|
2208
|
-
catch {
|
|
2209
|
-
|
|
2213
|
+
catch (error) {
|
|
2214
|
+
return result("unverified", null, error instanceof PtyDiagnosticError ? error.reasonCode : "native_failure");
|
|
2210
2215
|
}
|
|
2211
|
-
return
|
|
2216
|
+
return result("unverified", null, "native_failure");
|
|
2212
2217
|
}
|
|
2213
2218
|
/** 別processが待機中・送信中のsessionは閉じない。閉じる前の操作(下のClaude Codeへの終了の鍵)より先に確かめる。 */
|
|
2214
2219
|
function assertSessionClosable(name) {
|
|
@@ -2648,18 +2653,40 @@ function runAgentApprovalInNative(options) {
|
|
|
2648
2653
|
}
|
|
2649
2654
|
const DEFAULT_AGENT_DONE_TIMEOUT = 600;
|
|
2650
2655
|
const agentMetadataNegativeCache = new Map();
|
|
2651
|
-
function writeClaudeOperationMarker(meta, operationId) {
|
|
2656
|
+
function writeClaudeOperationMarker(meta, operationId, eventCursor, inputId) {
|
|
2652
2657
|
if (meta.kind !== "claude")
|
|
2653
2658
|
throw new AitermError("operation_id はClaude agent sessionだけで使用できます", 2);
|
|
2654
2659
|
const operation = operationId === null ? null : validateOperationId(operationId);
|
|
2655
|
-
//
|
|
2656
|
-
//
|
|
2660
|
+
// Private interruption retains its original request frame; v3 also captures
|
|
2661
|
+
// the public dispatch observation, never native input acceptance.
|
|
2657
2662
|
const captured = operation === null ? readExecutionSendBoundary(meta.aiterm_session) : null;
|
|
2658
2663
|
if (captured && (!isDeepStrictEqual(captured.launch, { session_id: meta.aiterm_session, launch_id: meta.launch_id })
|
|
2659
2664
|
|| !captured.boundary || captured.boundary.operation_id !== null || captured.boundary.turn_id !== null
|
|
2660
2665
|
|| captured.boundary.steer_id !== null))
|
|
2661
2666
|
throw new ExecutionError("EXECUTION_CONFLICT");
|
|
2662
|
-
|
|
2667
|
+
if (captured && eventCursor !== undefined && captured.boundary.event_cursor !== eventCursor)
|
|
2668
|
+
throw new ExecutionError("EXECUTION_CONFLICT");
|
|
2669
|
+
let transcript = null;
|
|
2670
|
+
const file = claudeSessionTranscriptPath(meta);
|
|
2671
|
+
if (eventCursor !== undefined && file && meta.vendor_session_id) {
|
|
2672
|
+
let stat;
|
|
2673
|
+
try {
|
|
2674
|
+
stat = fs.statSync(file, { bigint: true });
|
|
2675
|
+
}
|
|
2676
|
+
catch (error) {
|
|
2677
|
+
if (error.code !== "ENOENT")
|
|
2678
|
+
throw error;
|
|
2679
|
+
stat = null;
|
|
2680
|
+
}
|
|
2681
|
+
if (stat && !stat.isFile())
|
|
2682
|
+
throw new AitermError("CLAUDE_TRANSCRIPT_INVALID: input boundary is not a file", 2);
|
|
2683
|
+
if (stat && !Number.isSafeInteger(Number(stat.size)))
|
|
2684
|
+
throw new AitermError("CLAUDE_TRANSCRIPT_INVALID: input boundary is too large", 2);
|
|
2685
|
+
transcript = { session_id: meta.vendor_session_id, cursor: Number(stat?.size ?? 0), device: stat?.dev.toString() ?? null, inode: stat?.ino.toString() ?? null };
|
|
2686
|
+
}
|
|
2687
|
+
withExecutionPreparation(meta.aiterm_session, () => writeJson0600(agentClaudeOperationPath(meta.aiterm_session, meta.launch_id), eventCursor !== undefined ? {
|
|
2688
|
+
schema: "aiterm.claude-operation-marker.v3", operation_id: operation, event_cursor: eventCursor, input_id: inputId, transcript,
|
|
2689
|
+
} : captured ? {
|
|
2663
2690
|
schema: "aiterm.claude-operation-marker.v2", operation_id: null, event_cursor: captured.boundary.event_cursor,
|
|
2664
2691
|
} : { schema: "aiterm.claude-operation-marker.v1", operation_id: operation }));
|
|
2665
2692
|
}
|
|
@@ -2700,7 +2727,7 @@ function readClaudeOperationMarker(meta) {
|
|
|
2700
2727
|
fs.closeSync(fd);
|
|
2701
2728
|
}
|
|
2702
2729
|
}
|
|
2703
|
-
function reserveClaudeOperation(meta, operationId) {
|
|
2730
|
+
function reserveClaudeOperation(meta, operationId, eventCursor, inputId) {
|
|
2704
2731
|
const validated = validateOperationId(operationId);
|
|
2705
2732
|
const active = readClaudeOperationMarker(meta);
|
|
2706
2733
|
if (active?.operationId === validated) {
|
|
@@ -2722,7 +2749,7 @@ function reserveClaudeOperation(meta, operationId) {
|
|
|
2722
2749
|
throw new AitermError(`operation ${validated} は既にdispatch済みです。再送しません。`, 2);
|
|
2723
2750
|
}
|
|
2724
2751
|
try {
|
|
2725
|
-
writeClaudeOperationMarker(meta, validated);
|
|
2752
|
+
writeClaudeOperationMarker(meta, validated, eventCursor, inputId);
|
|
2726
2753
|
}
|
|
2727
2754
|
catch (error) {
|
|
2728
2755
|
try {
|
|
@@ -2732,13 +2759,13 @@ function reserveClaudeOperation(meta, operationId) {
|
|
|
2732
2759
|
throw error;
|
|
2733
2760
|
}
|
|
2734
2761
|
}
|
|
2735
|
-
function reserveAnonymousClaudeTurn(meta) {
|
|
2762
|
+
function reserveAnonymousClaudeTurn(meta, eventCursor, inputId) {
|
|
2736
2763
|
const active = readClaudeOperationMarker(meta);
|
|
2737
2764
|
if (active) {
|
|
2738
2765
|
throw new AitermError(`${active.operationId ? `operation ${active.operationId}` : "operation_idなしのClaude turn"} が未解決です。` +
|
|
2739
2766
|
"Stop結果を回収するかsessionをcloseするまで次のturnを送れません。", 2);
|
|
2740
2767
|
}
|
|
2741
|
-
writeClaudeOperationMarker(meta, null);
|
|
2768
|
+
writeClaudeOperationMarker(meta, null, eventCursor, inputId);
|
|
2742
2769
|
}
|
|
2743
2770
|
function managedClaudeOperation(name) {
|
|
2744
2771
|
let meta;
|
|
@@ -3427,6 +3454,7 @@ function parseAgentDoneEvent(line, meta) {
|
|
|
3427
3454
|
vendor_session_id: typeof ev.vendor_session_id === "string" ? ev.vendor_session_id : null,
|
|
3428
3455
|
turn_id: typeof ev.turn_id === "string" ? ev.turn_id : null,
|
|
3429
3456
|
operation_id: typeof ev.operation_id === "string" && OPERATION_ID_RE.test(ev.operation_id) ? ev.operation_id : null,
|
|
3457
|
+
...(typeof ev.input_id === "string" && /^[a-f0-9]{32}$/.test(ev.input_id) ? { input_id: ev.input_id } : {}),
|
|
3430
3458
|
reason: typeof ev.reason === "string" ? ev.reason : "Stop",
|
|
3431
3459
|
done_status: ev.done_status === "turn_error" ? "turn_error" : "turn_done",
|
|
3432
3460
|
stop_hook_active: !!ev.stop_hook_active,
|
|
@@ -3437,7 +3465,7 @@ function parseAgentDoneEvent(line, meta) {
|
|
|
3437
3465
|
malformed: false,
|
|
3438
3466
|
};
|
|
3439
3467
|
}
|
|
3440
|
-
function scanAgentDoneLines(lines, meta, expectedOperationId = null) {
|
|
3468
|
+
function scanAgentDoneLines(lines, meta, expectedOperationId = null, expectedInputId) {
|
|
3441
3469
|
let malformedEvents = 0;
|
|
3442
3470
|
let candidate = null;
|
|
3443
3471
|
for (const line of lines) {
|
|
@@ -3457,6 +3485,8 @@ function scanAgentDoneLines(lines, meta, expectedOperationId = null) {
|
|
|
3457
3485
|
continue;
|
|
3458
3486
|
if (expectedOperationId && ev.operation_id !== expectedOperationId)
|
|
3459
3487
|
continue;
|
|
3488
|
+
if (expectedInputId && ev.input_id !== expectedInputId)
|
|
3489
|
+
continue;
|
|
3460
3490
|
if (meta.vendor_session_id)
|
|
3461
3491
|
return { event: ev, malformedEvents, ambiguousHarnessSession: false };
|
|
3462
3492
|
if (candidate?.vendor_session_id &&
|
|
@@ -3901,6 +3931,7 @@ export function agentWaitProcess(session, cursor, runtime = {}, steer = null) {
|
|
|
3901
3931
|
// 差し込みを取った番の終わりを待つ(ADR 0122)。
|
|
3902
3932
|
...(steer ? ["--steer", steer] : []),
|
|
3903
3933
|
...(runtime.launchId ? ["--launch", runtime.launchId] : []),
|
|
3934
|
+
...(runtime.inputId ? ["--input", runtime.inputId] : []),
|
|
3904
3935
|
];
|
|
3905
3936
|
return {
|
|
3906
3937
|
executable,
|
|
@@ -3999,6 +4030,8 @@ export async function observeAgentDone(name, o = {}) {
|
|
|
3999
4030
|
}
|
|
4000
4031
|
async function observeAgentDoneInternal(name, o = {}) {
|
|
4001
4032
|
const meta = loadAgentMetadata(name);
|
|
4033
|
+
if (o.input_id !== undefined && (!/^[a-f0-9]{32}$/.test(o.input_id) || meta.kind !== "claude" || o.steer != null))
|
|
4034
|
+
throw new AitermError("AGENT_WAIT_INPUT_INVALID: input_id requires a Claude dispatch boundary", 2);
|
|
4002
4035
|
if (o.expected_launch_id && meta.launch_id !== o.expected_launch_id)
|
|
4003
4036
|
throw new ExecutionError("EXECUTION_STALE_GENERATION");
|
|
4004
4037
|
const operationId = o.operation_id == null ? null : validateOperationId(o.operation_id);
|
|
@@ -4052,11 +4085,20 @@ async function observeAgentDoneInternal(name, o = {}) {
|
|
|
4052
4085
|
let cursor = startOffset;
|
|
4053
4086
|
let carry = "";
|
|
4054
4087
|
let malformedEvents = 0;
|
|
4055
|
-
// Claude
|
|
4056
|
-
//
|
|
4088
|
+
// New Claude input reservations retain the pre-submit transcript offset.
|
|
4089
|
+
// Legacy waits start at EOF and never acquire a missing input binding.
|
|
4057
4090
|
const transcriptFile = claudeSessionTranscriptPath(meta);
|
|
4058
|
-
let
|
|
4091
|
+
let marker = meta.kind === "claude" ? readClaudeOperationMarker(meta) : null;
|
|
4092
|
+
let capturedTranscript = marker?.transcript;
|
|
4093
|
+
let matchesBoundary = !!capturedTranscript && capturedTranscript.session_id === meta.vendor_session_id
|
|
4094
|
+
&& marker.operationId === operationId && (o.cursor != null ? marker.eventCursor === o.cursor : operationId !== null);
|
|
4095
|
+
let transcriptCursor = matchesBoundary ? capturedTranscript.cursor : transcriptFile ? safeStatSize(transcriptFile) : 0;
|
|
4059
4096
|
let transcriptCarry = "";
|
|
4097
|
+
let parentUuid = null;
|
|
4098
|
+
let sawUser = false;
|
|
4099
|
+
let sawExecution = false;
|
|
4100
|
+
let transcriptBound = matchesBoundary && (operationId !== null || (o.input_id !== undefined && marker?.inputId === o.input_id));
|
|
4101
|
+
let transcriptIdentity = capturedTranscript?.device === null ? null : capturedTranscript;
|
|
4060
4102
|
// 利用上限の知らせは画面でしか分からない。画面を読むとtmuxを起動するので、完了の見回りより間隔を空ける。
|
|
4061
4103
|
// 実被弾: 完了の見回り(100ms)のたびに読んでいて、待ち1本が1秒に約10回tmuxを起動していた(4本でコンテナのCPUが148%)。
|
|
4062
4104
|
const rateLimitDue = pollGate(AGENT_RATE_LIMIT_POLL_MS);
|
|
@@ -4068,18 +4110,36 @@ async function observeAgentDoneInternal(name, o = {}) {
|
|
|
4068
4110
|
harness: agentHarness(meta.kind),
|
|
4069
4111
|
outcome,
|
|
4070
4112
|
operation_id: ev?.operation_id ?? operationId,
|
|
4113
|
+
...(o.input_id ? { input_id: o.input_id } : {}),
|
|
4071
4114
|
vendor_session_id: ev?.vendor_session_id ?? meta.vendor_session_id ?? null,
|
|
4072
4115
|
turn_id: ev?.turn_id ?? null,
|
|
4073
4116
|
malformed_events: malformedEvents,
|
|
4074
4117
|
at: ev?.at ?? apiError?.at ?? null,
|
|
4075
4118
|
rate_limit: rateLimit,
|
|
4076
4119
|
error: apiError?.text ?? null,
|
|
4077
|
-
error_kind: null,
|
|
4120
|
+
error_kind: apiError?.status ? `http_${apiError.status}` : null,
|
|
4121
|
+
...(apiError ? { failure: { category: claudeFailureCategory(apiError), execution: sawExecution ? "started" : "unknown",
|
|
4122
|
+
boundary: transcriptBound && sawUser && apiError.session_id === meta.vendor_session_id && parentUuid !== null && apiError.parent_uuid === parentUuid && apiError.uuid !== null ? {
|
|
4123
|
+
event_cursor: marker.eventCursor, operation_id: operationId, turn_id: null, input_id: marker.inputId
|
|
4124
|
+
} : null,
|
|
4125
|
+
terminal: transcriptBound && sawUser && apiError.session_id === meta.vendor_session_id && parentUuid !== null && apiError.parent_uuid === parentUuid && apiError.uuid !== null,
|
|
4126
|
+
future_effects: "unknown" } } : {}),
|
|
4078
4127
|
});
|
|
4079
4128
|
for (;;) {
|
|
4080
4129
|
o.signal?.throwIfAborted();
|
|
4081
4130
|
if (!fs.existsSync(metadataFile))
|
|
4082
4131
|
return observation("closed");
|
|
4132
|
+
if (o.input_id && !marker) {
|
|
4133
|
+
marker = readClaudeOperationMarker(meta);
|
|
4134
|
+
capturedTranscript = marker?.transcript;
|
|
4135
|
+
matchesBoundary = !!capturedTranscript && capturedTranscript.session_id === meta.vendor_session_id
|
|
4136
|
+
&& marker.operationId === operationId && marker.eventCursor === o.cursor && marker.inputId === o.input_id;
|
|
4137
|
+
if (matchesBoundary) {
|
|
4138
|
+
transcriptCursor = capturedTranscript.cursor;
|
|
4139
|
+
transcriptBound = true;
|
|
4140
|
+
transcriptIdentity = capturedTranscript.device === null ? null : capturedTranscript;
|
|
4141
|
+
}
|
|
4142
|
+
}
|
|
4083
4143
|
const size = safeStatSize(meta.event_file);
|
|
4084
4144
|
if (size < cursor) {
|
|
4085
4145
|
cursor = 0;
|
|
@@ -4093,20 +4153,52 @@ async function observeAgentDoneInternal(name, o = {}) {
|
|
|
4093
4153
|
cursor = size;
|
|
4094
4154
|
const parts = carry.split("\n");
|
|
4095
4155
|
carry = parts.pop() ?? "";
|
|
4096
|
-
const scanned = scanAgentDoneLines(parts, meta, operationId);
|
|
4156
|
+
const scanned = scanAgentDoneLines(parts, meta, operationId, o.input_id);
|
|
4097
4157
|
malformedEvents += scanned.malformedEvents;
|
|
4098
4158
|
if (scanned.ambiguousHarnessSession) {
|
|
4099
4159
|
throw new AitermError("agent event file に複数の vendor_session_id が混在しています。該当セッションを閉じて起動し直してください。", 2);
|
|
4100
4160
|
}
|
|
4161
|
+
if (o.input_id && !scanned.event && parts.some(line => parseAgentDoneEvent(line, meta).event !== null))
|
|
4162
|
+
throw new AitermError("AGENT_WAIT_INPUT_CHANGED: completion belongs to another or unconfirmed input", 2);
|
|
4101
4163
|
if (scanned.event)
|
|
4102
4164
|
return scanned.event.done_status === "turn_error"
|
|
4103
4165
|
? { ...observation("error", scanned.event), error: `Antigravity execution ended: ${scanned.event.reason}`, error_kind: scanned.event.reason }
|
|
4104
4166
|
: observation("done", scanned.event);
|
|
4105
4167
|
}
|
|
4168
|
+
if (o.input_id) {
|
|
4169
|
+
const current = readClaudeOperationMarker(meta);
|
|
4170
|
+
if ((current && (current.inputId !== o.input_id || current.eventCursor !== o.cursor)) || (!current && marker)) {
|
|
4171
|
+
// Stop saves its event before consuming the marker; capture that event
|
|
4172
|
+
// if it arrived after this iteration's event-file read.
|
|
4173
|
+
if (safeStatSize(meta.event_file) > cursor)
|
|
4174
|
+
continue;
|
|
4175
|
+
throw new AitermError("AGENT_WAIT_INPUT_CHANGED: original input marker was replaced", 2);
|
|
4176
|
+
}
|
|
4177
|
+
if (!current) {
|
|
4178
|
+
if (performance.now() >= deadline)
|
|
4179
|
+
return observation(timeout === 0 ? "running" : "timeout");
|
|
4180
|
+
await sleep(AGENT_DONE_POLL_MS);
|
|
4181
|
+
continue;
|
|
4182
|
+
}
|
|
4183
|
+
}
|
|
4106
4184
|
if (transcriptFile && fs.existsSync(transcriptFile)) {
|
|
4107
|
-
const
|
|
4185
|
+
const transcriptStat = fs.statSync(transcriptFile, { bigint: true });
|
|
4186
|
+
const transcriptSize = Number(transcriptStat.size);
|
|
4187
|
+
if (!transcriptStat.isFile() || !Number.isSafeInteger(transcriptSize))
|
|
4188
|
+
throw new AitermError("CLAUDE_TRANSCRIPT_INVALID: cannot read input boundary", 2);
|
|
4189
|
+
if (transcriptBound && transcriptIdentity
|
|
4190
|
+
&& (transcriptStat.dev.toString() !== transcriptIdentity.device || transcriptStat.ino.toString() !== transcriptIdentity.inode)) {
|
|
4191
|
+
transcriptBound = false;
|
|
4192
|
+
parentUuid = null;
|
|
4193
|
+
transcriptCursor = transcriptSize;
|
|
4194
|
+
transcriptCarry = "";
|
|
4195
|
+
}
|
|
4196
|
+
if (transcriptBound && !transcriptIdentity)
|
|
4197
|
+
transcriptIdentity = { ...capturedTranscript, device: transcriptStat.dev.toString(), inode: transcriptStat.ino.toString() };
|
|
4108
4198
|
if (transcriptSize < transcriptCursor) {
|
|
4109
|
-
|
|
4199
|
+
transcriptBound = false;
|
|
4200
|
+
parentUuid = null;
|
|
4201
|
+
transcriptCursor = transcriptSize;
|
|
4110
4202
|
transcriptCarry = "";
|
|
4111
4203
|
}
|
|
4112
4204
|
if (transcriptSize > transcriptCursor) {
|
|
@@ -4116,8 +4208,36 @@ async function observeAgentDoneInternal(name, o = {}) {
|
|
|
4116
4208
|
transcriptCarry = lines.pop() ?? "";
|
|
4117
4209
|
for (const line of lines) {
|
|
4118
4210
|
const apiError = claudeApiErrorFromLine(line);
|
|
4119
|
-
if (apiError)
|
|
4211
|
+
if (apiError && (apiError.session_id === null || apiError.session_id === meta.vendor_session_id))
|
|
4120
4212
|
return observation("error", null, null, apiError);
|
|
4213
|
+
let record;
|
|
4214
|
+
try {
|
|
4215
|
+
record = JSON.parse(line);
|
|
4216
|
+
}
|
|
4217
|
+
catch {
|
|
4218
|
+
transcriptBound = false;
|
|
4219
|
+
continue;
|
|
4220
|
+
}
|
|
4221
|
+
if (record.isSidechain === true || (record.sessionId && record.sessionId !== meta.vendor_session_id))
|
|
4222
|
+
continue;
|
|
4223
|
+
if (record.type === "user" || record.type === "assistant") {
|
|
4224
|
+
if (typeof record.uuid !== "string" || (parentUuid !== null && record.parentUuid !== parentUuid))
|
|
4225
|
+
transcriptBound = false;
|
|
4226
|
+
if (!sawUser && record.type !== "user")
|
|
4227
|
+
transcriptBound = false;
|
|
4228
|
+
if (record.sessionId !== meta.vendor_session_id)
|
|
4229
|
+
transcriptBound = false;
|
|
4230
|
+
if (record.type === "user") {
|
|
4231
|
+
const content = record.message?.content;
|
|
4232
|
+
const toolResult = Array.isArray(content) && content.length > 0 && content.every((part) => part?.type === "tool_result");
|
|
4233
|
+
if (sawUser && !toolResult)
|
|
4234
|
+
transcriptBound = false;
|
|
4235
|
+
sawUser = true;
|
|
4236
|
+
}
|
|
4237
|
+
if (record.type === "assistant")
|
|
4238
|
+
sawExecution = true;
|
|
4239
|
+
parentUuid = typeof record.uuid === "string" ? record.uuid : null;
|
|
4240
|
+
}
|
|
4121
4241
|
}
|
|
4122
4242
|
}
|
|
4123
4243
|
}
|
|
@@ -4127,7 +4247,8 @@ async function observeAgentDoneInternal(name, o = {}) {
|
|
|
4127
4247
|
if (rateLimitDue()) {
|
|
4128
4248
|
const limited = detectAgentRateLimit(meta.kind, meta.aiterm_session);
|
|
4129
4249
|
if (limited)
|
|
4130
|
-
return observation("rate_limited", null, limited)
|
|
4250
|
+
return { ...observation("rate_limited", null, limited), failure: { category: "rate_limited", execution: "unknown",
|
|
4251
|
+
boundary: null, terminal: false, future_effects: "unknown" } };
|
|
4131
4252
|
}
|
|
4132
4253
|
if (performance.now() >= deadline)
|
|
4133
4254
|
return observation(timeout === 0 ? "running" : "timeout");
|
|
@@ -4420,16 +4541,17 @@ async function sendInitialAgentPromptInLock(name, text, o) {
|
|
|
4420
4541
|
await o.after_ready?.(name, meta);
|
|
4421
4542
|
const promptText = meta.kind === "cursor" ? cursorPromptWithLineage(meta, text) : text;
|
|
4422
4543
|
const startOffset = agentCompletionCursor(meta);
|
|
4544
|
+
const inputId = meta.kind === "claude" ? randomBytes(16).toString("hex") : undefined;
|
|
4423
4545
|
try {
|
|
4424
4546
|
prepareSendText(promptText, { raw: false });
|
|
4425
4547
|
await o.before_send?.({ session_id: name, launch_id: meta.launch_id, vendor: meta.kind,
|
|
4426
|
-
harness: agentHarness(meta.kind), event_cursor: startOffset, operation_id: null });
|
|
4548
|
+
harness: agentHarness(meta.kind), event_cursor: startOffset, operation_id: null, ...(inputId ? { input_id: inputId } : {}) });
|
|
4427
4549
|
captureExecutionSendBoundary({ launch: { session_id: name, launch_id: meta.launch_id }, boundary: {
|
|
4428
4550
|
event_cursor: startOffset, operation_id: null, turn_id: null, steer_id: null
|
|
4429
4551
|
} });
|
|
4430
4552
|
if (meta.kind === "claude") {
|
|
4431
4553
|
prepareSendText(text, { raw: false });
|
|
4432
|
-
reserveAnonymousClaudeTurn(meta);
|
|
4554
|
+
reserveAnonymousClaudeTurn(meta, startOffset, inputId);
|
|
4433
4555
|
}
|
|
4434
4556
|
setInitialDelivery(meta, { status: "submitted_unconfirmed", reason: "dispatch_in_progress", turn_started: null }, startOffset);
|
|
4435
4557
|
await sendAgentPromptText(name, promptText, meta.kind, meta);
|
|
@@ -4468,7 +4590,7 @@ async function sendInitialAgentPromptInLock(name, text, o) {
|
|
|
4468
4590
|
setInitialPromptState(meta, "failed");
|
|
4469
4591
|
throw new AitermError(userHookBlockedMessage(`initial_prompt=failed vendor=${meta.kind} harness=${agentHarness(meta.kind)}`, "起動時prompt", state.detail), 2);
|
|
4470
4592
|
}
|
|
4471
|
-
const completed = await observeAgentDone(name, { cursor: startOffset, timeout: 0 });
|
|
4593
|
+
const completed = await observeAgentDone(name, { cursor: startOffset, timeout: 0, input_id: inputId });
|
|
4472
4594
|
if (completed.outcome === "done") {
|
|
4473
4595
|
delivery = { status: "started", reason: "turn_completed", turn_started: true };
|
|
4474
4596
|
break;
|
|
@@ -6706,8 +6828,9 @@ async function dispatchAgentTurnInLock(name, text, o, pendingSend) {
|
|
|
6706
6828
|
? `${subagentInstruction(meta)}\n\n${prefaced.body}`
|
|
6707
6829
|
: prefaced.body;
|
|
6708
6830
|
prepareSendText(dispatchText, { raw: o.raw });
|
|
6831
|
+
const inputId = meta.kind === "claude" ? randomBytes(16).toString("hex") : undefined;
|
|
6709
6832
|
await o.before_send?.({ session_id: name, launch_id: meta.launch_id, vendor: meta.kind,
|
|
6710
|
-
harness: agentHarness(meta.kind), event_cursor: startOffset, operation_id: operationId });
|
|
6833
|
+
harness: agentHarness(meta.kind), event_cursor: startOffset, operation_id: operationId, ...(inputId ? { input_id: inputId } : {}) });
|
|
6711
6834
|
await submitAgentComposerText(name, meta.kind, dispatchText, {
|
|
6712
6835
|
inputMeta: meta,
|
|
6713
6836
|
force: o.force, raw: o.raw, typedPreface: prefaced.typedPreface, preserveAgentOperation: meta.kind === "claude",
|
|
@@ -6723,10 +6846,10 @@ async function dispatchAgentTurnInLock(name, text, o, pendingSend) {
|
|
|
6723
6846
|
// receipt/active markerだけを残して、来ないStopを待つ状態を作らない。
|
|
6724
6847
|
prepareSendText(text, { raw: o.raw });
|
|
6725
6848
|
if (operationId) {
|
|
6726
|
-
reserveClaudeOperation(meta, operationId);
|
|
6849
|
+
reserveClaudeOperation(meta, operationId, startOffset, inputId);
|
|
6727
6850
|
}
|
|
6728
6851
|
else
|
|
6729
|
-
reserveAnonymousClaudeTurn(meta);
|
|
6852
|
+
reserveAnonymousClaudeTurn(meta, startOffset, inputId);
|
|
6730
6853
|
}
|
|
6731
6854
|
},
|
|
6732
6855
|
});
|
|
@@ -6745,6 +6868,7 @@ async function dispatchAgentTurnInLock(name, text, o, pendingSend) {
|
|
|
6745
6868
|
harness: agentHarness(meta.kind),
|
|
6746
6869
|
event_cursor: startOffset,
|
|
6747
6870
|
operation_id: operationId,
|
|
6871
|
+
...(inputId ? { input_id: inputId } : {}),
|
|
6748
6872
|
submit_residue: residue.residue,
|
|
6749
6873
|
pane_input_recovery: paneInputRecovery,
|
|
6750
6874
|
};
|