aiterm-steer-delivery 0.1.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/LICENSE +22 -0
  3. package/README.md +75 -0
  4. package/dist/channel.d.ts +106 -0
  5. package/dist/channel.js +484 -0
  6. package/dist/claude-receiver.d.ts +20 -0
  7. package/dist/claude-receiver.js +171 -0
  8. package/dist/cli.d.ts +4 -0
  9. package/dist/cli.js +98 -0
  10. package/dist/codex-binary.d.ts +22 -0
  11. package/dist/codex-binary.js +176 -0
  12. package/dist/codex-hook-state.d.ts +45 -0
  13. package/dist/codex-hook-state.js +119 -0
  14. package/dist/codex-hook.d.ts +2 -0
  15. package/dist/codex-hook.js +13 -0
  16. package/dist/codex-hooks.d.ts +7 -0
  17. package/dist/codex-hooks.js +114 -0
  18. package/dist/codex-receiver.d.ts +20 -0
  19. package/dist/codex-receiver.js +145 -0
  20. package/dist/codex-setup.d.ts +35 -0
  21. package/dist/codex-setup.js +160 -0
  22. package/dist/cursor-receive.d.ts +9 -0
  23. package/dist/cursor-receive.js +31 -0
  24. package/dist/cursor-receiver.d.ts +29 -0
  25. package/dist/cursor-receiver.js +242 -0
  26. package/dist/errors.d.ts +17 -0
  27. package/dist/errors.js +26 -0
  28. package/dist/files.d.ts +4 -0
  29. package/dist/files.js +79 -0
  30. package/dist/hook-main.d.ts +16 -0
  31. package/dist/hook-main.js +139 -0
  32. package/dist/hook-setup.d.ts +16 -0
  33. package/dist/hook-setup.js +222 -0
  34. package/dist/index.d.ts +18 -0
  35. package/dist/index.js +20 -0
  36. package/dist/process.d.ts +17 -0
  37. package/dist/process.js +79 -0
  38. package/dist/profile.d.ts +42 -0
  39. package/dist/profile.js +14 -0
  40. package/dist/setup-node.d.ts +1 -0
  41. package/dist/setup-node.js +16 -0
  42. package/dist/windows.d.ts +13 -0
  43. package/dist/windows.js +76 -0
  44. package/package.json +28 -0
