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,145 @@
1
+ // Codex親への配送。公式App Serverのキュー(thread/queue/add)へ一度だけ入れる。
2
+ // 親が作業中なら製品の同期hook(PostToolUse/Stop)が同じturnへ取り込み、idleなら公式キューが通常の入力として届ける。
3
+ import { spawn } from "node:child_process";
4
+ import { createInterface } from "node:readline";
5
+ import * as path from "node:path";
6
+ import { CodexDeliveryError } from "./errors.js";
7
+ import { codexHookDirectory } from "./profile.js";
8
+ import { currentCodexDesktopBinary, realCodexHome, resolveCodexExecutable } from "./codex-binary.js";
9
+ import { finishCodexHookSubmission, assertCodexHookParentCurrent, assertCodexHooksReady, readCodexHookConfig, registerCodexHookInput } from "./codex-hook-state.js";
10
+ /** modelの引数ではなく、CodexがMCP要求へ付けるmetadataだけを宛先にする。 */
11
+ export function codexParentFromRequest(clientName, metadata) {
12
+ if (clientName !== "codex-mcp-client")
13
+ return null;
14
+ const threadId = metadata?.threadId;
15
+ if (typeof threadId !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(threadId)) {
16
+ throw new CodexDeliveryError("CODEX_PARENT_ID_UNAVAILABLE", "MCP要求に親のthreadIdがありません。対応するCodexへ更新してください");
17
+ }
18
+ return { thread_id: threadId, codex_home: path.resolve(realCodexHome()) };
19
+ }
20
+ export async function withCodexReceiver(profile, parent, action, runtime = {}) {
21
+ const config = runtime.executable ? null : readCodexHookConfig(profile);
22
+ const executable = runtime.executable ?? (config?.enabled ? await currentCodexDesktopBinary(profile, config) : null) ?? resolveCodexExecutable();
23
+ if (!executable)
24
+ throw new CodexDeliveryError("CODEX_RECEIVER_UNAVAILABLE", "Codexの実行ファイルを確認できません");
25
+ const child = spawn(executable, runtime.args ?? ["app-server", "--listen", "stdio://"], {
26
+ stdio: ["pipe", "pipe", "ignore"],
27
+ env: { ...process.env, CODEX_HOME: parent.codex_home },
28
+ windowsHide: true,
29
+ });
30
+ const pending = new Map();
31
+ let sequence = 0;
32
+ let stopped = false;
33
+ let transportError = null;
34
+ const failTransport = (message) => {
35
+ transportError = message;
36
+ for (const item of pending.values()) {
37
+ clearTimeout(item.timer);
38
+ item.reject(new CodexDeliveryError("CODEX_RECEIVER_TRANSPORT_FAILED", message, item.method === "thread/queue/add"));
39
+ }
40
+ pending.clear();
41
+ };
42
+ child.on("error", (error) => failTransport(`Codexを起動できません(${error.code ?? "unknown"})`));
43
+ child.stdin.on("error", (error) => failTransport(`Codexへの書込みに失敗しました(${error.code ?? "unknown"})`));
44
+ const exited = new Promise((resolve) => child.once("close", (code, signal) => {
45
+ if (!stopped)
46
+ failTransport(`Codexの接続が終了しました(exit=${code}, signal=${signal})`);
47
+ resolve();
48
+ }));
49
+ const reader = createInterface({ input: child.stdout });
50
+ reader.on("line", (line) => {
51
+ let value;
52
+ try {
53
+ value = JSON.parse(line);
54
+ }
55
+ catch {
56
+ failTransport("Codexが不正なJSON応答を返しました");
57
+ return;
58
+ }
59
+ const item = pending.get(value?.id);
60
+ if (!item)
61
+ return;
62
+ clearTimeout(item.timer);
63
+ pending.delete(value.id);
64
+ if (value.error) {
65
+ item.reject(new CodexDeliveryError("CODEX_RECEIVER_REJECTED", typeof value.error.message === "string" ? value.error.message : "公式受信口が要求を拒否しました"));
66
+ }
67
+ else if ("result" in value)
68
+ item.resolve(value.result);
69
+ else
70
+ item.reject(new CodexDeliveryError("CODEX_RECEIVER_INVALID_RESPONSE", "公式受信口の応答にresultがありません", item.method === "thread/queue/add"));
71
+ });
72
+ const request = (method, params) => new Promise((resolve, reject) => {
73
+ if (transportError) {
74
+ reject(new CodexDeliveryError("CODEX_RECEIVER_TRANSPORT_FAILED", transportError));
75
+ return;
76
+ }
77
+ const id = ++sequence;
78
+ const timer = setTimeout(() => {
79
+ pending.delete(id);
80
+ reject(new CodexDeliveryError("CODEX_RECEIVER_TIMEOUT", `${method}の応答を確認できません`, method === "thread/queue/add"));
81
+ }, runtime.timeout_ms ?? 15_000);
82
+ pending.set(id, { resolve, reject, timer, method });
83
+ child.stdin.write(JSON.stringify({ id, method, params }) + "\n");
84
+ });
85
+ try {
86
+ await request("initialize", { clientInfo: { name: profile.codex_client_name, version: "1" }, capabilities: { experimentalApi: true } });
87
+ child.stdin.write(JSON.stringify({ method: "initialized" }) + "\n");
88
+ return await action(request);
89
+ }
90
+ finally {
91
+ stopped = true;
92
+ for (const item of pending.values())
93
+ clearTimeout(item.timer);
94
+ pending.clear();
95
+ child.stdin.end();
96
+ // stdio終了を公式processへ伝える。終了しない外部processだけを明示的に停止する。
97
+ const terminate = setTimeout(() => child.kill("SIGKILL"), 2_000);
98
+ await exited;
99
+ clearTimeout(terminate);
100
+ reader.close();
101
+ }
102
+ }
103
+ /** 送る前に、同じstoreの宛先と公式キューの対応を確認する。本文は保存・表示しない。 */
104
+ export async function verifyCodexParent(profile, parent, runtime) {
105
+ await withCodexReceiver(profile, parent, async (request) => {
106
+ const response = await request("thread/read", { threadId: parent.thread_id, includeTurns: false });
107
+ if (response?.thread?.id !== parent.thread_id) {
108
+ throw new CodexDeliveryError("CODEX_PARENT_UNAVAILABLE", "同じCodex環境で親threadを確認できません");
109
+ }
110
+ const subagent = response.thread.source?.subAgent;
111
+ if (subagent && typeof subagent === "object" && "thread_spawn" in subagent) {
112
+ throw new CodexDeliveryError("CODEX_PARENT_UNSUPPORTED", "Codexのnative sub-agentは外部processからのキュー入力を受け付けません");
113
+ }
114
+ await request("thread/queue/list", { threadId: parent.thread_id, limit: 1 });
115
+ const config = runtime ? (runtime.hook_directory ? readCodexHookConfig(profile, runtime.hook_directory) : null) : readCodexHookConfig(profile);
116
+ if (config?.enabled) {
117
+ assertCodexHookParentCurrent(profile, config);
118
+ assertCodexHooksReady(profile, await request("hooks/list", { cwds: [response.thread.cwd] }), config.command, path.join(parent.codex_home, "hooks.json"));
119
+ }
120
+ }, runtime);
121
+ }
122
+ /** 確定した本文を公式キューへ一度だけ入れる。受付IDを返す。受付の成否が不明な失敗はoutcome_unknownで区別する。 */
123
+ export async function submitCodexParentAnswer(profile, parent, deliveryId, text, runtime) {
124
+ const root = runtime ? runtime.hook_directory : codexHookDirectory(profile);
125
+ const hook = root && readCodexHookConfig(profile, root)?.enabled;
126
+ if (hook)
127
+ registerCodexHookInput(parent.codex_home, parent.thread_id, deliveryId, text, root);
128
+ try {
129
+ return await withCodexReceiver(profile, parent, async (request) => {
130
+ const result = await request("thread/queue/add", {
131
+ threadId: parent.thread_id,
132
+ input: [{ type: "text", text, text_elements: [] }],
133
+ clientUserMessageId: deliveryId,
134
+ });
135
+ if (typeof result?.queuedSubmission?.id !== "string") {
136
+ throw new CodexDeliveryError("CODEX_RECEIVER_INVALID_RESPONSE", "キューの受付IDを確認できません", true);
137
+ }
138
+ return { queued_submission_id: result.queuedSubmission.id };
139
+ }, runtime);
140
+ }
141
+ finally {
142
+ if (hook)
143
+ finishCodexHookSubmission(parent.codex_home, parent.thread_id, deliveryId, root);
144
+ }
145
+ }
@@ -0,0 +1,35 @@
1
+ import { type RuntimeProcess } from "./process.js";
2
+ import { type ProductProfile } from "./profile.js";
3
+ import { type CodexHookConfig } from "./codex-hook-state.js";
4
+ export type CodexSteerAction = "enable" | "disable" | "status";
5
+ export type CodexSteerResult = {
6
+ status: "ready" | "disabled" | "restart_required" | "unsupported" | "failed";
7
+ reason_code?: string;
8
+ };
9
+ export declare function codexHookCommand(node: string, hook: string, directory: string, platform?: NodeJS.Platform, powershell?: () => string): string;
10
+ export declare function mergeCodexParentHooks(profile: ProductProfile, file: string, command: string | null, previousCommand?: string): boolean;
11
+ export type CodexSteerRuntime = {
12
+ platform: string;
13
+ directory: string;
14
+ codex_home: string;
15
+ node: string;
16
+ hook: string;
17
+ findBinary: () => string;
18
+ processes: () => RuntimeProcess[];
19
+ /** 製品が以前使っていた別方式の選択。新規の製品は持たない。binaryは旧方式が起動していたCodex。 */
20
+ legacy: () => {
21
+ enabled: boolean;
22
+ binary?: string;
23
+ } | null;
24
+ disableLegacy: () => Promise<CodexSteerResult>;
25
+ verify: (config: CodexHookConfig, approve: boolean) => Promise<void>;
26
+ /** 設定を保存する前にhook directoryを整える(WindowsのACL等)。 */
27
+ prepareDirectory: (directory: string) => void;
28
+ /** Windowsでhookを起動するPowerShell 7の絶対path。 */
29
+ powershell: () => string;
30
+ };
31
+ export declare function verifyCodexHookRegistration(profile: ProductProfile, config: CodexHookConfig, approve: boolean, directory?: string): Promise<void>;
32
+ /** hookは製品が同梱するCodex hook入口(パッケージのrunCodexResultHookを呼ぶ小さなファイル)の絶対path。 */
33
+ export declare function configureCodexSteer(profile: ProductProfile, action: CodexSteerAction | undefined, overrides: Partial<CodexSteerRuntime> & {
34
+ hook: string;
35
+ }): Promise<CodexSteerResult>;
@@ -0,0 +1,160 @@
1
+ // Steerの正規導入。公式hookを登録・承認してから、製品の旧方式(あれば)を解除する。
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { currentCodexDesktopBinary, platformDesktopFinder, realCodexHome } from "./codex-binary.js";
6
+ import { withCodexReceiver } from "./codex-receiver.js";
7
+ import { SetupError } from "./errors.js";
8
+ import { setupNodeExecutable } from "./setup-node.js";
9
+ import { readRuntimeProcesses } from "./process.js";
10
+ import { resolveWindowsPowerShell7, quotePowerShell } from "./windows.js";
11
+ import { codexHookDirectory } from "./profile.js";
12
+ import { assertCodexHooksReady, ownedCodexHooks, readCodexHookConfig, writeHookJson } from "./codex-hook-state.js";
13
+ export function codexHookCommand(node, hook, directory, platform = process.platform, powershell = () => resolveWindowsPowerShell7()) {
14
+ if (platform === "win32") {
15
+ const script = `& ${[node, hook, directory].map(quotePowerShell).join(" ")}; exit $LASTEXITCODE`;
16
+ // Codexは利用中のPowerShellでhookを評価する。引用した実行パスには呼出し演算子が必要。
17
+ return `& ${quotePowerShell(powershell())} -NoLogo -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script, "utf16le").toString("base64")}`;
18
+ }
19
+ return [node, hook, directory].map(value => "'" + value.replace(/'/g, "'\"'\"'") + "'").join(" ");
20
+ }
21
+ export function mergeCodexParentHooks(profile, file, command, previousCommand) {
22
+ if (!fs.existsSync(file)) {
23
+ try {
24
+ if (fs.lstatSync(file).isSymbolicLink())
25
+ throw new SetupError("codex_hook_config_invalid", "hook設定symlinkの参照先がありません");
26
+ }
27
+ catch (error) {
28
+ if (error.code !== "ENOENT")
29
+ throw error;
30
+ }
31
+ }
32
+ const target = fs.existsSync(file) ? fs.realpathSync(file) : file;
33
+ let current = {};
34
+ if (fs.existsSync(target)) {
35
+ try {
36
+ current = JSON.parse(fs.readFileSync(target, "utf8"));
37
+ }
38
+ catch {
39
+ throw new SetupError("codex_hook_config_invalid", "Codexのhook設定JSONを読めません");
40
+ }
41
+ }
42
+ const object = (value) => value && typeof value === "object" && !Array.isArray(value);
43
+ if (!object(current) || (current.hooks !== undefined && !object(current.hooks)))
44
+ throw new SetupError("codex_hook_config_invalid", "Codexのhooks設定を読めません");
45
+ const hooks = { ...current.hooks };
46
+ for (const event of ["PostToolUse", "Stop"]) {
47
+ const groups = hooks[event] ?? [];
48
+ if (!Array.isArray(groups) || groups.some(group => !object(group) || !Array.isArray(group.hooks)))
49
+ throw new SetupError("codex_hook_config_invalid", `${event}のhook設定を読めません`);
50
+ // 既存の位置で置換する。末尾へ移すと同じ設定の再導入でも変更扱いになり、
51
+ // 稼働中のCodexへ不要な再起動を要求してしまう。
52
+ hooks[event] = [];
53
+ let insertionIndex = null;
54
+ for (const group of groups) {
55
+ const remaining = group.hooks.filter((hook) => !(hook?.type === "command" && ((command !== null && hook.command === command) || (previousCommand && hook.command === previousCommand))));
56
+ if (remaining.length !== group.hooks.length && insertionIndex === null)
57
+ insertionIndex = hooks[event].length;
58
+ if (remaining.length)
59
+ hooks[event].push({ ...group, hooks: remaining });
60
+ }
61
+ if (command !== null)
62
+ hooks[event].splice(insertionIndex ?? hooks[event].length, 0, { ...(event === "PostToolUse" ? { matcher: ".*" } : {}),
63
+ hooks: [{ type: "command", command, timeout: 20, ...(event === "PostToolUse" ? { additionalContextLimit: 0 } : {}) }] });
64
+ if (!hooks[event].length)
65
+ delete hooks[event];
66
+ }
67
+ const next = { ...current, hooks };
68
+ if (isDeepStrictEqual(current, next))
69
+ return false;
70
+ if (fs.existsSync(target))
71
+ fs.copyFileSync(target, `${target}${profile.backup_suffix}`);
72
+ writeHookJson(target, next);
73
+ if (!isDeepStrictEqual(JSON.parse(fs.readFileSync(target, "utf8")), next))
74
+ throw new SetupError("codex_hook_readback_failed", "Codex hookの読戻しが一致しません");
75
+ return true;
76
+ }
77
+ export async function verifyCodexHookRegistration(profile, config, approve, directory = codexHookDirectory(profile)) {
78
+ fs.accessSync(config.node, fs.constants.X_OK);
79
+ fs.accessSync(config.hook, fs.constants.R_OK);
80
+ const file = path.join(config.codex_home, "hooks.json");
81
+ await withCodexReceiver(profile, { thread_id: "00000000-0000-4000-8000-000000000000", codex_home: config.codex_home }, async (request) => {
82
+ const list = () => request("hooks/list", { cwds: [config.codex_home] });
83
+ const hooks = ownedCodexHooks(profile, await list(), config.command, file);
84
+ if (approve) {
85
+ const edits = hooks.filter(hook => !hook.enabled || hook.trustStatus !== "trusted").flatMap(hook => {
86
+ if (typeof hook.key !== "string" || typeof hook.currentHash !== "string")
87
+ throw new SetupError("codex_hook_schema_unknown", "公式hookの承認情報を認識できません");
88
+ const key = `hooks.state.${JSON.stringify(hook.key)}`;
89
+ return [
90
+ { keyPath: `${key}.trusted_hash`, value: hook.currentHash, mergeStrategy: "replace" },
91
+ { keyPath: `${key}.enabled`, value: true, mergeStrategy: "replace" },
92
+ ];
93
+ });
94
+ if (edits.length)
95
+ await request("config/batchWrite", { edits, filePath: path.join(config.codex_home, "config.toml") });
96
+ }
97
+ assertCodexHooksReady(profile, await list(), config.command, file);
98
+ }, { executable: await currentCodexDesktopBinary(profile, config, { directory }) });
99
+ }
100
+ /** hookは製品が同梱するCodex hook入口(パッケージのrunCodexResultHookを呼ぶ小さなファイル)の絶対path。 */
101
+ export async function configureCodexSteer(profile, action = "status", overrides) {
102
+ const directory = overrides.directory ?? codexHookDirectory(profile);
103
+ const runtime = { platform: process.platform, directory, codex_home: realCodexHome(),
104
+ node: process.execPath, findBinary: platformDesktopFinder(),
105
+ processes: readRuntimeProcesses, legacy: () => null,
106
+ disableLegacy: async () => ({ status: "disabled" }), verify: (config, approve) => verifyCodexHookRegistration(profile, config, approve, directory),
107
+ prepareDirectory: () => undefined, powershell: () => resolveWindowsPowerShell7(), ...overrides };
108
+ const previous = readCodexHookConfig(profile, runtime.directory);
109
+ const legacy = runtime.legacy();
110
+ const file = path.join(action === "disable" && previous ? previous.codex_home : runtime.codex_home, "hooks.json");
111
+ const save = (config) => {
112
+ runtime.prepareDirectory(runtime.directory);
113
+ writeHookJson(path.join(runtime.directory, "config.json"), config);
114
+ };
115
+ const needsRestart = (config) => runtime.processes().some(process => config.stale_processes.some(stale => stale.pid === process.pid && stale.started_identity === process.started_identity));
116
+ if (action === "status") {
117
+ if (!previous?.enabled)
118
+ return legacy?.enabled ? { status: "failed", reason_code: "codex_steer_migration_required" } : { status: "disabled" };
119
+ await runtime.verify(previous, false);
120
+ return legacy?.enabled || needsRestart(previous) ? { status: "restart_required", reason_code: "codex_restart_required" } : { status: "ready" };
121
+ }
122
+ if (action === "disable") {
123
+ if (previous?.enabled) {
124
+ mergeCodexParentHooks(profile, file, null, previous.command);
125
+ save({ ...previous, enabled: false });
126
+ }
127
+ if (legacy?.enabled)
128
+ return runtime.disableLegacy();
129
+ return previous?.enabled ? { status: "restart_required", reason_code: "codex_restart_required" } : { status: "disabled" };
130
+ }
131
+ if (!["darwin", "win32"].includes(runtime.platform))
132
+ return { status: "unsupported", reason_code: "codex_steer_platform_unsupported" };
133
+ if (previous?.enabled && fs.realpathSync(previous.codex_home) !== fs.realpathSync(runtime.codex_home))
134
+ throw new SetupError("codex_steer_configuration_conflict", "別のCODEX_HOMEでSteerが有効です。先に既存の選択を解除してください");
135
+ const node = setupNodeExecutable(runtime.node);
136
+ fs.accessSync(node, fs.constants.X_OK);
137
+ fs.accessSync(runtime.hook, fs.constants.R_OK);
138
+ const binary = runtime.findBinary();
139
+ const command = codexHookCommand(node, runtime.hook, runtime.directory, runtime.platform, runtime.powershell);
140
+ const changed = mergeCodexParentHooks(profile, file, command, previous?.command);
141
+ // hook導入前から動いているCodexを再起動待ちとして記録する。今のDesktop、前回の登録、旧方式が起動したCodexを、
142
+ // 引用符付きのコマンド行も含めて照合する(Windowsは区切りと大文字小文字を揃える)。
143
+ const normalize = (value) => runtime.platform === "win32" ? value.replaceAll("/", "\\").toLowerCase() : value;
144
+ const binaries = [binary, legacy?.binary, previous?.binary].filter((value) => !!value).map(normalize);
145
+ const stale = !previous?.enabled || changed || legacy?.enabled
146
+ ? runtime.processes().filter(row => binaries.some(candidate => {
147
+ const command = normalize(row.command);
148
+ return (row.executable !== undefined && normalize(row.executable) === candidate) || command === candidate || command === `"${candidate}"`
149
+ || command.startsWith(candidate + " ") || command.startsWith(`"${candidate}" `);
150
+ })).map(({ pid, started_identity }) => ({ pid, started_identity }))
151
+ : previous.stale_processes;
152
+ const config = { schema: profile.codex_hook_schema, enabled: true,
153
+ codex_home: runtime.codex_home, binary, command, node, hook: runtime.hook, stale_processes: stale };
154
+ await runtime.verify(config, true);
155
+ // 解除が中断しても、次のenableで移行を続行できるよう所有情報を先に保存する。
156
+ save(config);
157
+ if (legacy?.enabled)
158
+ await runtime.disableLegacy();
159
+ return needsRestart(config) ? { status: "restart_required", reason_code: "codex_restart_required" } : { status: "ready" };
160
+ }
@@ -0,0 +1,9 @@
1
+ export interface WaitProcess {
2
+ executable: string;
3
+ args: string[];
4
+ windows_start_process_argument_list: string | null;
5
+ }
6
+ /** 親の背景process APIへそのまま渡す起動情報。scriptは製品のCursor受信入口の絶対path。 */
7
+ export declare function cursorReceiveProcess(script: string, deliveryId: string, executable?: string): WaitProcess;
8
+ /** 受信入口の本体。結果を1行のJSONでstdoutへ出し、exit codeを返す(0=受取、3=期限切れ、1=誤り)。 */
9
+ export declare function runCursorReceive(hookRoot: string, argv: string[], emit?: (value: unknown) => void, usage?: string): Promise<number>;
@@ -0,0 +1,31 @@
1
+ // Cursor親がidleのとき、背景で起動して回答本文の到着を待つ受け口。
2
+ // 起動するファイルは製品が同梱する入口で、そこからrunCursorReceiveを呼ぶ。
3
+ import { receiveCursorAnswer } from "./cursor-receiver.js";
4
+ import { windowsStartProcessArgumentList } from "./windows.js";
5
+ /** 親の背景process APIへそのまま渡す起動情報。scriptは製品のCursor受信入口の絶対path。 */
6
+ export function cursorReceiveProcess(script, deliveryId, executable = process.execPath) {
7
+ const args = [script, "--delivery", deliveryId];
8
+ return {
9
+ executable,
10
+ args,
11
+ windows_start_process_argument_list: process.platform === "win32" ? windowsStartProcessArgumentList(args) : null,
12
+ };
13
+ }
14
+ /** 受信入口の本体。結果を1行のJSONでstdoutへ出し、exit codeを返す(0=受取、3=期限切れ、1=誤り)。 */
15
+ export async function runCursorReceive(hookRoot, argv, emit = value => { process.stdout.write(JSON.stringify(value) + "\n"); }, usage = "usage: cursor-parent-receive --delivery <uuid>") {
16
+ if (argv.length !== 2 || argv[0] !== "--delivery" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(argv[1])) {
17
+ emit({ ok: false, code: "CURSOR_PARENT_RECEIVE_USAGE", message: usage });
18
+ return 1;
19
+ }
20
+ const result = await receiveCursorAnswer(hookRoot, argv[1]);
21
+ if (result.outcome === "timeout") {
22
+ emit({ delivery_id: argv[1], outcome: "timeout" });
23
+ return 3;
24
+ }
25
+ if (result.outcome === "delivered_by_hook") {
26
+ emit({ delivery_id: argv[1], outcome: "delivered_by_hook" });
27
+ return 0;
28
+ }
29
+ emit({ delivery_id: argv[1], outcome: "delivered", text: result.text });
30
+ return 0;
31
+ }
@@ -0,0 +1,29 @@
1
+ import { z } from "zod";
2
+ import type { ProductProfile } from "./profile.js";
3
+ export declare const cursorParentSchema: z.ZodObject<{
4
+ kind: z.ZodLiteral<"cursor">;
5
+ hook_root: z.ZodString;
6
+ }, z.core.$strict>;
7
+ export type CursorParent = z.infer<typeof cursorParentSchema>;
8
+ export declare function isCursorMcpClient(clientName: string | undefined): boolean;
9
+ export declare function cursorHooksFile(home?: string): string;
10
+ export declare function cursorParentHooksRegistered(profile: ProductProfile, document: unknown): boolean;
11
+ export declare function verifyCursorParent(profile: ProductProfile, parent: CursorParent, hooksFile?: string): void;
12
+ export declare function cursorParentFromRequest(profile: ProductProfile, clientName: string | undefined, options: {
13
+ hookRoot: string;
14
+ hooksFile?: string;
15
+ }): CursorParent | null;
16
+ export declare function prepareCursorDelivery(parent: CursorParent, deliveryId: string): void;
17
+ export declare function submitCursorParentAnswer(parent: CursorParent, deliveryId: string, text: string, timeoutMs?: number): Promise<{
18
+ queued_submission_id: null;
19
+ }>;
20
+ export declare function handleCursorHook(profile: ProductProfile, raw: string, hookRoot: string): Promise<Record<string, unknown>>;
21
+ export type CursorReceiveResult = {
22
+ outcome: "delivered";
23
+ text: string;
24
+ } | {
25
+ outcome: "delivered_by_hook";
26
+ } | {
27
+ outcome: "timeout";
28
+ };
29
+ export declare function receiveCursorAnswer(hookRoot: string, deliveryId: string, timeoutMs?: number): Promise<CursorReceiveResult>;
@@ -0,0 +1,242 @@
1
+ // Cursor親の受信口。会話への差し込みはCursor公式hookのadditional_context、idle時の起床は受け口processが担う。
2
+ // MCP要求に会話IDは届かないので、tool結果に載せた配送IDを公式hookが読み、実際のconversation_idへ結ぶ。
3
+ import * as fs from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import * as path from "node:path";
6
+ import { z } from "zod";
7
+ import { waitForFileState, writeJson0600 } from "./files.js";
8
+ import { CursorDeliveryError } from "./errors.js";
9
+ export const cursorParentSchema = z.object({
10
+ kind: z.literal("cursor"),
11
+ hook_root: z.string(),
12
+ }).strict();
13
+ const deliveryIdSchema = z.string().uuid();
14
+ export function isCursorMcpClient(clientName) {
15
+ if (clientName === undefined)
16
+ return false;
17
+ return clientName === "cursor-vscode" || clientName.startsWith("cursor-vscode ");
18
+ }
19
+ export function cursorHooksFile(home = process.env.HOME ?? homedir()) {
20
+ return path.join(process.env.CURSOR_HOME ?? path.join(home, ".cursor"), "hooks.json");
21
+ }
22
+ export function cursorParentHooksRegistered(profile, document) {
23
+ if (document === null || typeof document !== "object" || Array.isArray(document))
24
+ return false;
25
+ const hooks = document.hooks;
26
+ if (hooks === null || typeof hooks !== "object" || Array.isArray(hooks))
27
+ return false;
28
+ const owns = (event) => {
29
+ const list = hooks[event];
30
+ return Array.isArray(list) && list.some(entry => {
31
+ if (entry === null || typeof entry !== "object")
32
+ return false;
33
+ const command = entry.command;
34
+ return typeof command === "string" && command.includes(profile.hooks.cursor);
35
+ });
36
+ };
37
+ return owns("postToolUse") && owns("afterMCPExecution");
38
+ }
39
+ export function verifyCursorParent(profile, parent, hooksFile = cursorHooksFile()) {
40
+ cursorParentSchema.parse(parent);
41
+ let document;
42
+ try {
43
+ document = JSON.parse(fs.readFileSync(hooksFile, "utf8"));
44
+ }
45
+ catch {
46
+ throw new CursorDeliveryError("CURSOR_PARENT_HOOK_UNAVAILABLE", `Cursorのhookが登録されていません。${profile.setup_command}を実行してください`);
47
+ }
48
+ if (!cursorParentHooksRegistered(profile, document)) {
49
+ throw new CursorDeliveryError("CURSOR_PARENT_HOOK_UNAVAILABLE", `Cursorのhookが登録されていません。${profile.setup_command}を実行してください`);
50
+ }
51
+ }
52
+ export function cursorParentFromRequest(profile, clientName, options) {
53
+ if (!isCursorMcpClient(clientName))
54
+ return null;
55
+ const parent = { kind: "cursor", hook_root: options.hookRoot };
56
+ verifyCursorParent(profile, parent, options.hooksFile);
57
+ return parent;
58
+ }
59
+ function deliveryDir(parent, deliveryId) {
60
+ return path.join(parent.hook_root, "deliveries", deliveryIdSchema.parse(deliveryId));
61
+ }
62
+ export function prepareCursorDelivery(parent, deliveryId) {
63
+ cursorParentSchema.parse(parent);
64
+ fs.mkdirSync(deliveryDir(parent, deliveryId), { recursive: true, mode: 0o700 });
65
+ }
66
+ export async function submitCursorParentAnswer(parent, deliveryId, text, timeoutMs = 86_400_000) {
67
+ const dir = deliveryDir(parent, deliveryId);
68
+ writeJson0600(path.join(dir, "answer.json"), { delivery_id: deliveryId, text });
69
+ try {
70
+ await waitForFileState(dir, () => fs.existsSync(path.join(dir, "claim.json")) ? true : undefined, timeoutMs);
71
+ }
72
+ catch (error) {
73
+ if (error instanceof Error && error.message === "WAIT_FOR_FILE_TIMEOUT") {
74
+ throw new CursorDeliveryError("CURSOR_PARENT_DELIVERY_UNCLAIMED", "Cursor親が時間内に回答を受け取りませんでした。回答は保存したままです");
75
+ }
76
+ throw error;
77
+ }
78
+ return { queued_submission_id: null };
79
+ }
80
+ function conversationId(value) {
81
+ if (typeof value !== "string" || value.length === 0 || value.length > 200)
82
+ return null;
83
+ if (value.includes("/") || value.includes("\\") || value.includes(".."))
84
+ return null;
85
+ return value;
86
+ }
87
+ function parseJson(value) {
88
+ try {
89
+ return JSON.parse(value);
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ }
95
+ function deliveryIdFromResult(value, depth = 0) {
96
+ if (depth > 3 || value === null || value === undefined)
97
+ return null;
98
+ const parsed = typeof value === "string" ? parseJson(value) : value;
99
+ if (parsed === null || typeof parsed !== "object")
100
+ return null;
101
+ const record = parsed;
102
+ const structured = record.structuredContent;
103
+ const carrier = structured !== null && typeof structured === "object" ? structured : record;
104
+ const parentDelivery = carrier.parent_delivery;
105
+ if (parentDelivery !== null && typeof parentDelivery === "object") {
106
+ const id = parentDelivery.delivery_id;
107
+ if (typeof id === "string" && deliveryIdSchema.safeParse(id).success)
108
+ return id;
109
+ }
110
+ if (depth === 0 && Array.isArray(record.content)) {
111
+ for (const entry of record.content) {
112
+ if (entry !== null && typeof entry === "object" && entry.type === "text") {
113
+ const text = entry.text;
114
+ if (typeof text === "string") {
115
+ const id = deliveryIdFromResult(text, depth + 1) ?? deliveryIdInText(text);
116
+ if (id)
117
+ return id;
118
+ }
119
+ }
120
+ }
121
+ }
122
+ return null;
123
+ }
124
+ function deliveryIdInText(text) {
125
+ for (const line of text.split("\n")) {
126
+ const match = /^delivery_id=([0-9a-f-]{36})$/i.exec(line.trim());
127
+ if (match && deliveryIdSchema.safeParse(match[1]).success)
128
+ return match[1];
129
+ }
130
+ return null;
131
+ }
132
+ function toolBaseName(profile, name) {
133
+ const tail = name.split(/[:.]/).pop() ?? name;
134
+ const prefix = `mcp__${profile.mcp_server}__`;
135
+ return tail.startsWith(prefix) ? tail.slice(prefix.length) : tail;
136
+ }
137
+ function claim(dir, channel) {
138
+ try {
139
+ fs.writeFileSync(path.join(dir, "claim.json"), JSON.stringify({ channel, at: new Date().toISOString() }), { flag: "wx", mode: 0o600 });
140
+ return true;
141
+ }
142
+ catch (error) {
143
+ if (error.code === "EEXIST")
144
+ return false;
145
+ throw error;
146
+ }
147
+ }
148
+ function bind(hookRoot, deliveryId, conv) {
149
+ const dir = path.join(hookRoot, "deliveries", deliveryId);
150
+ if (!fs.existsSync(dir))
151
+ return;
152
+ const bindFile = path.join(dir, "bind.json");
153
+ if (!fs.existsSync(bindFile)) {
154
+ writeJson0600(bindFile, { conversation_id: conv, created_at: new Date().toISOString() });
155
+ }
156
+ const indexDir = path.join(hookRoot, "conversations", conv);
157
+ fs.mkdirSync(indexDir, { recursive: true, mode: 0o700 });
158
+ const index = path.join(indexDir, deliveryId);
159
+ if (!fs.existsSync(index))
160
+ fs.writeFileSync(index, "", { mode: 0o600 });
161
+ }
162
+ function inject(hookRoot, conv) {
163
+ const indexDir = path.join(hookRoot, "conversations", conv);
164
+ if (!fs.existsSync(indexDir))
165
+ return [];
166
+ const pending = fs.readdirSync(indexDir).flatMap(deliveryId => {
167
+ const dir = path.join(hookRoot, "deliveries", deliveryId);
168
+ const answerFile = path.join(dir, "answer.json");
169
+ const bindFile = path.join(dir, "bind.json");
170
+ if (!fs.existsSync(answerFile) || !fs.existsSync(bindFile))
171
+ return [];
172
+ const answer = z.object({ delivery_id: z.string(), text: z.string() }).parse(JSON.parse(fs.readFileSync(answerFile, "utf8")));
173
+ const bound = z.object({ conversation_id: z.string(), created_at: z.string() }).parse(JSON.parse(fs.readFileSync(bindFile, "utf8")));
174
+ if (answer.delivery_id !== deliveryId || bound.conversation_id !== conv)
175
+ return [];
176
+ return [{ deliveryId, dir, created_at: bound.created_at, text: answer.text }];
177
+ }).sort((a, b) => a.created_at.localeCompare(b.created_at));
178
+ const texts = [];
179
+ for (const item of pending) {
180
+ const index = path.join(indexDir, item.deliveryId);
181
+ if (!claim(item.dir, "hook")) {
182
+ if (fs.existsSync(path.join(item.dir, "claim.json")))
183
+ fs.rmSync(index, { force: true });
184
+ continue;
185
+ }
186
+ texts.push(item.text);
187
+ fs.rmSync(index, { force: true });
188
+ }
189
+ return texts;
190
+ }
191
+ export async function handleCursorHook(profile, raw, hookRoot) {
192
+ let parsed;
193
+ try {
194
+ parsed = JSON.parse(raw);
195
+ }
196
+ catch {
197
+ return {};
198
+ }
199
+ if (parsed === null || typeof parsed !== "object")
200
+ return {};
201
+ const event = parsed;
202
+ const name = event.hook_event_name;
203
+ if (name !== "afterMCPExecution" && name !== "postToolUse" && name !== "postToolUseFailure")
204
+ return {};
205
+ const conv = conversationId(event.conversation_id);
206
+ if (!conv)
207
+ return {};
208
+ const toolName = typeof event.tool_name === "string" ? event.tool_name : "";
209
+ if (profile.dispatch_tools.includes(toolBaseName(profile, toolName))) {
210
+ const payload = name === "afterMCPExecution" ? event.result_json : event.tool_output;
211
+ const deliveryId = deliveryIdFromResult(payload);
212
+ if (deliveryId)
213
+ bind(hookRoot, deliveryId, conv);
214
+ }
215
+ if (name === "postToolUse" || name === "postToolUseFailure") {
216
+ const texts = inject(hookRoot, conv);
217
+ if (texts.length > 0)
218
+ return { additional_context: texts.join("\n\n") };
219
+ }
220
+ return {};
221
+ }
222
+ export async function receiveCursorAnswer(hookRoot, deliveryId, timeoutMs = 86_400_000) {
223
+ const id = deliveryIdSchema.parse(deliveryId);
224
+ const dir = path.join(hookRoot, "deliveries", id);
225
+ if (!fs.existsSync(dir))
226
+ throw new CursorDeliveryError("CURSOR_PARENT_DELIVERY_UNKNOWN", "Cursor配送の記録がありません");
227
+ const answerFile = path.join(dir, "answer.json");
228
+ try {
229
+ await waitForFileState(dir, () => fs.existsSync(answerFile) ? true : undefined, timeoutMs);
230
+ }
231
+ catch (error) {
232
+ if (error instanceof Error && error.message === "WAIT_FOR_FILE_TIMEOUT")
233
+ return { outcome: "timeout" };
234
+ throw error;
235
+ }
236
+ const answer = z.object({ delivery_id: z.string(), text: z.string() }).parse(JSON.parse(fs.readFileSync(answerFile, "utf8")));
237
+ if (answer.delivery_id !== id)
238
+ throw new CursorDeliveryError("CURSOR_PARENT_DELIVERY_MISMATCH", "保存された回答の配送IDが一致しません");
239
+ if (!claim(dir, "receiver"))
240
+ return { outcome: "delivered_by_hook" };
241
+ return { outcome: "delivered", text: answer.text };
242
+ }