aiterm-steer-delivery 0.1.12 → 0.2.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,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0
4
+
5
+ Claude Codeのhookの登録の形が変わります。利用製品は、依存を`^0.2.0`へ上げてsetupを流し直してください。
6
+
7
+ - **Claude Codeのhookを、`args`を使わずshellを通す1行で書く。** Grokは共有の`~/.claude/settings.json`のhookも動かすが、`args`を落として`command`だけを動かす。0.1系の`command=node, args=[入口]`の形では、Grokがnodeだけを起こし、nodeがhookの入力のJSONをscriptとして読んで、Stopと会話の終わりのたびに`[stdin]:1`で失敗していた(ティア席のGrok 1.0.46で報告。Linuxとfoxで再現)。
8
+ - POSIX: `exec '<node>' '<入口>'`。Claude Codeは`/bin/sh -c`で動かし、`exec`を書かないとshがhookの親として残る(Linuxの2.1.289で確認)。
9
+ - Windows: `& '<node>' '<入口>'; exit (Get-Variable LASTEXITCODE -ValueOnly)`と`shell: "powershell"`。GrokはWindowsでhookをPowerShellで動かし、`shell`は読まない。PowerShellは終了codeを0か1へ丸めるので、asyncRewakeの2をそのまま返す。`$LASTEXITCODE`とは書かない(Grokが`$名前`を環境変数として読み、未設定としてhookを動かさずに失敗と記録する)。
10
+ - `claudeParentHookCommand`を公開する。`claudeParentHookEntries`は3つ目の引数でplatformを受け取る。
11
+ - **PreToolUseのhookは、間に挟まったshellではなく、hookを起動したClaude Codeを親として記録する。** 今までは`process.ppid`をそのまま記録していた。shellを通す形では、WindowsのPowerShell(とexecを書かないsh)がhookと一緒に終わるので、受信の時に「依頼元のClaude processは終了しました」になる。`hookOwnerProcess`を公開する。
12
+ - **Grokから起こされたhook(`runClaudeHookMain`)は、何もせず0で終わる。** 形を直した後は、GrokのStopでhookが本当に走る。失敗の2を返すと、GrokはStopを「止めずに続ける」、PreToolUseを「拒否」と読む。見分けは、Grokだけが入力へ入れる`hookEventName`。
13
+ - **再登録と解除は、0.1系の形と新しい形の両方を自製品のhookと数える。** `mergeClaudeParentHooks`は0.1系の登録を新しい形へ置き換え、`removeClaudeParentHooks`は両方を除く。他製品と利用者のhookは、どちらの形でも残す。
14
+ - **`claudeParentHooksRegistered`と`claudeParentHookScripts`を公開する。** 設定を読むだけで、登録の有無と、登録が指す入口のpathを返す。製品が`args`を自分で読んで登録を確かめていると、新しい形を「未登録」と読む。
15
+ - **`submitClaudeParentAnswer`が、届いた配送を`CLAUDE_PARENT_HOOK_CLOSED`と数えない。** 送り主は「出し終えた記録が無い」→「hookのprocessが居ない」の順に見ていた。process表を読む間(Windowsは約1秒)にhookが本文を出し終えて終わると、親には届いているのに、送り主には失敗(結果不明)で返っていた(foxのClaude Code 2.1.289、0.1.13で再現)。「居ない」と読んだ後に、出し終えた記録を見直す。process表は1回の確かめにつき1回だけ読む。
16
+ - 0.1系へ戻す時の注意: 0.1系は新しい形の登録を自製品のhookと数えない。0.2.0で登録した後に0.1系のsetupを流すと、0.1系の形が足されて2組になる。戻す前に0.2.0の`removeClaudeParentHooks`を呼ぶ。
17
+ - Windowsでは、待っているhook1つにつきPowerShellのprocessが1つ残る(Claude Codeが起こす`pwsh -Command`)。直接起動の形ではnodeだけだった。
18
+ - 確かめた実物: Claude Code 2.1.289で、ライブラリが書いた登録のまま、作業中の親へ本文が差し込まれる事(Linux・macOS・Windows)。Grok 1.0.46で、Stopと会話の終わりのhookが失敗の記録を残さない事(Linux)。WindowsのGrokは、同じ書き方の1行が動く事までを見た。
19
+
20
+ ## 0.1.13
21
+
22
+ - `sendClaudeInbox`を公開する。ClaudeのSessionStartが渡すinbox socketとtokenへuserメッセージを1通送る。MCPを呼んでいない新規会話にも使え、既存のClaudeParent・channel・asyncRewake配送は変えない。Windowsはauthを必須とし、POSIXでもtokenを渡せる。
23
+ - raw投稿の書き込みを受付済みとはしない。利用製品がUserPromptSubmit等を照合する`confirm_acceptance`を渡し、確認できた時だけ`accepted`にする。書き込み前の失敗は`not_sent`、書き込み後の確認不能は`unknown`と`outcome_unknown:true`。token・本文・宛先を結果へ含めず、自動再送しない。
24
+
3
25
  ## 0.1.12
