aiterm-steer-delivery 0.4.7 → 0.5.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 CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ## 0.5.0
6
+
7
+ - Optional native delivery admission passes existing request/parent references through queue, dequeue, emit and wake hooks without creating a second queue or resending input.
8
+ - 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.
9
+
3
10
  ## 0.4.7
4
11
 
5
12
  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): Promise<0 | 2>;
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 {};
@@ -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,7 +249,7 @@ 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
255
  const invocation = readInvocation(profile, parent);
@@ -257,7 +260,9 @@ export async function runClaudeResultHook(profile, input, emit, root) {
257
260
  return 0;
258
261
  }
259
262
  const deliveryId = z.uuid().parse(JSON.parse(fs.readFileSync(binding, "utf8")).delivery_id);
260
- const identity = processIdentity(process.pid);
263
+ if (profile.delivery_admission && !runtime.resume)
264
+ throw new DeliveryAdmissionError("DELIVERY_ADMISSION_UNSUPPORTED", "Claude再開信号の作用口が未接続です");
265
+ const identity = (runtime.identity ?? processIdentity)(process.pid);
261
266
  if (!identity)
262
267
  throw new ClaudeDeliveryError("CLAUDE_PARENT_HOOK_UNAVAILABLE", "受信hookのprocessを確認できません");
263
268
  writeJson0600(path.join(dir, "hook.json"), { pid: process.pid, started_identity: identity });
