aiterm-mcp 0.62.5 → 0.63.0
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 +23 -1
- package/README.ja.md +8 -2
- package/README.md +8 -2
- package/dist/agent-activity.js +69 -0
- package/dist/agent-goal.js +3 -1
- package/dist/agent-idle-cli.js +36 -0
- package/dist/agent-idle-clock.js +100 -0
- package/dist/agent-idle.js +92 -0
- package/dist/agent-lifecycle.js +182 -0
- package/dist/agent-resolver.js +1 -1
- package/dist/agent-shared.js +61 -0
- package/dist/aiterm-wait-cli.js +11 -4
- package/dist/claude-stop-hook.js +12 -1
- package/dist/configure-goal.js +63 -0
- package/dist/core.js +1261 -304
- package/dist/errors.js +1 -0
- package/dist/execution-effect.js +8 -0
- package/dist/harnesses/claude.js +20 -5
- package/dist/harnesses/codex.js +170 -10
- package/dist/harnesses/grok.js +21 -0
- package/dist/harnesses/idle-settings.js +109 -0
- package/dist/index.js +14 -7
- package/dist/interim-words.js +18 -3
- package/dist/native-session.js +22 -0
- package/dist/process-runtime.js +83 -9
- package/dist/process-start.js +26 -7
- package/dist/process-tree-stop.js +91 -0
- package/dist/psmux-send-worker.js +7 -1
- package/dist/steer-follow.js +88 -3
- package/dist/tmux-runtime.js +157 -8
- package/docs/DESIGN.md +13 -1
- package/package.json +3 -2
package/dist/interim-words.js
CHANGED
|
@@ -14,7 +14,7 @@ import * as path from "node:path";
|
|
|
14
14
|
import { AitermError } from "./errors.js";
|
|
15
15
|
import { agentHarness, agentsDir, assertSessionName, LAUNCH_ID_RE, readFileRange, safeStatSize, writeJson0600, } from "./agent-shared.js";
|
|
16
16
|
import { claudeSessionTranscriptPath } from "./harnesses/claude.js";
|
|
17
|
-
import { codexBoundTranscript, codexRootTranscript, codexTurnError, codexTurnErrorLine } from "./harnesses/codex.js";
|
|
17
|
+
import { codexBoundTranscript, codexRootTranscript, codexResumeCursor, codexResumeTurnId, codexTurnError, codexTurnErrorLine } from "./harnesses/codex.js";
|
|
18
18
|
import { grokSessionDirectory } from "./harnesses/grok.js";
|
|
19
19
|
import { cursorTranscript } from "./harnesses/cursor.js";
|
|
20
20
|
/** BellTeamが要求の_metaへ入れる呼び手の印。値が "BellTeam" の時だけ合間の言葉を返す。 */
|
|
@@ -282,6 +282,21 @@ export function interimFromNow(meta, eventCursor) {
|
|
|
282
282
|
return { event_cursor: eventCursor, unit: "byte", boundary: file ? safeStatSize(file) : 0 };
|
|
283
283
|
}
|
|
284
284
|
/** 渡された位置より後に書かれた合間の言葉。位置の単位がharnessと合わない時は、言葉なし。 */
|
|
285
|
+
function codexLinesFrom(meta, boundary) {
|
|
286
|
+
const file = meta.vendor_session_id ? codexBoundTranscript(meta) : codexRootTranscript(meta);
|
|
287
|
+
const retiredTurn = codexResumeTurnId(meta, meta.vendor_session_id);
|
|
288
|
+
return readLines(file, file ? Math.max(boundary, codexResumeCursor(meta, file)) : boundary).filter(line => {
|
|
289
|
+
if (!retiredTurn)
|
|
290
|
+
return true;
|
|
291
|
+
try {
|
|
292
|
+
const payload = JSON.parse(line)?.payload;
|
|
293
|
+
return payload?.turn_id !== retiredTurn && payload?.internal_chat_message_metadata_passthrough?.turn_id !== retiredTurn;
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
}
|
|
285
300
|
function interimWordsFrom(meta, from) {
|
|
286
301
|
if (meta.kind === "grok")
|
|
287
302
|
return from.unit === "user" ? grokInterimWords(readLines(grokChatHistory(meta)), from.boundary) : [];
|
|
@@ -290,7 +305,7 @@ function interimWordsFrom(meta, from) {
|
|
|
290
305
|
if (meta.kind === "claude")
|
|
291
306
|
return claudeInterimWords(readLines(claudeSessionTranscriptPath(meta), from.boundary));
|
|
292
307
|
if (meta.kind === "codex")
|
|
293
|
-
return codexInterimWords(
|
|
308
|
+
return codexInterimWords(codexLinesFrom(meta, from.boundary));
|
|
294
309
|
// 位置より後の行だけを渡すので、user発話の数では絞らない。
|
|
295
310
|
return meta.kind === "cursor" ? cursorInterimWords(readLines(cursorTranscript(meta), from.boundary), -1) : [];
|
|
296
311
|
}
|
|
@@ -322,7 +337,7 @@ export function readInterimWords(meta, after, from = null) {
|
|
|
322
337
|
found = claudeInterimWords(readLines(claudeSessionTranscriptPath(meta), boundary));
|
|
323
338
|
// 境界は、送った時に結び付いていた会話のrolloutの位置。会話の切り替えは追わない(ADR 0105)。
|
|
324
339
|
else if (meta.kind === "codex")
|
|
325
|
-
found = codexInterimWords(
|
|
340
|
+
found = codexInterimWords(codexLinesFrom(meta, boundary));
|
|
326
341
|
else if (meta.kind === "grok")
|
|
327
342
|
found = grokInterimWords(readLines(grokChatHistory(meta)), boundary);
|
|
328
343
|
else if (meta.kind === "cursor")
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export function parseNativeSessionReceipt(receipt, platform = process.platform) {
|
|
2
|
+
const separator = platform === "win32" ? "[ \\t]" : "\\t";
|
|
3
|
+
const match = new RegExp(`^(\\$\\d+)${separator}([A-Za-z0-9_-]{1,64})${separator}([1-9][0-9]*)${separator}(%\\d+)${separator}([1-9][0-9]*)\\r?\\n?$`).exec(receipt);
|
|
4
|
+
if (!match || !Number.isSafeInteger(Number(match[3])) || !Number.isSafeInteger(Number(match[5])))
|
|
5
|
+
throw new Error("native_session_receipt_unconfirmed");
|
|
6
|
+
return { native_id: match[1], session_id: match[2], server_pid: Number(match[3]), pane_id: match[4], pane_pid: Number(match[5]) };
|
|
7
|
+
}
|
|
8
|
+
export function nativePaneTarget(target, platform = process.platform) {
|
|
9
|
+
// Qualify psmux panes by session; $ID routing under -L duplicates the namespace prefix.
|
|
10
|
+
return platform === "win32" ? `${target.session_id}:.${target.pane_id}` : target.pane_id;
|
|
11
|
+
}
|
|
12
|
+
export function nativeSessionTarget(target, platform = process.platform) {
|
|
13
|
+
// psmux kill-session compares the raw name; a trailing colon silently misses.
|
|
14
|
+
return platform === "win32" ? `=${target.session_id}` : target.native_id;
|
|
15
|
+
}
|
|
16
|
+
export function nativeSessionCondition(target, allowExitedPane = false) {
|
|
17
|
+
const pane = `#{==:#{pane_pid},${target.pane_pid}}`;
|
|
18
|
+
return [...[["pid", target.server_pid], ["session_id", target.native_id], ["session_name", target.session_id],
|
|
19
|
+
["pane_id", target.pane_id]].map(([key, value]) => `#{==:#{${key}},${value}}`),
|
|
20
|
+
allowExitedPane ? `#{||:${pane},#{&&:#{==:#{pane_dead},1},#{==:#{pane_pid},}}}` : pane]
|
|
21
|
+
.reduce((left, right) => `#{&&:${left},${right}}`);
|
|
22
|
+
}
|
package/dist/process-runtime.js
CHANGED
|
@@ -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
|
-
|
|
26
|
-
|
|
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
|
|
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
|
-
|
|
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
|
+
}
|
package/dist/process-start.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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) {
|
package/dist/steer-follow.js
CHANGED
|
@@ -12,8 +12,9 @@ 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
|
+
import { grokEventsTranscript, grokSessionDirectory, grokUserPrompt } from "./harnesses/grok.js";
|
|
17
18
|
/** 差し込みの返りの_metaで返すキー。 */
|
|
18
19
|
export const STEER_RESULT_META_KEY = "aiterm/steer";
|
|
19
20
|
/** pty_listの結果の_metaで返すキー。 */
|
|
@@ -70,6 +71,10 @@ export function recordSteer(meta, from, body) {
|
|
|
70
71
|
event_cursor: from.event_cursor,
|
|
71
72
|
interim_from: interimFromToken(from),
|
|
72
73
|
needle: steerNeedle(body),
|
|
74
|
+
...(meta.kind === "grok" ? {
|
|
75
|
+
body_digest: createHash("sha256").update(squeeze(body)).digest("hex"),
|
|
76
|
+
history_cursor: safeStatSize(path.join(grokSessionDirectory(meta) ?? "", "chat_history.jsonl")),
|
|
77
|
+
} : {}),
|
|
73
78
|
};
|
|
74
79
|
if (safeStatSize(file) > STEER_LEDGER_MAX_BYTES) {
|
|
75
80
|
const kept = fs.readFileSync(file, "utf8").split("\n").filter(line => parseSteerEntry(line)).slice(-STEER_LEDGER_KEEP);
|
|
@@ -173,15 +178,92 @@ function baseObservation(meta) {
|
|
|
173
178
|
/**
|
|
174
179
|
* 差し込んだ文を取った番の終わりを待つ。
|
|
175
180
|
* CodexとClaude Codeは、harnessの記録の中から文を見つけて、その番の終わりを返す。
|
|
176
|
-
* Grok
|
|
181
|
+
* Grokは送信後の本文全体とnative turn番号を照合する。照合できなければ旧turn完了で代用しない。
|
|
182
|
+
* Cursorはqueue操作で確認した現在turnの完了を追う。
|
|
177
183
|
*/
|
|
178
184
|
export async function observeSteerDone(meta, entry, timeoutSeconds, deps) {
|
|
179
185
|
if (meta.kind === "codex")
|
|
180
186
|
return observeCodexSteerDone(meta, entry, timeoutSeconds, deps);
|
|
181
187
|
if (meta.kind === "claude")
|
|
182
188
|
return observeClaudeSteerDone(meta, entry, timeoutSeconds, deps);
|
|
189
|
+
if (meta.kind === "grok") {
|
|
190
|
+
const deadline = performance.now() + timeoutSeconds * 1000;
|
|
191
|
+
for (;;) {
|
|
192
|
+
deps.signal?.throwIfAborted();
|
|
193
|
+
if (!fs.existsSync(agentMetadataPath(meta.aiterm_session, meta.launch_id)))
|
|
194
|
+
return { ...baseObservation(meta), outcome: "closed", steer: fate("unknown") };
|
|
195
|
+
const accepted = grokSteerAcceptance(meta, entry);
|
|
196
|
+
if (accepted)
|
|
197
|
+
return { ...await deps.plain(accepted.event_cursor, Math.max(0, (deadline - performance.now()) / 1000)),
|
|
198
|
+
steer: fate(accepted.placement, accepted.taken_at) };
|
|
199
|
+
if (performance.now() >= deadline)
|
|
200
|
+
return { ...baseObservation(meta), outcome: timeoutSeconds === 0 ? "running" : "timeout", steer: fate("unknown") };
|
|
201
|
+
await sleep(AGENT_DONE_POLL_MS);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
183
204
|
return { ...await deps.plain(entry.event_cursor, timeoutSeconds), steer: fate("same_turn") };
|
|
184
205
|
}
|
|
206
|
+
/** Correlate the newly appended full input with Grok's prompt_index/turn_number. */
|
|
207
|
+
export function grokSteerAcceptance(meta, entry) {
|
|
208
|
+
const directory = grokSessionDirectory(meta), events = grokEventsTranscript(meta);
|
|
209
|
+
if (!directory || !events || !entry.body_digest || !Number.isSafeInteger(entry.history_cursor) || entry.history_cursor < 0)
|
|
210
|
+
return null;
|
|
211
|
+
const history = path.join(directory, "chat_history.jsonl");
|
|
212
|
+
const completeLines = (file, from) => {
|
|
213
|
+
const size = safeStatSize(file);
|
|
214
|
+
// shortcut: refuse transcript increments above 4 MiB; add streaming if real input crosses this bound.
|
|
215
|
+
if (size < from || size - from > STEER_READ_CHUNK_BYTES || (from > 0 && readFileRange(file, from - 1, from)[0] !== 10))
|
|
216
|
+
return null;
|
|
217
|
+
return readFileRange(file, from, size).toString("utf8").split("\n").slice(0, -1);
|
|
218
|
+
};
|
|
219
|
+
try {
|
|
220
|
+
const rows = completeLines(history, entry.history_cursor), boundaries = completeLines(events, entry.event_cursor);
|
|
221
|
+
if (!rows || !boundaries)
|
|
222
|
+
return null;
|
|
223
|
+
const matches = [];
|
|
224
|
+
for (const line of rows) {
|
|
225
|
+
let row;
|
|
226
|
+
try {
|
|
227
|
+
row = JSON.parse(line);
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
const prompt = grokUserPrompt(row);
|
|
233
|
+
if (prompt !== null && createHash("sha256").update(squeeze(prompt)).digest("hex") === entry.body_digest) {
|
|
234
|
+
if (!Number.isSafeInteger(row.prompt_index) || row.prompt_index < 0)
|
|
235
|
+
return null;
|
|
236
|
+
matches.push(row.prompt_index);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (matches.length !== 1)
|
|
240
|
+
return null;
|
|
241
|
+
let offset = entry.event_cursor, sendNow = false;
|
|
242
|
+
const starts = [];
|
|
243
|
+
for (const line of boundaries) {
|
|
244
|
+
let row;
|
|
245
|
+
try {
|
|
246
|
+
row = JSON.parse(line);
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
if (row?.type === "turn_ended" && row.cancellation_context?.trigger === "send_now")
|
|
252
|
+
sendNow = true;
|
|
253
|
+
if (row?.type === "turn_started") {
|
|
254
|
+
if (row.turn_number === matches[0])
|
|
255
|
+
starts.push({ event_cursor: offset,
|
|
256
|
+
placement: sendNow ? "same_turn" : "next_turn", taken_at: typeof row.ts === "string" ? row.ts : null });
|
|
257
|
+
sendNow = false;
|
|
258
|
+
}
|
|
259
|
+
offset += Buffer.byteLength(line + "\n");
|
|
260
|
+
}
|
|
261
|
+
return starts.length === 1 ? starts[0] : null;
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
return null;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
185
267
|
// ------------------------------------------------ Codex
|
|
186
268
|
/**
|
|
187
269
|
* Codexの記録の、利用者の文の行。文でなければnull。
|
|
@@ -219,7 +301,7 @@ async function observeCodexSteerDone(meta, entry, timeoutSeconds, deps) {
|
|
|
219
301
|
return { ...await deps.plain(entry.event_cursor, timeoutSeconds), steer: fate("unknown") };
|
|
220
302
|
const metadataFile = agentMetadataPath(meta.aiterm_session, meta.launch_id);
|
|
221
303
|
const harnessSessionId = meta.vendor_session_id ? codexRolloutSessionId(meta, transcript) : codexTranscriptSessionId(transcript);
|
|
222
|
-
const follower = new LineFollower(transcript, entry.event_cursor);
|
|
304
|
+
const follower = new LineFollower(transcript, Math.max(entry.event_cursor, codexResumeCursor(meta, transcript)));
|
|
223
305
|
const sentAt = Date.parse(entry.at);
|
|
224
306
|
const deadline = performance.now() + timeoutSeconds * 1000;
|
|
225
307
|
let malformedEvents = 0;
|
|
@@ -250,6 +332,7 @@ async function observeCodexSteerDone(meta, entry, timeoutSeconds, deps) {
|
|
|
250
332
|
throw new AitermError("Codex transcript が完了待機中に短くなりました。該当セッションを閉じて起動し直してください。", 2);
|
|
251
333
|
if (lines.length)
|
|
252
334
|
quietSince = performance.now();
|
|
335
|
+
const retiredTurn = codexResumeTurnId(meta, harnessSessionId);
|
|
253
336
|
for (const line of lines) {
|
|
254
337
|
if (!line.trim())
|
|
255
338
|
continue;
|
|
@@ -266,6 +349,8 @@ async function observeCodexSteerDone(meta, entry, timeoutSeconds, deps) {
|
|
|
266
349
|
continue;
|
|
267
350
|
}
|
|
268
351
|
const payload = record?.payload;
|
|
352
|
+
if (retiredTurn && (payload?.turn_id === retiredTurn || payload?.internal_chat_message_metadata_passthrough?.turn_id === retiredTurn))
|
|
353
|
+
continue;
|
|
269
354
|
if (record?.type === "event_msg" && payload?.type === "task_started" && typeof payload.turn_id === "string") {
|
|
270
355
|
openTurn = payload.turn_id;
|
|
271
356
|
startedAfter.add(payload.turn_id);
|