4
26
 
5
27
  - Cursor親の背景受信(`runCursorReceive`)が、読み手の居ない時に回答を引き取らない。Cursorは受信processを切り離して起こすので、親が終わった後も受信processは残る。残ったprocessが回答を引き取り、送り主は誰も読んでいない回答を配送済みにしていた(実物のCursor CLI 2026.10.01で、席を再起動して20回中20回)。受信processは最長24時間残っていた。
package/README.ja.md CHANGED
@@ -120,9 +120,18 @@ Cursor の親は、1回の回答の受信 process を切り離して起こすの
120
120
 
121
121
  他の製品や利用者の hook とその順序は保ち、書き換える前にファイルの控えを残します。解除は `removeClaudeParentHooks`、`removeCursorParentHooks`、`configureCodexSteer(PROFILE, "disable", …)` です。hook を入れる前から動いている Codex が残っていると、`configureCodexSteer` は `restart_required` を返します。 PowerShell の path は実体の表記に揃えるため、PATH の大文字小文字だけでは Codex hook を書き換えず、再起動を求めません。
122
122
 
123
+ Claude Code の hook は、`args` を使わず、shell を通す1行で書きます。
124
+
125
+ - POSIX: `exec '<node>' '<hook>'`。`exec` で `sh` を node に置き換え、Claude Code を hook の直接の親に保ちます。
126
+ - Windows: `& '<node>' '<hook>'; exit (Get-Variable LASTEXITCODE -ValueOnly)` と `shell: "powershell"`。こう書かないと、PowerShell が hook の終了 code 2 を 1 に変えます。`asyncRewake` は 2 で親を起こします。
127
+
128
+ Grok も `~/.claude/settings.json` の hook を動かしますが、`args` を落として `command` だけを動かします。0.1 系が書いていた `command` + `args` の形では、Grok は node だけを起こし、node が hook の入力を script として読んで、`Stop` のたびに失敗していました。`runClaudeHookMain` は、Grok から起こされた時は何もせずに 0 で終わります(Grok だけが入力に入れる `hookEventName` で見分けます)。Grok の親は hook ではなく、背景の受信プロセスで受け取るためです。
129
+
130
+ `mergeClaudeParentHooks` は、製品の 0.1 系の登録を新しい形へ置き換えます。`removeClaudeParentHooks` は両方の形を取り除きます。設定ファイルを書き換えずに登録を確かめる時は、`claudeParentHooksRegistered(PROFILE, document)` と `claudeParentHookScripts(PROFILE, document)`(登録が指している hook ファイルの path)を使い、`args` を自分で読まないでください。0.1 系へ戻す時は、先に 0.2 系の `removeClaudeParentHooks` を呼んでください。0.1 系は新しい形の登録を自分の物と数えず、もう1組を足します。
131
+
123
132
  ### 4. 届ける
124
133
 
125
- 届け方は2つあります。
134
+ MCPを呼んだ親への届け方は2つあります。
126
135
 
127
136
  **1回の依頼に1つの答え**(Aiterm の使い方): MCP 要求から親を見分け、配送IDを結び付け、確定した本文を一度だけ送ります。
128
137
 
@@ -148,6 +157,25 @@ Claude Code は `Stop` のたびに待機を張り直します。Cursor はツ
148
157
 
149
158
  marker と受信コマンドは、`structuredContent` だけでなくツール結果の**本文**にも書いてください。Cursor CLI のモデルは structured content を読みません。`steer.waitProcessCommandLine(steer.channelReceiveProcess(script, channel.channel_id))` で、受信コマンドをシェルの1行にできます(POSIX sh、Windows では PowerShell)。
150
159
 
160
+ ### 新しいClaude会話へ送る
161
+
162
+ `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`は要りません。
163
+
164
+ ```js
165
+ import { sendClaudeInbox } from "aiterm-steer-delivery";
166
+
167
+ const text = "作業を続けて";
168
+ const result = await sendClaudeInbox({ socket_path, token }, text, {
169
+ timeout_ms: 30_000,
170
+ // UserPromptSubmitの受領記録を観測する処理は、利用製品が用意します。
171
+ confirm_acceptance: signal => productReceipts.waitForPrompt({ session_id, text, signal }),
172
+ });
173
+ ```
174
+
175
+ 宛先はhookから得て、PIDから推測しません。Windowsではtokenが必須で、POSIXでも渡したtokenは先頭のauth行で送ります。tokenは非公開で扱います。`confirm_acceptance`は接続前に開始します。受領票の事前登録が必要なら呼出前に済ませ、対象sessionと今回の文を照合します。古い記録や時刻の変化だけでは確認しません。終了時は`AbortSignal`で観測を取り消します。`false`は未確認を意味します。
176
+
177
+ raw投稿には同じ接続上の受付票がありません。`accepted`はUserPromptSubmitなどの受領観測が一致した時だけ返し、作業の完了までは示しません。`not_sent`はメッセージの書き込みを試みていない場合です。書き込みを試みた後の失敗や確認不能は`unknown`と`outcome_unknown:true`を返します。観測処理を渡さなければ、書き込みが成功しても`unknown`です。自動再送はしません。Claudeの受信制御はそのまま適用されます。結果は`status`・`reason`・`outcome_unknown`だけで、token・本文・宛先を含めません。
178
+
151
179
  ## エラーと配送の状態
