aiterm-steer-delivery 0.1.11 → 0.1.13

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,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.13
4
+
5
+ - `sendClaudeInbox`を公開する。ClaudeのSessionStartが渡すinbox socketとtokenへuserメッセージを1通送る。MCPを呼んでいない新規会話にも使え、既存のClaudeParent・channel・asyncRewake配送は変えない。Windowsはauthを必須とし、POSIXでもtokenを渡せる。
6
+ - raw投稿の書き込みを受付済みとはしない。利用製品がUserPromptSubmit等を照合する`confirm_acceptance`を渡し、確認できた時だけ`accepted`にする。書き込み前の失敗は`not_sent`、書き込み後の確認不能は`unknown`と`outcome_unknown:true`。token・本文・宛先を結果へ含めず、自動再送しない。
7
+
8
+ ## 0.1.12
9
+
10
+ - Cursor親の背景受信(`runCursorReceive`)が、読み手の居ない時に回答を引き取らない。Cursorは受信processを切り離して起こすので、親が終わった後も受信processは残る。残ったprocessが回答を引き取り、送り主は誰も読んでいない回答を配送済みにしていた(実物のCursor CLI 2026.10.01で、席を再起動して20回中20回)。受信processは最長24時間残っていた。
11
+ - 出力先を `stdoutOutput()` で扱う。stdoutがsocket(POSIXのNodeが子へ渡す形)なら読み口も開き、親が終わった時点で受信を終える。引き取る前には1行書いて、書けるかを確かめる(Windowsのpipeなど、終了を知る方法が無い出力先のため)。
12
+ - 読み手が居ない時は引き取らずにexit code 5で終わる。回答は置き場に残り、`submitCursorParentAnswer` は期限まで待って `CURSOR_PARENT_DELIVERY_UNCLAIMED` になる。
13
+ - `receiveCursorAnswer` の4番目の引数に読み手(`CursorReceiveReader`)を渡した時だけ、結果に `reader_gone` が加わる。`runCursorReceive` の3番目の引数へ関数を渡す従来の呼び方は、読み手を確かめない。
14
+ - `waitForFileState` が `AbortSignal` を受け取る。
15
+
3
16
  ## 0.1.11
4
17
 
5
18
  - 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 コマンドで次を呼びます。
@@ -120,7 +122,7 @@ await runClaudeHookMain(PROFILE);
120
122
 
121
123
  ### 4. 届ける
122
124
 
123
- 届け方は2つあります。
125
+ MCPを呼んだ親への届け方は2つあります。
124
126
 
125
127
  **1回の依頼に1つの答え**(Aiterm の使い方): MCP 要求から親を見分け、配送IDを結び付け、確定した本文を一度だけ送ります。
126
128
 
@@ -146,6 +148,25 @@ Claude Code は `Stop` のたびに待機を張り直します。Cursor はツ
146
148
 
147
149
  marker と受信コマンドは、`structuredContent` だけでなくツール結果の**本文**にも書いてください。Cursor CLI のモデルは structured content を読みません。`steer.waitProcessCommandLine(steer.channelReceiveProcess(script, channel.channel_id))` で、受信コマンドをシェルの1行にできます(POSIX sh、Windows では PowerShell)。
148
150
 