@@ -0,0 +1,17 @@
1
+ export declare class SteerDeliveryError extends Error {
2
+ readonly delivery_code: string;
3
+ readonly outcome_unknown: boolean;
4
+ readonly code: number;
5
+ constructor(delivery_code: string, message: string, outcome_unknown?: boolean);
6
+ }
7
+ export declare class CodexDeliveryError extends SteerDeliveryError {
8
+ }
9
+ export declare class ClaudeDeliveryError extends SteerDeliveryError {
10
+ }
11
+ export declare class CursorDeliveryError extends SteerDeliveryError {
12
+ }
13
+ /** setupの失敗。codeは製品のsetup結果のreason_codeになる。 */
14
+ export declare class SetupError extends Error {
15
+ readonly code: string;
16
+ constructor(code: string, message: string);
17
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,26 @@
1
+ // 配送のエラー。delivery_codeが理由、outcome_unknownは「送ったかどうか確定できない」を表す。
2
+ // codeはAitermのAitermErrorと同じexit code(2)で、製品の既存のエラー表示へそのまま渡せる。
3
+ export class SteerDeliveryError extends Error {
4
+ delivery_code;
5
+ outcome_unknown;
6
+ code = 2;
7
+ constructor(delivery_code, message, outcome_unknown = false) {
8
+ super(`${delivery_code}: ${message}`);
9
+ this.delivery_code = delivery_code;
10
+ this.outcome_unknown = outcome_unknown;
11
+ }
12
+ }
13
+ export class CodexDeliveryError extends SteerDeliveryError {
14
+ }
15
+ export class ClaudeDeliveryError extends SteerDeliveryError {
16
+ }
17
+ export class CursorDeliveryError extends SteerDeliveryError {
18
+ }
19
+ /** setupの失敗。codeは製品のsetup結果のreason_codeになる。 */
20
+ export class SetupError extends Error {
21
+ code;
22
+ constructor(code, message) {
23
+ super(message);
24
+ this.code = code;
25
+ }
26
+ }
@@ -0,0 +1,4 @@
1
+ export declare function writeJson0600(p: string, v: unknown): void;
2
+ export declare function writeHookJson(file: string, value: unknown): void;
3
+ /** directory内の状態変化を待つ。inspectが値を返した時点でresolveする。timeoutMsを省くと期限なし。 */
4
+ export declare function waitForFileState<T>(dir: string, inspect: () => T | undefined, timeoutMs?: number): Promise<T>;
package/dist/files.js ADDED
@@ -0,0 +1,79 @@
1
+ // 配送記録の読み書き。途中までのJSONを残さないよう、一時ファイルからrenameで置き換える。
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { randomBytes, randomUUID } from "node:crypto";
5
+ export function writeJson0600(p, v) {
6
+ // truncate-in-place はクラッシュ/ENOSPC の窓で空・途中 JSON を残すので、temp→rename の原子的置換にする
7
+ const tmp = `${p}.${randomBytes(6).toString("hex")}.tmp`;
8
+ fs.writeFileSync(tmp, JSON.stringify(v, null, 2) + "\n", { mode: 0o600, flag: "wx" });
9
+ try {
10
+ fs.chmodSync(tmp, 0o600);
11
+ }
12
+ catch {
13
+ /* noop */
14
+ }
15
+ try {
16
+ fs.renameSync(tmp, p);
17
+ }
18
+ catch (e) {
19
+ try {
20
+ fs.unlinkSync(tmp);
21
+ }
22
+ catch {
23
+ /* noop */
24
+ }
25
+ throw e;
26
+ }
27
+ }
28
+ export function writeHookJson(file, value) {
29
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
30
+ const temporary = `${file}.${randomUUID()}.tmp`;
31
+ try {
32
+ fs.writeFileSync(temporary, JSON.stringify(value) + "\n", { flag: "wx", mode: 0o600 });
33
+ fs.renameSync(temporary, file);
34
+ }
35
+ finally {
36
+ if (fs.existsSync(temporary))
37
+ fs.unlinkSync(temporary);
38
+ }
39
+ }
40
+ /** directory内の状態変化を待つ。inspectが値を返した時点でresolveする。timeoutMsを省くと期限なし。 */
41
+ export function waitForFileState(dir, inspect, timeoutMs) {
42
+ return new Promise((resolve, reject) => {
43
+ let finished = false;
44
+ let timer;
45
+ let timeout;
46
+ const watcher = fs.watch(dir, () => check());
47
+ const finish = (error, value) => {
48
+ if (finished)
49
+ return;
50
+ finished = true;
51
+ watcher.close();
52
+ if (timer)
53
+ clearInterval(timer);
54
+ if (timeout)
55
+ clearTimeout(timeout);
56
+ if (error)
57
+ reject(error);
58
+ else
59
+ resolve(value);
60
+ };
61
+ const check = () => {
62
+ if (finished)
63
+ return;
64
+ try {
65
+ const value = inspect();
66
+ if (value !== undefined)
67
+ finish(null, value);
68
+ }
69
+ catch (error) {
70
+ finish(error);
71
+ }
72
+ };
73
+ watcher.on("error", error => finish(error));
74
+ timer = setInterval(check, 5000);
75
+ if (timeoutMs !== undefined)
76
+ timeout = setTimeout(() => finish(new Error("WAIT_FOR_FILE_TIMEOUT")), timeoutMs);
77
+ check();
78
+ });
79
+ }
@@ -0,0 +1,16 @@
1
+ import { type ProductProfile } from "./profile.js";
2
+ /** Codexの同期hook(PostToolUse/Stop)。stdoutはCodexの公式hook出力だけに使う。失敗をStop継続のexit 2に変換しない。 */
3
+ export declare function runCodexHookMain(profile: ProductProfile, directory?: string | undefined): Promise<void>;
4
+ /** Claude Codeが直接起動する公式hook(PreToolUse/PostToolUse/SessionEnd)。本文はstderrへ返す。 */
5
+ export declare function runClaudeHookMain(profile: ProductProfile, root?: string): Promise<void>;
6
+ /** Cursorが起動する公式hook。差し込み文をstdoutのJSONへ返す。 */
7
+ export declare function runCursorHookMain(profile: ProductProfile, root?: string): Promise<void>;
8
+ /** Cursor親の背景受信。 */
9
+ export declare function runCursorReceiveMain(profile: ProductProfile, argv?: string[], root?: string): Promise<void>;
10
+ /**
11
+ * channelの背景受信(Cursorのidle時、Grok等)。受け取った本文を1行のJSONで出して終わる(0=受取、3=期限切れ、4=閉鎖、1=誤り)。
12
+ * 受取と期限切れの結果には、同じ受信を張り直すための next_wait_process を付ける。
13
+ */
14
+ export declare function runChannelReceiveMain(profile: ProductProfile, argv?: string[], script?: string | undefined): Promise<void>;
15
+ /** 入口ファイルが直接起動されたか(importされただけでは動かない)。Windowsは大文字小文字を区別しない。 */
16
+ export declare function isDirectExecution(moduleUrl: string, entry?: string | undefined): boolean;
@@ -0,0 +1,139 @@
1
+ // 製品のhook入口から呼ぶ本体。入口ファイルは「import して呼ぶだけ」にし、hook commandのpathは製品が持つ。
2
+ import * as fs from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { claudeHookRoot, cursorHookRoot } from "./profile.js";
5
+ import { runCodexResultHook } from "./codex-hooks.js";
6
+ import { prepareClaudeHookRequest, runClaudeResultHook, closeClaudeParentSession } from "./claude-receiver.js";
7
+ import { handleCursorHook } from "./cursor-receiver.js";
8
+ import { runCursorReceive } from "./cursor-receive.js";
9
+ import { channelReceiveProcess, closeClaudeSessionChannels, handleCursorChannelHook, receiveFromChannel, runClaudeChannelWaiter } from "./channel.js";
10
+ async function readStdin() {
11
+ let input = "";
12
+ process.stdin.setEncoding("utf8");
13
+ for await (const chunk of process.stdin)
14
+ input += chunk;
15
+ return input;
16
+ }
17
+ /** Codexの同期hook(PostToolUse/Stop)。stdoutはCodexの公式hook出力だけに使う。失敗をStop継続のexit 2に変換しない。 */
18
+ export async function runCodexHookMain(profile, directory = process.argv[2]) {
19
+ try {
20
+ const input = await readStdin();
21
+ await runCodexResultHook(profile, JSON.parse(input), value => new Promise((resolve, reject) => {
22
+ process.stdout.write(JSON.stringify(value) + "\n", error => error ? reject(error) : resolve());
23
+ }), { directory });
24
+ }
25
+ catch (error) {
26
+ process.stderr.write(`CODEX_PARENT_HOOK_FAILED: ${error instanceof Error ? error.message : String(error)}\n`);
27
+ process.exitCode = 1;
28
+ }
29
+ }
30
+ /** Claude Codeが直接起動する公式hook(PreToolUse/PostToolUse/SessionEnd)。本文はstderrへ返す。 */
31
+ export async function runClaudeHookMain(profile, root = claudeHookRoot(profile)) {
32
+ try {
33
+ const event = JSON.parse(await readStdin());
34
+ const write = (text) => new Promise((resolve, reject) => {
35
+ process.stderr.write(text, error => error ? reject(error) : resolve());
36
+ });
37
+ switch (event.hook_event_name) {
38
+ case "PreToolUse":
39
+ prepareClaudeHookRequest(event, root);
40
+ break;
41
+ case "PostToolUse":
42
+ process.exitCode = await runClaudeResultHook(profile, event, write, root);
43
+ // 単発の依頼が無いtoolの返りでは、channelの待機を張る(長く続く受信を使う製品だけ)。
44
+ if (process.exitCode === 0 && profile.channels)
45
+ process.exitCode = await runClaudeChannelWaiter(profile, event, write);
46
+ break;
47
+ case "Stop":
48
+ if (!profile.channels)
49
+ throw new Error("CLAUDE_PARENT_HOOK_EVENT_INVALID: 未対応のhookです");
50
+ process.exitCode = await runClaudeChannelWaiter(profile, event, write);
51
+ break;
52
+ case "SessionEnd":
53
+ closeClaudeParentSession(event, root);
54
+ if (profile.channels)
55
+ closeClaudeSessionChannels(profile, event);
56
+ break;
57
+ default: throw new Error("CLAUDE_PARENT_HOOK_EVENT_INVALID: 未対応のhookです");
58
+ }
59
+ }
60
+ catch (error) {
61
+ process.stderr.write(`${error instanceof Error ? error.message : "CLAUDE_PARENT_HOOK_FAILED"}\n`);
62
+ process.exitCode = 2;
63
+ }
64
+ }
65
+ /** Cursorが起動する公式hook。差し込み文をstdoutのJSONへ返す。 */
66
+ export async function runCursorHookMain(profile, root = cursorHookRoot(profile)) {
67
+ try {
68
+ const input = await readStdin();
69
+ const result = await handleCursorHook(profile, input.length > 0 ? input : "{}", root);
70
+ if (profile.channels) {
71
+ let event = null;
72
+ try {
73
+ event = JSON.parse(input);
74
+ }
75
+ catch { /* 単発配送と同じく、読めない入力には何も返さない */ }
76
+ if (event !== null && typeof event === "object") {
77
+ await handleCursorChannelHook(profile, event, text => {
78
+ result.additional_context = typeof result.additional_context === "string" ? `${result.additional_context}\n\n${text}` : text;
79
+ });
80
+ }
81
+ }
82
+ process.stdout.write(`${JSON.stringify(result)}\n`);
83
+ }
84
+ catch (error) {
85
+ process.stderr.write(`${error instanceof Error ? error.message : "CURSOR_PARENT_HOOK_FAILED"}\n`);
86
+ process.exitCode = 2;
87
+ }
88
+ }
89
+ /** Cursor親の背景受信。 */
90
+ export async function runCursorReceiveMain(profile, argv = process.argv.slice(2), root = cursorHookRoot(profile)) {
91
+ const emit = (value) => { process.stdout.write(JSON.stringify(value) + "\n"); };
92
+ try {
93
+ process.exitCode = await runCursorReceive(root, argv, emit);
94
+ }
95
+ catch (error) {
96
+ emit({ ok: false, code: "CURSOR_PARENT_RECEIVE_FAILED", message: error instanceof Error ? error.message : "cursor-parent-receive: operation failed" });
97
+ process.exitCode = 1;
98
+ }
99
+ }
100
+ /**
101
+ * channelの背景受信(Cursorのidle時、Grok等)。受け取った本文を1行のJSONで出して終わる(0=受取、3=期限切れ、4=閉鎖、1=誤り)。
102
+ * 受取と期限切れの結果には、同じ受信を張り直すための next_wait_process を付ける。
103
+ */
104
+ export async function runChannelReceiveMain(profile, argv = process.argv.slice(2), script = process.argv[1]) {
105
+ const emit = (value) => new Promise((resolve, reject) => {
106
+ process.stdout.write(JSON.stringify(value) + "\n", error => error ? reject(error) : resolve());
107
+ });
108
+ try {
109
+ if (argv.length !== 2 || argv[0] !== "--channel" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(argv[1])) {
110
+ await emit({ ok: false, code: "CHANNEL_RECEIVE_USAGE", message: "usage: <receive> --channel <uuid>" });
111
+ process.exitCode = 1;
112
+ return;
113
+ }
114
+ const next = script ? channelReceiveProcess(script, argv[1]) : null;
115
+ const result = await receiveFromChannel(profile, argv[1], {
116
+ emit: value => emit(value.outcome === "closed" ? value : { ...value, next_wait_process: next }),
117
+ });
118
+ process.exitCode = result.outcome === "delivered" ? 0 : result.outcome === "timeout" ? 3 : 4;
119
+ }
120
+ catch (error) {
121
+ await emit({ ok: false, code: "CHANNEL_RECEIVE_FAILED", message: error instanceof Error ? error.message : "channel receive failed" });
122
+ process.exitCode = 1;
123
+ }
124
+ }
125
+ /** 入口ファイルが直接起動されたか(importされただけでは動かない)。Windowsは大文字小文字を区別しない。 */
126
+ export function isDirectExecution(moduleUrl, entry = process.argv[1]) {
127
+ if (!entry)
128
+ return false;
129
+ try {
130
+ const a = fs.realpathSync(entry);
131
+ const b = fs.realpathSync(fileURLToPath(moduleUrl));
132
+ if (a === b)
133
+ return true;
134
+ return process.platform === "win32" && a.toLowerCase() === b.toLowerCase();
135
+ }
136
+ catch {
137
+ return false;
138
+ }
139
+ }
@@ -0,0 +1,16 @@
1
+ import type { ProductProfile } from "./profile.js";
2
+ /** hookを起動するNodeと、製品が同梱するhook入口の絶対path。 */
3
+ export type HookRuntime = {
4
+ command: string;
5
+ script: string;
6
+ };
7
+ export declare function claudeParentHookEntries(profile: ProductProfile, hook: HookRuntime): Record<string, {
8
+ matcher?: string;
9
+ hooks: Record<string, unknown>[];
10
+ }[]>;
11
+ export declare function mergeClaudeParentHooks(profile: ProductProfile, file: string, hook: HookRuntime): "configured" | "unchanged";
12
+ /** hookを持たない旧版へ戻す前に、当製品の登録だけを除く。 */
13
+ export declare function removeClaudeParentHooks(profile: ProductProfile, file: string): "removed" | "unchanged";
14
+ export declare function cursorParentHookCommand(hook: HookRuntime): string;
15
+ export declare function mergeCursorParentHooks(profile: ProductProfile, file: string, hook: HookRuntime): "configured" | "unchanged";
16
+ export declare function removeCursorParentHooks(profile: ProductProfile, file: string): "removed" | "unchanged";
@@ -0,0 +1,222 @@
1
+ // Claude Code・Cursorの設定ファイルへ、製品の配送hookを登録・解除する。他製品やユーザーのhookと順序は保つ。
2
+ import { copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { isDeepStrictEqual } from "node:util";
6
+ import { SetupError } from "./errors.js";
7
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8
+ /** 引数の末尾が製品のhook入口と同じファイル名か。path区切りまで見るので、名前の一部だけ重なる他製品を拾わない。 */
9
+ function endsWithFile(value, file) {
10
+ return value === file || value.endsWith(`/${file}`) || value.endsWith(`\\${file}`);
11
+ }
12
+ export function claudeParentHookEntries(profile, hook) {
13
+ const command = { type: "command", command: hook.command, args: [hook.script] };
14
+ const matcher = `^mcp__${profile.mcp_server}__(${profile.dispatch_tools.join("|")})$`;
15
+ return {
16
+ PreToolUse: [{ matcher, hooks: [{ ...command, timeout: 15 }] }],
17
+ PostToolUse: [{ matcher, hooks: [{ ...command, asyncRewake: true, timeout: 86400 }] }],
18
+ // 長く続く受信(channel)では、turnが終わるたびに待機を張り直す。
19
+ ...(profile.channels ? { Stop: [{ hooks: [{ ...command, asyncRewake: true, timeout: 86400 }] }] } : {}),
20
+ SessionEnd: [{ hooks: [{ ...command, timeout: 15 }] }],
21
+ };
22
+ }
23
+ export function mergeClaudeParentHooks(profile, file, hook) {
24
+ const target = existsSync(file) ? realpathSync(file) : file;
25
+ let current = {};
26
+ if (existsSync(target)) {
27
+ try {
28
+ current = JSON.parse(readFileSync(target, "utf8"));
29
+ }
30
+ catch {
31
+ throw new SetupError("config_invalid", "Claudeのhook設定JSONを読めません");
32
+ }
33
+ }
34
+ if (!record(current) || (current.hooks !== undefined && !record(current.hooks))) {
35
+ throw new SetupError("config_invalid", "Claudeのhooks設定はobjectである必要があります");
36
+ }
37
+ if (current.disableAllHooks === true)
38
+ throw new SetupError("claude_parent_hooks_disabled", "Claudeのhookが無効です。disableAllHooksをfalseに変更してからsetupしてください");
39
+ const hooks = { ...current.hooks };
40
+ for (const [event, additions] of Object.entries(claudeParentHookEntries(profile, hook))) {
41
+ const previous = hooks[event] ?? [];
42
+ if (!Array.isArray(previous) || previous.some(group => !record(group) || !Array.isArray(group.hooks))) {
43
+ throw new SetupError("config_invalid", `Claudeの${event} hook形式を読めません`);
44
+ }
45
+ // 他製品のhookとmatcherはそのまま保ち、当製品の専用entryだけを更新する。
46
+ const retained = previous.map(group => ({ ...group, hooks: group.hooks.filter(entry => !isClaudeParentHook(profile, entry))
47
+ })).filter(group => group.hooks.length > 0);
48
+ hooks[event] = [...retained, ...additions];
49
+ }
50
+ const next = { ...current, hooks };
51
+ if (isDeepStrictEqual(current, next))
52
+ return "unchanged";
53
+ mkdirSync(dirname(target), { recursive: true });
54
+ const temporary = `${target}.${profile.id}-${randomUUID()}`;
55
+ try {
56
+ writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, flag: "wx" });
57
+ if (existsSync(target))
58
+ copyFileSync(target, `${target}${profile.backup_suffix}`);
59
+ renameSync(temporary, target);
60
+ }
61
+ finally {
62
+ if (existsSync(temporary))
63
+ unlinkSync(temporary);
64
+ }
65
+ if (!isDeepStrictEqual(JSON.parse(readFileSync(target, "utf8")), next)) {
66
+ throw new SetupError("config_readback_failed", "Claudeのhook登録の読戻しが一致しません");
67
+ }
68
+ return "configured";
69
+ }
70
+ function isClaudeParentHook(profile, hook) {
71
+ return record(hook) && hook.type === "command" && Array.isArray(hook.args)
72
+ && typeof hook.args[0] === "string" && endsWithFile(hook.args[0], profile.hooks.claude);
73
+ }
74
+ /** hookを持たない旧版へ戻す前に、当製品の登録だけを除く。 */
75
+ export function removeClaudeParentHooks(profile, file) {
76
+ if (!existsSync(file))
77
+ return "unchanged";
78
+ const target = realpathSync(file);
79
+ const current = JSON.parse(readFileSync(target, "utf8"));
80
+ if (!record(current) || (current.hooks !== undefined && !record(current.hooks))) {
81
+ throw new SetupError("config_invalid", "Claudeのhook設定を読めません");
82
+ }
83
+ if (current.hooks === undefined)
84
+ return "unchanged";
85
+ const hooks = { ...current.hooks };
86
+ for (const event of ["PreToolUse", "PostToolUse", "Stop", "SessionEnd"]) {
87
+ if (hooks[event] === undefined)
88
+ continue;
89
+ if (!Array.isArray(hooks[event]))
90
+ throw new SetupError("config_invalid", "Claudeのhook設定を読めません");
91
+ hooks[event] = hooks[event].map(group => {
92
+ if (!record(group) || !Array.isArray(group.hooks))
93
+ throw new SetupError("config_invalid", "Claudeのhook設定を読めません");
94
+ return { ...group, hooks: group.hooks.filter(entry => !isClaudeParentHook(profile, entry)) };
95
+ }).filter(group => group.hooks.length > 0);
96
+ }
97
+ const next = { ...current, hooks };
98
+ if (isDeepStrictEqual(current, next))
99
+ return "unchanged";
100
+ const temporary = `${target}.${profile.id}-${randomUUID()}`;
101
+ try {
102
+ writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, flag: "wx" });
103
+ copyFileSync(target, `${target}${profile.backup_suffix}`);
104
+ renameSync(temporary, target);
105
+ }
106
+ finally {
107
+ if (existsSync(temporary))
108
+ unlinkSync(temporary);
109
+ }
110
+ if (!isDeepStrictEqual(JSON.parse(readFileSync(target, "utf8")), next))
111
+ throw new SetupError("config_readback_failed", "Claude hook解除の読戻しが一致しません");
112
+ return "removed";
113
+ }
114
+ function shellQuote(value) {
115
+ if (process.platform === "win32")
116
+ return `'${value.replace(/'/g, "''")}'`;
117
+ return `'${value.replace(/'/g, `'"'"'`)}'`;
118
+ }
119
+ export function cursorParentHookCommand(hook) {
120
+ const command = `${shellQuote(hook.command)} ${shellQuote(hook.script)}`;
121
+ return process.platform === "win32" ? `& ${command}` : command;
122
+ }
123
+ function ownsCursorParentHook(profile, hook) {
124
+ return record(hook) && typeof hook.command === "string" && hook.command.includes(profile.hooks.cursor);
125
+ }
126
+ export function mergeCursorParentHooks(profile, file, hook) {
127
+ const target = existsSync(file) ? realpathSync(file) : file;
128
+ let current = { version: 1, hooks: {} };
129
+ if (existsSync(target)) {
130
+ try {
131
+ current = JSON.parse(readFileSync(target, "utf8"));
132
+ }
133
+ catch {
134
+ throw new SetupError("config_invalid", "Cursorのhook設定JSONを読めません");
135
+ }
136
+ }
137
+ else {
138
+ try {
139
+ if (lstatSync(file).isSymbolicLink())
140
+ throw new SetupError("config_invalid", "Cursorのhooks設定symlinkの参照先がありません");
141
+ }
142
+ catch (error) {
143
+ if (error.code !== "ENOENT")
144
+ throw error;
145
+ }
146
+ }
147
+ if (!record(current) || (current.hooks !== undefined && !record(current.hooks))) {
148
+ throw new SetupError("config_invalid", "Cursorのhooks設定はobjectである必要があります");
149
+ }
150
+ const hooks = { ...current.hooks };
151
+ const entry = { command: cursorParentHookCommand(hook), timeout: 15 };
152
+ for (const event of ["afterMCPExecution", "postToolUse"]) {
153
+ const previous = hooks[event] ?? [];
154
+ if (!Array.isArray(previous))
155
+ throw new SetupError("config_invalid", `Cursorの${event} hook形式を読めません`);
156
+ const retained = previous.filter(hook => !ownsCursorParentHook(profile, hook));
157
+ const owned = previous.filter(hook => ownsCursorParentHook(profile, hook));
158
+ if (owned.length === 1 && isDeepStrictEqual(owned[0], entry) && retained.length + 1 === previous.length)
159
+ continue;
160
+ const index = previous.findIndex(hook => ownsCursorParentHook(profile, hook));
161
+ hooks[event] = index < 0 ? [...retained, entry] : previous.map((hook, i) => i === index ? entry : hook).filter((hook, i) => i === index || !ownsCursorParentHook(profile, hook));
162
+ }
163
+ const next = { ...current, version: current.version ?? 1, hooks };
164
+ if (isDeepStrictEqual(current, next))
165
+ return "unchanged";
166
+ mkdirSync(dirname(target), { recursive: true });
167
+ const temporary = `${target}.${profile.id}-${randomUUID()}`;
168
+ try {
169
+ writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, flag: "wx" });
170
+ if (existsSync(target))
171
+ copyFileSync(target, `${target}${profile.backup_suffix}`);
172
+ renameSync(temporary, target);
173
+ }
174
+ finally {
175
+ if (existsSync(temporary))
176
+ unlinkSync(temporary);
177
+ }
178
+ if (!isDeepStrictEqual(JSON.parse(readFileSync(target, "utf8")), next)) {
179
+ throw new SetupError("config_readback_failed", "Cursorのhook登録の読戻しが一致しません");
180
+ }
181
+ return "configured";
182
+ }
183
+ export function removeCursorParentHooks(profile, file) {
184
+ if (!existsSync(file))
185
+ return "unchanged";
186
+ const target = realpathSync(file);
187
+ const current = JSON.parse(readFileSync(target, "utf8"));
188
+ if (!record(current) || (current.hooks !== undefined && !record(current.hooks))) {
189
+ throw new SetupError("config_invalid", "Cursorのhook設定を読めません");
190
+ }
191
+ if (current.hooks === undefined)
192
+ return "unchanged";
193
+ const hooks = { ...current.hooks };
194
+ for (const event of ["afterMCPExecution", "postToolUse"]) {
195
+ if (hooks[event] === undefined)
196
+ continue;
197
+ if (!Array.isArray(hooks[event]))
198
+ throw new SetupError("config_invalid", "Cursorのhook設定を読めません");
199
+ const retained = hooks[event].filter(hook => !ownsCursorParentHook(profile, hook));
200
+ if (retained.length)
201
+ hooks[event] = retained;
202
+ else
203
+ delete hooks[event];
204
+ }
205
+ const next = { ...current, hooks };
206
+ if (isDeepStrictEqual(current, next))
207
+ return "unchanged";
208
+ const temporary = `${target}.${profile.id}-${randomUUID()}`;
209
+ try {
210
+ writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, flag: "wx" });
211
+ copyFileSync(target, `${target}${profile.backup_suffix}`);
212
+ renameSync(temporary, target);
213
+ }
214
+ finally {
215
+ if (existsSync(temporary))
216
+ unlinkSync(temporary);
217
+ }
218
+ if (!isDeepStrictEqual(JSON.parse(readFileSync(target, "utf8")), next)) {
219
+ throw new SetupError("config_readback_failed", "Cursor hook解除の読戻しが一致しません");
220
+ }
221
+ return "removed";
222
+ }
@@ -0,0 +1,18 @@
1
+ export * from "./profile.js";
2
+ export * from "./errors.js";
3
+ export { writeJson0600, writeHookJson, waitForFileState } from "./files.js";
4
+ export { readRuntimeProcesses, parsePosixProcessTable, type RuntimeProcess, type NativeProcessIdentity } from "./process.js";
5
+ export { resolveWindowsPowerShell7, quotePowerShell, windowsPowerShellSync, windowsStartProcessArgumentList } from "./windows.js";
6
+ export { setupNodeExecutable } from "./setup-node.js";
7
+ export { realCodexHome, resolveCodexExecutable, desktopBundledCodex, findDesktopBinary, findWindowsCodexCache, findWindowsCodexBinary, platformDesktopFinder, currentCodexDesktopBinary, type DesktopBinaryFinder, } from "./codex-binary.js";
8
+ export { codexHookConfigSchema, readCodexHookConfig, codexInputDirectory, hookInputSchema, answerDigest, registerCodexHookInput, finishCodexHookSubmission, codexHookDeliveryState, ownedCodexHooks, assertCodexHooksReady, assertCodexHookParentCurrent, type CodexHookConfig, } from "./codex-hook-state.js";
9
+ export { codexParentFromRequest, withCodexReceiver, verifyCodexParent, submitCodexParentAnswer, type CodexParent, type CodexReceiverRuntime, } from "./codex-receiver.js";
10
+ export { runCodexResultHook } from "./codex-hooks.js";
11
+ export { codexHookCommand, mergeCodexParentHooks, verifyCodexHookRegistration, configureCodexSteer, type CodexSteerAction, type CodexSteerResult, type CodexSteerRuntime, } from "./codex-setup.js";
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, type WaitProcess } from "./cursor-receive.js";
15
+ export { claudeParentHookEntries, mergeClaudeParentHooks, removeClaudeParentHooks, cursorParentHookCommand, mergeCursorParentHooks, removeCursorParentHooks, type HookRuntime, } from "./hook-setup.js";
16
+ export { runCodexHookMain, runClaudeHookMain, runCursorHookMain, runCursorReceiveMain, isDirectExecution } from "./hook-main.js";
17
+ export { runChannelReceiveMain } from "./hook-main.js";
18
+ 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 ADDED
@@ -0,0 +1,20 @@
1
+ // aiterm-steer-delivery: Aitermの親配送(steer配送)を製品から使うためのライブラリ。
2
+ // 親AIが作業中ならそのturnへ差し込み、idleなら同じ会話へ普通に届ける。受信方式は親ごとに公式の仕組みを使う。
3
+ export * from "./profile.js";
4
+ export * from "./errors.js";
5
+ export { writeJson0600, writeHookJson, waitForFileState } from "./files.js";
6
+ export { readRuntimeProcesses, parsePosixProcessTable } from "./process.js";
7
+ export { resolveWindowsPowerShell7, quotePowerShell, windowsPowerShellSync, windowsStartProcessArgumentList } from "./windows.js";
8
+ export { setupNodeExecutable } from "./setup-node.js";
9
+ export { realCodexHome, resolveCodexExecutable, desktopBundledCodex, findDesktopBinary, findWindowsCodexCache, findWindowsCodexBinary, platformDesktopFinder, currentCodexDesktopBinary, } from "./codex-binary.js";
10
+ export { codexHookConfigSchema, readCodexHookConfig, codexInputDirectory, hookInputSchema, answerDigest, registerCodexHookInput, finishCodexHookSubmission, codexHookDeliveryState, ownedCodexHooks, assertCodexHooksReady, assertCodexHookParentCurrent, } from "./codex-hook-state.js";
11
+ export { codexParentFromRequest, withCodexReceiver, verifyCodexParent, submitCodexParentAnswer, } from "./codex-receiver.js";
12
+ export { runCodexResultHook } from "./codex-hooks.js";
13
+ export { codexHookCommand, mergeCodexParentHooks, verifyCodexHookRegistration, configureCodexSteer, } from "./codex-setup.js";
14
+ export { claudeParentSchema, prepareClaudeHookRequest, claudeParentFromRequest, verifyClaudeParent, bindClaudeParentDelivery, closeClaudeParentSession, submitClaudeParentAnswer, runClaudeResultHook, } from "./claude-receiver.js";
15
+ export { cursorParentSchema, isCursorMcpClient, cursorHooksFile, cursorParentHooksRegistered, verifyCursorParent, cursorParentFromRequest, prepareCursorDelivery, submitCursorParentAnswer, handleCursorHook, receiveCursorAnswer, } from "./cursor-receiver.js";
16
+ export { cursorReceiveProcess, runCursorReceive } from "./cursor-receive.js";
17
+ export { claudeParentHookEntries, mergeClaudeParentHooks, removeClaudeParentHooks, cursorParentHookCommand, mergeCursorParentHooks, removeCursorParentHooks, } from "./hook-setup.js";
18
+ export { runCodexHookMain, runClaudeHookMain, runCursorHookMain, runCursorReceiveMain, isDirectExecution } from "./hook-main.js";
19
+ export { runChannelReceiveMain } from "./hook-main.js";
20
+ export { openChannel, readChannel, channelClosed, closeChannel, sendToChannel, channelDeliveryState, withdrawFromChannel, runClaudeChannelWaiter, closeClaudeSessionChannels, channelIdFromResult, channelMarker, handleCursorChannelHook, channelReceiveProcess, receiveFromChannel, ChannelError, } from "./channel.js";
@@ -0,0 +1,17 @@
1
+ export interface NativeProcessIdentity {
2
+ pid: number;
3
+ process_group_id: number | null;
4
+ started_identity: string;
5
+ argv_digest: string;
6
+ }
7
+ export interface RuntimeProcess extends NativeProcessIdentity {
8
+ executable?: string;
9
+ parent_pid: number;
10
+ cpu_seconds: number;
11
+ command: string;
12
+ stopped: boolean | null;
13
+ }
14
+ export declare function processIdentity(process: RuntimeProcess): NativeProcessIdentity;
15
+ export declare function parseCpuTime(value: string): number;
16
+ export declare function parsePosixProcessTable(text: string): RuntimeProcess[];
17
+ export declare function readRuntimeProcesses(): RuntimeProcess[];