152
180
 
153
181
  配送のエラーは `SteerDeliveryError`(`CodexDeliveryError`、`ClaudeDeliveryError`、`CursorDeliveryError`、`ChannelError`)で、次を持ちます。
package/README.md CHANGED
@@ -120,9 +120,18 @@ In your setup command:
120
120
 
121
121
  They keep other products' and the user's hooks and their order, and back up the file before writing. `removeClaudeParentHooks`, `removeCursorParentHooks`, and `configureCodexSteer(PROFILE, "disable", …)` undo them. `configureCodexSteer` returns `restart_required` when Codex processes that started before the hooks were installed are still running. PowerShell paths use the actual filesystem spelling, so PATH casing alone does not rewrite Codex hooks or require a restart.
122
122
 
123
+ The Claude Code hooks are written as one shell line, without `args`:
124
+
125
+ - POSIX: `exec '<node>' '<hook>'`. `exec` replaces `sh`, so Claude Code stays the direct parent of the hook.
126
+ - Windows: `& '<node>' '<hook>'; exit (Get-Variable LASTEXITCODE -ValueOnly)` with `shell: "powershell"`. PowerShell would otherwise turn the hook's exit code 2 into 1, and `asyncRewake` needs the 2.
127
+
128
+ Grok also runs the hooks in `~/.claude/settings.json`, but it drops `args` and runs `command` alone. With the `command` + `args` form that 0.1.x wrote, Grok started bare `node`, which read the hook input as a script and failed at every `Stop`. `runClaudeHookMain` now does nothing and exits 0 when Grok starts it (Grok puts its own `hookEventName` in the input), because Grok parents receive through the background process, not through hooks.
129
+
130
+ `mergeClaudeParentHooks` replaces your product's 0.1.x entries with the new form, and `removeClaudeParentHooks` removes both forms. To check a settings file without writing it, use `claudeParentHooksRegistered(PROFILE, document)` and `claudeParentHookScripts(PROFILE, document)` (the hook file paths the entries point to); do not read `args` yourself. Before you go back to 0.1.x, call `removeClaudeParentHooks` from 0.2.x: 0.1.x does not recognize the new entries and would add a second set.
131
+
123
132
  ### 4. Deliver
124
133
 
125
- There are two ways to deliver.
134
+ The MCP parent-delivery APIs offer two ways to deliver.
126
135
 
127
136
  **One answer per request** (what Aiterm does): identify the parent from the MCP request, bind a delivery id, and submit the final text once.
128
137
 
