aiterm-mcp 0.62.6 → 0.63.1

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.
@@ -8,6 +8,12 @@ import { AitermError } from "./errors.js";
8
8
  import { lazyRelayExecutable } from "./lazy-relay.js";
9
9
  import { isWin } from "./tmux-runtime.js";
10
10
  import { resolveWindowsPowerShell7 } from "./windows-powershell.js";
11
+ /** Claude's native macOS keep-awake helper does no user work of its own. */
12
+ export function macKeepAwakeProcess(row, harness, platform = process.platform) {
13
+ const started = Date.parse(row.started_identity), parentStarted = Date.parse(harness?.started_identity ?? "");
14
+ return platform === "darwin" && !!harness && row.parent_pid === harness.pid && Number.isFinite(started)
15
+ && Number.isFinite(parentStarted) && started >= parentStarted && /^(?:\/usr\/bin\/)?caffeinate -i -t 300$/.test(row.command.trim());
16
+ }
11
17
  export function processIdentity(process) {
12
18
  return {
13
19
  pid: process.pid, process_group_id: process.process_group_id,
@@ -21,23 +27,47 @@ export function parseCpuTime(value) {
21
27
  return Number(match[1] ?? 0) * 86400 + Number(match[2] ?? 0) * 3600
22
28
  + Number(match[3]) * 60 + Number(match[4]);
23
29
  }
24
- export function parsePosixProcessTable(text) {
25
- return text.split("\n").filter(line => line.trim()).map(line => {
26
- const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+\s+\S+\s+\d+\s+\S+\s+\d+)\s+(\S+)\s+(.+)$/.exec(line);
30
+ export function parsePosixProcessTable(text, includeSession = false, platform = process.platform) {
31
+ const leaders = new Set();
32
+ const rows = text.split("\n").filter(line => line.trim()).map(line => {
33
+ const match = (includeSession
34
+ ? /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\S+\s+\S+\s+\d+\s+\S+\s+\d+)\s+(\S+)\s+(.+)$/
35
+ : /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+\s+\S+\s+\d+\s+\S+\s+\d+)\s+(\S+)\s+(.+)$/).exec(line);
27
36
  if (!match)
28
37
  throw new AitermError("process一覧の形式を認識できません", 2);
29
- const command = match[7].trim();
38
+ const offset = includeSession ? 1 : 0;
39
+ const command = match[7 + offset].trim();
40
+ if (match[4 + offset].includes("s"))
41
+ leaders.add(Number(match[1]));
30
42
  return {
31
43
  pid: Number(match[1]), parent_pid: Number(match[2]), process_group_id: Number(match[3]),
32
- stopped: match[4].includes("T"),
33
- started_identity: match[5].trim(), cpu_seconds: parseCpuTime(match[6]), command,
44
+ stopped: match[4 + offset].includes("T"), zombie: match[4 + offset].includes("Z"),
45
+ ...(includeSession ? { session_identity: match[4] } : {}),
46
+ started_identity: match[5 + offset].trim(), cpu_seconds: parseCpuTime(match[6 + offset]), command,
34
47
  argv_digest: createHash("sha256").update(command).digest("hex"),
35
48
  };
36
49
  });
50
+ // Darwin sess is a kernel pointer hidden as zero; stat's s is the actual session-leader flag.
51
+ if (includeSession && platform === "darwin") {
52
+ const byPid = new Map(rows.map(row => [row.pid, row]));
53
+ for (const row of rows) {
54
+ let leader = Number.isFinite(Date.parse(row.started_identity)) ? row : undefined;
55
+ const seen = new Set();
56
+ while (leader && !leaders.has(leader.pid) && !seen.has(leader.pid)) {
57
+ seen.add(leader.pid);
58
+ leader = leader.parent_pid <= 1 ? undefined : parentProcess(leader, byPid);
59
+ if (leader && !Number.isFinite(Date.parse(leader.started_identity)))
60
+ leader = undefined;
61
+ }
62
+ row.session_identity = leader && leaders.has(leader.pid) ? `${leader.pid}:${leader.started_identity}` : null;
63
+ }
64
+ }
65
+ return rows;
37
66
  }
38
67
  // AitermがOSのprocess表を引く時のコマンドの形。席のprocessを数える側が、これを利用者の作業と取り違えないために使う。
39
68
  const POSIX_PS = "/bin/ps";
40
69
  const POSIX_TABLE_ARGS = ["-axww", "-o", "pid=,ppid=,pgid=,stat=,lstart=,time=,command="];
70
+ const POSIX_SESSION_TABLE_ARGS = ["-axww", "-o", "pid=,ppid=,pgid=,sess=,stat=,lstart=,time=,command="];
41
71
  const POSIX_IDENTITY_ARGS = ["-o", "pid=,lstart=", "-p"];
42
72
  const POSIX_ELAPSED_ARGS = ["-o", "etime=", "-p"];
43
73
  const WINDOWS_PROBE_HEADER = ["$ErrorActionPreference='Stop'", "[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)"];
@@ -52,6 +82,7 @@ export function aitermProcessProbe(command) {
52
82
  if (command.includes(` ${WINDOWS_PROBE_ARGS.join(" ")} ${WINDOWS_PROBE_PREFIX}`))
53
83
  return true;
54
84
  return command === `${POSIX_PS} ${POSIX_TABLE_ARGS.join(" ")}` || command.startsWith(`${POSIX_PS} ${POSIX_IDENTITY_ARGS.join(" ")} `)
85
+ || command === `${POSIX_PS} ${POSIX_SESSION_TABLE_ARGS.join(" ")}`
55
86
  || command.startsWith(`${POSIX_PS} ${POSIX_ELAPSED_ARGS.join(" ")} `);
56
87
  }
57
88
  /** Windowsのconsole host。console processの起動に付いて立ち、最後のconsole processが終わると消える。 */
@@ -60,14 +91,14 @@ export function windowsConsoleHost(row) {
60
91
  const name = (row.executable || first?.[1] || first?.[2] || "").replace(/\\/g, "/");
61
92
  return path.posix.basename(name).toLowerCase() === "conhost.exe";
62
93
  }
63
- export function readRuntimeProcesses() {
94
+ export function readRuntimeProcesses(includeSession = false) {
64
95
  if (!isWin) {
65
- const result = spawnSync(POSIX_PS, POSIX_TABLE_ARGS, {
96
+ const result = spawnSync(POSIX_PS, includeSession ? POSIX_SESSION_TABLE_ARGS : POSIX_TABLE_ARGS, {
66
97
  encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 10000, maxBuffer: 16 * 1024 * 1024,
67
98
  });
68
99
  if (result.error || result.status !== 0)
69
100
  throw new AitermError("OSのprocess一覧を取得できません", 2);
70
- return parsePosixProcessTable(result.stdout);
101
+ return parsePosixProcessTable(result.stdout, includeSession);
71
102
  }
72
103
  const script = [
73
104
  ...WINDOWS_PROBE_HEADER,
@@ -103,6 +134,35 @@ export function readRuntimeProcesses() {
103
134
  };
104
135
  });
105
136
  }
137
+ /** A held Process handle on Windows prevents a PID replacement from becoming the target. */
138
+ export function signalRuntimeProcess(target, signal, group) {
139
+ if (!Number.isSafeInteger(target.pid) || target.pid <= 1 || !Number.isFinite(Date.parse(target.started_identity))
140
+ || (group && (!Number.isSafeInteger(target.process_group_id) || target.process_group_id <= 1)))
141
+ throw new Error("invalid_process_signal_target");
142
+ if (!isWin) {
143
+ try {
144
+ process.kill(group ? -target.process_group_id : target.pid, signal);
145
+ }
146
+ catch (error) {
147
+ if (error.code !== "ESRCH")
148
+ throw error;
149
+ }
150
+ return;
151
+ }
152
+ const script = [
153
+ "$ErrorActionPreference='Stop'",
154
+ `try { $target=[Diagnostics.Process]::GetProcessById(${target.pid}) } catch [ArgumentException] { exit 3 }`,
155
+ "try {",
156
+ "[void]$target.Handle",
157
+ `if(([DateTimeOffset]$target.StartTime.ToUniversalTime()).ToUnixTimeMilliseconds() -ne ${Date.parse(target.started_identity)}) { exit 4 }`,
158
+ signal === "SIGTERM" ? "[void]$target.CloseMainWindow()" : "$target.Kill()",
159
+ "} finally { $target.Dispose() }",
160
+ ].join("\n");
161
+ const result = spawnSync(resolveWindowsPowerShell7(), ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand",
162
+ Buffer.from(script, "utf16le").toString("base64")], { encoding: "utf8", timeout: 10_000, windowsHide: true });
163
+ if (result.error || ![0, 3].includes(result.status))
164
+ throw new Error("native_process_signal_unconfirmed");
165
+ }
106
166
  /** そのpidのprocessが今あるか。OSへ直接聞き、processを起こさない。権限が無くて触れないprocessも「ある」と読む。 */
107
167
  function pidExists(pid) {
108
168
  if (pid <= 0)
@@ -312,3 +372,17 @@ export function readLinuxProcessRegistrationIdentity(pid) {
312
372
  return null;
313
373
  }
314
374
  }
375
+ /** A detached seat clock sleeps in the native shell; exit 75 retries admission without keeping Node resident. */
376
+ export function idleClockCommand(delayMs, executable, args, windows = isWin) {
377
+ if (!Number.isFinite(delayMs) || !executable || [executable, ...args].some(value => value.includes("\0")))
378
+ throw new Error("invalid_delayed_process");
379
+ const seconds = Math.min(86_400, Math.max(1, Math.ceil(delayMs / 1000)));
380
+ if (!windows)
381
+ return { executable: "/bin/sh", args: ["-c",
382
+ 'aiterm_delay=$1; shift; sleep "$aiterm_delay" || exit; while :; do "$@"; aiterm_status=$?; [ "$aiterm_status" -eq 75 ] || exit "$aiterm_status"; sleep 60 || exit; done',
383
+ "aiterm-idle-clock", String(seconds), executable, ...args] };
384
+ const quote = (value) => "'" + value.replace(/'/g, "''") + "'";
385
+ const script = `$ErrorActionPreference='Stop'; Start-Sleep -Seconds ${seconds}; do { & ${[executable, ...args].map(quote).join(" ")}; if ($null -eq $LASTEXITCODE) { exit 2 }; $aiterm_status=$LASTEXITCODE; if ($aiterm_status -eq 75) { Start-Sleep -Seconds 60 } } while ($aiterm_status -eq 75); exit $aiterm_status`;
386
+ return { executable: resolveWindowsPowerShell7(), args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand",
387
+ Buffer.from(script, "utf16le").toString("base64")] };
388
+ }
@@ -2,6 +2,31 @@
2
2
  import * as fs from "node:fs";
3
3
  import { spawnSync } from "node:child_process";
4
4
  import { resolveWindowsPowerShell7 } from "./windows-powershell.js";
5
+ export function processStartIdentities(pids, platform, timeoutMs = 1000) {
6
+ if (platform !== "win32")
7
+ return pids.map(pid => processStartIdentity(pid, platform, timeoutMs));
8
+ const wanted = [...new Set(pids.filter(pid => Number.isSafeInteger(pid) && pid > 0))];
9
+ if (!wanted.length)
10
+ return pids.map(() => null);
11
+ const script = "$rows=@(foreach($id in ($env:AITERMMCP_PROCESS_IDS -split ',')){ $start=$null; try { $p=Get-Process -Id ([int]$id) -ErrorAction Stop; $start=$p.StartTime.ToUniversalTime().Ticks.ToString() } catch {}; [ordered]@{pid=[int]$id;start=$start} }); ConvertTo-Json -InputObject $rows -Compress";
12
+ const result = spawnSync(resolveWindowsPowerShell7(), ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
13
+ encoding: "utf8", timeout: timeoutMs, maxBuffer: 4096, windowsHide: true,
14
+ env: { ...process.env, AITERMMCP_PROCESS_IDS: wanted.join(",") },
15
+ });
16
+ let rows;
17
+ try {
18
+ rows = result.status === 0 ? JSON.parse(result.stdout ?? "") : null;
19
+ }
20
+ catch {
21
+ rows = null;
22
+ }
23
+ if (!Array.isArray(rows) || rows.length !== wanted.length
24
+ || rows.some((row, i) => !row || row.pid !== wanted[i]
25
+ || row.start !== null && (typeof row.start !== "string" || !/^\d+$/.test(row.start))))
26
+ return pids.map(() => null);
27
+ const starts = new Map(rows.map(row => [row.pid, row.start === null ? null : `win32:${row.start}`]));
28
+ return pids.map(pid => starts.get(pid) ?? null);
29
+ }
5
30
  export function processStartIdentity(pid, platform, timeoutMs = 1000) {
6
31
  if (!Number.isInteger(pid) || pid < 1)
7
32
  return null;
@@ -17,13 +42,7 @@ export function processStartIdentity(pid, platform, timeoutMs = 1000) {
17
42
  }
18
43
  }
19
44
  if (platform === "win32") {
20
- const script = "$p=Get-Process -Id $env:AITERMMCP_PROCESS_ID -ErrorAction Stop; $p.StartTime.ToUniversalTime().Ticks";
21
- const result = spawnSync(resolveWindowsPowerShell7(), ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
22
- encoding: "utf8", timeout: timeoutMs, maxBuffer: 4096, windowsHide: true,
23
- env: { ...process.env, AITERMMCP_PROCESS_ID: String(pid) },
24
- });
25
- const value = result.status === 0 ? (result.stdout ?? "").trim() : "";
26
- return /^\d+$/.test(value) ? `win32:${value}` : null;
45
+ return processStartIdentities([pid], platform, timeoutMs)[0];
27
46
  }
28
47
  // lstart の日付書式は LC_TIME で変わり、locale の違う観測者間で identity が割れる
29
48
  // (caveat: ps-locale-lstart-lc-time-ascii-argv-lc-ctype-digest。Lattice 0.63.4 と同じ固定)
@@ -0,0 +1,91 @@
1
+ import { readRuntimeProcesses, signalRuntimeProcess, processSubtree } from "./process-runtime.js";
2
+ const same = (a, b) => a.pid === b.pid
3
+ && a.started_identity === b.started_identity && a.argv_digest === b.argv_digest && a.process_group_id === b.process_group_id;
4
+ const nativeRuntime = {
5
+ read: () => readRuntimeProcesses(true), signal: signalRuntimeProcess,
6
+ pause: ms => new Promise(resolve => setTimeout(resolve, ms)), now: () => performance.now(),
7
+ };
8
+ /** TERM, a five-second grace, then KILL; only the original pane tree and verified groups are selected. */
9
+ export async function stopProcessTree(root, verify, runtime = nativeRuntime) {
10
+ if (!Number.isSafeInteger(root.pid) || root.pid <= 1 || root.pid === process.pid)
11
+ throw new Error("invalid_process_tree_root");
12
+ const initial = runtime.read();
13
+ const liveRoot = initial.find(row => row.pid === root.pid && !row.zombie);
14
+ if (!liveRoot || !same(root, liveRoot))
15
+ throw new Error("process_tree_root_changed");
16
+ if (liveRoot.session_identity === null)
17
+ throw new Error("process_tree_session_unconfirmed");
18
+ const tree = processSubtree(initial, root.pid);
19
+ if (tree.some(row => row.session_identity === null))
20
+ throw new Error("process_tree_session_unconfirmed");
21
+ if (tree.some(row => row.pid === process.pid))
22
+ throw new Error("process_tree_contains_checker");
23
+ const inSession = (row) => liveRoot.session_identity === undefined || row.session_identity === liveRoot.session_identity;
24
+ const selected = new Map(tree.filter(inSession).map(row => [row.pid, row]));
25
+ const groups = new Set([...selected.values()].map(row => row.process_group_id).filter((group) => group !== null && group > 1 && initial.some(row => row.pid === group && selected.has(row.pid))
26
+ && initial.filter(row => row.process_group_id === group).every(row => selected.has(row.pid))));
27
+ const terminated = new Set();
28
+ const key = (row) => `${row.pid}:${row.started_identity}`;
29
+ const childrenFirst = (rows) => {
30
+ const depth = (row) => {
31
+ const seen = new Set();
32
+ for (let parent = selected.get(row.parent_pid); parent && !seen.has(parent.pid); parent = selected.get(parent.parent_pid))
33
+ seen.add(parent.pid);
34
+ return seen.size;
35
+ };
36
+ return [...rows].sort((a, b) => depth(b) - depth(a));
37
+ };
38
+ const refresh = () => {
39
+ const rows = runtime.read();
40
+ const still = rows.filter(row => !row.zombie && selected.has(row.pid) && same(selected.get(row.pid), row));
41
+ for (const parent of still)
42
+ for (const row of processSubtree(rows, parent.pid)) {
43
+ if (inSession(row) && !selected.has(row.pid))
44
+ selected.set(row.pid, row);
45
+ }
46
+ for (const row of rows)
47
+ if (inSession(row) && row.process_group_id !== null && groups.has(row.process_group_id)) {
48
+ if (!selected.has(row.pid))
49
+ selected.set(row.pid, row);
50
+ }
51
+ if (selected.has(process.pid))
52
+ throw new Error("process_tree_contains_checker");
53
+ return rows.filter(row => !row.zombie && selected.has(row.pid) && same(selected.get(row.pid), row));
54
+ };
55
+ const signal = (row, wanted) => (runtime.prepare ?? (body => body()))(() => {
56
+ verify();
57
+ const current = runtime.read();
58
+ const target = current.find(value => value.pid === row.pid && !value.zombie);
59
+ if (!target || !same(row, target))
60
+ return;
61
+ const group = target.process_group_id !== null && groups.has(target.process_group_id)
62
+ && current.filter(value => value.process_group_id === target.process_group_id && !value.zombie)
63
+ .every(value => selected.has(value.pid) && same(selected.get(value.pid), value));
64
+ runtime.signal(target, wanted, group);
65
+ if (wanted === "SIGTERM") {
66
+ for (const member of group ? current.filter(value => value.process_group_id === target.process_group_id) : [target])
67
+ terminated.add(key(member));
68
+ }
69
+ });
70
+ let until = null;
71
+ for (;;) {
72
+ const alive = refresh();
73
+ if (alive.length === 0)
74
+ return true;
75
+ if (until !== null && runtime.now() >= until)
76
+ break;
77
+ for (const row of childrenFirst(alive))
78
+ if (!terminated.has(key(row)))
79
+ signal(row, "SIGTERM");
80
+ until ??= runtime.now() + 5000;
81
+ await runtime.pause(Math.min(100, Math.max(0, until - runtime.now())));
82
+ }
83
+ for (const row of childrenFirst(refresh()))
84
+ signal(row, "SIGKILL");
85
+ for (const deadline = runtime.now() + 2000; runtime.now() < deadline;) {
86
+ if (refresh().length === 0)
87
+ return true;
88
+ await runtime.pause(100);
89
+ }
90
+ return refresh().length === 0;
91
+ }
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as net from "node:net";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
+ import { parseNativeSessionReceipt, nativeSessionCondition } from "./native-session.js";
5
6
  // 公開本文64KiBのBase64に加え、UTF-8初期化文・scriptblock構文・paste markerを含む。
6
7
  // 最大本文の変換増分は336byte以内。本文の公開上限は変えず、内部の包みを512byte確保する。
7
8
  const MAX_PAYLOAD_BYTES = Math.ceil(64 * 1024 / 3) * 4 + 512;
@@ -70,6 +71,9 @@ async function send() {
70
71
  const sessionBase = process.argv[2] ?? "";
71
72
  if (!SESSION_BASE_RE.test(sessionBase))
72
73
  throw new Error("invalid psmux session base");
74
+ const expected = process.argv[3] === undefined ? null : parseNativeSessionReceipt(process.argv[3], "linux");
75
+ if (process.argv.length > 4 || expected && !sessionBase.endsWith(`__${expected.session_id}`))
76
+ throw new Error("psmux native target does not match session base");
73
77
  const payload = await readPayload();
74
78
  const dir = psmuxDataDir();
75
79
  const portText = fs.readFileSync(path.join(dir, `${sessionBase}.port`), "utf8").trim();
@@ -83,7 +87,9 @@ async function send() {
83
87
  for (let offset = 0; offset < payload.length; offset += PTY_CHUNK_BYTES) {
84
88
  const chunk = payload.subarray(offset, offset + PTY_CHUNK_BYTES);
85
89
  const hex = Array.from(chunk, (byte) => byte.toString(16).padStart(2, "0")).join(" ");
86
- subcommands.push(`send -H ${hex}`);
90
+ const send = `send -H ${expected ? `-t ${expected.pane_id} ` : ""}${hex}`;
91
+ // A fixed authenticated peer keeps later chunks off a replacement server; no registry re-read occurs.
92
+ subcommands.push(expected ? `if-shell -F '${nativeSessionCondition(expected)}' '${send}' 'display-message -p AITERM_NATIVE_REFUSED'` : send);
87
93
  }
88
94
  const chunkDrainMs = payload.length > 1024 ? 300 : 100;
89
95
  for (const command of subcommands) {
@@ -12,7 +12,7 @@ import { createHash, randomBytes } from "node:crypto";
12
12
  import { AitermError } from "./errors.js";
13
13
  import { AGENT_DONE_POLL_MS, AGENT_EVENT_MAX_BYTES, AGENT_RATE_LIMIT_POLL_MS, AGENT_TURN_BOUNDARY_TAIL_BYTES, agentHarness, agentMetadataPath, agentsDir, assertSessionName, LAUNCH_ID_RE, readFileRange, safeStatSize, scanLinesNewestFirst, sleep, } from "./agent-shared.js";
14
14
  import { claudeApiErrorFromLine, claudeSessionTranscriptPath } from "./harnesses/claude.js";
15
- import { codexBoundTranscript, codexCompletionEvent, codexRolloutSessionId, codexRootTranscript, codexRunningTurn, codexTranscriptSessionId, codexTurnError, codexTurnErrorLine, codexUsageLimit, } from "./harnesses/codex.js";
15
+ import { codexBoundTranscript, codexCompletionEvent, codexRolloutSessionId, codexRootTranscript, codexResumeCursor, codexResumeTurnId, codexRunningTurn, codexTranscriptSessionId, codexTurnError, codexTurnErrorLine, codexUsageLimit, } from "./harnesses/codex.js";
16
16
  import { interimFromToken, parseInterimFrom } from "./interim-words.js";
17
17
  import { grokEventsTranscript, grokSessionDirectory, grokUserPrompt } from "./harnesses/grok.js";
18
18
  /** 差し込みの返りの_metaで返すキー。 */
@@ -301,7 +301,7 @@ async function observeCodexSteerDone(meta, entry, timeoutSeconds, deps) {
301
301
  return { ...await deps.plain(entry.event_cursor, timeoutSeconds), steer: fate("unknown") };
302
302
  const metadataFile = agentMetadataPath(meta.aiterm_session, meta.launch_id);
303
303
  const harnessSessionId = meta.vendor_session_id ? codexRolloutSessionId(meta, transcript) : codexTranscriptSessionId(transcript);
304
- const follower = new LineFollower(transcript, entry.event_cursor);
304
+ const follower = new LineFollower(transcript, Math.max(entry.event_cursor, codexResumeCursor(meta, transcript)));
305
305
  const sentAt = Date.parse(entry.at);
306
306
  const deadline = performance.now() + timeoutSeconds * 1000;
307
307
  let malformedEvents = 0;
@@ -332,6 +332,7 @@ async function observeCodexSteerDone(meta, entry, timeoutSeconds, deps) {
332
332
  throw new AitermError("Codex transcript が完了待機中に短くなりました。該当セッションを閉じて起動し直してください。", 2);
333
333
  if (lines.length)
334
334
  quietSince = performance.now();
335
+ const retiredTurn = codexResumeTurnId(meta, harnessSessionId);
335
336
  for (const line of lines) {
336
337
  if (!line.trim())
337
338
  continue;
@@ -348,6 +349,8 @@ async function observeCodexSteerDone(meta, entry, timeoutSeconds, deps) {
348
349
  continue;
349
350
  }
350
351
  const payload = record?.payload;
352
+ if (retiredTurn && (payload?.turn_id === retiredTurn || payload?.internal_chat_message_metadata_passthrough?.turn_id === retiredTurn))
353
+ continue;
351
354
  if (record?.type === "event_msg" && payload?.type === "task_started" && typeof payload.turn_id === "string") {
352
355
  openTurn = payload.turn_id;
353
356
  startedAfter.add(payload.turn_id);
@@ -7,10 +7,120 @@ import * as path from "node:path";
7
7
  import * as os from "node:os";
8
8
  import { createHash } from "node:crypto";
9
9
  import { fileURLToPath } from "node:url";
10
+ import { AsyncLocalStorage } from "node:async_hooks";
10
11
  import stringWidth from 'string-width';
11
12
  import { AitermError, ptyDependencyError } from "./errors.js";
12
13
  import { guardTmuxExecution, beforeExecutionEffect, hasExecutionCreationScope, prepareExecutionCreation, captureExecutionCreatedNative } from "./execution-effect.js";
13
14
  import { ExecutionError } from "./execution-wire.js";
15
+ import { parseNativeSessionReceipt, nativePaneTarget, nativeSessionTarget, nativeSessionCondition } from "./native-session.js";
16
+ const nativeTargets = new AsyncLocalStorage();
17
+ const nativeReads = new Set(["list-sessions", "list-commands", "list-panes", "list-windows", "has-session", "display-message", "capture-pane", "show-environment", "show-options"]);
18
+ const nativePanes = new Set(["send-keys", "paste-buffer", "pipe-pane", "capture-pane", "display-message", "list-panes"]);
19
+ const nativeTargetUnavailable = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 復帰したnative端末の本人性を確認できません。", 2);
20
+ function verifyNativeTarget(frame) {
21
+ if (frame.checking)
22
+ return;
23
+ frame.checking = true;
24
+ try {
25
+ frame.verify();
26
+ }
27
+ finally {
28
+ frame.checking = false;
29
+ }
30
+ }
31
+ /** Target routing only: guardTmuxExecution still owns every effect authorization. */
32
+ export function withNativeSessionTarget(target, verify, body, allowExitedPane = false) {
33
+ const enclosing = nativeTargets.getStore();
34
+ if (enclosing && JSON.stringify(enclosing.target) !== JSON.stringify(target))
35
+ throw nativeTargetUnavailable();
36
+ const frame = { session: target.session_id, target, verify, allowExitedPane };
37
+ return nativeTargets.run(frame, () => { verifyNativeTarget(frame); return body(); });
38
+ }
39
+ export function hasVerifiedNativeSessionTarget(name) {
40
+ const frame = nativeTargets.getStore();
41
+ if (!frame?.target || frame.session !== name)
42
+ return false;
43
+ verifyNativeTarget(frame);
44
+ return true;
45
+ }
46
+ export function withNativeSessionCreation(session, created, verify, body) {
47
+ if (nativeTargets.getStore())
48
+ throw nativeTargetUnavailable();
49
+ return nativeTargets.run({ session, target: null, created, verify }, body);
50
+ }
51
+ function captureNativeSessionReceipt(receipt) {
52
+ const frame = nativeTargets.getStore();
53
+ if (!frame?.created || frame.target)
54
+ throw nativeTargetUnavailable();
55
+ let target;
56
+ try {
57
+ target = parseNativeSessionReceipt(receipt);
58
+ }
59
+ catch {
60
+ throw nativeTargetUnavailable();
61
+ }
62
+ if (frame.session !== null && target.session_id !== frame.session)
63
+ throw nativeTargetUnavailable();
64
+ frame.session = target.session_id;
65
+ frame.target = target;
66
+ frame.created({ ...frame.target });
67
+ verifyNativeTarget(frame);
68
+ }
69
+ function nativeSessionArgs(input) {
70
+ const frame = nativeTargets.getStore();
71
+ if (!frame)
72
+ return input;
73
+ const args = [...input];
74
+ let effect = false, targetedRead = false;
75
+ for (let start = 0; start < args.length;) {
76
+ let end = args.indexOf(";", start);
77
+ if (end < 0)
78
+ end = args.length;
79
+ const command = args[start];
80
+ if (!nativeReads.has(command) && command !== "delete-buffer")
81
+ effect = true;
82
+ if (command === "new-session") {
83
+ const named = args.findIndex((value, index) => index > start && index < end && value === "-s");
84
+ if (frame.target || !frame.created || named < 0 || frame.session !== null && args[named + 1] !== frame.session)
85
+ throw nativeTargetUnavailable();
86
+ }
87
+ const at = args.findIndex((value, index) => index > start && index < end && value === "-t");
88
+ if (at >= 0) {
89
+ if (frame.session === null && !frame.target && nativeReads.has(command)) {
90
+ start = end + 1;
91
+ continue;
92
+ }
93
+ targetedRead ||= nativeReads.has(command);
94
+ const raw = args[at + 1], named = /^=?([A-Za-z0-9_-]{1,64})(?::(?:\d+(?:\.\d+)?)?)?$/.exec(raw);
95
+ const own = named?.[1] === frame.session || raw === frame.target?.native_id || raw === frame.target?.pane_id
96
+ || frame.target !== null && raw === nativePaneTarget(frame.target);
97
+ if (!own || (!frame.target && !nativeReads.has(command)))
98
+ throw nativeTargetUnavailable();
99
+ args[at + 1] = frame.target ? (nativePanes.has(command) ? nativePaneTarget(frame.target) : nativeSessionTarget(frame.target)) : `=${frame.session}`;
100
+ }
101
+ start = end + 1;
102
+ }
103
+ if (effect || (targetedRead && frame.target)) {
104
+ if (frame.target)
105
+ verifyNativeTarget(frame);
106
+ else if (!args.includes("new-session") && !(args.length === 3 && args[0] === "set-option" && args[1] === "-gu" && args[2] === "update-environment"))
107
+ throw nativeTargetUnavailable();
108
+ }
109
+ return args;
110
+ }
111
+ const NATIVE_REFUSED = "__AITERM_NATIVE_GENERATION_REFUSED__";
112
+ /** Check on the receiving server too: a new server may recycle session and pane IDs. */
113
+ function nativeConditionalArgs(args) {
114
+ const target = nativeTargets.getStore()?.target;
115
+ if (!target || nativeReads.has(args[0]) || args[0] === "delete-buffer")
116
+ return args;
117
+ const condition = nativeSessionCondition(target, nativeTargets.getStore()?.allowExitedPane);
118
+ const quote = (value) => isWin
119
+ ? `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`
120
+ : `'${value.replace(/'/g, "'\\''")}'`;
121
+ const command = args.map(quote).join(" ");
122
+ return ["if-shell", "-F", "-t", nativePaneTarget(target), condition, command, `display-message -p ${NATIVE_REFUSED}`];
123
+ }
14
124
  // Windows ネイティブには tmux が無いため、tmux CLI 互換の native psmux を叩く
15
125
  // (POSIX = Linux/WSL2/macOS は従来どおり tmux を直接叩く。WSL 橋は e3f5fc8 で全廃)。
16
126
  export const isWin = process.platform === "win32";
@@ -243,7 +353,9 @@ export function tmuxCommandWithInput(observe, input, ...args) {
243
353
  // session は、新しい session を作る呼び出しの時だけ渡す client の環境(POSIX のみ)。server を起こし得るのは
244
354
  // この呼び出しだけなので、空 config の指定と macOS の gui domain での起動もここに限る。
245
355
  function runTmux(observe, input, args, session) {
246
- args = guardTmuxExecution(args);
356
+ // Authorize the logical/native session before routing it to its pinned pane.
357
+ args = nativeSessionArgs(guardTmuxExecution(args));
358
+ args = nativeConditionalArgs(args);
247
359
  // maxBuffer は既定 1MiB。capture-pane(大きなスクロールバック)や多セッションの list-sessions で
248
360
  // 頭打ちになり stdout が切れる/空になる。Python の subprocess.run は無制限だったので 64MiB へ広げる。
249
361
  // Windows は tmux CLI 互換の native psmux を -L namespace 隔離で叩く(WSL 非依存)。
@@ -272,6 +384,11 @@ function runTmux(observe, input, args, session) {
272
384
  tmuxBin = null; // 次回 resolveTmux で再解決を許す
273
385
  ptyDependencyError(tmuxMissingMessage(), observe);
274
386
  }
387
+ const native = nativeTargets.getStore();
388
+ if (native?.target && args[0] === "if-shell" && (r.stdout ?? "").trim() === NATIVE_REFUSED)
389
+ throw nativeTargetUnavailable();
390
+ if (native?.target && r.status !== 0)
391
+ verifyNativeTarget(native);
275
392
  return { code: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
276
393
  }
277
394
  // macOS の login keychain は GUI(Aqua)の security session からしか読めない。SSH 等から立てた
@@ -394,9 +511,16 @@ export function sendPsmuxPayload(observe, sessionName, text, bracketedPaste) {
394
511
  return { code: 1, stdout: "", stderr: "psmux direct send is Windows-only" };
395
512
  ensureWinPsmux(observe);
396
513
  beforeExecutionEffect(sessionName);
514
+ const frame = nativeTargets.getStore();
515
+ if (frame && (!frame.target || frame.session !== sessionName))
516
+ throw nativeTargetUnavailable();
517
+ if (frame)
518
+ verifyNativeTarget(frame);
519
+ const target = frame?.target;
520
+ const proof = target ? [target.native_id, target.session_id, target.server_pid, target.pane_id, target.pane_pid].join("\t") : null;
397
521
  const worker = fileURLToPath(new URL("./psmux-send-worker.js", import.meta.url));
398
522
  const body = bracketedPaste ? `\x1b[200~${text}\x1b[201~` : text;
399
- const result = spawnSync(process.execPath, [worker, `${WIN_NS}__${sessionName}`], {
523
+ const result = spawnSync(process.execPath, [worker, `${WIN_NS}__${sessionName}`, ...(proof === null ? [] : [proof])], {
400
524
  encoding: "utf8",
401
525
  maxBuffer: 1024 * 1024,
402
526
  input: Buffer.from(body, "utf8"),
@@ -457,8 +581,9 @@ export function sessionEnvironmentLaunch(shell, environment, version) {
457
581
  environment = [...environment, `PATH=${callerPath}`];
458
582
  }
459
583
  const modern = isWin || tmuxHasSessionEnvironmentFlags(version);
584
+ // tmux's argv parser treats even an environment value's trailing semicolon as a command separator.
460
585
  if (modern)
461
- return { shell, args: environment.flatMap(entry => ["-e", entry]), register_after_start: false };
586
+ return { shell, args: environment.flatMap(entry => ["-e", isWin ? entry : entry.replace(/;$/, "\\;")]), register_after_start: false };
462
587
  // tmux <3.2はnew-session -eを持たない。子への継承とsession台帳への登録を製品内で完結する。
463
588
  const quote = (value) => `'${value.replace(/'/g, "'\\''")}'`;
464
589
  return { shell: `exec /usr/bin/env ${environment.map(quote).join(" ")} ${quote(shell)}`, args: [], register_after_start: true };
@@ -498,6 +623,11 @@ export function registeredSessionEnvironment(name) {
498
623
  const r = runTmux(false, undefined, ["show-options", "-t", `=${name}:`, "-v", REGISTERED_ENV_OPTION]);
499
624
  return r.code === 0 && r.stdout.trim() ? r.stdout.trim().split(" ") : null;
500
625
  }
626
+ export function registerSessionEnvironment(observe, name, keys) {
627
+ if (keys.some(key => !ENV_NAME.test(key)))
628
+ throw new AitermError("env_varsの環境変数名が不正です", 2);
629
+ return runTmux(observe, undefined, ["set-option", "-t", `=${name}:`, REGISTERED_ENV_OPTION, [...new Set(keys)].join(" ")]);
630
+ }
501
631
  // tmux は、server を起こした client の環境を共通環境として全 session へ配る。何もしないと、最初に端末を
502
632
  // 開いた呼び出し元の値が、後から別の呼び出し元が開く端末へ入る。新しい端末の環境を「開いた process の環境」に
503
633
  // するため、new-session の間だけ update-environment を差し替えて client の環境を session へ写し、共通環境に
@@ -505,6 +635,7 @@ export function registeredSessionEnvironment(name) {
505
635
  // 変えない。同じ server を使う旧版の process が、開く端末の環境をそこから受け取っている。
506
636
  export function tmuxNewSession(observe, name, launch, registered = []) {
507
637
  const guarded = hasExecutionCreationScope();
638
+ const pinned = nativeTargets.getStore()?.created !== undefined;
508
639
  // Windows per-session server creation needs a separate native-owner proof.
509
640
  // The legacy public launcher is unchanged.
510
641
  let cold = false;
@@ -513,11 +644,27 @@ export function tmuxNewSession(observe, name, launch, registered = []) {
513
644
  throw new ExecutionError("EXECUTION_UNSUPPORTED");
514
645
  cold = prepareExecutionCreation();
515
646
  }
516
- const printNative = guarded ? ["-P", "-F", "#{session_id}\t#{session_name}\t#{pid}"] : [];
647
+ const printNative = pinned ? ["-P", "-F", "#{session_id}\t#{session_name}\t#{pid}\t#{pane_id}\t#{pane_pid}"]
648
+ : guarded ? ["-P", "-F", "#{session_id}\t#{session_name}\t#{pid}"] : [];
517
649
  if (isWin) {
518
650
  const result = runTmux(observe, undefined, ["new-session", "-d", "-s", name, ...printNative, ...launch.args, "-f", TMUX_EMPTY_CONFIG, launch.shell]);
651
+ if (result.code === 0) {
652
+ if (pinned) {
653
+ try {
654
+ if (parseNativeSessionReceipt(result.stdout).session_id !== name)
655
+ throw nativeTargetUnavailable();
656
+ }
657
+ catch {
658
+ throw nativeTargetUnavailable();
659
+ }
660
+ }
661
+ // Existing psmux 3.3.8 registry protection must run before identity reads can trigger registry reaping.
662
+ openPsmuxServerToDesktop(name);
663
+ }
519
664
  if (guarded && (result.code === 0 || result.stdout))
520
665
  captureExecutionCreatedNative(result.stdout);
666
+ if (pinned && (result.code === 0 || result.stdout))
667
+ captureNativeSessionReceipt(result.stdout);
521
668
  return result;
522
669
  }
523
670
  const env = sessionCallerEnvironment();
@@ -540,20 +687,22 @@ export function tmuxNewSession(observe, name, launch, registered = []) {
540
687
  const r = runTmux(observe, undefined, [
541
688
  "set-option", "-g", "update-environment", updateEnvironmentPatterns(Object.keys(env), [...others], wildcard).join(" "), ";",
542
689
  "new-session", "-d", "-s", name, ...printNative, ...launch.args, ...command, ";",
543
- ...(guarded ? [] : ["set-option", "-t", `=${name}:`, REGISTERED_ENV_OPTION, registered.join(" "), ";"]),
690
+ ...(guarded || pinned ? [] : ["set-option", "-t", `=${name}:`, REGISTERED_ENV_OPTION, registered.join(" "), ";"]),
544
691
  "set-option", "-gu", "update-environment",
545
692
  ], env);
546
693
  // Bind only the ID printed by this exact create command. Target-specific
547
694
  // setup runs later through that native ID, never a fresh same-name lookup.
548
695
  if (guarded && (r.code === 0 || r.stdout))
549
696
  captureExecutionCreatedNative(r.stdout);
697
+ if (pinned && (r.code === 0 || r.stdout))
698
+ captureNativeSessionReceipt(r.stdout);
550
699
  if (r.code !== 0) {
551
700
  // 途中の命令が失敗すると、後続の命令は実行されない。差し替えた設定を戻す。
552
701
  runTmux(false, undefined, ["set-option", "-gu", "update-environment"]);
553
702
  return r;
554
703
  }
555
- if (guarded) {
556
- const registeredResult = runTmux(observe, undefined, ["set-option", "-t", `=${name}:`, REGISTERED_ENV_OPTION, registered.join(" ")]);
704
+ if (guarded || pinned) {
705
+ const registeredResult = registerSessionEnvironment(observe, name, registered);
557
706
  if (registeredResult.code !== 0)
558
707
  return registeredResult;
559
708
  }
@@ -565,7 +714,7 @@ export function tmuxNewSession(observe, name, launch, registered = []) {
565
714
  if (uncovered?.length === 0)
566
715
  return r;
567
716
  runTmux(false, undefined, ["kill-session", "-t", `=${name}`]);
568
- if (guarded || !uncovered || attempt >= 2) {
717
+ if (guarded || pinned || !uncovered || attempt >= 2) {
569
718
  return { code: 1, stdout: "", stderr: "共通環境の変数をsessionから外せなかったため、sessionを破棄しました" };
570
719
  }
571
720
  for (const key of uncovered)