151
+ ### 新しいClaude会話へ送る
152
+
153
+ `sendClaudeInbox(target, text, options)` はClaude Codeの[会話のinbox](https://code.claude.com/docs/en/cross-session-messaging#the-sessions-inbox-socket)へuserメッセージを1通送ります。宛先の`SessionStart` hookで`CLAUDE_CODE_MESSAGING_SOCKET`と`CLAUDE_CODE_MESSAGING_TOKEN`を取得します。その会話がMCPを呼ぶ前にも使え、`ProductProfile`や`ClaudeParent`は要りません。
154
+
155
+ ```js
156
+ import { sendClaudeInbox } from "aiterm-steer-delivery";
157
+
158
+ const text = "作業を続けて";
159
+ const result = await sendClaudeInbox({ socket_path, token }, text, {
160
+ timeout_ms: 30_000,
161
+ // UserPromptSubmitの受領記録を観測する処理は、利用製品が用意します。
162
+ confirm_acceptance: signal => productReceipts.waitForPrompt({ session_id, text, signal }),
163
+ });
164
+ ```
165
+
166
+ 宛先はhookから得て、PIDから推測しません。Windowsではtokenが必須で、POSIXでも渡したtokenは先頭のauth行で送ります。tokenは非公開で扱います。`confirm_acceptance`は接続前に開始します。受領票の事前登録が必要なら呼出前に済ませ、対象sessionと今回の文を照合します。古い記録や時刻の変化だけでは確認しません。終了時は`AbortSignal`で観測を取り消します。`false`は未確認を意味します。
167
+
168
+ raw投稿には同じ接続上の受付票がありません。`accepted`はUserPromptSubmitなどの受領観測が一致した時だけ返し、作業の完了までは示しません。`not_sent`はメッセージの書き込みを試みていない場合です。書き込みを試みた後の失敗や確認不能は`unknown`と`outcome_unknown:true`を返します。観測処理を渡さなければ、書き込みが成功しても`unknown`です。自動再送はしません。Claudeの受信制御はそのまま適用されます。結果は`status`・`reason`・`outcome_unknown`だけで、token・本文・宛先を含めません。
169
+
149
170
  ## エラーと配送の状態
150
171
 
151
172
  配送のエラーは `SteerDeliveryError`(`CodexDeliveryError`、`ClaudeDeliveryError`、`CursorDeliveryError`、`ChannelError`)で、次を持ちます。
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:
@@ -120,7 +122,7 @@ They keep other products' and the user's hooks and their order, and back up the
120
122
 
121
123
  ### 4. Deliver
122
124
 
123
- There are two ways to deliver.
125
+ The MCP parent-delivery APIs offer two ways to deliver.
124
126
 
125
127
  **One answer per request** (what Aiterm does): identify the parent from the MCP request, bind a delivery id, and submit the final text once.
126
128
 
@@ -146,6 +148,25 @@ Claude Code re-arms its waiter at every `Stop`. Cursor binds the channel with `s
146
148
 
147
149
  Put both the marker and the receiver command in the **text** of your tool result, not only in `structuredContent`: the Cursor CLI model does not read structured content. `steer.waitProcessCommandLine(steer.channelReceiveProcess(script, channel.channel_id))` gives the command as one shell line (POSIX sh, or PowerShell on Windows).
148
150
 
151
+ ### Send to a new Claude conversation
152
+
153
+ `sendClaudeInbox(target, text, options)` sends one user message to Claude Code's [session inbox](https://code.claude.com/docs/en/cross-session-messaging#the-sessions-inbox-socket). Capture `CLAUDE_CODE_MESSAGING_SOCKET` and `CLAUDE_CODE_MESSAGING_TOKEN` in the target's `SessionStart` hook. This API works before that conversation has called an MCP tool, and needs no `ProductProfile` or `ClaudeParent`.
154
+
155
+ ```js
156
+ import { sendClaudeInbox } from "aiterm-steer-delivery";
157
+
158
+ const text = "Continue the work.";
159
+ const result = await sendClaudeInbox({ socket_path, token }, text, {
160
+ timeout_ms: 30_000,
161
+ // Your product observes the target's UserPromptSubmit receipt.
162
+ confirm_acceptance: signal => productReceipts.waitForPrompt({ session_id, text, signal }),
163
+ });
164
+ ```
165
+
166
+ Capture the endpoint from the target hook; do not infer it from a PID. Windows requires a token; POSIX sends the authentication line when a token is supplied. Keep the token private. `confirm_acceptance` starts before connecting; arm any receipt registration before calling. Match the target session and this message, rather than an older receipt or merely a new timestamp. The observer receives an `AbortSignal` when the call finishes. Its `false` result means unconfirmed.
167
+
168
+ The raw inbox post has no same-connection acknowledgement proving conversation acceptance. `accepted` requires your observer to confirm receipt, for example at `UserPromptSubmit`; it does not prove task completion. `not_sent` means no message write was attempted. After a write is attempted, a failure or missing confirmation returns `unknown` with `outcome_unknown:true`. With no observer, even a successful write returns `unknown`. The library never retries. Claude's inbound controls still apply. The result contains only `status`, `reason`, and `outcome_unknown` and excludes the token, message, and endpoint.
169
+
149
170
  ## Errors and delivery states
150
171
 
151
172
  Delivery errors are `SteerDeliveryError` (`CodexDeliveryError`, `ClaudeDeliveryError`, `CursorDeliveryError`, `ChannelError`) with:
@@ -0,0 +1,31 @@
1
+ export interface ClaudeInboxTarget {
2
+ /** CLAUDE_CODE_MESSAGING_SOCKETの値。PIDから推測せず、宛先のSessionStartで取得する。 */
3
+ socket_path: string;
4
+ /** 宛先のCLAUDE_CODE_MESSAGING_TOKEN。Windowsでは必須。receiptやエラーには含めない。 */
5
+ token?: string;
6
+ }
7
+ export interface ClaudeInboxSendOptions {
8
+ /** 接続・書き込み・受領確認を合わせた期限。既定30秒。 */
9
+ timeout_ms?: number;
10
+ /**
11
+ * 接続前に開始する受領観測。対象sessionと今回の文のUserPromptSubmit等を照合してtrueを返す。
12
+ * falseは「まだ観測できていない」であり、未送信の証明ではない。終了時はsignalで取り消される。
13
+ * ライブラリは観測開始が解決するのを待たずに接続する。受信票の事前登録が必要なら、呼出元で登録を済ませておく。
14
+ */
15
+ confirm_acceptance?: (signal: AbortSignal) => Promise<boolean>;
16
+ }
17
+ export type ClaudeInboxSendResult = {
18
+ status: "accepted";
19
+ outcome_unknown: false;
20
+ reason: "receiver_confirmed";
21
+ } | {
22
+ status: "not_sent";
23
+ outcome_unknown: false;
24
+ reason: "invalid_request" | "token_required" | "connect_failed" | "confirmation_failed" | "timeout";
25
+ } | {
26
+ status: "unknown";
27
+ outcome_unknown: true;
28
+ reason: "unconfirmed" | "confirmation_failed" | "write_failed" | "timeout";
29
+ };
30
+ /** 明示した会話のinboxへ1通だけ送る。自動再送、他の宛先へのfallback、設定変更は行わない。 */
31
+ export declare function sendClaudeInbox(target: ClaudeInboxTarget, text: string, options?: ClaudeInboxSendOptions): Promise<ClaudeInboxSendResult>;
@@ -0,0 +1,128 @@
1
+ // ClaudeがSessionStartへ渡すinboxへ1通送る。MCPの要求記録やasyncRewake hookは不要。
2
+ // raw user行には受付票が無い。書き込みを受付済みとはせず、呼出元の受領観測でのみacceptedにする。
3
+ import * as net from "node:net";
4
+ import * as path from "node:path";
5
+ /** 明示した会話のinboxへ1通だけ送る。自動再送、他の宛先へのfallback、設定変更は行わない。 */
6
+ export async function sendClaudeInbox(target, text, options = {}) {
7
+ if (!options || typeof options !== "object")
8
+ return { status: "not_sent", outcome_unknown: false, reason: "invalid_request" };
9
+ const timeout = options.timeout_ms ?? 30_000;
10
+ if (!target || typeof target.socket_path !== "string" || !target.socket_path || target.socket_path.includes("\0")
11
+ || typeof text !== "string" || !text || !Number.isSafeInteger(timeout) || timeout < 1 || timeout > 300_000
12
+ || (target.token !== undefined && (typeof target.token !== "string" || !target.token))
13
+ || (options.confirm_acceptance !== undefined && typeof options.confirm_acceptance !== "function")
14
+ || (process.platform !== "win32" && !path.isAbsolute(target.socket_path))) {
15
+ return { status: "not_sent", outcome_unknown: false, reason: "invalid_request" };
16
+ }
17
+ if (process.platform === "win32" && !target.token) {
18
+ return { status: "not_sent", outcome_unknown: false, reason: "token_required" };
19
+ }
20
+ const message = JSON.stringify({ type: "user", message: { role: "user", content: text } }) + "\n";
21
+ // Claudeの同一端末配送の上限より小さいフレームだけ送る。送信前に拒否する。
22
+ if (Buffer.byteLength(message) > 1_000_000) {
23
+ return { status: "not_sent", outcome_unknown: false, reason: "invalid_request" };
24
+ }
25
+ const auth = target.token === undefined ? "" : JSON.stringify({ type: "auth", token: target.token }) + "\n";
26
+ if (Buffer.byteLength(auth + message) > 1_000_000)
27
+ return { status: "not_sent", outcome_unknown: false, reason: "invalid_request" };
28
+ const controller = new AbortController();
29
+ return await new Promise(resolve => {
30
+ let settled = false;
31
+ let attempted = false;
32
+ let written = false;
33
+ let confirmed;
34
+ let confirmationFailed = false;
35
+ let socket;
36
+ const finish = (result) => {
37
+ if (settled)
38
+ return;
39
+ settled = true;
40
+ clearTimeout(timer);
41
+ controller.abort();
42
+ socket?.destroy();
43
+ resolve(result);
44
+ };
45
+ const unknown = (reason) => finish({ status: "unknown", outcome_unknown: true, reason });
46
+ const afterWrite = () => {
47
+ if (!written)
48
+ return;
49
+ if (confirmed === true)
50
+ finish({ status: "accepted", outcome_unknown: false, reason: "receiver_confirmed" });
51
+ else if (confirmationFailed)
52
+ unknown("confirmation_failed");
53
+ else if (!options.confirm_acceptance || confirmed === false)
54
+ unknown("unconfirmed");
55
+ };
56
+ const timer = setTimeout(() => {
57
+ if (attempted)
58
+ unknown("timeout");
59
+ else
60
+ finish({ status: "not_sent", outcome_unknown: false, reason: "timeout" });
61
+ }, timeout);
62
+ if (options.confirm_acceptance) {
63
+ // 観測側がthrow/rejectしても、書き込み後を未送信へ戻さない。
64
+ let observing;
65
+ try {
66
+ observing = options.confirm_acceptance(controller.signal);
67
+ }
68
+ catch {
69
+ finish({ status: "not_sent", outcome_unknown: false, reason: "confirmation_failed" });
70
+ return;
71
+ }
72
+ Promise.resolve(observing).then(value => {
73
+ if (value === true && !attempted) {
74
+ // 今回の書き込み前に届いた「受付済み」は、今回の送信を証明できない。
75
+ finish({ status: "not_sent", outcome_unknown: false, reason: "confirmation_failed" });
76
+ return;
77
+ }
78
+ confirmed = value === true;
79
+ afterWrite();
80
+ }, () => {
81
+ if (!attempted) {
82
+ finish({ status: "not_sent", outcome_unknown: false, reason: "confirmation_failed" });
83
+ return;
84
+ }
85
+ confirmationFailed = true;
86
+ afterWrite();
87
+ });
88
+ }
89
+ try {
90
+ socket = net.createConnection({ path: target.socket_path });
91
+ socket.once("error", () => {
92
+ if (attempted)
93
+ unknown("write_failed");
94
+ else
95
+ finish({ status: "not_sent", outcome_unknown: false, reason: "connect_failed" });
96
+ });
97
+ socket.once("connect", () => {
98
+ if (settled)
99
+ return;
100
+ attempted = true;
101
+ socket.end(auth + message, (error) => {
102
+ if (error)
103
+ unknown("write_failed");
104
+ else {
105
+ written = true;
106
+ afterWrite();
107
+ }
108
+ });
109
+ });
110
+ socket.on("data", () => { }); // raw投稿には受付票の仕様が無い。任意の返信を成功と解釈しない。
111
+ socket.once("close", () => {
112
+ if (settled)
113
+ return;
114
+ if (!attempted)
115
+ finish({ status: "not_sent", outcome_unknown: false, reason: "connect_failed" });
116
+ else if (!written)
117
+ unknown("write_failed");
118
+ // 書き込み後の切断でも、別経路の受領確認を期限まで待つ。
119
+ });
120
+ }
121
+ catch {
122
+ if (attempted)
123
+ unknown("write_failed");
124
+ else
125
+ finish({ status: "not_sent", outcome_unknown: false, reason: "connect_failed" });
126
+ }
127
+ });
128
+ }
@@ -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,9 @@ 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 { sendClaudeInbox, type ClaudeInboxTarget, type ClaudeInboxSendOptions, type ClaudeInboxSendResult, } from "./claude-inbox.js";
14
+ export { cursorParentSchema, isCursorMcpClient, cursorHooksFile, cursorParentHooksRegistered, verifyCursorParent, cursorParentFromRequest, prepareCursorDelivery, submitCursorParentAnswer, handleCursorHook, receiveCursorAnswer, type CursorParent, type CursorReceiveResult, type CursorReceiveReader, } from "./cursor-receiver.js";
15
+ export { cursorReceiveProcess, runCursorReceive, stdoutOutput, waitProcessCommandLine, type WaitProcess, type ReceiveOutput } from "./cursor-receive.js";
15
16
  export { claudeParentHookEntries, mergeClaudeParentHooks, removeClaudeParentHooks, cursorParentHookCommand, mergeCursorParentHooks, removeCursorParentHooks, commandNamesFile, type HookRuntime, } from "./hook-setup.js";
16
17
  export { runCodexHookMain, runClaudeHookMain, runCursorHookMain, runCursorReceiveMain, isDirectExecution } from "./hook-main.js";
17
18
  export { runChannelReceiveMain } from "./hook-main.js";
package/dist/index.js CHANGED
@@ -12,8 +12,9 @@ export { codexParentFromRequest, withCodexReceiver, verifyCodexParent, submitCod
12
12
  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
+ export { sendClaudeInbox, } from "./claude-inbox.js";
15
16
  export { cursorParentSchema, isCursorMcpClient, cursorHooksFile, cursorParentHooksRegistered, verifyCursorParent, cursorParentFromRequest, prepareCursorDelivery, submitCursorParentAnswer, handleCursorHook, receiveCursorAnswer, } from "./cursor-receiver.js";
16
- export { cursorReceiveProcess, runCursorReceive, waitProcessCommandLine } from "./cursor-receive.js";
17
+ export { cursorReceiveProcess, runCursorReceive, stdoutOutput, waitProcessCommandLine } from "./cursor-receive.js";
17
18
  export { claudeParentHookEntries, mergeClaudeParentHooks, removeClaudeParentHooks, cursorParentHookCommand, mergeCursorParentHooks, removeCursorParentHooks, commandNamesFile, } from "./hook-setup.js";
18
19
  export { runCodexHookMain, runClaudeHookMain, runCursorHookMain, runCursorReceiveMain, isDirectExecution } from "./hook-main.js";
19
20
  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.13",
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",