aiterm-steer-delivery 0.4.4 → 0.4.5
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 -0
- package/dist/channel.d.ts +6 -9
- package/dist/channel.js +19 -8
- package/dist/claude-receiver.d.ts +3 -2
- package/dist/claude-receiver.js +17 -11
- package/dist/codex-hook-state.js +4 -3
- package/dist/codex-hooks.js +4 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/process.d.ts +18 -0
- package/dist/process.js +142 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.5
|
|
4
|
+
|
|
5
|
+
待機や受信hookが、端末の全processの一覧を取り続けて端末を重くしていたのを直します。関数の名前・引数・返り、置き場の作り、符号は変わりません。
|
|
6
|
+
|
|
7
|
+
- **起きていた事。** channelの待機(`runClaudeChannelWaiter`。hookから起きて最長1日待つ)は、出す先のClaude Codeが生きているかを、
|
|
8
|
+
5秒おきに全processの一覧(`readRuntimeProcesses`)で確かめていた。Windowsでは1回ごとにPowerShell 7を起こし、WMIで全processを引く。
|
|
9
|
+
待機は会話の数だけ同時に動く。process 1300個のWindowsで、待機11個が5秒おきにこれを回し、WMIの側のprocessがCPUを2〜7コア使っていた
|
|
10
|
+
(2026-10-12)。受信hookが走るたびにも、自分・持ち主・前の待機を確かめるために、全processの一覧を2〜3回取っていた。
|
|
11
|
+
- **5秒おきは、pidの有無だけを見る。** OSへ直接聞き(`process.kill(pid, 0)`)、processを起こさない。開始時刻の照合は、最初と60秒に1回だけ。
|
|
12
|
+
出す先が終わった直後に同じpidが別のprocessへ使い回された時だけ、待機の終わりが最長60秒遅れる。
|
|
13
|
+
- **1個のprocessを読む時は、その1個だけを読む。** 足した口: `readProcessIdentities(pids)`(指定したpidの開始時刻)、
|
|
14
|
+
`processIsRunning(pid, started_identity)`(記録にある本人のまま居るか。居ないと分かっている時はprocessを起こさない)、
|
|
15
|
+
`processExists(pid)`、`readProcessLineage(pid)`(そのpidと先祖。hookの持ち主を探す)。
|
|
16
|
+
今までの`readRuntimeProcesses`(全processの一覧)は残してある。
|
|
17
|
+
- **Windowsでは、1個を読むのにWMIを使わない。** .NETのprocessの読み(`Process.StartTime`と`Parent`)を使う。WMIは絞っても1回に0.1〜0.3秒かかり、
|
|
18
|
+
.NETは1個1.5ミリ秒。開始時刻は今までと同じ文字列になる(WMIはマイクロ秒で切り捨てた値を返し、どちらも1ミリ秒で切り捨てて使う。
|
|
19
|
+
実物の888個のprocessで食い違いは0)。権限が無くて読めないprocessだけ、WMIへ聞き直す。
|
|
20
|
+
- 置き換えた所: channelの待機と持ち主の確かめ、受け口が取った記録の確かめ、受信hookの依頼の記録と古い置き場の見回り、
|
|
21
|
+
回答を届ける間の確かめ(`submitClaudeParentAnswer`)、Codexの受信hookの自分の確かめと先祖の確かめ。
|
|
22
|
+
- `sweepClaudeHookRequests`の2つ目の引数は、今までの一覧のほかに、確かめる関数(`(pid, started_identity) => boolean`)も受ける。
|
|
23
|
+
`submitClaudeParentAnswer`の`runtime`は、今までの`processes`のほかに`running`も受ける。今までの渡し方はそのまま動く。
|
|
24
|
+
- 今動いている待機と受信hookは、古い中身のまま動き続ける。新しい中身になるのは、部品を入れ替えた後に起きたprocessから。
|
|
25
|
+
|
|
3
26
|
## 0.4.4
|
|
4
27
|
|
|
5
28
|
channelへ同じ配送IDの本文を送り直した時に、親へ同じ文が2回出る事があったのを直します。関数の形、置き場の作り、符号は変わりません。
|
package/dist/channel.d.ts
CHANGED
|
@@ -55,15 +55,6 @@ export declare function channelDeliveryState(profile: ProductProfile, channelId:
|
|
|
55
55
|
* 受け口が先に取っていたらfalse。channelを張り直す時に、未取得の本文を新しいchannelへ送り直すために使う。
|
|
56
56
|
*/
|
|
57
57
|
export declare function withdrawFromChannel(profile: ProductProfile, channelId: string, deliveryId: string): boolean;
|
|
58
|
-
/**
|
|
59
|
-
* Claude Codeのhook(PostToolUse・Stop、asyncRewake)から呼ぶ。その会話のchannelに届いた本文を待ち、
|
|
60
|
-
* 出力したら2(親を起こす)、待つものが無い・他の待機が生きている・会話が終わったなら0を返す。
|
|
61
|
-
*
|
|
62
|
-
* 待機は、このhookを起こしたClaude Codeのprocessが生きている間だけ続ける。本文はそのprocessへ出すので、居なくなった後に取ると失う。
|
|
63
|
-
* channelを開いた時のprocess(`channel.claude.parent_pid`)が居なくなっていても、同じ会話(session_id)のhookを走らせている今のprocessへ出す。
|
|
64
|
-
* Claude Codeが起動し直して同じ会話を再開した後も、前のprocessが開いたchannelの本文が届く。
|
|
65
|
-
* hookを起こしたprocessを確かめられない時だけ、channelを開いた時のprocessの生き死にで決める。
|
|
66
|
-
*/
|
|
67
58
|
export declare function runClaudeChannelWaiter(profile: ProductProfile, input: unknown, emit: (text: string) => Promise<void> | void, options?: {
|
|
68
59
|
wait_ms?: number;
|
|
69
60
|
poll_ms?: number;
|
|
@@ -71,6 +62,12 @@ export declare function runClaudeChannelWaiter(profile: ProductProfile, input: u
|
|
|
71
62
|
pid: number;
|
|
72
63
|
started_identity: string;
|
|
73
64
|
} | null;
|
|
65
|
+
owner_check_ms?: number;
|
|
66
|
+
identity_recheck_ms?: number;
|
|
67
|
+
runtime?: {
|
|
68
|
+
exists: (pid: number) => boolean;
|
|
69
|
+
identity: (pid: number) => string | undefined;
|
|
70
|
+
};
|
|
74
71
|
}): Promise<0 | 2>;
|
|
75
72
|
/** Claude CodeのSessionEndで、その会話のchannelを閉じる。未取得の本文は残る。 */
|
|
76
73
|
export declare function closeClaudeSessionChannels(profile: ProductProfile, input: unknown): void;
|
package/dist/channel.js
CHANGED
|
@@ -12,7 +12,7 @@ import { randomUUID } from "node:crypto";
|
|
|
12
12
|
import { setTimeout as delay } from "node:timers/promises";
|
|
13
13
|
import { z } from "zod";
|
|
14
14
|
import { writeJson0600 } from "./files.js";
|
|
15
|
-
import { hookOwnerProcess,
|
|
15
|
+
import { hookOwnerProcess, processExists, processIsRunning, readProcessIdentities, readProcessLineage } from "./process.js";
|
|
16
16
|
import { channelRoot } from "./profile.js";
|
|
17
17
|
import { SteerDeliveryError } from "./errors.js";
|
|
18
18
|
import { submitCodexParentAnswer } from "./codex-receiver.js";
|
|
@@ -33,8 +33,9 @@ const itemSchema = z.object({ delivery_id: z.uuid(), text: z.string(), at: z.str
|
|
|
33
33
|
function channelDir(profile, channelId) {
|
|
34
34
|
return path.join(channelRoot(profile), uuid.parse(channelId));
|
|
35
35
|
}
|
|
36
|
+
// 1個のprocessだけを読む。全processの一覧は取らない(Windowsでは1回が重く、待機の数だけ回ると端末全体を重くする)。
|
|
36
37
|
function processIdentity(pid) {
|
|
37
|
-
return
|
|
38
|
+
return readProcessIdentities([pid])[0]?.started_identity ?? undefined;
|
|
38
39
|
}
|
|
39
40
|
function mkdirs(...dirs) { for (const dir of dirs)
|
|
40
41
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); }
|
|
@@ -155,7 +156,7 @@ export function channelDeliveryState(profile, channelId, deliveryId) {
|
|
|
155
156
|
return "unknown";
|
|
156
157
|
if (value.state === "withdrawn")
|
|
157
158
|
return "withdrawn";
|
|
158
|
-
if (typeof value.pid === "number" && typeof value.started_identity === "string" &&
|
|
159
|
+
if (typeof value.pid === "number" && typeof value.started_identity === "string" && !processIsRunning(value.pid, value.started_identity))
|
|
159
160
|
return "unknown";
|
|
160
161
|
return "sending";
|
|
161
162
|
}
|
|
@@ -300,7 +301,7 @@ function acquireWaiter(index) {
|
|
|
300
301
|
owner = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
301
302
|
}
|
|
302
303
|
catch { /* 書き込み途中。次の試行で読む */ }
|
|
303
|
-
if (typeof owner.pid === "number" && typeof owner.started_identity === "string" &&
|
|
304
|
+
if (typeof owner.pid === "number" && typeof owner.started_identity === "string" && processIsRunning(owner.pid, owner.started_identity))
|
|
304
305
|
return null;
|
|
305
306
|
// 終了した待機の記録。renameで一つのprocessだけが片付ける。
|
|
306
307
|
try {
|
|
@@ -323,7 +324,7 @@ function releaseWaiter(index, identity) {
|
|
|
323
324
|
}
|
|
324
325
|
/** このhookを起こしたClaude Codeのprocess。shellを通す形のhookでは、直接の親のshellの先をたどる。分からなければnull。 */
|
|
325
326
|
function currentHookOwner() {
|
|
326
|
-
const owner = hookOwnerProcess(
|
|
327
|
+
const owner = hookOwnerProcess(readProcessLineage(process.ppid), process.ppid);
|
|
327
328
|
return owner ? { pid: owner.pid, started_identity: owner.started_identity } : null;
|
|
328
329
|
}
|
|
329
330
|
/**
|
|
@@ -335,6 +336,9 @@ function currentHookOwner() {
|
|
|
335
336
|
* Claude Codeが起動し直して同じ会話を再開した後も、前のprocessが開いたchannelの本文が届く。
|
|
336
337
|
* hookを起こしたprocessを確かめられない時だけ、channelを開いた時のprocessの生き死にで決める。
|
|
337
338
|
*/
|
|
339
|
+
// 待機は最長で1日続き、会話の数だけ同時に動く。5秒おきの確かめはpidの有無だけにして(processを起こさない)、
|
|
340
|
+
// 開始時刻は最初とこの間隔でだけ照合する。出す先が終わった直後に同じpidが使い回された時だけ、待機の終わりが最長でこの間隔だけ遅れる。
|
|
341
|
+
const WAITER_OWNER_IDENTITY_RECHECK_MS = 60_000;
|
|
338
342
|
export async function runClaudeChannelWaiter(profile, input, emit, options = {}) {
|
|
339
343
|
const event = z.object({ session_id: z.uuid() }).loose().parse(input);
|
|
340
344
|
if (!openClaudeChannels(profile, event.session_id).length)
|
|
@@ -345,17 +349,24 @@ export async function runClaudeChannelWaiter(profile, input, emit, options = {})
|
|
|
345
349
|
if (!identity)
|
|
346
350
|
return 0;
|
|
347
351
|
const deadline = Date.now() + (options.wait_ms ?? 86_340_000);
|
|
352
|
+
const runtime = options.runtime ?? { exists: processExists, identity: processIdentity };
|
|
353
|
+
const recheckMs = options.identity_recheck_ms ?? WAITER_OWNER_IDENTITY_RECHECK_MS;
|
|
348
354
|
let lastParentCheck = 0;
|
|
355
|
+
let lastIdentityCheck = null;
|
|
349
356
|
try {
|
|
350
357
|
for (;;) {
|
|
351
358
|
const channels = openClaudeChannels(profile, event.session_id);
|
|
352
359
|
if (!channels.length)
|
|
353
360
|
return 0;
|
|
354
|
-
if (Date.now() - lastParentCheck >= 5_000) {
|
|
361
|
+
if (Date.now() - lastParentCheck >= (options.owner_check_ms ?? 5_000)) {
|
|
355
362
|
lastParentCheck = Date.now();
|
|
356
363
|
// 本文を出す先(このhookを起こしたClaude process)が終わっていたら、本文を取らずに待機を終える。
|
|
357
|
-
const
|
|
358
|
-
|
|
364
|
+
const verify = lastIdentityCheck === null || lastParentCheck - lastIdentityCheck >= recheckMs;
|
|
365
|
+
if (verify)
|
|
366
|
+
lastIdentityCheck = lastParentCheck;
|
|
367
|
+
const running = (pid, identity) => runtime.exists(pid) && (!verify || runtime.identity(pid) === identity);
|
|
368
|
+
const alive = owner ? running(owner.pid, owner.started_identity)
|
|
369
|
+
: channels.some(channel => running(channel.claude.parent_pid, channel.claude.parent_started_identity));
|
|
359
370
|
if (!alive)
|
|
360
371
|
return 0;
|
|
361
372
|
}
|
|
@@ -15,7 +15,7 @@ export declare function prepareClaudeHookRequest(input: unknown, root: string):
|
|
|
15
15
|
* 消すのは、最後に書かれてから1日たち、待っている配送が無い置き場だけ。依頼元のClaude processが居て、配送を結んであり、
|
|
16
16
|
* まだ出し終えていない置き場は、何日たっても残す(子が長く動いている配送)。1日は、届かなかった時に原因を調べる間。
|
|
17
17
|
*/
|
|
18
|
-
export declare function sweepClaudeHookRequests(root: string, rows: readonly RuntimeProcess[], now?: number): number;
|
|
18
|
+
export declare function sweepClaudeHookRequests(root: string, rows: readonly RuntimeProcess[] | ((pid: number, startedIdentity: string) => boolean), now?: number): number;
|
|
19
19
|
/**
|
|
20
20
|
* 誤りで返す呼び出しの置き場を消し、消したかを返す。製品は、toolの返りを誤り(`isError`)にする時に、返す前に呼ぶ。
|
|
21
21
|
* Claude Codeは誤りの返りでPostToolUseを走らせないので、配送の無い呼び出しの片付け(runClaudeResultHook)が走らない。
|
|
@@ -30,7 +30,8 @@ export declare function bindClaudeParentDelivery(profile: ProductProfile, parent
|
|
|
30
30
|
/** SessionEndはその時点の依頼だけを終了する。同じ会話をresumeした新規依頼は別requestになる。 */
|
|
31
31
|
export declare function closeClaudeParentSession(input: unknown, root: string): void;
|
|
32
32
|
export declare function submitClaudeParentAnswer(profile: ProductProfile, parent: ClaudeParent, deliveryId: string, text: string, runtime?: {
|
|
33
|
-
processes
|
|
33
|
+
processes?: () => RuntimeProcess[];
|
|
34
|
+
running?: (pid: number, startedIdentity: string) => boolean;
|
|
34
35
|
}): Promise<{
|
|
35
36
|
queued_submission_id: null;
|
|
36
37
|
}>;
|
package/dist/claude-receiver.js
CHANGED
|
@@ -5,7 +5,7 @@ import * as fs from "node:fs";
|
|
|
5
5
|
import * as path from "node:path";
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
import { waitForFileState, writeJson0600 } from "./files.js";
|
|
8
|
-
import { hookOwnerProcess,
|
|
8
|
+
import { hookOwnerProcess, processIsRunning, readProcessIdentities, readProcessLineage } from "./process.js";
|
|
9
9
|
import { ClaudeDeliveryError } from "./errors.js";
|
|
10
10
|
const requestId = z.string().regex(/^[A-Za-z0-9_-]{1,160}$/);
|
|
11
11
|
const invocationSchema = z.object({
|
|
@@ -15,7 +15,8 @@ const invocationSchema = z.object({
|
|
|
15
15
|
export const claudeParentSchema = z.object({
|
|
16
16
|
kind: z.literal("claude"), request_id: requestId, session_id: z.uuid(), hook_root: z.string(),
|
|
17
17
|
}).strict();
|
|
18
|
-
|
|
18
|
+
// 1個のprocessだけを読む。全processの一覧は取らない。
|
|
19
|
+
function processIdentity(pid) { return readProcessIdentities([pid])[0]?.started_identity ?? undefined; }
|
|
19
20
|
function directory(parent) { return path.join(parent.hook_root, parent.request_id); }
|
|
20
21
|
function readInvocation(profile, parent) {
|
|
21
22
|
let value;
|
|
@@ -38,8 +39,7 @@ function assertOpen(parent) {
|
|
|
38
39
|
export function prepareClaudeHookRequest(input, root) {
|
|
39
40
|
const event = z.object({ session_id: z.uuid(), tool_use_id: requestId, agent_id: z.string().optional() }).parse(input);
|
|
40
41
|
// shellを通す形のhookでは、直接の親はshellになる。shellはこのhookと一緒に終わるので、その先のClaude processを記録する。
|
|
41
|
-
const
|
|
42
|
-
const owner = hookOwnerProcess(rows, process.ppid);
|
|
42
|
+
const owner = hookOwnerProcess(readProcessLineage(process.ppid), process.ppid);
|
|
43
43
|
if (!owner)
|
|
44
44
|
throw new ClaudeDeliveryError("CLAUDE_PARENT_PROCESS_UNAVAILABLE", "hookを起動した親processを確認できません");
|
|
45
45
|
const dir = path.join(root, event.tool_use_id);
|
|
@@ -48,9 +48,9 @@ export function prepareClaudeHookRequest(input, root) {
|
|
|
48
48
|
request_id: event.tool_use_id, session_id: event.session_id, agent_id: event.agent_id ?? null,
|
|
49
49
|
parent_pid: owner.pid, parent_started_identity: owner.started_identity,
|
|
50
50
|
});
|
|
51
|
-
//
|
|
51
|
+
// 記録を置いた後に見回る。依頼元の生き死には、古い置き場が在る時にだけ、その1個を読む。見回りの失敗で依頼を止めない。
|
|
52
52
|
try {
|
|
53
|
-
sweepClaudeHookRequests(root,
|
|
53
|
+
sweepClaudeHookRequests(root, processIsRunning);
|
|
54
54
|
}
|
|
55
55
|
catch { /* 次の依頼でまた見回る */ }
|
|
56
56
|
}
|
|
@@ -64,6 +64,8 @@ const REQUEST_FILES = new Set(["request.json", "delivery.json", "answer.json", "
|
|
|
64
64
|
* まだ出し終えていない置き場は、何日たっても残す(子が長く動いている配送)。1日は、届かなかった時に原因を調べる間。
|
|
65
65
|
*/
|
|
66
66
|
export function sweepClaudeHookRequests(root, rows, now = Date.now()) {
|
|
67
|
+
const running = typeof rows === "function" ? rows
|
|
68
|
+
: (pid, startedIdentity) => rows.find(row => row.pid === pid)?.started_identity === startedIdentity;
|
|
67
69
|
let entries;
|
|
68
70
|
try {
|
|
69
71
|
entries = fs.readdirSync(root, { withFileTypes: true });
|
|
@@ -92,7 +94,7 @@ export function sweepClaudeHookRequests(root, rows, now = Date.now()) {
|
|
|
92
94
|
invocation = invocationSchema.parse(JSON.parse(fs.readFileSync(path.join(dir, "request.json"), "utf8")));
|
|
93
95
|
}
|
|
94
96
|
catch { /* 消す */ }
|
|
95
|
-
if (invocation &&
|
|
97
|
+
if (invocation && running(invocation.parent_pid, invocation.parent_started_identity))
|
|
96
98
|
continue;
|
|
97
99
|
}
|
|
98
100
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
@@ -185,11 +187,13 @@ export function closeClaudeParentSession(input, root) {
|
|
|
185
187
|
throw failure;
|
|
186
188
|
}
|
|
187
189
|
function assertParentAlive(invocation) {
|
|
188
|
-
if (
|
|
190
|
+
if (!processIsRunning(invocation.parent_pid, invocation.parent_started_identity)) {
|
|
189
191
|
throw new ClaudeDeliveryError("CLAUDE_PARENT_PROCESS_CLOSED", "依頼元のClaude processは終了しました。回答は保存したままです");
|
|
190
192
|
}
|
|
191
193
|
}
|
|
192
|
-
export async function submitClaudeParentAnswer(profile, parent, deliveryId, text,
|
|
194
|
+
export async function submitClaudeParentAnswer(profile, parent, deliveryId, text,
|
|
195
|
+
// 既定は、確かめる2個(受信hookと依頼元)だけを読む。`processes` を渡した時は、その一覧で確かめる。
|
|
196
|
+
runtime = { running: processIsRunning }) {
|
|
193
197
|
const invocation = readInvocation(profile, parent);
|
|
194
198
|
const dir = directory(parent);
|
|
195
199
|
// 会話終了でも確定本文を失わない。終了判定より先に保存する。
|
|
@@ -212,8 +216,10 @@ export async function submitClaudeParentAnswer(profile, parent, deliveryId, text
|
|
|
212
216
|
const value = JSON.parse(fs.readFileSync(failed, "utf8"));
|
|
213
217
|
throw new ClaudeDeliveryError("CLAUDE_PARENT_HOOK_FAILED", "親へのhook出力が失敗しました。回答は保存したままです", value.outcome_unknown === true);
|
|
214
218
|
}
|
|
215
|
-
const rows = runtime.processes();
|
|
216
|
-
const alive = (pid, identity) => rows
|
|
219
|
+
const rows = runtime.processes?.();
|
|
220
|
+
const alive = (pid, identity) => rows
|
|
221
|
+
? rows.find(entry => entry.pid === pid)?.started_identity === identity
|
|
222
|
+
: (runtime.running ?? processIsRunning)(pid, identity);
|
|
217
223
|
let gone;
|
|
218
224
|
const hookFile = path.join(dir, "hook.json");
|
|
219
225
|
if (fs.existsSync(hookFile)) {
|
package/dist/codex-hook-state.js
CHANGED
|
@@ -6,7 +6,7 @@ import { createHash } from "node:crypto";
|
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
import { CodexDeliveryError } from "./errors.js";
|
|
8
8
|
import { codexHookDirectory } from "./profile.js";
|
|
9
|
-
import {
|
|
9
|
+
import { processIsRunning, readProcessLineage } from "./process.js";
|
|
10
10
|
import { writeHookJson } from "./files.js";
|
|
11
11
|
export { writeHookJson };
|
|
12
12
|
const processSchema = z.object({ pid: z.number().int(), started_identity: z.string() });
|
|
@@ -69,7 +69,7 @@ export function codexHookDeliveryState(home, thread, id, root) {
|
|
|
69
69
|
if (value.state === "unknown")
|
|
70
70
|
return "unknown";
|
|
71
71
|
if (value.state === "deleting")
|
|
72
|
-
return
|
|
72
|
+
return processIsRunning(value.pid, value.started_identity) ? "sending" : "unknown";
|
|
73
73
|
if (["emitted", "not_in_queue"].includes(value.state))
|
|
74
74
|
return null;
|
|
75
75
|
throw new CodexDeliveryError("CODEX_HOOK_STATE_INVALID", "hookの配送状態を読めません");
|
|
@@ -106,7 +106,8 @@ export function assertCodexHookParentCurrent(profile, config, rows, pid = proces
|
|
|
106
106
|
}
|
|
107
107
|
if (!config.stale_processes.length)
|
|
108
108
|
return;
|
|
109
|
-
|
|
109
|
+
// 見るのは、このhookの先祖だけ。全processの一覧は取らない。
|
|
110
|
+
const processes = new Map((rows ?? readProcessLineage(pid, 32)).map(row => [row.pid, row]));
|
|
110
111
|
const seen = new Set();
|
|
111
112
|
let current = processes.get(pid);
|
|
112
113
|
while (current && !seen.has(current.pid)) {
|
package/dist/codex-hooks.js
CHANGED
|
@@ -6,7 +6,7 @@ import { z } from "zod";
|
|
|
6
6
|
import { realCodexHome, currentCodexDesktopBinary } from "./codex-binary.js";
|
|
7
7
|
import { withCodexReceiver } from "./codex-receiver.js";
|
|
8
8
|
import { CodexDeliveryError } from "./errors.js";
|
|
9
|
-
import {
|
|
9
|
+
import { readProcessIdentities } from "./process.js";
|
|
10
10
|
import { codexHookDirectory } from "./profile.js";
|
|
11
11
|
import { answerDigest, codexInputDirectory, hookInputSchema, readCodexHookConfig, writeHookJson } from "./codex-hook-state.js";
|
|
12
12
|
export async function runCodexResultHook(profile, input, emit, options = {}) {
|
|
@@ -31,9 +31,10 @@ export async function runCodexResultHook(profile, input, emit, options = {}) {
|
|
|
31
31
|
const claims = path.join(directory, "claims");
|
|
32
32
|
fs.mkdirSync(claims, { recursive: true, mode: 0o700 });
|
|
33
33
|
const taken = [];
|
|
34
|
-
const
|
|
35
|
-
if (!
|
|
34
|
+
const own = readProcessIdentities([process.pid])[0];
|
|
35
|
+
if (!own || own.started_identity === null)
|
|
36
36
|
throw new CodexDeliveryError("CODEX_HOOK_PROCESS_UNAVAILABLE", "受信hookのprocessを確認できません");
|
|
37
|
+
const identity = { pid: own.pid, started_identity: own.started_identity };
|
|
37
38
|
try {
|
|
38
39
|
await withCodexReceiver(profile, { thread_id: event.session_id, codex_home: home }, async (request) => {
|
|
39
40
|
// 削除でoffsetが動くため、全ページを読んでから取り出す。
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export * from "./profile.js";
|
|
2
2
|
export * from "./errors.js";
|
|
3
3
|
export { writeJson0600, writeHookJson, waitForFileState, withoutBom } from "./files.js";
|
|
4
|
-
export { readRuntimeProcesses, parsePosixProcessTable, hookOwnerProcess, type RuntimeProcess, type NativeProcessIdentity } from "./process.js";
|
|
4
|
+
export { readRuntimeProcesses, readProcessIdentities, readProcessLineage, processExists, processIsRunning, parsePosixProcessTable, hookOwnerProcess, type RuntimeProcess, type NativeProcessIdentity } from "./process.js";
|
|
5
5
|
export { resolveWindowsPowerShell7, quotePowerShell, windowsPowerShellSync, windowsStartProcessArgumentList } from "./windows.js";
|
|
6
6
|
export { setupNodeExecutable } from "./setup-node.js";
|
|
7
7
|
export { realCodexHome, resolveCodexExecutable, codexSpawnEnv, desktopBundledCodex, findDesktopBinary, findWindowsCodexCache, findWindowsCodexBinary, findLinuxDesktopBinary, findCliBinary, findSteerBinary, platformDesktopFinder, currentCodexDesktopBinary, type DesktopBinaryFinder, } from "./codex-binary.js";
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
export * from "./profile.js";
|
|
4
4
|
export * from "./errors.js";
|
|
5
5
|
export { writeJson0600, writeHookJson, waitForFileState, withoutBom } from "./files.js";
|
|
6
|
-
export { readRuntimeProcesses, parsePosixProcessTable, hookOwnerProcess } from "./process.js";
|
|
6
|
+
export { readRuntimeProcesses, readProcessIdentities, readProcessLineage, processExists, processIsRunning, parsePosixProcessTable, hookOwnerProcess } from "./process.js";
|
|
7
7
|
export { resolveWindowsPowerShell7, quotePowerShell, windowsPowerShellSync, windowsStartProcessArgumentList } from "./windows.js";
|
|
8
8
|
export { setupNodeExecutable } from "./setup-node.js";
|
|
9
9
|
export { realCodexHome, resolveCodexExecutable, codexSpawnEnv, desktopBundledCodex, findDesktopBinary, findWindowsCodexCache, findWindowsCodexBinary, findLinuxDesktopBinary, findCliBinary, findSteerBinary, platformDesktopFinder, currentCodexDesktopBinary, } from "./codex-binary.js";
|
package/dist/process.d.ts
CHANGED
|
@@ -19,4 +19,22 @@ export declare function parsePosixProcessTable(text: string): RuntimeProcess[];
|
|
|
19
19
|
* 挟まったshellはhookと一緒に終わるので、`pid`から先祖をたどり、shellでない最初のprocessを返す。
|
|
20
20
|
*/
|
|
21
21
|
export declare function hookOwnerProcess(rows: readonly RuntimeProcess[], pid: number): RuntimeProcess | undefined;
|
|
22
|
+
/** そのpidのprocessが今あるか。OSへ直接聞き、processを起こさない。権限が無くて触れないprocessも「ある」と読む。 */
|
|
23
|
+
export declare function processExists(pid: number): boolean;
|
|
24
|
+
/**
|
|
25
|
+
* 指定したpidだけの開始時刻。readRuntimeProcessesと同じ値を返し、process表に無いpidは返さない。全processの一覧を取らない。
|
|
26
|
+
* 開始時刻を読めないprocess(別の権限のserviceなど)は、pidがprocess表にある印として `started_identity: null` で返す。
|
|
27
|
+
*/
|
|
28
|
+
export declare function readProcessIdentities(pids: readonly number[]): {
|
|
29
|
+
pid: number;
|
|
30
|
+
started_identity: string | null;
|
|
31
|
+
}[];
|
|
32
|
+
/** そのpidのprocessが、記録にある本人(pidと開始時刻の組)のまま居るか。居ないと分かっている時はprocessを起こさない。 */
|
|
33
|
+
export declare function processIsRunning(pid: number, startedIdentity: string): boolean;
|
|
34
|
+
/**
|
|
35
|
+
* `pid` と、その先祖のprocess(近い順)。hookOwnerProcessへ渡す行を、全processの一覧を取らずに作る。
|
|
36
|
+
* Windowsは.NETのprocessの読みで親をたどる(`command` は実行fileのpathで、引数は入らない)。読めない時と、ほかのOSは、
|
|
37
|
+
* 今までどおり全processの一覧を返す。
|
|
38
|
+
*/
|
|
39
|
+
export declare function readProcessLineage(pid: number, depth?: number): RuntimeProcess[];
|
|
22
40
|
export declare function readRuntimeProcesses(): RuntimeProcess[];
|
package/dist/process.js
CHANGED
|
@@ -50,6 +50,148 @@ export function hookOwnerProcess(rows, pid) {
|
|
|
50
50
|
current = byPid.get(current.parent_pid);
|
|
51
51
|
return current;
|
|
52
52
|
}
|
|
53
|
+
/** そのpidのprocessが今あるか。OSへ直接聞き、processを起こさない。権限が無くて触れないprocessも「ある」と読む。 */
|
|
54
|
+
export function processExists(pid) {
|
|
55
|
+
// 0以下はprocess groupを指す。
|
|
56
|
+
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
57
|
+
return false;
|
|
58
|
+
try {
|
|
59
|
+
process.kill(pid, 0);
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
return error.code === "EPERM";
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function windowsJson(script, failure) {
|
|
67
|
+
const source = ["$ErrorActionPreference='Stop'", "[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)", script].join("\n");
|
|
68
|
+
const result = spawnSync(resolveWindowsPowerShell7(), ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(source, "utf16le").toString("base64")], {
|
|
69
|
+
encoding: "utf8", timeout: 15000, maxBuffer: 16 * 1024 * 1024, windowsHide: true,
|
|
70
|
+
});
|
|
71
|
+
if (result.error || result.status !== 0)
|
|
72
|
+
throw new ProcessTableError(failure);
|
|
73
|
+
try {
|
|
74
|
+
return JSON.parse(result.stdout);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
throw new ProcessTableError(failure);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function assertPids(pids) {
|
|
81
|
+
const wanted = [...new Set(pids)];
|
|
82
|
+
if (wanted.some(pid => !Number.isSafeInteger(pid) || pid < 0))
|
|
83
|
+
throw new ProcessTableError("process照会のpidが不正です");
|
|
84
|
+
return wanted;
|
|
85
|
+
}
|
|
86
|
+
// Windowsで1個のprocessを読む時は、WMI(Win32_Process)を使わない。WMIは絞っても1回に0.1〜0.3秒かかり、WMIの側のprocess
|
|
87
|
+
// (wmiprvse)のCPUを使う(process 1300個のWindowsで測った 2026-10-12)。.NETのprocessの読み(OpenProcessとGetProcessTimes)は
|
|
88
|
+
// 1個1.5ミリ秒で、WMIを起こさない。起動時刻は同じ値になる(WMIはマイクロ秒で切り捨てた値を返し、どちらも1ミリ秒で切り捨てて使う。
|
|
89
|
+
// 888個のprocessで食い違いは0だった)。権限が無くて読めないprocessだけ、WMIへ聞き直す。
|
|
90
|
+
const WINDOWS_STARTED = [
|
|
91
|
+
"function Started($p) {",
|
|
92
|
+
" try { return $p.StartTime.ToUniversalTime().ToString('o') }",
|
|
93
|
+
" catch [InvalidOperationException] { return '' }",
|
|
94
|
+
" catch { $w = Get-CimInstance Win32_Process -Filter \"ProcessId=$($p.Id)\" -Property CreationDate; if ($null -eq $w) { return '' }",
|
|
95
|
+
" if ($null -eq $w.CreationDate) { return $null }; return $w.CreationDate.ToUniversalTime().ToString('o') }",
|
|
96
|
+
"}",
|
|
97
|
+
].join("\n");
|
|
98
|
+
/**
|
|
99
|
+
* 指定したpidだけの開始時刻。readRuntimeProcessesと同じ値を返し、process表に無いpidは返さない。全processの一覧を取らない。
|
|
100
|
+
* 開始時刻を読めないprocess(別の権限のserviceなど)は、pidがprocess表にある印として `started_identity: null` で返す。
|
|
101
|
+
*/
|
|
102
|
+
export function readProcessIdentities(pids) {
|
|
103
|
+
// 居ないpidは、OSへ直接聞いて先に除く。全部居なければ、processを起こさない。
|
|
104
|
+
// macOSのpsは、範囲の外のpidが1つ混ざると、居るprocessの分も出さずに誤りで終わる。
|
|
105
|
+
const wanted = assertPids(pids).filter(processExists);
|
|
106
|
+
if (wanted.length === 0)
|
|
107
|
+
return [];
|
|
108
|
+
if (!isWin) {
|
|
109
|
+
const result = spawnSync("/bin/ps", ["-o", "pid=,lstart=", "-p", wanted.join(",")], {
|
|
110
|
+
encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 10000,
|
|
111
|
+
});
|
|
112
|
+
// 該当するprocessが一つも無い時、psは何も出さずstatus 1で終わる。
|
|
113
|
+
if (result.error || (result.status !== 0 && !(result.status === 1 && !result.stdout.trim()))) {
|
|
114
|
+
throw new ProcessTableError("OSのprocess一覧を取得できません");
|
|
115
|
+
}
|
|
116
|
+
return result.stdout.split("\n").filter(line => line.trim()).map(line => {
|
|
117
|
+
const match = /^\s*(\d+)\s+(\S+\s+\S+\s+\d+\s+\S+\s+\d+)\s*$/.exec(line);
|
|
118
|
+
if (!match)
|
|
119
|
+
throw new ProcessTableError("process一覧の形式を認識できません");
|
|
120
|
+
return { pid: Number(match[1]), started_identity: match[2].trim() };
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
const rows = windowsJson([
|
|
124
|
+
WINDOWS_STARTED,
|
|
125
|
+
"$rows=@()",
|
|
126
|
+
`foreach ($id in @(${wanted.join(",")})) {`,
|
|
127
|
+
" try { $p=[Diagnostics.Process]::GetProcessById($id) } catch [ArgumentException] { continue }",
|
|
128
|
+
" $started=Started $p",
|
|
129
|
+
" if ($started -eq '') { continue }",
|
|
130
|
+
" $rows += [ordered]@{ pid=[int]$id; started_identity=$started }",
|
|
131
|
+
"}",
|
|
132
|
+
"ConvertTo-Json -Compress -InputObject $rows",
|
|
133
|
+
].join("\n"), "Windowsのprocessの開始時刻を取得できません");
|
|
134
|
+
if (!Array.isArray(rows))
|
|
135
|
+
throw new ProcessTableError("Windows processの読みが配列ではありません");
|
|
136
|
+
return rows.map(row => {
|
|
137
|
+
if (!row || !Number.isSafeInteger(row.pid))
|
|
138
|
+
throw new ProcessTableError("Windows processの読みのfieldが不正です");
|
|
139
|
+
if (row.started_identity === null)
|
|
140
|
+
return { pid: row.pid, started_identity: null };
|
|
141
|
+
if (typeof row.started_identity !== "string" || !Number.isFinite(Date.parse(row.started_identity)))
|
|
142
|
+
throw new ProcessTableError("Windows processの読みのfieldが不正です");
|
|
143
|
+
return { pid: row.pid, started_identity: new Date(row.started_identity).toISOString() };
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
/** そのpidのprocessが、記録にある本人(pidと開始時刻の組)のまま居るか。居ないと分かっている時はprocessを起こさない。 */
|
|
147
|
+
export function processIsRunning(pid, startedIdentity) {
|
|
148
|
+
return processExists(pid) && readProcessIdentities([pid])[0]?.started_identity === startedIdentity;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* `pid` と、その先祖のprocess(近い順)。hookOwnerProcessへ渡す行を、全processの一覧を取らずに作る。
|
|
152
|
+
* Windowsは.NETのprocessの読みで親をたどる(`command` は実行fileのpathで、引数は入らない)。読めない時と、ほかのOSは、
|
|
153
|
+
* 今までどおり全processの一覧を返す。
|
|
154
|
+
*/
|
|
155
|
+
export function readProcessLineage(pid, depth = 8) {
|
|
156
|
+
if (!isWin)
|
|
157
|
+
return readRuntimeProcesses();
|
|
158
|
+
if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isSafeInteger(depth) || depth <= 0)
|
|
159
|
+
throw new ProcessTableError("process照会のpidが不正です");
|
|
160
|
+
let rows;
|
|
161
|
+
try {
|
|
162
|
+
rows = windowsJson([
|
|
163
|
+
"$rows=@(); $child=$null",
|
|
164
|
+
`$id=${pid}`,
|
|
165
|
+
`for ($i=0; $i -lt ${depth} -and $id -gt 0; $i++) {`,
|
|
166
|
+
" try { $p=Get-Process -Id $id; $started=$p.StartTime.ToUniversalTime() } catch { break }",
|
|
167
|
+
// Windowsの親PIDは親の終了後も残り、別のprocessへ使い回される。子より後に始まったprocessは親でない。
|
|
168
|
+
" if ($null -ne $child -and $started -gt $child) { break }",
|
|
169
|
+
" $parent=0; try { if ($null -ne $p.Parent) { $parent=[int]$p.Parent.Id } } catch { }",
|
|
170
|
+
" $exe=''; try { $exe=[string]$p.Path } catch { }",
|
|
171
|
+
" if (-not $exe) { $exe=[string]$p.ProcessName }",
|
|
172
|
+
" $cpu=0.0; try { $cpu=[double]$p.TotalProcessorTime.TotalSeconds } catch { }",
|
|
173
|
+
" $rows += [ordered]@{ pid=[int]$p.Id; parent_pid=$parent; executable=$exe; started_identity=$started.ToString('o'); cpu_seconds=$cpu }",
|
|
174
|
+
" $child=$started; $id=$parent",
|
|
175
|
+
"}",
|
|
176
|
+
"ConvertTo-Json -Compress -InputObject $rows",
|
|
177
|
+
].join("\n"), "Windowsのprocessの先祖を取得できません");
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return readRuntimeProcesses();
|
|
181
|
+
}
|
|
182
|
+
if (!Array.isArray(rows) || rows[0]?.pid !== pid)
|
|
183
|
+
return readRuntimeProcesses();
|
|
184
|
+
return rows.map(row => {
|
|
185
|
+
if (!row || !Number.isSafeInteger(row.pid) || !Number.isSafeInteger(row.parent_pid) || typeof row.executable !== "string"
|
|
186
|
+
|| !Number.isFinite(row.cpu_seconds) || typeof row.started_identity !== "string" || !Number.isFinite(Date.parse(row.started_identity)))
|
|
187
|
+
throw new ProcessTableError("Windows processの読みのfieldが不正です");
|
|
188
|
+
return {
|
|
189
|
+
pid: row.pid, parent_pid: row.parent_pid, process_group_id: null, stopped: null, executable: row.executable,
|
|
190
|
+
started_identity: new Date(row.started_identity).toISOString(), command: row.executable, cpu_seconds: row.cpu_seconds,
|
|
191
|
+
argv_digest: createHash("sha256").update(row.executable).digest("hex"),
|
|
192
|
+
};
|
|
193
|
+
});
|
|
194
|
+
}
|
|
53
195
|
export function readRuntimeProcesses() {
|
|
54
196
|
if (!isWin) {
|
|
55
197
|
const result = spawnSync("/bin/ps", ["-axww", "-o", "pid=,ppid=,pgid=,stat=,lstart=,time=,command="], {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiterm-steer-delivery",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.5",
|
|
4
4
|
"description": "Aiterm's steer delivery as a library: deliver text to the parent AI session that called your MCP tool — steered into the running turn when it is busy, delivered normally when it is idle. Codex (official queue + sync hooks), Claude Code (asyncRewake hooks), Cursor (hooks + background receiver).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|