aiterm-steer-delivery 0.1.13 → 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,22 @@
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
+
3
20
  ## 0.1.13
4
21
 
5
22
  - `sendClaudeInbox`を公開する。ClaudeのSessionStartが渡すinbox socketとtokenへuserメッセージを1通送る。MCPを呼んでいない新規会話にも使え、既存のClaudeParent・channel・asyncRewake配送は変えない。Windowsはauthを必須とし、POSIXでもtokenを渡せる。
package/README.ja.md CHANGED
@@ -120,6 +120,15 @@ 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
134
  MCPを呼んだ親への届け方は2つあります。
package/README.md CHANGED
@@ -120,6 +120,15 @@ 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
134
  The MCP parent-delivery APIs offer two ways to deliver.
@@ -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";
@@ -13,7 +13,7 @@ export { claudeParentSchema, prepareClaudeHookRequest, claudeParentFromRequest,
13
13
  export { sendClaudeInbox, type ClaudeInboxTarget, type ClaudeInboxSendOptions, type ClaudeInboxSendResult, } from "./claude-inbox.js";
14
14
  export { cursorParentSchema, isCursorMcpClient, cursorHooksFile, cursorParentHooksRegistered, verifyCursorParent, cursorParentFromRequest, prepareCursorDelivery, submitCursorParentAnswer, handleCursorHook, receiveCursorAnswer, type CursorParent, type CursorReceiveResult, type CursorReceiveReader, } from "./cursor-receiver.js";
15
15
  export { cursorReceiveProcess, runCursorReceive, stdoutOutput, waitProcessCommandLine, type WaitProcess, type ReceiveOutput } from "./cursor-receive.js";
16
- 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";
17
17
  export { runCodexHookMain, runClaudeHookMain, runCursorHookMain, runCursorReceiveMain, isDirectExecution } from "./hook-main.js";
18
18
  export { runChannelReceiveMain } from "./hook-main.js";
19
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";
@@ -15,7 +15,7 @@ export { claudeParentSchema, prepareClaudeHookRequest, claudeParentFromRequest,
15
15
  export { sendClaudeInbox, } from "./claude-inbox.js";
16
16
  export { cursorParentSchema, isCursorMcpClient, cursorHooksFile, cursorParentHooksRegistered, verifyCursorParent, cursorParentFromRequest, prepareCursorDelivery, submitCursorParentAnswer, handleCursorHook, receiveCursorAnswer, } from "./cursor-receiver.js";
17
17
  export { cursorReceiveProcess, runCursorReceive, stdoutOutput, waitProcessCommandLine } from "./cursor-receive.js";
18
- 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";
19
19
  export { runCodexHookMain, runClaudeHookMain, runCursorHookMain, runCursorReceiveMain, isDirectExecution } from "./hook-main.js";
20
20
  export { runChannelReceiveMain } from "./hook-main.js";
21
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.13",
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",