@@ -148,6 +157,25 @@ Claude Code re-arms its waiter at every `Stop`. Cursor binds the channel with `s
148
157
 
149
158
  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).
150
159
 
160
+ ### Send to a new Claude conversation
161
+
162
+ `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`.
163
+
164
+ ```js
165
+ import { sendClaudeInbox } from "aiterm-steer-delivery";
166
+
167
+ const text = "Continue the work.";
168
+ const result = await sendClaudeInbox({ socket_path, token }, text, {
169
+ timeout_ms: 30_000,
170
+ // Your product observes the target's UserPromptSubmit receipt.
171
+ confirm_acceptance: signal => productReceipts.waitForPrompt({ session_id, text, signal }),
172
+ });
173
+ ```
174
+
175
+ 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.
176
+
177
+ 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.
178
+
151
179
  ## Errors and delivery states
152
180
 
153
181
  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,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { type RuntimeProcess } from "./process.js";
2
3
  import type { ProductProfile } from "./profile.js";
3
4
  export declare const claudeParentSchema: z.ZodObject<{
4
5
  kind: z.ZodLiteral<"claude">;
@@ -14,7 +15,9 @@ export declare function verifyClaudeParent(profile: ProductProfile, parent: Clau
14
15
  export declare function bindClaudeParentDelivery(profile: ProductProfile, parent: ClaudeParent, deliveryId: string): void;
15
16
  /** SessionEndはその時点の依頼だけを終了する。同じ会話をresumeした新規依頼は別requestになる。 */
16
17
  export declare function closeClaudeParentSession(input: unknown, root: string): void;
17
- export declare function submitClaudeParentAnswer(profile: ProductProfile, parent: ClaudeParent, deliveryId: string, text: string): Promise<{
18
+ export declare function submitClaudeParentAnswer(profile: ProductProfile, parent: ClaudeParent, deliveryId: string, text: string, runtime?: {
19
+ processes: () => RuntimeProcess[];
20
+ }): Promise<{
18
21
  queued_submission_id: null;
19
22
  }>;
20
23
  export declare function runClaudeResultHook(profile: ProductProfile, input: unknown, emit: (text: string) => void | Promise<void>, root: string): Promise<0 | 2>;
@@ -1,11 +1,11 @@
1
1
  // Claude Codeの公式hookを受信口にする。待機processはharnessが所有し、親のturnを止めない。
2
- // PreToolUseが実際の会話(session_id)と親processを記録し、MCP要求のtoolUseIdと結ぶ。
2
+ // PreToolUseが実際の会話(session_id)と親process(hookを起動したClaude Code)を記録し、MCP要求のtoolUseIdと結ぶ。
3
3
  // PostToolUseのasyncRewake hookが本文の到着を待ち、stderrへ出してexit 2で親を起こす(作業中ならそのturnへ入る)。
4
4
  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 { readRuntimeProcesses } from "./process.js";
8
+ import { hookOwnerProcess, readRuntimeProcesses } from "./process.js";
9
9
  import { ClaudeDeliveryError } from "./errors.js";
10
10
  const requestId = z.string().regex(/^[A-Za-z0-9_-]{1,160}$/);
11
11
  const invocationSchema = z.object({
@@ -37,14 +37,15 @@ function assertOpen(parent) {
37
37
  }
38
38
  export function prepareClaudeHookRequest(input, root) {
39
39
  const event = z.object({ session_id: z.uuid(), tool_use_id: requestId, agent_id: z.string().optional() }).parse(input);
40
- const identity = processIdentity(process.ppid);
41
- if (!identity)
40
+ // shellを通す形のhookでは、直接の親はshellになる。shellはこのhookと一緒に終わるので、その先のClaude processを記録する。
41
+ const owner = hookOwnerProcess(readRuntimeProcesses(), process.ppid);
42
+ if (!owner)
42
43
  throw new ClaudeDeliveryError("CLAUDE_PARENT_PROCESS_UNAVAILABLE", "hookを起動した親processを確認できません");
43
44
  const dir = path.join(root, event.tool_use_id);
44
45
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
45
46
  writeJson0600(path.join(dir, "request.json"), {
46
47
  request_id: event.tool_use_id, session_id: event.session_id, agent_id: event.agent_id ?? null,
47
- parent_pid: process.ppid, parent_started_identity: identity,
48
+ parent_pid: owner.pid, parent_started_identity: owner.started_identity,
48
49
  });
49
50
  }
50
51
  /** 起動時envのsession IDは/clearで古くなるため、実際のPreToolUseとの相関だけを使う。 */
@@ -96,34 +97,48 @@ function assertParentAlive(invocation) {
96
97
  throw new ClaudeDeliveryError("CLAUDE_PARENT_PROCESS_CLOSED", "依頼元のClaude processは終了しました。回答は保存したままです");
97
98
  }
98
99
  }
99
- export async function submitClaudeParentAnswer(profile, parent, deliveryId, text) {
100
+ export async function submitClaudeParentAnswer(profile, parent, deliveryId, text, runtime = { processes: readRuntimeProcesses }) {
100
101
  const invocation = readInvocation(profile, parent);
101
102
  const dir = directory(parent);
102
103
  // 会話終了でも確定本文を失わない。終了判定より先に保存する。
103
104
  writeJson0600(path.join(dir, "answer.json"), { delivery_id: deliveryId, text });
105
+ const emitted = () => {
106
+ const file = path.join(dir, "emitted.json");
107
+ if (!fs.existsSync(file))
108
+ return false;
109
+ const value = JSON.parse(fs.readFileSync(file, "utf8"));
110
+ if (value.delivery_id !== deliveryId)
111
+ throw new ClaudeDeliveryError("CLAUDE_PARENT_DELIVERY_MISMATCH", "hookの配送IDが一致しません", true);
112
+ return true;
113
+ };
104
114
  await waitForFileState(dir, () => {
105
- const emitted = path.join(dir, "emitted.json");
106
- if (fs.existsSync(emitted)) {
107
- const value = JSON.parse(fs.readFileSync(emitted, "utf8"));
108
- if (value.delivery_id !== deliveryId)
109
- throw new ClaudeDeliveryError("CLAUDE_PARENT_DELIVERY_MISMATCH", "hookの配送IDが一致しません", true);
115
+ if (emitted())
110
116
  return true;
111
- }
112
117
  assertOpen(parent);
113
118
  const failed = path.join(dir, "failed.json");
114
119
  if (fs.existsSync(failed)) {
115
120
  const value = JSON.parse(fs.readFileSync(failed, "utf8"));
116
121
  throw new ClaudeDeliveryError("CLAUDE_PARENT_HOOK_FAILED", "親へのhook出力が失敗しました。回答は保存したままです", value.outcome_unknown === true);
117
122
  }
123
+ const rows = runtime.processes();
124
+ const alive = (pid, identity) => rows.find(entry => entry.pid === pid)?.started_identity === identity;
125
+ let gone;
118
126
  const hookFile = path.join(dir, "hook.json");
119
127
  if (fs.existsSync(hookFile)) {
120
128
  const hook = z.object({ pid: z.number().int().positive(), started_identity: z.string() }).parse(JSON.parse(fs.readFileSync(hookFile, "utf8")));
121
- if (processIdentity(hook.pid) !== hook.started_identity) {
122
- throw new ClaudeDeliveryError("CLAUDE_PARENT_HOOK_CLOSED", "親の受信hookが終了しました。自動再送はしていません", fs.existsSync(path.join(dir, "sending.json")));
129
+ if (!alive(hook.pid, hook.started_identity)) {
130
+ gone = new ClaudeDeliveryError("CLAUDE_PARENT_HOOK_CLOSED", "親の受信hookが終了しました。自動再送はしていません", fs.existsSync(path.join(dir, "sending.json")));
123
131
  }
124
132
  }
125
- assertParentAlive(invocation);
126
- return undefined;
133
+ if (!gone && !alive(invocation.parent_pid, invocation.parent_started_identity)) {
134
+ gone = new ClaudeDeliveryError("CLAUDE_PARENT_PROCESS_CLOSED", "依頼元のClaude processは終了しました。回答は保存したままです");
135
+ }
136
+ if (!gone)
137
+ return undefined;
138
+ // process表を読む間(Windowsは約1秒)に、hookが本文を出し終えて終わる事がある。「居ない」と読んだ後に、出し終えた記録を見直す。
139
+ if (emitted())
140
+ return true;
141
+ throw gone;
127
142
  });
128
143
  return { queued_submission_id: null };
129
144
  }
@@ -1,7 +1,11 @@
1
1
  import { type ProductProfile } from "./profile.js";
2
2
  /** Codexの同期hook(PostToolUse/Stop)。stdoutはCodexの公式hook出力だけに使う。失敗をStop継続のexit 2に変換しない。 */
3
3
  export declare function runCodexHookMain(profile: ProductProfile, directory?: string | undefined): Promise<void>;
4
- /** Claude Codeが直接起動する公式hook(PreToolUse/PostToolUse/SessionEnd)。本文はstderrへ返す。 */
4
+ /**
5
+ * Claude Codeが起動する公式hook(PreToolUse/PostToolUse/Stop/SessionEnd)。本文はstderrへ返す。
6
+ * Grokは共有の`~/.claude/settings.json`のhookも動かす。Grokの親への配送はhookを使わないので、Grokからの起動では何もせず0で終わる。
7
+ * 失敗の2を返すと、GrokはStopを「止めずに続ける」、PreToolUseを「拒否」と読む。見分けは、Grokだけが入力へ入れる`hookEventName`。
8
+ */
5
9
  export declare function runClaudeHookMain(profile: ProductProfile, root?: string): Promise<void>;
6
10
  /**
7
11
  * Cursorが起動する公式hook。差し込み文をstdoutのJSONへ返す。
package/dist/hook-main.js CHANGED
@@ -28,10 +28,16 @@ export async function runCodexHookMain(profile, directory = process.argv[2]) {
28
28
  process.exitCode = 1;
29
29
  }
30
30
  }
31
- /** Claude Codeが直接起動する公式hook(PreToolUse/PostToolUse/SessionEnd)。本文はstderrへ返す。 */
31
+ /**
32
+ * Claude Codeが起動する公式hook(PreToolUse/PostToolUse/Stop/SessionEnd)。本文はstderrへ返す。
33
+ * Grokは共有の`~/.claude/settings.json`のhookも動かす。Grokの親への配送はhookを使わないので、Grokからの起動では何もせず0で終わる。
34
+ * 失敗の2を返すと、GrokはStopを「止めずに続ける」、PreToolUseを「拒否」と読む。見分けは、Grokだけが入力へ入れる`hookEventName`。
35
+ */
32
36
  export async function runClaudeHookMain(profile, root = claudeHookRoot(profile)) {
33
37
  try {
34
38
  const event = JSON.parse(await readStdin());
39
+ if (event !== null && typeof event === "object" && typeof event.hookEventName === "string")
40
+ return;
35
41
  const write = (text) => new Promise((resolve, reject) => {
36
42
  process.stderr.write(text, error => error ? reject(error) : resolve());
37
43
  });
@@ -4,11 +4,26 @@ export type HookRuntime = {
4
4
  command: string;
5
5
  script: string;
6
6
  };
7
- export declare function claudeParentHookEntries(profile: ProductProfile, hook: HookRuntime): Record<string, {
7
+ /**
8
+ * Claude Codeの設定へ書くhookのcommand。shellを通す形で書く。
9
+ * `args`を付ける直接起動の形は、同じ設定を読むGrokが`args`を落として`command`だけを動かす(nodeが入力のJSONをscriptとして読んで失敗する)。
10
+ * - POSIX: `sh -c`で動く。`exec`でshをnodeへ置き換え、Claude Codeをhookの直接の親に保つ。
11
+ * - Windows: PowerShellで動かす(GrokもPowerShellで動かす)。PowerShellは終了codeを0か1へ丸めるので、asyncRewakeの2をそのまま返す。
12
+ * `$LASTEXITCODE`とは書かない。Grokが`$名前`を環境変数として読み、未設定としてhookを動かさない。
13
+ */
14
+ export declare function claudeParentHookCommand(hook: HookRuntime, platform?: NodeJS.Platform): {
15
+ command: string;
16
+ shell?: "powershell";
17
+ };
18
+ export declare function claudeParentHookEntries(profile: ProductProfile, hook: HookRuntime, platform?: NodeJS.Platform): Record<string, {
8
19
  matcher?: string;
9
20
  hooks: Record<string, unknown>[];
10
21
  }[]>;
11
22
  export declare function mergeClaudeParentHooks(profile: ProductProfile, file: string, hook: HookRuntime): "configured" | "unchanged";
23
+ /** 製品が登録する全てのeventに、当製品のhookがあるか(設定を読むだけ。形は旧・新のどちらでもよい)。 */
24
+ export declare function claudeParentHooksRegistered(profile: ProductProfile, document: unknown): boolean;
25
+ /** 登録済みの当製品のhookが指す入口のpath。入口のfileが残っているかを製品が確かめるために使う。 */
26
+ export declare function claudeParentHookScripts(profile: ProductProfile, document: unknown): string[];
12
27
  /** hookを持たない旧版へ戻す前に、当製品の登録だけを除く。 */
13
28
  export declare function removeClaudeParentHooks(profile: ProductProfile, file: string): "removed" | "unchanged";
14
29
  export declare function cursorParentHookCommand(hook: HookRuntime): string;
@@ -9,8 +9,26 @@ const record = (value) => typeof value === "object" && value !== null && !Array.
9
9
  function endsWithFile(value, file) {
10
10
  return value === file || value.endsWith(`/${file}`) || value.endsWith(`\\${file}`);
11
11
  }
12
- export function claudeParentHookEntries(profile, hook) {
13
- const command = { type: "command", command: hook.command, args: [hook.script] };
12
+ function shellQuote(value, platform = process.platform) {
13
+ if (platform === "win32")
14
+ return `'${value.replace(/'/g, "''")}'`;
15
+ return `'${value.replace(/'/g, `'"'"'`)}'`;
16
+ }
17
+ /**
18
+ * Claude Codeの設定へ書くhookのcommand。shellを通す形で書く。
19
+ * `args`を付ける直接起動の形は、同じ設定を読むGrokが`args`を落として`command`だけを動かす(nodeが入力のJSONをscriptとして読んで失敗する)。
20
+ * - POSIX: `sh -c`で動く。`exec`でshをnodeへ置き換え、Claude Codeをhookの直接の親に保つ。
21
+ * - Windows: PowerShellで動かす(GrokもPowerShellで動かす)。PowerShellは終了codeを0か1へ丸めるので、asyncRewakeの2をそのまま返す。
22
+ * `$LASTEXITCODE`とは書かない。Grokが`$名前`を環境変数として読み、未設定としてhookを動かさない。
23
+ */
24
+ export function claudeParentHookCommand(hook, platform = process.platform) {
25
+ const words = `${shellQuote(hook.command, platform)} ${shellQuote(hook.script, platform)}`;
26
+ if (platform === "win32")
27
+ return { command: `& ${words}; exit (Get-Variable LASTEXITCODE -ValueOnly)`, shell: "powershell" };
28
+ return { command: `exec ${words}` };
29
+ }
30
+ export function claudeParentHookEntries(profile, hook, platform = process.platform) {
31
+ const command = { type: "command", ...claudeParentHookCommand(hook, platform) };
14
32
  const matcher = `^mcp__${profile.mcp_server}__(${profile.dispatch_tools.join("|")})$`;
15
33
  return {
16
34
  PreToolUse: [{ matcher, hooks: [{ ...command, timeout: 15 }] }],
@@ -72,9 +90,37 @@ export function mergeClaudeParentHooks(profile, file, hook) {
72
90
  }
73
91
  return "configured";
74
92
  }
93
+ /** 当製品のhookか。0.1系が書いた直接起動の形(`args[0]`が入口)と、今の形(`command`が入口を指す)の両方を数える。 */
75
94
  function isClaudeParentHook(profile, hook) {
76
- return record(hook) && hook.type === "command" && Array.isArray(hook.args)
77
- && typeof hook.args[0] === "string" && endsWithFile(hook.args[0], profile.hooks.claude);
95
+ if (!record(hook) || hook.type !== "command")
96
+ return false;
97
+ if (Array.isArray(hook.args))
98
+ return typeof hook.args[0] === "string" && endsWithFile(hook.args[0], profile.hooks.claude);
99
+ return typeof hook.command === "string" && commandNamesFile(hook.command, profile.hooks.claude);
100
+ }
101
+ /** 引用符で囲んだ語を取り出す。`claudeParentHookCommand`が書いた行を読み戻すためのもので、PowerShellの行は`''`、shの行は`'"'"'`を引用符に戻す。 */
102
+ function quotedWords(command) {
103
+ const powershell = command.startsWith("& ");
104
+ const pattern = powershell ? /'((?:[^']|'')*)'/gu : /'((?:[^']|'"'"')*)'/gu;
105
+ return [...command.matchAll(pattern)].map(match => powershell ? match[1].replace(/''/g, "'") : match[1].replace(/'"'"'/g, "'"));
106
+ }
107
+ function ownedClaudeParentHooks(profile, document, event) {
108
+ const hooks = record(document) && record(document.hooks) ? document.hooks[event] : undefined;
109
+ if (!Array.isArray(hooks))
110
+ return [];
111
+ return hooks.flatMap(group => record(group) && Array.isArray(group.hooks) ? group.hooks : []).filter(entry => isClaudeParentHook(profile, entry));
112
+ }
113
+ /** 製品が登録する全てのeventに、当製品のhookがあるか(設定を読むだけ。形は旧・新のどちらでもよい)。 */
114
+ export function claudeParentHooksRegistered(profile, document) {
115
+ return Object.keys(claudeParentHookEntries(profile, { command: "", script: profile.hooks.claude }))
116
+ .every(event => ownedClaudeParentHooks(profile, document, event).length > 0);
117
+ }
118
+ /** 登録済みの当製品のhookが指す入口のpath。入口のfileが残っているかを製品が確かめるために使う。 */
119
+ export function claudeParentHookScripts(profile, document) {
120
+ return Object.keys(claudeParentHookEntries(profile, { command: "", script: profile.hooks.claude })).flatMap(event => ownedClaudeParentHooks(profile, document, event).flatMap(hook => {
121
+ const words = Array.isArray(hook.args) ? hook.args.filter((arg) => typeof arg === "string") : quotedWords(String(hook.command));
122
+ return words.filter(word => endsWithFile(word, profile.hooks.claude));
123
+ }));
78
124
  }
79
125
  /** hookを持たない旧版へ戻す前に、当製品の登録だけを除く。 */
80
126
  export function removeClaudeParentHooks(profile, file) {
@@ -116,11 +162,6 @@ export function removeClaudeParentHooks(profile, file) {
116
162
  throw new SetupError("config_readback_failed", "Claude hook解除の読戻しが一致しません");
117
163
  return "removed";
118
164
  }
119
- function shellQuote(value) {
120
- if (process.platform === "win32")
121
- return `'${value.replace(/'/g, "''")}'`;
122
- return `'${value.replace(/'/g, `'"'"'`)}'`;
123
- }
124
165
  export function cursorParentHookCommand(hook) {
125
166
  const command = `${shellQuote(hook.command)} ${shellQuote(hook.script)}`;
126
167
  return process.platform === "win32" ? `& ${command}` : command;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export * from "./profile.js";
2
2
  export * from "./errors.js";
3
3
  export { writeJson0600, writeHookJson, waitForFileState, withoutBom } from "./files.js";
4
- export { readRuntimeProcesses, parsePosixProcessTable, type RuntimeProcess, type NativeProcessIdentity } from "./process.js";
4
+ export { readRuntimeProcesses, parsePosixProcessTable, hookOwnerProcess, type RuntimeProcess, type NativeProcessIdentity } from "./process.js";
5
5
  export { resolveWindowsPowerShell7, quotePowerShell, windowsPowerShellSync, windowsStartProcessArgumentList } from "./windows.js";
6
6
  export { setupNodeExecutable } from "./setup-node.js";
7
7
  export { realCodexHome, resolveCodexExecutable, desktopBundledCodex, findDesktopBinary, findWindowsCodexCache, findWindowsCodexBinary, findLinuxDesktopBinary, findCliBinary, findSteerBinary, platformDesktopFinder, currentCodexDesktopBinary, type DesktopBinaryFinder, } from "./codex-binary.js";
@@ -10,9 +10,10 @@ 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 { sendClaudeInbox, type ClaudeInboxTarget, type ClaudeInboxSendOptions, type ClaudeInboxSendResult, } from "./claude-inbox.js";
13
14
  export { cursorParentSchema, isCursorMcpClient, cursorHooksFile, cursorParentHooksRegistered, verifyCursorParent, cursorParentFromRequest, prepareCursorDelivery, submitCursorParentAnswer, handleCursorHook, receiveCursorAnswer, type CursorParent, type CursorReceiveResult, type CursorReceiveReader, } from "./cursor-receiver.js";
14
15
  export { cursorReceiveProcess, runCursorReceive, stdoutOutput, waitProcessCommandLine, type WaitProcess, type ReceiveOutput } from "./cursor-receive.js";
15
- export { claudeParentHookEntries, mergeClaudeParentHooks, removeClaudeParentHooks, cursorParentHookCommand, mergeCursorParentHooks, removeCursorParentHooks, commandNamesFile, type HookRuntime, } from "./hook-setup.js";
16
+ export { claudeParentHookCommand, claudeParentHookEntries, claudeParentHooksRegistered, claudeParentHookScripts, 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";
18
19
  export { openChannel, readChannel, channelClosed, closeChannel, sendToChannel, channelDeliveryState, withdrawFromChannel, runClaudeChannelWaiter, closeClaudeSessionChannels, channelIdFromResult, channelMarker, handleCursorChannelHook, channelReceiveProcess, receiveFromChannel, ChannelError, type Channel, type ChannelKind, type ChannelDeliveryState, type ChannelReceiveResult, } from "./channel.js";
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@
3
3
  export * from "./profile.js";
4
4
  export * from "./errors.js";
5
5
  export { writeJson0600, writeHookJson, waitForFileState, withoutBom } from "./files.js";
6
- export { readRuntimeProcesses, parsePosixProcessTable } from "./process.js";
6
+ export { readRuntimeProcesses, parsePosixProcessTable, hookOwnerProcess } from "./process.js";
7
7
  export { resolveWindowsPowerShell7, quotePowerShell, windowsPowerShellSync, windowsStartProcessArgumentList } from "./windows.js";
8
8
  export { setupNodeExecutable } from "./setup-node.js";
9
9
  export { realCodexHome, resolveCodexExecutable, desktopBundledCodex, findDesktopBinary, findWindowsCodexCache, findWindowsCodexBinary, findLinuxDesktopBinary, findCliBinary, findSteerBinary, platformDesktopFinder, currentCodexDesktopBinary, } from "./codex-binary.js";
@@ -12,9 +12,10 @@ 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
17
  export { cursorReceiveProcess, runCursorReceive, stdoutOutput, waitProcessCommandLine } from "./cursor-receive.js";
17
- export { claudeParentHookEntries, mergeClaudeParentHooks, removeClaudeParentHooks, cursorParentHookCommand, mergeCursorParentHooks, removeCursorParentHooks, commandNamesFile, } from "./hook-setup.js";
18
+ export { claudeParentHookCommand, claudeParentHookEntries, claudeParentHooksRegistered, claudeParentHookScripts, 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";
20
21
  export { openChannel, readChannel, channelClosed, closeChannel, sendToChannel, channelDeliveryState, withdrawFromChannel, runClaudeChannelWaiter, closeClaudeSessionChannels, channelIdFromResult, channelMarker, handleCursorChannelHook, channelReceiveProcess, receiveFromChannel, ChannelError, } from "./channel.js";
package/dist/process.d.ts CHANGED
@@ -14,4 +14,9 @@ export interface RuntimeProcess extends NativeProcessIdentity {
14
14
  export declare function processIdentity(process: RuntimeProcess): NativeProcessIdentity;
15
15
  export declare function parseCpuTime(value: string): number;
16
16
  export declare function parsePosixProcessTable(text: string): RuntimeProcess[];
17
+ /**
18
+ * hookを起動したharnessのprocess。shellを通す形のhookでは、harnessとhookの間にshellが挟まる。
19
+ * 挟まったshellはhookと一緒に終わるので、`pid`から先祖をたどり、shellでない最初のprocessを返す。
20
+ */
21
+ export declare function hookOwnerProcess(rows: readonly RuntimeProcess[], pid: number): RuntimeProcess | undefined;
17
22
  export declare function readRuntimeProcesses(): RuntimeProcess[];
package/dist/process.js CHANGED
@@ -33,6 +33,23 @@ export function parsePosixProcessTable(text) {
33
33
  };
34
34
  });
35
35
  }
36
+ /** hookのcommandを動かすshell。Claude Codeは`sh -c`(POSIX)、PowerShellかGit Bash(Windows)を使う。 */
37
+ const HOOK_SHELLS = new Set(["sh", "bash", "dash", "zsh", "ksh", "ash", "busybox", "pwsh", "powershell", "cmd"]);
38
+ function executableName(row) {
39
+ const source = row.executable || (row.command.startsWith('"') ? row.command.slice(1).split('"')[0] : row.command.split(/\s+/u)[0]);
40
+ return (source.split(/[\\/]/u).pop() ?? "").replace(/^-/u, "").replace(/\.exe$/iu, "").toLowerCase();
41
+ }
42
+ /**
43
+ * hookを起動したharnessのprocess。shellを通す形のhookでは、harnessとhookの間にshellが挟まる。
44
+ * 挟まったshellはhookと一緒に終わるので、`pid`から先祖をたどり、shellでない最初のprocessを返す。
45
+ */
46
+ export function hookOwnerProcess(rows, pid) {
47
+ const byPid = new Map(rows.map(row => [row.pid, row]));
48
+ let current = byPid.get(pid);
49
+ for (let depth = 0; current && depth < 4 && HOOK_SHELLS.has(executableName(current)); depth += 1)
50
+ current = byPid.get(current.parent_pid);
51
+ return current;
52
+ }
36
53
  export function readRuntimeProcesses() {
37
54
  if (!isWin) {
38
55
  const result = spawnSync("/bin/ps", ["-axww", "-o", "pid=,ppid=,pgid=,stat=,lstart=,time=,command="], {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-steer-delivery",
3
- "version": "0.1.12",
3
+ "version": "0.2.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",