aiterm-steer-delivery 0.1.11 → 0.1.12

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,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.12
4
+
5
+ - Cursor親の背景受信(`runCursorReceive`)が、読み手の居ない時に回答を引き取らない。Cursorは受信processを切り離して起こすので、親が終わった後も受信processは残る。残ったprocessが回答を引き取り、送り主は誰も読んでいない回答を配送済みにしていた(実物のCursor CLI 2026.10.01で、席を再起動して20回中20回)。受信processは最長24時間残っていた。
6
+ - 出力先を `stdoutOutput()` で扱う。stdoutがsocket(POSIXのNodeが子へ渡す形)なら読み口も開き、親が終わった時点で受信を終える。引き取る前には1行書いて、書けるかを確かめる(Windowsのpipeなど、終了を知る方法が無い出力先のため)。
7
+ - 読み手が居ない時は引き取らずにexit code 5で終わる。回答は置き場に残り、`submitCursorParentAnswer` は期限まで待って `CURSOR_PARENT_DELIVERY_UNCLAIMED` になる。
8
+ - `receiveCursorAnswer` の4番目の引数に読み手(`CursorReceiveReader`)を渡した時だけ、結果に `reader_gone` が加わる。`runCursorReceive` の3番目の引数へ関数を渡す従来の呼び方は、読み手を確かめない。
9
+ - `waitForFileState` が `AbortSignal` を受け取る。
10
+
3
11
  ## 0.1.11
4
12
 
5
13
  - WindowsのPowerShell 7を実体のpathへ解決する。同じ実行ファイルがPATHの大文字小文字だけ違う形で見つかっても、Codex hookのcommandと承認hashを変えず、不要な再起動待ちを作らない(foxの定期更新とSSHからのsetupで再現)。既に記録されている再起動待ちは保持する。
package/README.ja.md CHANGED
@@ -108,6 +108,8 @@ await runClaudeHookMain(PROFILE);
108
108
 
109
109
  3つの hook ファイルには `runCodexHookMain`、`runClaudeHookMain`、`runCursorHookMain` を使います。背景の受信には `runCursorReceiveMain`(1回の回答)か `runChannelReceiveMain`(channel)を使います。
110
110
 
111
+ Cursor の親は、1回の回答の受信 process を切り離して起こすので、親が終わった後も受信 process は残ります。受信 process は回答を引き取る前に、親がまだ出力を読んでいるかを確かめます。親が居なければ引き取らずに exit code 5 で終わり、送り主からは「配送済み」ではなく「まだ受け取られていない」と見えます。
112
+
111
113
  ### 3. hook を登録する
112
114
 
113
115
  製品の setup コマンドで次を呼びます。
package/README.md CHANGED
@@ -108,6 +108,8 @@ await runClaudeHookMain(PROFILE);
108
108
 
109
109
  Use `runCodexHookMain`, `runClaudeHookMain`, and `runCursorHookMain` for the three hook files. Background receivers use `runCursorReceiveMain` (one answer) or `runChannelReceiveMain` (channels).
110
110
 
111
+ The Cursor parent starts the one-answer receiver detached, so it outlives the parent. Before it claims an answer, the receiver checks that the parent is still reading its output. If the parent is gone, it leaves the answer unclaimed and exits with code 5; the sender sees the delivery as not yet received instead of delivered.
112
+
111
113
  ### 3. Register the hooks
112
114
 
113
115
  In your setup command:
