aiterm-steer-delivery 0.4.7 → 0.5.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.
- package/CHANGELOG.md +16 -0
- package/dist/claude-receiver.d.ts +14 -1
- package/dist/claude-receiver.js +22 -7
- package/dist/codex-hooks.d.ts +4 -0
- package/dist/codex-hooks.js +11 -4
- package/dist/codex-receiver.js +9 -5
- package/dist/codex-setup.d.ts +1 -0
- package/dist/codex-setup.js +2 -1
- package/dist/codex-wake.js +9 -4
- package/dist/cursor-receive.d.ts +2 -1
- package/dist/cursor-receive.js +9 -2
- package/dist/cursor-receiver.d.ts +2 -2
- package/dist/cursor-receiver.js +38 -7
- package/dist/delivery-effect.d.ts +21 -0
- package/dist/delivery-effect.js +64 -0
- package/dist/hook-main.js +71 -6
- package/dist/hook-setup.d.ts +1 -0
- package/dist/hook-setup.js +2 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/process.js +28 -2
- package/dist/profile.d.ts +7 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
## 0.5.1
|
|
6
|
+
|
|
7
|
+
Claude Codeのhookが、送信前(PreToolUse)の記録が無い時に送信後(PostToolUse)で例外終了し、channelの待機が張られず返信が次のhookまで止まっていたのを直します。関数の名前・引数・返りの形、hookの登録、置き場の作りは変わりません。hookの置き場に記録ファイルが1つ増えます。
|
|
8
|
+
|
|
9
|
+
- **起きていた事。** 2026-10-31、Macの全試験の負荷中に、Claude Codeの`call_send`のPreToolUse hook(登録timeout 15秒、全processの一覧を取る)が記録(`request.json`)を残さないまま道具が進んだ。PostToolUse hookは`CLAUDE_PARENT_HOOK_UNAVAILABLE`で例外終了し、channelの待機(`runClaudeChannelWaiter`)に進まなかった。その間にchannelへ入った返信2通は、次のhookが走るまで会話へ出なかった。
|
|
10
|
+
- **PostToolUseは、PreToolUseの記録が無ければ「配送の依頼が無い」として0で終え、channelの待機へ進む。** 記録があって壊れている時は従来どおり断る。
|
|
11
|
+
- **hookの実行記録を`<hook root>/hook-events.log`へ1行JSONで残す。** event名・会話ID・tool_use_id・所要ms・終了code・失敗の符号だけで、本文・引数・stderrの文は書かない。1MBを超えたら前の世代を1つ残して入れ替える。記録の失敗でhookの結果は変わらない。
|
|
12
|
+
- **POSIXの先祖の読み(`readProcessLineage`)は、全processの一覧でなく1個ずつ親方向へ最大8段たどる。** 読めない時だけ全一覧へ戻す。返す行の形と`hookOwnerProcess`の判定は同じ。
|
|
13
|
+
|
|
14
|
+
## 0.5.0
|
|
15
|
+
|
|
16
|
+
- Optional native delivery admission passes existing request/parent references through queue, dequeue, emit and wake hooks without creating a second queue or resending input.
|
|
17
|
+
- Hook runtime arguments and Codex custom hook commands preserve a shared native MCP entry, scope and provider. The admission capability advertises `native_hook_args:true`. Existing registrations without these optional arguments retain their command shape.
|
|
18
|
+
|
|
3
19
|
## 0.4.7
|
|
4
20
|
|
|
5
21
|
Codexの受け口が断った配送の所有記録が残り、同じ配送IDの渡し直しが通らなくなっていたのを直します。関数の名前・引数・返りの形と置き場の作りは変わりません。符号が1つ増えます。
|
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { type RuntimeProcess } from "./process.js";
|
|
3
3
|
import type { ProductProfile } from "./profile.js";
|
|
4
|
+
declare const invocationSchema: z.ZodObject<{
|
|
5
|
+
request_id: z.ZodString;
|
|
6
|
+
session_id: z.ZodUUID;
|
|
7
|
+
agent_id: z.ZodNullable<z.ZodString>;
|
|
8
|
+
parent_pid: z.ZodNumber;
|
|
9
|
+
parent_started_identity: z.ZodString;
|
|
10
|
+
}, z.core.$strict>;
|
|
11
|
+
type Invocation = z.infer<typeof invocationSchema>;
|
|
4
12
|
export declare const claudeParentSchema: z.ZodObject<{
|
|
5
13
|
kind: z.ZodLiteral<"claude">;
|
|
6
14
|
request_id: z.ZodString;
|
|
@@ -35,4 +43,9 @@ export declare function submitClaudeParentAnswer(profile: ProductProfile, parent
|
|
|
35
43
|
}): Promise<{
|
|
36
44
|
queued_submission_id: null;
|
|
37
45
|
}>;
|
|
38
|
-
export declare function runClaudeResultHook(profile: ProductProfile, input: unknown, emit: (text: string) => void | Promise<void>, root: string
|
|
46
|
+
export declare function runClaudeResultHook(profile: ProductProfile, input: unknown, emit: (text: string) => void | Promise<void>, root: string, runtime?: {
|
|
47
|
+
identity?: (pid: number) => string | undefined;
|
|
48
|
+
parentAlive?: (invocation: Invocation) => void;
|
|
49
|
+
resume?: (code: 2) => void | Promise<void>;
|
|
50
|
+
}): Promise<0 | 2>;
|
|
51
|
+
export {};
|
package/dist/claude-receiver.js
CHANGED
|
@@ -5,6 +5,8 @@ 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 { withDeliveryEffect } from "./delivery-effect.js";
|
|
9
|
+
import { DeliveryAdmissionError } from "./delivery-effect.js";
|
|
8
10
|
import { hookOwnerProcess, processIsRunning, readProcessIdentities, readProcessLineage } from "./process.js";
|
|
9
11
|
import { ClaudeDeliveryError } from "./errors.js";
|
|
10
12
|
const requestId = z.string().regex(/^[A-Za-z0-9_-]{1,160}$/);
|
|
@@ -194,10 +196,11 @@ function assertParentAlive(invocation) {
|
|
|
194
196
|
export async function submitClaudeParentAnswer(profile, parent, deliveryId, text,
|
|
195
197
|
// 既定は、確かめる2個(受信hookと依頼元)だけを読む。`processes` を渡した時は、その一覧で確かめる。
|
|
196
198
|
runtime = { running: processIsRunning }) {
|
|
199
|
+
parent = claudeParentSchema.parse(parent);
|
|
197
200
|
const invocation = readInvocation(profile, parent);
|
|
198
201
|
const dir = directory(parent);
|
|
199
202
|
// 会話終了でも確定本文を失わない。終了判定より先に保存する。
|
|
200
|
-
writeJson0600(path.join(dir, "answer.json"), { delivery_id: deliveryId, text });
|
|
203
|
+
await withDeliveryEffect(profile, { vendor: "claude", stage: "queue", delivery_ids: [deliveryId], endpoint: parent }, () => writeJson0600(path.join(dir, "answer.json"), { delivery_id: deliveryId, text }));
|
|
201
204
|
const emitted = () => {
|
|
202
205
|
const file = path.join(dir, "emitted.json");
|
|
203
206
|
if (!fs.existsSync(file))
|
|
@@ -246,18 +249,24 @@ runtime = { running: processIsRunning }) {
|
|
|
246
249
|
catch { /* 見回りへ回す */ }
|
|
247
250
|
return { queued_submission_id: null };
|
|
248
251
|
}
|
|
249
|
-
export async function runClaudeResultHook(profile, input, emit, root) {
|
|
252
|
+
export async function runClaudeResultHook(profile, input, emit, root, runtime = {}) {
|
|
250
253
|
const event = z.object({ session_id: z.uuid(), tool_use_id: requestId }).parse(input);
|
|
251
254
|
const parent = { kind: "claude", request_id: event.tool_use_id, session_id: event.session_id, hook_root: root };
|
|
252
|
-
const invocation = readInvocation(profile, parent);
|
|
253
255
|
const dir = directory(parent);
|
|
256
|
+
// PreToolUseの記録が無い(hookがtimeoutし、Claude Codeが道具を先へ進めた時など)。配送の依頼は結べていないので配送無しとして0で終え、
|
|
257
|
+
// 呼ぶ側はchannelの待機へ進む(2026-10-31、Macの負荷中に記録が1回欠け、ここで例外終了して待機が張られず返信が次のhookまで止まった)。
|
|
258
|
+
if (!fs.existsSync(path.join(dir, "request.json")))
|
|
259
|
+
return 0;
|
|
260
|
+
const invocation = readInvocation(profile, parent);
|
|
254
261
|
const binding = path.join(dir, "delivery.json");
|
|
255
262
|
if (!fs.existsSync(binding)) {
|
|
256
263
|
fs.rmSync(dir, { recursive: true });
|
|
257
264
|
return 0;
|
|
258
265
|
}
|
|
259
266
|
const deliveryId = z.uuid().parse(JSON.parse(fs.readFileSync(binding, "utf8")).delivery_id);
|
|
260
|
-
|
|
267
|
+
if (profile.delivery_admission && !runtime.resume)
|
|
268
|
+
throw new DeliveryAdmissionError("DELIVERY_ADMISSION_UNSUPPORTED", "Claude再開信号の作用口が未接続です");
|
|
269
|
+
const identity = (runtime.identity ?? processIdentity)(process.pid);
|
|
261
270
|
if (!identity)
|
|
262
271
|
throw new ClaudeDeliveryError("CLAUDE_PARENT_HOOK_UNAVAILABLE", "受信hookのprocessを確認できません");
|
|
263
272
|
writeJson0600(path.join(dir, "hook.json"), { pid: process.pid, started_identity: identity });
|
|
@@ -265,7 +274,7 @@ export async function runClaudeResultHook(profile, input, emit, root) {
|
|
|
265
274
|
const answer = await waitForFileState(dir, () => {
|
|
266
275
|
if (fs.existsSync(path.join(dir, "closed.json")))
|
|
267
276
|
return null;
|
|
268
|
-
assertParentAlive(invocation);
|
|
277
|
+
(runtime.parentAlive ?? assertParentAlive)(invocation);
|
|
269
278
|
const file = path.join(dir, "answer.json");
|
|
270
279
|
if (!fs.existsSync(file))
|
|
271
280
|
return undefined;
|
|
@@ -277,9 +286,15 @@ export async function runClaudeResultHook(profile, input, emit, root) {
|
|
|
277
286
|
if (!answer)
|
|
278
287
|
return 0;
|
|
279
288
|
assertOpen(parent);
|
|
280
|
-
|
|
281
|
-
|
|
289
|
+
await withDeliveryEffect(profile, { vendor: "claude", stage: "emit", delivery_ids: [deliveryId], endpoint: parent,
|
|
290
|
+
native_context: { session_id: event.session_id, tool_use_id: event.tool_use_id } }, async () => {
|
|
291
|
+
writeJson0600(path.join(dir, "sending.json"), { delivery_id: deliveryId });
|
|
292
|
+
await emit(answer.text);
|
|
293
|
+
});
|
|
282
294
|
writeJson0600(path.join(dir, "emitted.json"), { delivery_id: deliveryId });
|
|
295
|
+
if (profile.delivery_admission)
|
|
296
|
+
await withDeliveryEffect(profile, { vendor: "claude", stage: "wake", delivery_ids: [deliveryId], endpoint: parent,
|
|
297
|
+
native_context: { session_id: event.session_id, tool_use_id: event.tool_use_id } }, () => runtime.resume(2));
|
|
283
298
|
// Claudeが定めるasyncRewakeの再開信号。子の成功/失敗は本文のoutcomeで区別する。
|
|
284
299
|
return 2;
|
|
285
300
|
}
|
package/dist/codex-hooks.d.ts
CHANGED
|
@@ -4,4 +4,8 @@ export declare function runCodexResultHook(profile: ProductProfile, input: unkno
|
|
|
4
4
|
directory?: string;
|
|
5
5
|
codex_home?: string;
|
|
6
6
|
runtime?: CodexReceiverRuntime;
|
|
7
|
+
identity?: () => {
|
|
8
|
+
pid: number;
|
|
9
|
+
started_identity: string | null;
|
|
10
|
+
} | undefined;
|
|
7
11
|
}): Promise<void>;
|
package/dist/codex-hooks.js
CHANGED
|
@@ -9,6 +9,7 @@ import { CodexDeliveryError } from "./errors.js";
|
|
|
9
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
|
+
import { withDeliveryEffect } from "./delivery-effect.js";
|
|
12
13
|
export async function runCodexResultHook(profile, input, emit, options = {}) {
|
|
13
14
|
const event = z.object({ session_id: z.uuid(), turn_id: z.string().min(1),
|
|
14
15
|
hook_event_name: z.enum(["PostToolUse", "Stop"]) }).parse(input);
|
|
@@ -31,7 +32,7 @@ export async function runCodexResultHook(profile, input, emit, options = {}) {
|
|
|
31
32
|
const claims = path.join(directory, "claims");
|
|
32
33
|
fs.mkdirSync(claims, { recursive: true, mode: 0o700 });
|
|
33
34
|
const taken = [];
|
|
34
|
-
const own = readProcessIdentities([process.pid])[0];
|
|
35
|
+
const own = options.identity ? options.identity() : readProcessIdentities([process.pid])[0];
|
|
35
36
|
if (!own || own.started_identity === null)
|
|
36
37
|
throw new CodexDeliveryError("CODEX_HOOK_PROCESS_UNAVAILABLE", "受信hookのprocessを確認できません");
|
|
37
38
|
const identity = { pid: own.pid, started_identity: own.started_identity };
|
|
@@ -91,7 +92,8 @@ export async function runCodexResultHook(profile, input, emit, options = {}) {
|
|
|
91
92
|
taken.push(item);
|
|
92
93
|
writeHookJson(file, { ...owner, text, state: "deleting", turn_id: event.turn_id, queued_submission_id: entry.id,
|
|
93
94
|
pid: identity.pid, started_identity: identity.started_identity });
|
|
94
|
-
const result = await
|
|
95
|
+
const result = await withDeliveryEffect(profile, { vendor: "codex", stage: "dequeue", delivery_ids: [id.data],
|
|
96
|
+
endpoint: { thread_id: event.session_id, codex_home: home }, native_context: { session_id: event.session_id, turn_id: event.turn_id, hook_event_name: event.hook_event_name } }, () => request("thread/queue/delete", { threadId: event.session_id, queuedSubmissionId: entry.id }));
|
|
95
97
|
if (typeof result?.deleted !== "boolean")
|
|
96
98
|
throw new CodexDeliveryError("CODEX_HOOK_QUEUE_INVALID", "キュー削除の結果を確認できません", true);
|
|
97
99
|
if (!result.deleted) {
|
|
@@ -101,9 +103,14 @@ export async function runCodexResultHook(profile, input, emit, options = {}) {
|
|
|
101
103
|
}
|
|
102
104
|
}, options.runtime ?? { executable: await currentCodexDesktopBinary(profile, config, { directory: root }), timeout_ms: 5_000 });
|
|
103
105
|
const text = taken.map(item => item.text).join("\n\n");
|
|
104
|
-
|
|
106
|
+
const output = !taken.length ? {} : event.hook_event_name === "Stop"
|
|
105
107
|
? { decision: "block", reason: text }
|
|
106
|
-
: { hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: text } }
|
|
108
|
+
: { hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: text } };
|
|
109
|
+
if (taken.length)
|
|
110
|
+
await withDeliveryEffect(profile, { vendor: "codex", stage: "emit", delivery_ids: taken.map(item => item.delivery_id),
|
|
111
|
+
endpoint: { thread_id: event.session_id, codex_home: home }, native_context: { session_id: event.session_id, turn_id: event.turn_id, hook_event_name: event.hook_event_name } }, () => emit(output));
|
|
112
|
+
else
|
|
113
|
+
await emit(output);
|
|
107
114
|
for (const item of taken)
|
|
108
115
|
writeHookJson(item.file, { delivery_id: item.delivery_id, state: "emitted", turn_id: event.turn_id, text: item.text });
|
|
109
116
|
}
|
package/dist/codex-receiver.js
CHANGED
|
@@ -9,6 +9,7 @@ import { codexHookDirectory } from "./profile.js";
|
|
|
9
9
|
import { codexSpawnEnv, currentCodexDesktopBinary, realCodexHome, resolveCodexExecutable } from "./codex-binary.js";
|
|
10
10
|
import { finishCodexHookSubmission, assertCodexHookParentCurrent, assertCodexHooksReady, readCodexHookConfig, registerCodexHookInput, withdrawCodexHookInput } from "./codex-hook-state.js";
|
|
11
11
|
import { startCodexWakeWatch } from "./codex-wake.js";
|
|
12
|
+
import { withDeliveryEffect } from "./delivery-effect.js";
|
|
12
13
|
/** modelの引数ではなく、CodexがMCP要求へ付けるmetadataだけを宛先にする。 */
|
|
13
14
|
export function codexParentFromRequest(clientName, metadata) {
|
|
14
15
|
if (clientName !== "codex-mcp-client")
|
|
@@ -127,6 +128,7 @@ export async function verifyCodexParent(profile, parent, runtime) {
|
|
|
127
128
|
* 入れた後、寝ている会話を起こす見張りを別のprocessで起こす(`startCodexWakeWatch`)。見張りの成否は、受付の結果を変えない。
|
|
128
129
|
*/
|
|
129
130
|
export async function submitCodexParentAnswer(profile, parent, deliveryId, text, runtime) {
|
|
131
|
+
parent = { ...parent };
|
|
130
132
|
const root = runtime ? runtime.hook_directory : codexHookDirectory(profile);
|
|
131
133
|
const hook = root && readCodexHookConfig(profile, root)?.enabled;
|
|
132
134
|
if (hook)
|
|
@@ -135,11 +137,13 @@ export async function submitCodexParentAnswer(profile, parent, deliveryId, text,
|
|
|
135
137
|
let asked = false;
|
|
136
138
|
try {
|
|
137
139
|
accepted = await withCodexReceiver(profile, parent, async (request) => {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
140
|
+
const result = await withDeliveryEffect(profile, { vendor: "codex", stage: "queue", delivery_ids: [deliveryId], endpoint: parent }, () => {
|
|
141
|
+
asked = true;
|
|
142
|
+
return request("thread/queue/add", {
|
|
143
|
+
threadId: parent.thread_id,
|
|
144
|
+
input: [{ type: "text", text, text_elements: [] }],
|
|
145
|
+
clientUserMessageId: deliveryId,
|
|
146
|
+
});
|
|
143
147
|
});
|
|
144
148
|
if (typeof result?.queuedSubmission?.id !== "string") {
|
|
145
149
|
throw new CodexDeliveryError("CODEX_RECEIVER_INVALID_RESPONSE", "キューの受付IDを確認できません", true);
|
package/dist/codex-setup.d.ts
CHANGED
|
@@ -39,6 +39,7 @@ export type CodexSteerRuntime = {
|
|
|
39
39
|
codex_home: string;
|
|
40
40
|
node: string;
|
|
41
41
|
hook: string;
|
|
42
|
+
hookCommand?: (node: string, hook: string, directory: string) => string;
|
|
42
43
|
findBinary: () => string;
|
|
43
44
|
processes: () => RuntimeProcess[];
|
|
44
45
|
/** 製品が以前使っていた別方式の選択。新規の製品は持たない。binaryは旧方式が起動していたCodex。 */
|
package/dist/codex-setup.js
CHANGED
|
@@ -262,7 +262,8 @@ export async function configureCodexSteer(profile, action = "status", overrides)
|
|
|
262
262
|
fs.accessSync(node, fs.constants.X_OK);
|
|
263
263
|
fs.accessSync(runtime.hook, fs.constants.R_OK);
|
|
264
264
|
const binary = runtime.findBinary();
|
|
265
|
-
const command =
|
|
265
|
+
const command = runtime.hookCommand?.(node, runtime.hook, runtime.directory)
|
|
266
|
+
?? codexHookCommand(node, runtime.hook, runtime.directory, runtime.platform, runtime.powershell);
|
|
266
267
|
const changed = await applyCodexHookPlan(profile, planCodexParentHooks(file, command, previous?.command), runtime.codex_home, binary);
|
|
267
268
|
// hook導入前から動いているCodexを再起動待ちとして記録する。今のDesktop、前回の登録、旧方式が起動したCodexを、
|
|
268
269
|
// 引用符付きのコマンド行も含めて照合する(Windowsは区切りと大文字小文字を揃える)。
|
package/dist/codex-wake.js
CHANGED
|
@@ -9,6 +9,7 @@ import { spawn, spawnSync } from "node:child_process";
|
|
|
9
9
|
import { fileURLToPath } from "node:url";
|
|
10
10
|
import { z } from "zod";
|
|
11
11
|
import { codexHookDirectory } from "./profile.js";
|
|
12
|
+
import { withDeliveryEffect } from "./delivery-effect.js";
|
|
12
13
|
import { withCodexReceiver } from "./codex-receiver.js";
|
|
13
14
|
import { writeHookJson } from "./files.js";
|
|
14
15
|
import { liveNodeExecutable } from "./setup-node.js";
|
|
@@ -152,6 +153,7 @@ export function readCodexWakeResult(profile, deliveryId, directory = codexWakeDi
|
|
|
152
153
|
* 起こすのは、アプリの会話(sourceがvscode)で、最後の番が普通に終わっている(または番が1つも無い)時だけ。
|
|
153
154
|
*/
|
|
154
155
|
export async function wakeCodexParentIfAsleep(profile, parent, deliveryId, options = {}) {
|
|
156
|
+
parent = { ...parent };
|
|
155
157
|
const sleep = options.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
|
|
156
158
|
const directory = options.directory ?? codexWakeDirectory(profile);
|
|
157
159
|
const result = { delivery_id: z.uuid().parse(deliveryId), thread_id: z.uuid().parse(parent.thread_id),
|
|
@@ -210,8 +212,10 @@ export async function wakeCodexParentIfAsleep(profile, parent, deliveryId, optio
|
|
|
210
212
|
}
|
|
211
213
|
catch { /* まだ誰も開いていない */ }
|
|
212
214
|
if (!recent) {
|
|
213
|
-
|
|
214
|
-
|
|
215
|
+
const opened = await withDeliveryEffect(profile, { vendor: "codex", stage: "wake", delivery_ids: [deliveryId], endpoint: parent }, () => {
|
|
216
|
+
writeHookJson(stamp, { thread_id: parent.thread_id, delivery_id: deliveryId });
|
|
217
|
+
return open(codexThreadUrl(parent.thread_id));
|
|
218
|
+
});
|
|
215
219
|
if (!opened.ok) {
|
|
216
220
|
result.outcome = "open_failed";
|
|
217
221
|
if (opened.detail)
|
|
@@ -251,8 +255,9 @@ export function codexWakeWatchEnabled(platform = process.platform, env = process
|
|
|
251
255
|
export const CODEX_WAKE_PAYLOAD_ENV = "AITERM_STEER_CODEX_WAKE_PAYLOAD";
|
|
252
256
|
/** 見張りのprocessへ渡す、関数を含まない製品の識別情報。 */
|
|
253
257
|
export function serializeWakeProfile(profile) {
|
|
254
|
-
const { state_root, config_root, channels: _channels, ...rest } = profile;
|
|
255
|
-
return { ...rest, dispatch_tools: [...profile.dispatch_tools], state_root: state_root(), config_root: config_root()
|
|
258
|
+
const { state_root, config_root, channels: _channels, delivery_admission, ...rest } = profile;
|
|
259
|
+
return { ...rest, dispatch_tools: [...profile.dispatch_tools], state_root: state_root(), config_root: config_root(),
|
|
260
|
+
...(delivery_admission ? { delivery_admission: { required: true } } : {}) };
|
|
256
261
|
}
|
|
257
262
|
/**
|
|
258
263
|
* 配送を呼んだprocessとは別に、見張りを1つ起こす。呼んだprocessがすぐ終わっても(製品のCLI)、見直しと起こしは最後まで走る。
|
package/dist/cursor-receive.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type CursorReceiveReader } from "./cursor-receiver.js";
|
|
2
|
+
import type { ProductProfile } from "./profile.js";
|
|
2
3
|
export interface WaitProcess {
|
|
3
4
|
executable: string;
|
|
4
5
|
args: string[];
|
|
@@ -28,4 +29,4 @@ export declare function stdoutOutput(): ReceiveOutput;
|
|
|
28
29
|
/** 受信入口の本体。結果を1行のJSONでstdoutへ出し、exit codeを返す(0=受取、3=期限切れ、5=読み手なし、1=誤り)。
|
|
29
30
|
* hookRootを複数渡すと、配送記録のある置き場で待つ(runCursorHookMainと同じ理由)。どこにも無ければ先頭の置き場で誤りを返す。
|
|
30
31
|
* outputに関数を渡すと、読み手を確かめずにその関数へ結果を渡す。 */
|
|
31
|
-
export declare function runCursorReceive(hookRoot: string | readonly string[], argv: string[], output?: ((value: unknown) => void) | ReceiveOutput, usage?: string): Promise<number>;
|
|
32
|
+
export declare function runCursorReceive(hookRoot: string | readonly string[], argv: string[], output?: ((value: unknown) => void) | ReceiveOutput, usage?: string, profile?: ProductProfile): Promise<number>;
|
package/dist/cursor-receive.js
CHANGED
|
@@ -6,6 +6,7 @@ import * as path from "node:path";
|
|
|
6
6
|
import { receiveCursorAnswer } from "./cursor-receiver.js";
|
|
7
7
|
import { windowsStartProcessArgumentList } from "./windows.js";
|
|
8
8
|
import { liveNodeExecutable } from "./setup-node.js";
|
|
9
|
+
import { withDeliveryEffect } from "./delivery-effect.js";
|
|
9
10
|
/** 親の背景process APIへそのまま渡す起動情報。scriptは製品のCursor受信入口の絶対path。 */
|
|
10
11
|
export function cursorReceiveProcess(script, deliveryId, executable = liveNodeExecutable()) {
|
|
11
12
|
const args = [script, "--delivery", deliveryId];
|
|
@@ -76,7 +77,8 @@ export function stdoutOutput() {
|
|
|
76
77
|
/** 受信入口の本体。結果を1行のJSONでstdoutへ出し、exit codeを返す(0=受取、3=期限切れ、5=読み手なし、1=誤り)。
|
|
77
78
|
* hookRootを複数渡すと、配送記録のある置き場で待つ(runCursorHookMainと同じ理由)。どこにも無ければ先頭の置き場で誤りを返す。
|
|
78
79
|
* outputに関数を渡すと、読み手を確かめずにその関数へ結果を渡す。 */
|
|
79
|
-
export async function runCursorReceive(hookRoot, argv, output = stdoutOutput(), usage = "usage: cursor-parent-receive --delivery <uuid>") {
|
|
80
|
+
export async function runCursorReceive(hookRoot, argv, output = stdoutOutput(), usage = "usage: cursor-parent-receive --delivery <uuid>", profile) {
|
|
81
|
+
argv = [...argv];
|
|
80
82
|
const reader = typeof output === "function" ? undefined : output;
|
|
81
83
|
const emit = async (value) => { if (typeof output === "function")
|
|
82
84
|
output(value);
|
|
@@ -103,7 +105,12 @@ export async function runCursorReceive(hookRoot, argv, output = stdoutOutput(),
|
|
|
103
105
|
await emit({ delivery_id: argv[1], outcome: "delivered_by_hook" });
|
|
104
106
|
return 0;
|
|
105
107
|
}
|
|
106
|
-
|
|
108
|
+
const deliver = () => emit({ delivery_id: argv[1], outcome: "delivered", text: result.text });
|
|
109
|
+
if (profile)
|
|
110
|
+
await withDeliveryEffect(profile, { vendor: "cursor", stage: "emit", delivery_ids: [argv[1]],
|
|
111
|
+
endpoint: { kind: "cursor", hook_root: root } }, deliver);
|
|
112
|
+
else
|
|
113
|
+
await deliver();
|
|
107
114
|
return 0;
|
|
108
115
|
}
|
|
109
116
|
finally {
|
|
@@ -14,10 +14,10 @@ export declare function cursorParentFromRequest(profile: ProductProfile, clientN
|
|
|
14
14
|
hooksFile?: string;
|
|
15
15
|
}): CursorParent | null;
|
|
16
16
|
export declare function prepareCursorDelivery(parent: CursorParent, deliveryId: string): void;
|
|
17
|
-
export declare function submitCursorParentAnswer(parent: CursorParent, deliveryId: string, text: string, timeoutMs?: number): Promise<{
|
|
17
|
+
export declare function submitCursorParentAnswer(parent: CursorParent, deliveryId: string, text: string, timeoutMs?: number, profile?: ProductProfile): Promise<{
|
|
18
18
|
queued_submission_id: null;
|
|
19
19
|
}>;
|
|
20
|
-
export declare function handleCursorHook(profile: ProductProfile, raw: string, hookRoot: string): Promise<Record<string, unknown>>;
|
|
20
|
+
export declare function handleCursorHook(profile: ProductProfile, raw: string, hookRoot: string, nativeEmit?: (output: Record<string, unknown>) => Promise<void>): Promise<Record<string, unknown>>;
|
|
21
21
|
export type CursorReceiveResult = {
|
|
22
22
|
outcome: "delivered";
|
|
23
23
|
text: string;
|
package/dist/cursor-receiver.js
CHANGED
|
@@ -5,6 +5,7 @@ import { homedir } from "node:os";
|
|
|
5
5
|
import * as path from "node:path";
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
import { waitForFileState, withoutBom, writeJson0600 } from "./files.js";
|
|
8
|
+
import { withDeliveryEffect, DeliveryAdmissionError } from "./delivery-effect.js";
|
|
8
9
|
import { CursorDeliveryError } from "./errors.js";
|
|
9
10
|
import { commandNamesFile } from "./hook-setup.js";
|
|
10
11
|
export const cursorParentSchema = z.object({
|
|
@@ -66,9 +67,14 @@ export function prepareCursorDelivery(parent, deliveryId) {
|
|
|
66
67
|
cursorParentSchema.parse(parent);
|
|
67
68
|
fs.mkdirSync(deliveryDir(parent, deliveryId), { recursive: true, mode: 0o700 });
|
|
68
69
|
}
|
|
69
|
-
export async function submitCursorParentAnswer(parent, deliveryId, text, timeoutMs = 86_400_000) {
|
|
70
|
+
export async function submitCursorParentAnswer(parent, deliveryId, text, timeoutMs = 86_400_000, profile) {
|
|
71
|
+
parent = cursorParentSchema.parse(parent);
|
|
70
72
|
const dir = deliveryDir(parent, deliveryId);
|
|
71
|
-
writeJson0600(path.join(dir, "answer.json"), { delivery_id: deliveryId, text });
|
|
73
|
+
const write = () => writeJson0600(path.join(dir, "answer.json"), { delivery_id: deliveryId, text });
|
|
74
|
+
if (profile)
|
|
75
|
+
await withDeliveryEffect(profile, { vendor: "cursor", stage: "queue", delivery_ids: [deliveryId], endpoint: parent }, write);
|
|
76
|
+
else
|
|
77
|
+
write();
|
|
72
78
|
try {
|
|
73
79
|
await waitForFileState(dir, () => fs.existsSync(path.join(dir, "claim.json")) ? true : undefined, timeoutMs);
|
|
74
80
|
}
|
|
@@ -186,12 +192,12 @@ function inject(hookRoot, conv) {
|
|
|
186
192
|
fs.rmSync(index, { force: true });
|
|
187
193
|
continue;
|
|
188
194
|
}
|
|
189
|
-
texts.push(item.text);
|
|
195
|
+
texts.push({ delivery_id: item.deliveryId, text: item.text });
|
|
190
196
|
fs.rmSync(index, { force: true });
|
|
191
197
|
}
|
|
192
198
|
return texts;
|
|
193
199
|
}
|
|
194
|
-
export async function handleCursorHook(profile, raw, hookRoot) {
|
|
200
|
+
export async function handleCursorHook(profile, raw, hookRoot, nativeEmit) {
|
|
195
201
|
let parsed;
|
|
196
202
|
try {
|
|
197
203
|
parsed = JSON.parse(withoutBom(raw));
|
|
@@ -216,9 +222,28 @@ export async function handleCursorHook(profile, raw, hookRoot) {
|
|
|
216
222
|
bind(hookRoot, deliveryId, conv);
|
|
217
223
|
}
|
|
218
224
|
if (name === "postToolUse" || name === "postToolUseFailure") {
|
|
225
|
+
// This legacy return-value API has no actual stdout effect boundary.
|
|
226
|
+
// Required admission must not release a lease before a caller emits it.
|
|
227
|
+
if (profile.delivery_admission && !nativeEmit)
|
|
228
|
+
throw new DeliveryAdmissionError("DELIVERY_ADMISSION_UNSUPPORTED", "Cursor hookの出力受付が未接続です");
|
|
219
229
|
const texts = inject(hookRoot, conv);
|
|
220
|
-
if (texts.length > 0)
|
|
221
|
-
|
|
230
|
+
if (texts.length > 0) {
|
|
231
|
+
const result = { additional_context: texts.map(item => item.text).join("\n\n") };
|
|
232
|
+
if (!profile.delivery_admission)
|
|
233
|
+
return result;
|
|
234
|
+
try {
|
|
235
|
+
await withDeliveryEffect(profile, { vendor: "cursor", stage: "emit", delivery_ids: texts.map(item => item.delivery_id),
|
|
236
|
+
endpoint: { kind: "cursor", hook_root: hookRoot }, native_context: { conversation_id: conv, hook_event_name: name } }, () => nativeEmit(result));
|
|
237
|
+
return {}; // stdout was emitted inside the lease, never emit it twice
|
|
238
|
+
}
|
|
239
|
+
catch (error) {
|
|
240
|
+
for (const item of texts)
|
|
241
|
+
writeJson0600(path.join(hookRoot, "deliveries", item.delivery_id, "failed.json"), {
|
|
242
|
+
delivery_id: item.delivery_id, outcome_unknown: error.outcome_unknown === true,
|
|
243
|
+
});
|
|
244
|
+
throw error;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
222
247
|
}
|
|
223
248
|
return {};
|
|
224
249
|
}
|
|
@@ -247,7 +272,13 @@ export async function receiveCursorAnswer(hookRoot, deliveryId, timeoutMs = 86_4
|
|
|
247
272
|
// 引き取ると送り主は配送済みにする。読み手が居ない時は引き取らず、回答を置き場に残す。
|
|
248
273
|
if (reader && (gone || !(await reader.probe())))
|
|
249
274
|
return { outcome: "reader_gone" };
|
|
250
|
-
if (!claim(dir, "receiver"))
|
|
275
|
+
if (!claim(dir, "receiver")) {
|
|
276
|
+
const failed = path.join(dir, "failed.json");
|
|
277
|
+
if (fs.existsSync(failed)) {
|
|
278
|
+
const value = JSON.parse(fs.readFileSync(failed, "utf8"));
|
|
279
|
+
throw new CursorDeliveryError("CURSOR_PARENT_DELIVERY_UNCONFIRMED", "前の受信結果を確認できません。自動再送はしていません", value.outcome_unknown === true);
|
|
280
|
+
}
|
|
251
281
|
return { outcome: "delivered_by_hook" };
|
|
282
|
+
}
|
|
252
283
|
return { outcome: "delivered", text: answer.text };
|
|
253
284
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ProductProfile } from "./profile.js";
|
|
2
|
+
import { SteerDeliveryError } from "./errors.js";
|
|
3
|
+
export interface DeliveryEffect {
|
|
4
|
+
delivery_ids: readonly string[];
|
|
5
|
+
stage: "queue" | "dequeue" | "emit" | "wake";
|
|
6
|
+
vendor: "codex" | "claude" | "cursor";
|
|
7
|
+
endpoint: unknown;
|
|
8
|
+
native_context?: unknown;
|
|
9
|
+
}
|
|
10
|
+
export declare class DeliveryAdmissionError extends SteerDeliveryError {
|
|
11
|
+
}
|
|
12
|
+
export declare const DELIVERY_ADMISSION_CONTRACT: Readonly<{
|
|
13
|
+
schema: "steer.delivery-admission.v1";
|
|
14
|
+
native_context: true;
|
|
15
|
+
cursor_profile_parameter: true;
|
|
16
|
+
multi_delivery_emit: true;
|
|
17
|
+
serialized_required: true;
|
|
18
|
+
codex_hook_event: true;
|
|
19
|
+
native_hook_args: true;
|
|
20
|
+
}>;
|
|
21
|
+
export declare function withDeliveryEffect<T>(profile: ProductProfile, input: DeliveryEffect, action: () => T | Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Product callback at the actual native input boundary. No state, IDs, graph,
|
|
2
|
+
// payload queue or retries belong to this package's admission adapter.
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { SteerDeliveryError } from "./errors.js";
|
|
5
|
+
export class DeliveryAdmissionError extends SteerDeliveryError {
|
|
6
|
+
}
|
|
7
|
+
export const DELIVERY_ADMISSION_CONTRACT = Object.freeze({
|
|
8
|
+
schema: "steer.delivery-admission.v1", native_context: true, cursor_profile_parameter: true,
|
|
9
|
+
multi_delivery_emit: true, serialized_required: true, codex_hook_event: true, native_hook_args: true,
|
|
10
|
+
});
|
|
11
|
+
export async function withDeliveryEffect(profile, input, action) {
|
|
12
|
+
const admission = profile.delivery_admission;
|
|
13
|
+
if (!admission)
|
|
14
|
+
return action();
|
|
15
|
+
if (admission.required !== true || !admission.run)
|
|
16
|
+
throw new DeliveryAdmissionError("DELIVERY_ADMISSION_UNAVAILABLE", "入力の実行受付を確認できません");
|
|
17
|
+
const effect = { ...input, delivery_ids: z.array(z.uuid()).min(1).parse(input.delivery_ids), endpoint: structuredClone(input.endpoint),
|
|
18
|
+
...(input.native_context === undefined ? {} : { native_context: structuredClone(input.native_context) }) };
|
|
19
|
+
if (new Set(effect.delivery_ids).size !== effect.delivery_ids.length)
|
|
20
|
+
throw new DeliveryAdmissionError("DELIVERY_ADMISSION_INVALID", "配送参照が重複しています");
|
|
21
|
+
let used = false, active = true, settled = false, failure, pending;
|
|
22
|
+
const guarded = () => {
|
|
23
|
+
if (!active || used) {
|
|
24
|
+
const error = new DeliveryAdmissionError("DELIVERY_ADMISSION_CONFLICT", "入力callbackを再利用できません", used);
|
|
25
|
+
failure = error;
|
|
26
|
+
return Promise.reject(error);
|
|
27
|
+
}
|
|
28
|
+
used = true;
|
|
29
|
+
pending = (async () => {
|
|
30
|
+
try {
|
|
31
|
+
return await action();
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
failure = error;
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
settled = true;
|
|
39
|
+
}
|
|
40
|
+
})();
|
|
41
|
+
// A broken runner must not leave a detached native rejection unobserved.
|
|
42
|
+
void pending.catch(() => { });
|
|
43
|
+
return pending;
|
|
44
|
+
};
|
|
45
|
+
try {
|
|
46
|
+
await admission.run(effect, guarded);
|
|
47
|
+
if (failure)
|
|
48
|
+
throw failure;
|
|
49
|
+
if (!used)
|
|
50
|
+
throw new DeliveryAdmissionError("DELIVERY_ADMISSION_REFUSED", "入力は発行されていません");
|
|
51
|
+
if (!settled)
|
|
52
|
+
throw new DeliveryAdmissionError("DELIVERY_NATIVE_UNCONFIRMED", "実作用の応答より前に受付が終了しました", true);
|
|
53
|
+
return await pending; // preserve the actual native receipt, not a substitute
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
if (error instanceof SteerDeliveryError)
|
|
57
|
+
throw error;
|
|
58
|
+
const possible = used || error?.effect === "possible";
|
|
59
|
+
throw new DeliveryAdmissionError(possible ? "DELIVERY_NATIVE_UNCONFIRMED" : "DELIVERY_ADMISSION_REFUSED", possible ? "入力結果を確認できません" : "入力の実行受付が拒否されました", possible);
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
active = false;
|
|
63
|
+
}
|
|
64
|
+
}
|
package/dist/hook-main.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// 製品のhook入口から呼ぶ本体。入口ファイルは「import して呼ぶだけ」にし、hook commandのpathは製品が持つ。
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
3
4
|
import { fileURLToPath } from "node:url";
|
|
4
5
|
import { claudeHookRoot, cursorHookRoot } from "./profile.js";
|
|
5
6
|
import { runCodexResultHook } from "./codex-hooks.js";
|
|
@@ -8,6 +9,7 @@ import { handleCursorHook } from "./cursor-receiver.js";
|
|
|
8
9
|
import { withoutBom } from "./files.js";
|
|
9
10
|
import { runCursorReceive } from "./cursor-receive.js";
|
|
10
11
|
import { channelReceiveProcess, closeClaudeSessionChannels, handleCursorChannelHook, receiveFromChannel, runClaudeChannelWaiter } from "./channel.js";
|
|
12
|
+
import { DeliveryAdmissionError } from "./delivery-effect.js";
|
|
11
13
|
async function readStdin() {
|
|
12
14
|
let input = "";
|
|
13
15
|
process.stdin.setEncoding("utf8");
|
|
@@ -34,19 +36,33 @@ export async function runCodexHookMain(profile, directory = process.argv[2]) {
|
|
|
34
36
|
* 失敗の2を返すと、GrokはStopを「止めずに続ける」、PreToolUseを「拒否」と読む。見分けは、Grokだけが入力へ入れる`hookEventName`。
|
|
35
37
|
*/
|
|
36
38
|
export async function runClaudeHookMain(profile, root = claudeHookRoot(profile)) {
|
|
39
|
+
const started = Date.now();
|
|
40
|
+
let event = null, failure, foreign = false;
|
|
37
41
|
try {
|
|
38
|
-
|
|
39
|
-
|
|
42
|
+
event = JSON.parse(await readStdin());
|
|
43
|
+
// Grokの起動では何も記録しない(共有のsettingsのhookが動いただけ)。
|
|
44
|
+
if (event !== null && typeof event === "object" && typeof event.hookEventName === "string") {
|
|
45
|
+
foreign = true;
|
|
40
46
|
return;
|
|
47
|
+
}
|
|
48
|
+
if (profile.delivery_admission && profile.channels)
|
|
49
|
+
throw new DeliveryAdmissionError("DELIVERY_ADMISSION_UNSUPPORTED", "channel入力の実行受付が未接続です");
|
|
41
50
|
const write = (text) => new Promise((resolve, reject) => {
|
|
42
51
|
process.stderr.write(text, error => error ? reject(error) : resolve());
|
|
43
52
|
});
|
|
44
|
-
switch (event
|
|
53
|
+
switch (event?.hook_event_name) {
|
|
45
54
|
case "PreToolUse":
|
|
46
55
|
prepareClaudeHookRequest(event, root);
|
|
47
56
|
break;
|
|
48
57
|
case "PostToolUse":
|
|
49
|
-
|
|
58
|
+
if (profile.delivery_admission) {
|
|
59
|
+
let signaled = false;
|
|
60
|
+
const code = await runClaudeResultHook(profile, event, write, root, { resume: value => { process.exitCode = value; signaled = true; } });
|
|
61
|
+
if (!signaled)
|
|
62
|
+
process.exitCode = code;
|
|
63
|
+
}
|
|
64
|
+
else
|
|
65
|
+
process.exitCode = await runClaudeResultHook(profile, event, write, root);
|
|
50
66
|
// 単発の依頼が無いtoolの返りでは、channelの待機を張る(長く続く受信を使う製品だけ)。
|
|
51
67
|
if (process.exitCode === 0 && profile.channels)
|
|
52
68
|
process.exitCode = await runClaudeChannelWaiter(profile, event, write);
|
|
@@ -72,10 +88,44 @@ export async function runClaudeHookMain(profile, root = claudeHookRoot(profile))
|
|
|
72
88
|
}
|
|
73
89
|
}
|
|
74
90
|
catch (error) {
|
|
91
|
+
failure = error;
|
|
75
92
|
process.stderr.write(`${error instanceof Error ? error.message : "CLAUDE_PARENT_HOOK_FAILED"}\n`);
|
|
76
|
-
|
|
93
|
+
// PostToolUse exit 2 is a resume signal, not a safe admission refusal.
|
|
94
|
+
process.exitCode = profile.delivery_admission ? 1 : 2;
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
if (!foreign)
|
|
98
|
+
recordClaudeHookEvent(root, event, started, failure);
|
|
77
99
|
}
|
|
78
100
|
}
|
|
101
|
+
/**
|
|
102
|
+
* hookの実行記録を`<hook root>/hook-events.log`へ1行JSONで足す。event名・会話ID・tool_use_id・所要・終了code・失敗の符号だけで、
|
|
103
|
+
* 本文・引数・stderrの文は書かない。PreToolUseの記録が欠けた時に、hookが走ったか・timeoutに近かったかを後から確かめる為。
|
|
104
|
+
* 記録の失敗でhookの結果を変えない。
|
|
105
|
+
*/
|
|
106
|
+
function recordClaudeHookEvent(root, event, started, failure) {
|
|
107
|
+
try {
|
|
108
|
+
const input = event !== null && typeof event === "object" ? event : {};
|
|
109
|
+
const safe = (value, pattern) => typeof value === "string" && pattern.test(value) ? value : null;
|
|
110
|
+
const message = failure instanceof Error ? failure.message : failure === undefined ? "" : "CLAUDE_PARENT_HOOK_FAILED";
|
|
111
|
+
const code = failure?.delivery_code;
|
|
112
|
+
fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
113
|
+
const file = path.join(root, "hook-events.log");
|
|
114
|
+
// shortcut: 1MBを超えたら前の世代を1つだけ残して入れ替える, 長い保全が要る時に世代管理へ上げる
|
|
115
|
+
try {
|
|
116
|
+
if (fs.statSync(file).size > 1_000_000)
|
|
117
|
+
fs.renameSync(file, `${file}.1`);
|
|
118
|
+
}
|
|
119
|
+
catch { /* まだ無い */ }
|
|
120
|
+
fs.appendFileSync(file, JSON.stringify({
|
|
121
|
+
at: new Date(started).toISOString(), event: safe(input.hook_event_name, /^[A-Za-z]{1,32}$/u),
|
|
122
|
+
session_id: safe(input.session_id, /^[0-9a-fA-F-]{36}$/u), tool_use_id: safe(input.tool_use_id, /^[A-Za-z0-9_-]{1,160}$/u),
|
|
123
|
+
ms: Date.now() - started, exit: process.exitCode ?? 0,
|
|
124
|
+
code: typeof code === "string" ? code : (failure === undefined ? null : (/^[A-Z][A-Z0-9_]*/u.exec(message)?.[0] ?? "FAILED")),
|
|
125
|
+
}) + "\n", { mode: 0o600 });
|
|
126
|
+
}
|
|
127
|
+
catch { /* 記録の失敗でhookを止めない */ }
|
|
128
|
+
}
|
|
79
129
|
/**
|
|
80
130
|
* Cursorが起動する公式hook。差し込み文をstdoutのJSONへ返す。
|
|
81
131
|
* rootを複数渡すと、各置き場で結び付けと差し込みを行う。Cursor CLIはMCPを削った環境で起動し、hookは画面側の環境で起動するため、
|
|
@@ -84,6 +134,19 @@ export async function runClaudeHookMain(profile, root = claudeHookRoot(profile))
|
|
|
84
134
|
export async function runCursorHookMain(profile, root = cursorHookRoot(profile)) {
|
|
85
135
|
try {
|
|
86
136
|
const input = await readStdin();
|
|
137
|
+
if (profile.delivery_admission) {
|
|
138
|
+
const roots = typeof root === "string" ? [root] : [...new Set(root)];
|
|
139
|
+
if (roots.length !== 1 || profile.channels)
|
|
140
|
+
throw new DeliveryAdmissionError("DELIVERY_ADMISSION_UNSUPPORTED", "複数scope/channelのCursor出力受付が未接続です");
|
|
141
|
+
let emitted = false;
|
|
142
|
+
const result = await handleCursorHook(profile, input.length ? input : "{}", roots[0], async (value) => {
|
|
143
|
+
await new Promise((resolve, reject) => process.stdout.write(`${JSON.stringify(value)}\n`, error => error ? reject(error) : resolve()));
|
|
144
|
+
emitted = true;
|
|
145
|
+
});
|
|
146
|
+
if (!emitted)
|
|
147
|
+
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
87
150
|
const result = {};
|
|
88
151
|
for (const each of typeof root === "string" ? [root] : [...new Set(root)]) {
|
|
89
152
|
const found = await handleCursorHook(profile, input.length > 0 ? input : "{}", each);
|
|
@@ -92,6 +155,8 @@ export async function runCursorHookMain(profile, root = cursorHookRoot(profile))
|
|
|
92
155
|
}
|
|
93
156
|
}
|
|
94
157
|
if (profile.channels) {
|
|
158
|
+
if (profile.delivery_admission)
|
|
159
|
+
throw new DeliveryAdmissionError("DELIVERY_ADMISSION_UNSUPPORTED", "channel入力の実行受付が未接続です");
|
|
95
160
|
let event = null;
|
|
96
161
|
try {
|
|
97
162
|
event = JSON.parse(input);
|
|
@@ -113,7 +178,7 @@ export async function runCursorHookMain(profile, root = cursorHookRoot(profile))
|
|
|
113
178
|
/** Cursor親の背景受信。 */
|
|
114
179
|
export async function runCursorReceiveMain(profile, argv = process.argv.slice(2), root = cursorHookRoot(profile)) {
|
|
115
180
|
try {
|
|
116
|
-
process.exitCode = await runCursorReceive(root, argv);
|
|
181
|
+
process.exitCode = await runCursorReceive(root, argv, undefined, undefined, profile);
|
|
117
182
|
}
|
|
118
183
|
catch (error) {
|
|
119
184
|
process.stdout.write(JSON.stringify({ ok: false, code: "CURSOR_PARENT_RECEIVE_FAILED", message: error instanceof Error ? error.message : "cursor-parent-receive: operation failed" }) + "\n");
|
package/dist/hook-setup.d.ts
CHANGED
package/dist/hook-setup.js
CHANGED
|
@@ -22,7 +22,7 @@ function shellQuote(value, platform = process.platform) {
|
|
|
22
22
|
* `$LASTEXITCODE`とは書かない。Grokが`$名前`を環境変数として読み、未設定としてhookを動かさない。
|
|
23
23
|
*/
|
|
24
24
|
export function claudeParentHookCommand(hook, platform = process.platform) {
|
|
25
|
-
const words =
|
|
25
|
+
const words = [hook.command, hook.script, ...(hook.args ?? [])].map(value => shellQuote(value, platform)).join(" ");
|
|
26
26
|
if (platform === "win32")
|
|
27
27
|
return { command: `& ${words}; exit (Get-Variable LASTEXITCODE -ValueOnly)`, shell: "powershell" };
|
|
28
28
|
return { command: `exec ${words}` };
|
|
@@ -174,7 +174,7 @@ export function removeClaudeParentHooks(profile, file) {
|
|
|
174
174
|
return "removed";
|
|
175
175
|
}
|
|
176
176
|
export function cursorParentHookCommand(hook) {
|
|
177
|
-
const command =
|
|
177
|
+
const command = [hook.command, hook.script, ...(hook.args ?? [])].map(value => shellQuote(value)).join(" ");
|
|
178
178
|
return process.platform === "win32" ? `& ${command}` : command;
|
|
179
179
|
}
|
|
180
180
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export * from "./profile.js";
|
|
2
2
|
export * from "./errors.js";
|
|
3
|
+
export { withDeliveryEffect, DeliveryAdmissionError, DELIVERY_ADMISSION_CONTRACT, type DeliveryEffect } from "./delivery-effect.js";
|
|
3
4
|
export { writeJson0600, writeHookJson, waitForFileState, withoutBom } from "./files.js";
|
|
4
5
|
export { readRuntimeProcesses, readProcessIdentities, readProcessLineage, processExists, processIsRunning, parsePosixProcessTable, hookOwnerProcess, type RuntimeProcess, type NativeProcessIdentity } from "./process.js";
|
|
5
6
|
export { resolveWindowsPowerShell7, quotePowerShell, windowsPowerShellSync, windowsStartProcessArgumentList } from "./windows.js";
|
package/dist/index.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// 親AIが作業中ならそのturnへ差し込み、idleなら同じ会話へ普通に届ける。受信方式は親ごとに公式の仕組みを使う。
|
|
3
3
|
export * from "./profile.js";
|
|
4
4
|
export * from "./errors.js";
|
|
5
|
+
export { withDeliveryEffect, DeliveryAdmissionError, DELIVERY_ADMISSION_CONTRACT } from "./delivery-effect.js";
|
|
5
6
|
export { writeJson0600, writeHookJson, waitForFileState, withoutBom } from "./files.js";
|
|
6
7
|
export { readRuntimeProcesses, readProcessIdentities, readProcessLineage, processExists, processIsRunning, parsePosixProcessTable, hookOwnerProcess } from "./process.js";
|
|
7
8
|
export { resolveWindowsPowerShell7, quotePowerShell, windowsPowerShellSync, windowsStartProcessArgumentList } from "./windows.js";
|
package/dist/process.js
CHANGED
|
@@ -153,10 +153,10 @@ export function processIsRunning(pid, startedIdentity) {
|
|
|
153
153
|
* 今までどおり全processの一覧を返す。
|
|
154
154
|
*/
|
|
155
155
|
export function readProcessLineage(pid, depth = 8) {
|
|
156
|
-
if (!isWin)
|
|
157
|
-
return readRuntimeProcesses();
|
|
158
156
|
if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isSafeInteger(depth) || depth <= 0)
|
|
159
157
|
throw new ProcessTableError("process照会のpidが不正です");
|
|
158
|
+
if (!isWin)
|
|
159
|
+
return readPosixLineage(pid, depth);
|
|
160
160
|
let rows;
|
|
161
161
|
try {
|
|
162
162
|
rows = windowsJson([
|
|
@@ -192,6 +192,32 @@ export function readProcessLineage(pid, depth = 8) {
|
|
|
192
192
|
};
|
|
193
193
|
});
|
|
194
194
|
}
|
|
195
|
+
/**
|
|
196
|
+
* POSIXで先祖を1個ずつたどる。全processの一覧(`ps -axww`、全commandを含む)は混んだMacで秒単位かかり、Claude CodeのPreToolUse
|
|
197
|
+
* hookの15秒に食い込む(2026-10-31)。1個読むpsを最大depth回で済ませ、読めない時だけ全一覧へ戻す。
|
|
198
|
+
*/
|
|
199
|
+
function readPosixLineage(pid, depth) {
|
|
200
|
+
const rows = [];
|
|
201
|
+
for (let id = pid; rows.length < depth && id > 0;) {
|
|
202
|
+
const result = spawnSync("/bin/ps", ["-o", "pid=,ppid=,pgid=,stat=,lstart=,time=,command=", "-p", String(id)], {
|
|
203
|
+
encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 10000, maxBuffer: 16 * 1024 * 1024,
|
|
204
|
+
});
|
|
205
|
+
if (result.error || result.status !== 0)
|
|
206
|
+
break;
|
|
207
|
+
let parsed;
|
|
208
|
+
try {
|
|
209
|
+
parsed = parsePosixProcessTable(result.stdout);
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
if (parsed.length !== 1 || parsed[0].pid !== id)
|
|
215
|
+
break;
|
|
216
|
+
rows.push(parsed[0]);
|
|
217
|
+
id = parsed[0].parent_pid;
|
|
218
|
+
}
|
|
219
|
+
return rows.length > 0 && rows[0].pid === pid ? rows : readRuntimeProcesses();
|
|
220
|
+
}
|
|
195
221
|
export function readRuntimeProcesses() {
|
|
196
222
|
if (!isWin) {
|
|
197
223
|
const result = spawnSync("/bin/ps", ["-axww", "-o", "pid=,ppid=,pgid=,stat=,lstart=,time=,command="], {
|
package/dist/profile.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { DeliveryEffect } from "./delivery-effect.js";
|
|
1
2
|
export interface ProductProfile {
|
|
2
3
|
/** 製品ID。stateのschema名やhookの見分けに使う(例: "aiterm")。 */
|
|
3
4
|
id: string;
|
|
@@ -35,6 +36,12 @@ export interface ProductProfile {
|
|
|
35
36
|
channels?: {
|
|
36
37
|
claude_expiry_notice?: string;
|
|
37
38
|
};
|
|
39
|
+
/** Product-owned execution admission. A serialized required marker without
|
|
40
|
+
* its process-local resolver refuses input; it never falls back to legacy. */
|
|
41
|
+
delivery_admission?: {
|
|
42
|
+
required: true;
|
|
43
|
+
run?<T>(effect: DeliveryEffect, action: () => Promise<T>): Promise<T>;
|
|
44
|
+
};
|
|
38
45
|
}
|
|
39
46
|
export declare function codexHookDirectory(profile: ProductProfile): string;
|
|
40
47
|
export declare function claudeHookRoot(profile: ProductProfile): string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiterm-steer-delivery",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
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",
|