@@ -265,7 +270,7 @@ export async function runClaudeResultHook(profile, input, emit, root) {
265
270
  const answer = await waitForFileState(dir, () => {
266
271
  if (fs.existsSync(path.join(dir, "closed.json")))
267
272
  return null;
268
- assertParentAlive(invocation);
273
+ (runtime.parentAlive ?? assertParentAlive)(invocation);
269
274
  const file = path.join(dir, "answer.json");
270
275
  if (!fs.existsSync(file))
271
276
  return undefined;
@@ -277,9 +282,15 @@ export async function runClaudeResultHook(profile, input, emit, root) {
277
282
  if (!answer)
278
283
  return 0;
279
284
  assertOpen(parent);
280
- writeJson0600(path.join(dir, "sending.json"), { delivery_id: deliveryId });
281
- await emit(answer.text);
285
+ await withDeliveryEffect(profile, { vendor: "claude", stage: "emit", delivery_ids: [deliveryId], endpoint: parent,
286
+ native_context: { session_id: event.session_id, tool_use_id: event.tool_use_id } }, async () => {
287
+ writeJson0600(path.join(dir, "sending.json"), { delivery_id: deliveryId });
288
+ await emit(answer.text);
289
+ });
282
290
  writeJson0600(path.join(dir, "emitted.json"), { delivery_id: deliveryId });
291
+ if (profile.delivery_admission)
292
+ await withDeliveryEffect(profile, { vendor: "claude", stage: "wake", delivery_ids: [deliveryId], endpoint: parent,
293
+ native_context: { session_id: event.session_id, tool_use_id: event.tool_use_id } }, () => runtime.resume(2));
283
294
  // Claudeが定めるasyncRewakeの再開信号。子の成功/失敗は本文のoutcomeで区別する。
284
295
  return 2;
285
296
  }
@@ -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>;
@@ -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 request("thread/queue/delete", { threadId: event.session_id, queuedSubmissionId: entry.id });
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
- await emit(!taken.length ? {} : event.hook_event_name === "Stop"
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
  }
@@ -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
- asked = true;
139
- const result = await request("thread/queue/add", {
140
- threadId: parent.thread_id,
141
- input: [{ type: "text", text, text_elements: [] }],
142
- clientUserMessageId: deliveryId,
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);
@@ -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。 */
@@ -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 = codexHookCommand(node, runtime.hook, runtime.directory, runtime.platform, runtime.powershell);
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は区切りと大文字小文字を揃える)。
@@ -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
- writeHookJson(stamp, { thread_id: parent.thread_id, delivery_id: deliveryId });
214
- const opened = open(codexThreadUrl(parent.thread_id));
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)、見直しと起こしは最後まで走る。
@@ -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>;
@@ -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
- await emit({ delivery_id: argv[1], outcome: "delivered", text: result.text });
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;
@@ -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
- return { additional_context: texts.join("\n\n") };
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
@@ -8,6 +8,7 @@ import { handleCursorHook } from "./cursor-receiver.js";
8
8
  import { withoutBom } from "./files.js";
9
9
  import { runCursorReceive } from "./cursor-receive.js";
10
10
  import { channelReceiveProcess, closeClaudeSessionChannels, handleCursorChannelHook, receiveFromChannel, runClaudeChannelWaiter } from "./channel.js";
11
+ import { DeliveryAdmissionError } from "./delivery-effect.js";
11
12
  async function readStdin() {
12
13
  let input = "";
13
14
  process.stdin.setEncoding("utf8");
@@ -38,6 +39,8 @@ export async function runClaudeHookMain(profile, root = claudeHookRoot(profile))
38
39
  const event = JSON.parse(await readStdin());
39
40
  if (event !== null && typeof event === "object" && typeof event.hookEventName === "string")
40
41
  return;
42
+ if (profile.delivery_admission && profile.channels)
43
+ throw new DeliveryAdmissionError("DELIVERY_ADMISSION_UNSUPPORTED", "channel入力の実行受付が未接続です");
41
44
  const write = (text) => new Promise((resolve, reject) => {
42
45
  process.stderr.write(text, error => error ? reject(error) : resolve());
43
46
  });
@@ -46,7 +49,14 @@ export async function runClaudeHookMain(profile, root = claudeHookRoot(profile))
46
49
  prepareClaudeHookRequest(event, root);
47
50
  break;
48
51
  case "PostToolUse":
49
- process.exitCode = await runClaudeResultHook(profile, event, write, root);
52
+ if (profile.delivery_admission) {
53
+ let signaled = false;
54
+ const code = await runClaudeResultHook(profile, event, write, root, { resume: value => { process.exitCode = value; signaled = true; } });
55
+ if (!signaled)
56
+ process.exitCode = code;
57
+ }
58
+ else
59
+ process.exitCode = await runClaudeResultHook(profile, event, write, root);
50
60
  // 単発の依頼が無いtoolの返りでは、channelの待機を張る(長く続く受信を使う製品だけ)。
51
61
  if (process.exitCode === 0 && profile.channels)
52
62
  process.exitCode = await runClaudeChannelWaiter(profile, event, write);
@@ -73,7 +83,8 @@ export async function runClaudeHookMain(profile, root = claudeHookRoot(profile))
73
83
  }
74
84
  catch (error) {
75
85
  process.stderr.write(`${error instanceof Error ? error.message : "CLAUDE_PARENT_HOOK_FAILED"}\n`);
76
- process.exitCode = 2;
86
+ // PostToolUse exit 2 is a resume signal, not a safe admission refusal.
87
+ process.exitCode = profile.delivery_admission ? 1 : 2;
77
88
  }
78
89
  }
79
90
  /**
@@ -84,6 +95,19 @@ export async function runClaudeHookMain(profile, root = claudeHookRoot(profile))
84
95
  export async function runCursorHookMain(profile, root = cursorHookRoot(profile)) {
85
96
  try {
86
97
  const input = await readStdin();
98
+ if (profile.delivery_admission) {
99
+ const roots = typeof root === "string" ? [root] : [...new Set(root)];
100
+ if (roots.length !== 1 || profile.channels)
101
+ throw new DeliveryAdmissionError("DELIVERY_ADMISSION_UNSUPPORTED", "複数scope/channelのCursor出力受付が未接続です");
102
+ let emitted = false;
103
+ const result = await handleCursorHook(profile, input.length ? input : "{}", roots[0], async (value) => {
104
+ await new Promise((resolve, reject) => process.stdout.write(`${JSON.stringify(value)}\n`, error => error ? reject(error) : resolve()));
105
+ emitted = true;
106
+ });
107
+ if (!emitted)
108
+ process.stdout.write(`${JSON.stringify(result)}\n`);
109
+ return;
110
+ }
87
111
  const result = {};
88
112
  for (const each of typeof root === "string" ? [root] : [...new Set(root)]) {
89
113
  const found = await handleCursorHook(profile, input.length > 0 ? input : "{}", each);
@@ -92,6 +116,8 @@ export async function runCursorHookMain(profile, root = cursorHookRoot(profile))
92
116
  }
93
117
  }
94
118
  if (profile.channels) {
119
+ if (profile.delivery_admission)
120
+ throw new DeliveryAdmissionError("DELIVERY_ADMISSION_UNSUPPORTED", "channel入力の実行受付が未接続です");
95
121
  let event = null;
96
122
  try {
97
123
  event = JSON.parse(input);
@@ -113,7 +139,7 @@ export async function runCursorHookMain(profile, root = cursorHookRoot(profile))
113
139
  /** Cursor親の背景受信。 */
114
140
  export async function runCursorReceiveMain(profile, argv = process.argv.slice(2), root = cursorHookRoot(profile)) {
115
141
  try {
116
- process.exitCode = await runCursorReceive(root, argv);
142
+ process.exitCode = await runCursorReceive(root, argv, undefined, undefined, profile);
117
143
  }
118
144
  catch (error) {
119
145
  process.stdout.write(JSON.stringify({ ok: false, code: "CURSOR_PARENT_RECEIVE_FAILED", message: error instanceof Error ? error.message : "cursor-parent-receive: operation failed" }) + "\n");
@@ -3,6 +3,7 @@ import type { ProductProfile } from "./profile.js";
3
3
  export type HookRuntime = {
4
4
  command: string;
5
5
  script: string;
6
+ args?: readonly string[];
6
7
  };
7
8
  /**
8
9
  * Claude Codeの設定へ書くhookのcommand。shellを通す形で書く。
@@ -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 = `${shellQuote(hook.command, platform)} ${shellQuote(hook.script, platform)}`;
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 = `${shellQuote(hook.command)} ${shellQuote(hook.script)}`;
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/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.4.7",
3
+ "version": "0.5.0",
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",