@@ -1,3 +1,4 @@
1
+ import { type CursorReceiveReader } from "./cursor-receiver.js";
1
2
  export interface WaitProcess {
2
3
  executable: string;
3
4
  args: string[];
@@ -13,6 +14,18 @@ export declare function waitProcessCommandLine(wait: {
13
14
  executable: string;
14
15
  args: readonly string[];
15
16
  }, platform?: NodeJS.Platform): string;
16
- /** 受信入口の本体。結果を1行のJSONでstdoutへ出し、exit codeを返す(0=受取、3=期限切れ、1=誤り)。
17
- * hookRootを複数渡すと、配送記録のある置き場で待つ(runCursorHookMainと同じ理由)。どこにも無ければ先頭の置き場で誤りを返す。 */
18
- export declare function runCursorReceive(hookRoot: string | readonly string[], argv: string[], emit?: (value: unknown) => void, usage?: string): Promise<number>;
17
+ /** 受信processの出力先。結果を書く口と、読み手(このprocessを背景で起こした親)が居るかを確かめる口。 */
18
+ export interface ReceiveOutput extends CursorReceiveReader {
19
+ emit(value: unknown): Promise<void>;
20
+ close(): void;
21
+ }
22
+ /**
23
+ * このprocessのstdoutを出力先にする。
24
+ * 親が終わると、親が持っていたstdoutの読み口が閉じる。POSIXのNodeは子のstdoutをsocketでつなぐので、閉じた時点で分かる。
25
+ * それ以外(Windowsのpipeなど)は、書いてみて失敗するかで確かめる。
26
+ */
27
+ export declare function stdoutOutput(): ReceiveOutput;
28
+ /** 受信入口の本体。結果を1行のJSONでstdoutへ出し、exit codeを返す(0=受取、3=期限切れ、5=読み手なし、1=誤り)。
29
+ * hookRootを複数渡すと、配送記録のある置き場で待つ(runCursorHookMainと同じ理由)。どこにも無ければ先頭の置き場で誤りを返す。
30
+ * outputに関数を渡すと、読み手を確かめずにその関数へ結果を渡す。 */
31
+ export declare function runCursorReceive(hookRoot: string | readonly string[], argv: string[], output?: ((value: unknown) => void) | ReceiveOutput, usage?: string): Promise<number>;
@@ -1,6 +1,7 @@
1
1
  // Cursor親がidleのとき、背景で起動して回答本文の到着を待つ受け口。
2
2
  // 起動するファイルは製品が同梱する入口で、そこからrunCursorReceiveを呼ぶ。
3
3
  import * as fs from "node:fs";
4
+ import * as net from "node:net";
4
5
  import * as path from "node:path";
5
6
  import { receiveCursorAnswer } from "./cursor-receiver.js";
6
7
  import { windowsStartProcessArgumentList } from "./windows.js";
@@ -23,26 +24,88 @@ export function waitProcessCommandLine(wait, platform = process.platform) {
23
24
  return `& ${values.map(value => `'${value.replace(/'/g, "''")}'`).join(" ")}`;
24
25
  return values.map(value => `'${value.replace(/'/g, "'\\''")}'`).join(" ");
25
26
  }
26
- /** 受信入口の本体。結果を1行のJSONでstdoutへ出し、exit codeを返す(0=受取、3=期限切れ、1=誤り)。
27
- * hookRootを複数渡すと、配送記録のある置き場で待つ(runCursorHookMainと同じ理由)。どこにも無ければ先頭の置き場で誤りを返す。 */
28
- export async function runCursorReceive(hookRoot, argv, emit = value => { process.stdout.write(JSON.stringify(value) + "\n"); }, usage = "usage: cursor-parent-receive --delivery <uuid>") {
29
- if (argv.length !== 2 || argv[0] !== "--delivery" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(argv[1])) {
30
- emit({ ok: false, code: "CURSOR_PARENT_RECEIVE_USAGE", message: usage });
31
- return 1;
27
+ /**
28
+ * このprocessのstdoutを出力先にする。
29
+ * 親が終わると、親が持っていたstdoutの読み口が閉じる。POSIXのNodeは子のstdoutをsocketでつなぐので、閉じた時点で分かる。
30
+ * それ以外(Windowsのpipeなど)は、書いてみて失敗するかで確かめる。
31
+ */
32
+ export function stdoutOutput() {
33
+ let socket = null;
34
+ try {
35
+ // process.stdoutは読み口を開かないので、相手が閉じても気づけない。同じfdを読み書きのsocketとして開く。
36
+ if (process.platform !== "win32" && fs.fstatSync(1).isSocket())
37
+ socket = new net.Socket({ fd: 1, readable: true, writable: true, allowHalfOpen: true });
32
38
  }
33
- const roots = typeof hookRoot === "string" ? [hookRoot] : [...hookRoot];
34
- const root = roots.find(each => fs.existsSync(path.join(each, "deliveries", argv[1]))) ?? roots[0];
35
- if (root === undefined)
36
- throw new Error("受信の置き場がありません");
37
- const result = await receiveCursorAnswer(root, argv[1]);
38
- if (result.outcome === "timeout") {
39
- emit({ delivery_id: argv[1], outcome: "timeout" });
40
- return 3;
39
+ catch {
40
+ socket = null;
41
41
  }
42
- if (result.outcome === "delivered_by_hook") {
43
- emit({ delivery_id: argv[1], outcome: "delivered_by_hook" });
42
+ const stream = socket ?? process.stdout;
43
+ let failed = false;
44
+ stream.on("error", () => { failed = true; });
45
+ const write = (text) => new Promise(resolve => {
46
+ if (failed) {
47
+ resolve(false);
48
+ return;
49
+ }
50
+ try {
51
+ stream.write(text, error => resolve(!error && !failed));
52
+ }
53
+ catch {
54
+ resolve(false);
55
+ }
56
+ });
57
+ const gone = new Promise(resolve => {
58
+ if (!socket)
59
+ return;
60
+ socket.on("error", () => resolve());
61
+ socket.on("close", () => resolve());
62
+ // 相手が書く側だけを閉じた時もendが来る。書けるなら読み手は居る。
63
+ socket.on("end", () => { void write("\n").then(alive => { if (!alive)
64
+ resolve(); }); });
65
+ socket.resume();
66
+ socket.unref();
67
+ });
68
+ return {
69
+ gone,
70
+ probe: () => write("\n"),
71
+ emit: async (value) => { await write(JSON.stringify(value) + "\n"); },
72
+ close: () => { socket?.destroy(); },
73
+ };
74
+ }
75
+ /** 受信入口の本体。結果を1行のJSONでstdoutへ出し、exit codeを返す(0=受取、3=期限切れ、5=読み手なし、1=誤り)。
76
+ * hookRootを複数渡すと、配送記録のある置き場で待つ(runCursorHookMainと同じ理由)。どこにも無ければ先頭の置き場で誤りを返す。
77
+ * outputに関数を渡すと、読み手を確かめずにその関数へ結果を渡す。 */
78
+ export async function runCursorReceive(hookRoot, argv, output = stdoutOutput(), usage = "usage: cursor-parent-receive --delivery <uuid>") {
79
+ const reader = typeof output === "function" ? undefined : output;
80
+ const emit = async (value) => { if (typeof output === "function")
81
+ output(value);
82
+ else
83
+ await output.emit(value); };
84
+ try {
85
+ if (argv.length !== 2 || argv[0] !== "--delivery" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(argv[1])) {
86
+ await emit({ ok: false, code: "CURSOR_PARENT_RECEIVE_USAGE", message: usage });
87
+ return 1;
88
+ }
89
+ const roots = typeof hookRoot === "string" ? [hookRoot] : [...hookRoot];
90
+ const root = roots.find(each => fs.existsSync(path.join(each, "deliveries", argv[1]))) ?? roots[0];
91
+ if (root === undefined)
92
+ throw new Error("受信の置き場がありません");
93
+ const result = await receiveCursorAnswer(root, argv[1], undefined, reader);
94
+ // 読み手が居ない。回答は引き取らず、置き場に残したまま終わる。
95
+ if (result.outcome === "reader_gone")
96
+ return 5;
97
+ if (result.outcome === "timeout") {
98
+ await emit({ delivery_id: argv[1], outcome: "timeout" });
99
+ return 3;
100
+ }
101
+ if (result.outcome === "delivered_by_hook") {
102
+ await emit({ delivery_id: argv[1], outcome: "delivered_by_hook" });
103
+ return 0;
104
+ }
105
+ await emit({ delivery_id: argv[1], outcome: "delivered", text: result.text });
44
106
  return 0;
45
107
  }
46
- emit({ delivery_id: argv[1], outcome: "delivered", text: result.text });
47
- return 0;
108
+ finally {
109
+ reader?.close();
110
+ }
48
111
  }
@@ -25,5 +25,17 @@ export type CursorReceiveResult = {
25
25
  outcome: "delivered_by_hook";
26
26
  } | {
27
27
  outcome: "timeout";
28
+ } | {
29
+ outcome: "reader_gone";
28
30
  };
29
- export declare function receiveCursorAnswer(hookRoot: string, deliveryId: string, timeoutMs?: number): Promise<CursorReceiveResult>;
31
+ /**
32
+ * 受信processの読み手(このprocessを背景で起こした親)が居るかを確かめる口。
33
+ * 親が終わった後も受信processは残る。確かめずに回答を引き取ると、誰も読まないのに配送済みになる。
34
+ */
35
+ export interface CursorReceiveReader {
36
+ /** 読み手が居なくなった時に解決する。見張れない出力先では解決しない。 */
37
+ readonly gone: Promise<void>;
38
+ /** 今、読み手へ書けるか。 */
39
+ probe(): Promise<boolean>;
40
+ }
41
+ export declare function receiveCursorAnswer(hookRoot: string, deliveryId: string, timeoutMs?: number, reader?: CursorReceiveReader): Promise<CursorReceiveResult>;
@@ -222,23 +222,31 @@ export async function handleCursorHook(profile, raw, hookRoot) {
222
222
  }
223
223
  return {};
224
224
  }
225
- export async function receiveCursorAnswer(hookRoot, deliveryId, timeoutMs = 86_400_000) {
225
+ export async function receiveCursorAnswer(hookRoot, deliveryId, timeoutMs = 86_400_000, reader) {
226
226
  const id = deliveryIdSchema.parse(deliveryId);
227
227
  const dir = path.join(hookRoot, "deliveries", id);
228
228
  if (!fs.existsSync(dir))
229
229
  throw new CursorDeliveryError("CURSOR_PARENT_DELIVERY_UNKNOWN", "Cursor配送の記録がありません");
230
230
  const answerFile = path.join(dir, "answer.json");
231
+ const waiting = new AbortController();
232
+ let gone = false;
233
+ void reader?.gone.then(() => { gone = true; waiting.abort(); });
231
234
  try {
232
- await waitForFileState(dir, () => fs.existsSync(answerFile) ? true : undefined, timeoutMs);
235
+ await waitForFileState(dir, () => fs.existsSync(answerFile) ? true : undefined, timeoutMs, waiting.signal);
233
236
  }
234
237
  catch (error) {
235
238
  if (error instanceof Error && error.message === "WAIT_FOR_FILE_TIMEOUT")
236
239
  return { outcome: "timeout" };
240
+ if (error instanceof Error && error.message === "WAIT_FOR_FILE_ABORTED")
241
+ return { outcome: "reader_gone" };
237
242
  throw error;
238
243
  }
239
244
  const answer = z.object({ delivery_id: z.string(), text: z.string() }).parse(JSON.parse(fs.readFileSync(answerFile, "utf8")));
240
245
  if (answer.delivery_id !== id)
241
246
  throw new CursorDeliveryError("CURSOR_PARENT_DELIVERY_MISMATCH", "保存された回答の配送IDが一致しません");
247
+ // 引き取ると送り主は配送済みにする。読み手が居ない時は引き取らず、回答を置き場に残す。
248
+ if (reader && (gone || !(await reader.probe())))
249
+ return { outcome: "reader_gone" };
242
250
  if (!claim(dir, "receiver"))
243
251
  return { outcome: "delivered_by_hook" };
244
252
  return { outcome: "delivered", text: answer.text };
package/dist/files.d.ts CHANGED
@@ -2,5 +2,6 @@
2
2
  export declare function withoutBom(text: string): string;
3
3
  export declare function writeJson0600(p: string, v: unknown): void;
4
4
  export declare function writeHookJson(file: string, value: unknown): void;
5
- /** directory内の状態変化を待つ。inspectが値を返した時点でresolveする。timeoutMsを省くと期限なし。 */
6
- export declare function waitForFileState<T>(dir: string, inspect: () => T | undefined, timeoutMs?: number): Promise<T>;
5
+ /** directory内の状態変化を待つ。inspectが値を返した時点でresolveする。timeoutMsを省くと期限なし。
6
+ * signalがabortされると WAIT_FOR_FILE_ABORTED でrejectする。 */
7
+ export declare function waitForFileState<T>(dir: string, inspect: () => T | undefined, timeoutMs?: number, signal?: AbortSignal): Promise<T>;
package/dist/files.js CHANGED
@@ -41,8 +41,9 @@ export function writeHookJson(file, value) {
41
41
  fs.unlinkSync(temporary);
42
42
  }
43
43
  }
44
- /** directory内の状態変化を待つ。inspectが値を返した時点でresolveする。timeoutMsを省くと期限なし。 */
45
- export function waitForFileState(dir, inspect, timeoutMs) {
44
+ /** directory内の状態変化を待つ。inspectが値を返した時点でresolveする。timeoutMsを省くと期限なし。
45
+ * signalがabortされると WAIT_FOR_FILE_ABORTED でrejectする。 */
46
+ export function waitForFileState(dir, inspect, timeoutMs, signal) {
46
47
  return new Promise((resolve, reject) => {
47
48
  let finished = false;
48
49
  let timer;
@@ -57,11 +58,13 @@ export function waitForFileState(dir, inspect, timeoutMs) {
57
58
  clearInterval(timer);
58
59
  if (timeout)
59
60
  clearTimeout(timeout);
61
+ signal?.removeEventListener("abort", abort);
60
62
  if (error)
61
63
  reject(error);
62
64
  else
63
65
  resolve(value);
64
66
  };
67
+ const abort = () => finish(new Error("WAIT_FOR_FILE_ABORTED"));
65
68
  const check = () => {
66
69
  if (finished)
67
70
  return;
@@ -78,6 +81,10 @@ export function waitForFileState(dir, inspect, timeoutMs) {
78
81
  timer = setInterval(check, 5000);
79
82
  if (timeoutMs !== undefined)
80
83
  timeout = setTimeout(() => finish(new Error("WAIT_FOR_FILE_TIMEOUT")), timeoutMs);
84
+ if (signal?.aborted)
85
+ abort();
86
+ else
87
+ signal?.addEventListener("abort", abort, { once: true });
81
88
  check();
82
89
  });
83
90
  }
package/dist/hook-main.js CHANGED
@@ -99,12 +99,11 @@ export async function runCursorHookMain(profile, root = cursorHookRoot(profile))
99
99
  }
100
100
  /** Cursor親の背景受信。 */
101
101
  export async function runCursorReceiveMain(profile, argv = process.argv.slice(2), root = cursorHookRoot(profile)) {
102
- const emit = (value) => { process.stdout.write(JSON.stringify(value) + "\n"); };
103
102
  try {
104
- process.exitCode = await runCursorReceive(root, argv, emit);
103
+ process.exitCode = await runCursorReceive(root, argv);
105
104
  }
106
105
  catch (error) {
107
- emit({ ok: false, code: "CURSOR_PARENT_RECEIVE_FAILED", message: error instanceof Error ? error.message : "cursor-parent-receive: operation failed" });
106
+ process.stdout.write(JSON.stringify({ ok: false, code: "CURSOR_PARENT_RECEIVE_FAILED", message: error instanceof Error ? error.message : "cursor-parent-receive: operation failed" }) + "\n");
108
107
  process.exitCode = 1;
109
108
  }
110
109
  }
package/dist/index.d.ts CHANGED
@@ -10,8 +10,8 @@ export { codexParentFromRequest, withCodexReceiver, verifyCodexParent, submitCod
10
10
  export { runCodexResultHook } from "./codex-hooks.js";
11
11
  export { codexHookCommand, processCodexHome, mergeCodexParentHooks, planCodexParentHooks, writeCodexHookPlan, applyCodexHookPlan, verifyCodexHookRegistration, configureCodexSteer, type CodexHookMove, type CodexHookPlan, type CodexSteerAction, type CodexSteerResult, type CodexSteerRuntime, } from "./codex-setup.js";
12
12
  export { claudeParentSchema, prepareClaudeHookRequest, claudeParentFromRequest, verifyClaudeParent, bindClaudeParentDelivery, closeClaudeParentSession, submitClaudeParentAnswer, runClaudeResultHook, type ClaudeParent, } from "./claude-receiver.js";
13
- export { cursorParentSchema, isCursorMcpClient, cursorHooksFile, cursorParentHooksRegistered, verifyCursorParent, cursorParentFromRequest, prepareCursorDelivery, submitCursorParentAnswer, handleCursorHook, receiveCursorAnswer, type CursorParent, type CursorReceiveResult, } from "./cursor-receiver.js";
14
- export { cursorReceiveProcess, runCursorReceive, waitProcessCommandLine, type WaitProcess } from "./cursor-receive.js";
13
+ export { cursorParentSchema, isCursorMcpClient, cursorHooksFile, cursorParentHooksRegistered, verifyCursorParent, cursorParentFromRequest, prepareCursorDelivery, submitCursorParentAnswer, handleCursorHook, receiveCursorAnswer, type CursorParent, type CursorReceiveResult, type CursorReceiveReader, } from "./cursor-receiver.js";
14
+ export { cursorReceiveProcess, runCursorReceive, stdoutOutput, waitProcessCommandLine, type WaitProcess, type ReceiveOutput } from "./cursor-receive.js";
15
15
  export { claudeParentHookEntries, mergeClaudeParentHooks, removeClaudeParentHooks, cursorParentHookCommand, mergeCursorParentHooks, removeCursorParentHooks, commandNamesFile, type HookRuntime, } from "./hook-setup.js";
16
16
  export { runCodexHookMain, runClaudeHookMain, runCursorHookMain, runCursorReceiveMain, isDirectExecution } from "./hook-main.js";
17
17
  export { runChannelReceiveMain } from "./hook-main.js";
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ export { runCodexResultHook } from "./codex-hooks.js";
13
13
  export { codexHookCommand, processCodexHome, mergeCodexParentHooks, planCodexParentHooks, writeCodexHookPlan, applyCodexHookPlan, verifyCodexHookRegistration, configureCodexSteer, } from "./codex-setup.js";
14
14
  export { claudeParentSchema, prepareClaudeHookRequest, claudeParentFromRequest, verifyClaudeParent, bindClaudeParentDelivery, closeClaudeParentSession, submitClaudeParentAnswer, runClaudeResultHook, } from "./claude-receiver.js";
15
15
  export { cursorParentSchema, isCursorMcpClient, cursorHooksFile, cursorParentHooksRegistered, verifyCursorParent, cursorParentFromRequest, prepareCursorDelivery, submitCursorParentAnswer, handleCursorHook, receiveCursorAnswer, } from "./cursor-receiver.js";
16
- export { cursorReceiveProcess, runCursorReceive, waitProcessCommandLine } from "./cursor-receive.js";
16
+ export { cursorReceiveProcess, runCursorReceive, stdoutOutput, waitProcessCommandLine } from "./cursor-receive.js";
17
17
  export { claudeParentHookEntries, mergeClaudeParentHooks, removeClaudeParentHooks, cursorParentHookCommand, mergeCursorParentHooks, removeCursorParentHooks, commandNamesFile, } from "./hook-setup.js";
18
18
  export { runCodexHookMain, runClaudeHookMain, runCursorHookMain, runCursorReceiveMain, isDirectExecution } from "./hook-main.js";
19
19
  export { runChannelReceiveMain } from "./hook-main.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-steer-delivery",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
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",