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,484 @@
1
+ // 同じ会話へ何通も送るための受け口(channel)。受信方式はAitermの単発配送と同じ公式の仕組みを使う。
2
+ // - Codex: 公式キューはthread単位なので、送るたびに単発配送と同じ submitCodexParentAnswer を呼ぶ。
3
+ // - Claude Code: PostToolUse・Stopのasync hook(asyncRewake)が会話ごとに1つだけ待ち、本文をstderrへ出してexit 2で起こす。
4
+ // turnが終わるたびにStopが待機を張り直すので、2通目以降も届く。
5
+ // - Cursor: tool結果のchannel IDを公式hookが会話へ結び、次のtool返りにadditional_contextで差し込む。
6
+ // idle中は親が背景で起動した受信processが次の1通を受け取って終わる(親は同じ受信processを張り直す)。
7
+ // - その他(Grok等): 背景の受信processだけで受け取る。
8
+ // 本文は受け口がclaimしてから出す。claim後に出力が確定しなければunknownとし、自動では再送しない。
9
+ import * as fs from "node:fs";
10
+ import * as path from "node:path";
11
+ import { randomUUID } from "node:crypto";
12
+ import { setTimeout as delay } from "node:timers/promises";
13
+ import { z } from "zod";
14
+ import { writeJson0600 } from "./files.js";
15
+ import { readRuntimeProcesses } from "./process.js";
16
+ import { channelRoot } from "./profile.js";
17
+ import { SteerDeliveryError } from "./errors.js";
18
+ import { submitCodexParentAnswer } from "./codex-receiver.js";
19
+ import { windowsStartProcessArgumentList } from "./windows.js";
20
+ const uuid = z.uuid();
21
+ const channelSchema = z.object({
22
+ schema: z.literal("aiterm-steer.channel.v1"),
23
+ channel_id: z.uuid(),
24
+ kind: z.enum(["codex", "claude", "cursor", "background"]),
25
+ created_at: z.string(),
26
+ codex: z.object({ thread_id: z.uuid(), codex_home: z.string() }).strict().optional(),
27
+ claude: z.object({ session_id: z.uuid(), parent_pid: z.number().int().positive(), parent_started_identity: z.string() }).strict().optional(),
28
+ }).strict();
29
+ export class ChannelError extends SteerDeliveryError {
30
+ }
31
+ let sendSequence = 0;
32
+ const itemSchema = z.object({ delivery_id: z.uuid(), text: z.string(), at: z.string() }).strict();
33
+ function channelDir(profile, channelId) {
34
+ return path.join(channelRoot(profile), uuid.parse(channelId));
35
+ }
36
+ function processIdentity(pid) {
37
+ return readRuntimeProcesses().find(entry => entry.pid === pid)?.started_identity;
38
+ }
39
+ function mkdirs(...dirs) { for (const dir of dirs)
40
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); }
41
+ /**
42
+ * 親の会話にchannelを開く。parentは単発配送と同じ方法で特定したもの(codexParentFromRequest、claudeParentFromRequest、
43
+ * cursorParentFromRequest)。Grok等の特定できない親は null を渡し、背景受信だけのchannelにする。
44
+ */
45
+ export function openChannel(profile, parent) {
46
+ const channel_id = randomUUID();
47
+ const dir = channelDir(profile, channel_id);
48
+ const created_at = new Date().toISOString();
49
+ let channel;
50
+ if (parent === null)
51
+ channel = { schema: "aiterm-steer.channel.v1", channel_id, kind: "background", created_at };
52
+ else if ("thread_id" in parent)
53
+ channel = { schema: "aiterm-steer.channel.v1", channel_id, kind: "codex", created_at, codex: { thread_id: parent.thread_id, codex_home: parent.codex_home } };
54
+ else if (parent.kind === "cursor")
55
+ channel = { schema: "aiterm-steer.channel.v1", channel_id, kind: "cursor", created_at };
56
+ else {
57
+ // PreToolUse hookが記録した実際の会話と親processに結ぶ。起動時envのsession IDは使わない。
58
+ const request = z.object({ session_id: z.uuid(), parent_pid: z.number().int().positive(), parent_started_identity: z.string() }).loose()
59
+ .parse(JSON.parse(fs.readFileSync(path.join(parent.hook_root, parent.request_id, "request.json"), "utf8")));
60
+ if (request.session_id !== parent.session_id)
61
+ throw new ChannelError("CHANNEL_PARENT_SESSION_MISMATCH", "要求とhookの会話が一致しません");
62
+ channel = { schema: "aiterm-steer.channel.v1", channel_id, kind: "claude", created_at,
63
+ claude: { session_id: request.session_id, parent_pid: request.parent_pid, parent_started_identity: request.parent_started_identity } };
64
+ }
65
+ mkdirs(path.join(dir, "inbox"), path.join(dir, "claims"), path.join(dir, "emitted"));
66
+ writeJson0600(path.join(dir, "channel.json"), channel);
67
+ if (channel.claude) {
68
+ const index = path.join(channelRoot(profile), "claude-sessions", channel.claude.session_id);
69
+ mkdirs(index);
70
+ fs.writeFileSync(path.join(index, channel_id), "", { mode: 0o600 });
71
+ }
72
+ return channel;
73
+ }
74
+ export function readChannel(profile, channelId) {
75
+ const file = path.join(channelDir(profile, channelId), "channel.json");
76
+ try {
77
+ return channelSchema.parse(JSON.parse(fs.readFileSync(file, "utf8")));
78
+ }
79
+ catch (error) {
80
+ if (error.code === "ENOENT")
81
+ throw new ChannelError("CHANNEL_UNKNOWN", "channelの記録がありません");
82
+ throw new ChannelError("CHANNEL_STATE_INVALID", "channelの記録を読めません");
83
+ }
84
+ }
85
+ export function channelClosed(profile, channelId) {
86
+ return fs.existsSync(path.join(channelDir(profile, channelId), "closed.json"));
87
+ }
88
+ /** channelを閉じる。未取得の本文は残し、待機中の受け口は次の確認で終わる。 */
89
+ export function closeChannel(profile, channelId, reason = "closed") {
90
+ const dir = channelDir(profile, channelId);
91
+ if (!fs.existsSync(dir))
92
+ return;
93
+ writeJson0600(path.join(dir, "closed.json"), { reason, at: new Date().toISOString() });
94
+ }
95
+ /**
96
+ * 確定した本文を送る。Codexは公式キューへ入れて受付IDを返す(state=submitted)。
97
+ * それ以外はchannelの受信箱へ保存し(state=queued)、受け口が出力した時点でemittedになる。deliveryIdは送る本文ごとに新しいUUID。
98
+ */
99
+ export async function sendToChannel(profile, channelId, deliveryId, text, runtime) {
100
+ uuid.parse(deliveryId);
101
+ const channel = readChannel(profile, channelId);
102
+ if (channelClosed(profile, channelId))
103
+ throw new ChannelError("CHANNEL_CLOSED", "channelは閉じています。本文は送っていません");
104
+ if (channel.kind === "codex") {
105
+ const result = await submitCodexParentAnswer(profile, channel.codex, deliveryId, text, runtime);
106
+ return { state: "submitted", queued_submission_id: result.queued_submission_id };
107
+ }
108
+ const dir = channelDir(profile, channelId);
109
+ for (const sub of ["claims", "emitted"]) {
110
+ if (fs.existsSync(path.join(dir, sub, `${deliveryId}.json`)))
111
+ throw new ChannelError("CHANNEL_DELIVERY_DUPLICATE", "同じ配送IDの本文はすでに受け取られています");
112
+ }
113
+ // 受け口は名前の順に取り出す。同じミリ秒に送った本文も送った順に並ぶよう、processの通し番号を挟む。
114
+ const name = `${Date.now().toString().padStart(15, "0")}-${(sendSequence++).toString().padStart(9, "0")}-${deliveryId}.json`;
115
+ const item = { delivery_id: deliveryId, text, at: new Date().toISOString() };
116
+ // 受け口に途中のファイルを見せない。一時名で書いてから受信箱へ移す。
117
+ const temporary = path.join(dir, `.${deliveryId}.${randomUUID()}.tmp`);
118
+ fs.writeFileSync(temporary, JSON.stringify(item) + "\n", { flag: "wx", mode: 0o600 });
119
+ try {
120
+ fs.linkSync(temporary, path.join(dir, "inbox", name));
121
+ }
122
+ catch (error) {
123
+ if (error.code === "EEXIST")
124
+ throw new ChannelError("CHANNEL_DELIVERY_DUPLICATE", "同じ配送IDの本文がすでに受信箱にあります");
125
+ throw error;
126
+ }
127
+ finally {
128
+ fs.rmSync(temporary, { force: true });
129
+ }
130
+ return { state: "queued", queued_submission_id: null };
131
+ }
132
+ /** 送った本文の現在の状態。Codexは公式キューの受付までを表す(submitted)。 */
133
+ export function channelDeliveryState(profile, channelId, deliveryId) {
134
+ uuid.parse(deliveryId);
135
+ const channel = readChannel(profile, channelId);
136
+ if (channel.kind === "codex")
137
+ return null;
138
+ const dir = channelDir(profile, channelId);
139
+ if (fs.existsSync(path.join(dir, "emitted", `${deliveryId}.json`)))
140
+ return "emitted";
141
+ const claim = path.join(dir, "claims", `${deliveryId}.json`);
142
+ if (fs.existsSync(claim)) {
143
+ let value;
144
+ try {
145
+ value = JSON.parse(fs.readFileSync(claim, "utf8"));
146
+ }
147
+ catch {
148
+ return "sending";
149
+ }
150
+ if (value.state === "unknown")
151
+ return "unknown";
152
+ if (value.state === "withdrawn")
153
+ return "withdrawn";
154
+ if (typeof value.pid === "number" && typeof value.started_identity === "string" && processIdentity(value.pid) !== value.started_identity)
155
+ return "unknown";
156
+ return "sending";
157
+ }
158
+ return fs.readdirSync(path.join(dir, "inbox")).some(name => name.endsWith(`-${deliveryId}.json`)) ? "queued" : null;
159
+ }
160
+ /**
161
+ * まだどの受け口も取っていない本文を受信箱から取り下げる。取り下げられたらtrue(親へは出ていない)。
162
+ * 受け口が先に取っていたらfalse。channelを張り直す時に、未取得の本文を新しいchannelへ送り直すために使う。
163
+ */
164
+ export function withdrawFromChannel(profile, channelId, deliveryId) {
165
+ uuid.parse(deliveryId);
166
+ const dir = channelDir(profile, channelId);
167
+ const inbox = path.join(dir, "inbox");
168
+ const name = fs.existsSync(inbox) ? fs.readdirSync(inbox).find(entry => entry.endsWith(`-${deliveryId}.json`)) : undefined;
169
+ if (!name)
170
+ return false;
171
+ const claim = path.join(dir, "claims", `${deliveryId}.json`);
172
+ // 受け口のclaimと同じhard linkで取り合う。どちらか一方だけが成功する。
173
+ try {
174
+ fs.linkSync(path.join(inbox, name), claim);
175
+ fs.unlinkSync(path.join(inbox, name));
176
+ }
177
+ catch (error) {
178
+ if (["ENOENT", "EEXIST"].includes(error.code ?? ""))
179
+ return false;
180
+ throw error;
181
+ }
182
+ writeJson0600(claim, { delivery_id: deliveryId, state: "withdrawn", at: new Date().toISOString() });
183
+ return true;
184
+ }
185
+ /** 受信箱の本文を到着順にclaimする。hard linkの作成で、同じ本文を二つの受け口が取らないようにする。 */
186
+ function claimPending(profile, channelId, by, limit = Infinity) {
187
+ const dir = channelDir(profile, channelId);
188
+ const inbox = path.join(dir, "inbox");
189
+ if (!fs.existsSync(inbox))
190
+ return [];
191
+ let identity;
192
+ const claimed = [];
193
+ for (const name of fs.readdirSync(inbox).filter(entry => entry.endsWith(".json")).sort()) {
194
+ if (claimed.length >= limit)
195
+ break;
196
+ const source = path.join(inbox, name);
197
+ let item;
198
+ try {
199
+ item = itemSchema.parse(JSON.parse(fs.readFileSync(source, "utf8")));
200
+ }
201
+ catch (error) {
202
+ if (error.code === "ENOENT")
203
+ continue;
204
+ throw error;
205
+ }
206
+ const claim = path.join(dir, "claims", `${item.delivery_id}.json`);
207
+ try {
208
+ fs.linkSync(source, claim);
209
+ fs.unlinkSync(source);
210
+ }
211
+ catch (error) {
212
+ if (["ENOENT", "EEXIST"].includes(error.code ?? ""))
213
+ continue;
214
+ throw error;
215
+ }
216
+ identity ??= processIdentity(process.pid) ?? "unknown";
217
+ writeJson0600(claim, { ...item, state: "sending", by, pid: process.pid, started_identity: identity });
218
+ claimed.push({ channel_id: channelId, item, claim, dir });
219
+ }
220
+ return claimed;
221
+ }
222
+ function settle(entries, by, state) {
223
+ for (const entry of entries) {
224
+ if (state === "emitted") {
225
+ writeJson0600(path.join(entry.dir, "emitted", `${entry.item.delivery_id}.json`), { delivery_id: entry.item.delivery_id, by, at: new Date().toISOString() });
226
+ fs.rmSync(entry.claim, { force: true });
227
+ }
228
+ else {
229
+ writeJson0600(entry.claim, { ...entry.item, state: "unknown", by });
230
+ }
231
+ }
232
+ }
233
+ /** claimした本文を出力し、出力が確定したものだけをemittedにする。出力の途中で失敗したらunknownにする。 */
234
+ async function emitClaimed(entries, by, emit) {
235
+ try {
236
+ await emit(entries.map(entry => entry.item.text));
237
+ }
238
+ catch (error) {
239
+ settle(entries, by, "unknown");
240
+ throw error;
241
+ }
242
+ settle(entries, by, "emitted");
243
+ }
244
+ // ---- Claude Code ----
245
+ function sessionIndex(profile, sessionId) {
246
+ return path.join(channelRoot(profile), "claude-sessions", uuid.parse(sessionId));
247
+ }
248
+ function openClaudeChannels(profile, sessionId) {
249
+ const index = sessionIndex(profile, sessionId);
250
+ if (!fs.existsSync(index))
251
+ return [];
252
+ return fs.readdirSync(index).filter(name => uuid.safeParse(name).success).flatMap(name => {
253
+ try {
254
+ const channel = readChannel(profile, name);
255
+ return channel.claude?.session_id === sessionId && !channelClosed(profile, name) ? [channel] : [];
256
+ }
257
+ catch (error) {
258
+ if (error instanceof ChannelError && error.delivery_code === "CHANNEL_UNKNOWN")
259
+ return [];
260
+ throw error;
261
+ }
262
+ });
263
+ }
264
+ /** 会話ごとに待機processを1つにする。生きている待機があればfalse。終了した待機の記録は引き継ぐ。 */
265
+ function acquireWaiter(index) {
266
+ const file = path.join(index, "waiter.json");
267
+ const identity = processIdentity(process.pid);
268
+ if (!identity)
269
+ throw new ChannelError("CHANNEL_WAITER_UNAVAILABLE", "受信hookのprocessを確認できません");
270
+ for (let attempt = 0; attempt < 3; attempt += 1) {
271
+ try {
272
+ fs.writeFileSync(file, JSON.stringify({ pid: process.pid, started_identity: identity }) + "\n", { flag: "wx", mode: 0o600 });
273
+ return identity;
274
+ }
275
+ catch (error) {
276
+ if (error.code !== "EEXIST")
277
+ throw error;
278
+ }
279
+ let owner = {};
280
+ try {
281
+ owner = JSON.parse(fs.readFileSync(file, "utf8"));
282
+ }
283
+ catch { /* 書き込み途中。次の試行で読む */ }
284
+ if (typeof owner.pid === "number" && typeof owner.started_identity === "string" && processIdentity(owner.pid) === owner.started_identity)
285
+ return null;
286
+ // 終了した待機の記録。renameで一つのprocessだけが片付ける。
287
+ try {
288
+ fs.renameSync(file, path.join(index, `waiter.${randomUUID()}.stale`));
289
+ }
290
+ catch { /* 他のprocessが先に片付けた */ }
291
+ for (const name of fs.readdirSync(index).filter(entry => entry.endsWith(".stale")))
292
+ fs.rmSync(path.join(index, name), { force: true });
293
+ }
294
+ return null;
295
+ }
296
+ function releaseWaiter(index, identity) {
297
+ const file = path.join(index, "waiter.json");
298
+ try {
299
+ const owner = JSON.parse(fs.readFileSync(file, "utf8"));
300
+ if (owner.pid === process.pid && owner.started_identity === identity)
301
+ fs.rmSync(file, { force: true });
302
+ }
303
+ catch { /* 既に無い */ }
304
+ }
305
+ /**
306
+ * Claude Codeのhook(PostToolUse・Stop、asyncRewake)から呼ぶ。その会話のchannelに届いた本文を待ち、
307
+ * 出力したら2(親を起こす)、待つものが無い・他の待機が生きている・会話が終わったなら0を返す。
308
+ */
309
+ export async function runClaudeChannelWaiter(profile, input, emit, options = {}) {
310
+ const event = z.object({ session_id: z.uuid() }).loose().parse(input);
311
+ if (!openClaudeChannels(profile, event.session_id).length)
312
+ return 0;
313
+ const index = sessionIndex(profile, event.session_id);
314
+ const identity = acquireWaiter(index);
315
+ if (!identity)
316
+ return 0;
317
+ const deadline = Date.now() + (options.wait_ms ?? 86_340_000);
318
+ let lastParentCheck = 0;
319
+ try {
320
+ for (;;) {
321
+ const channels = openClaudeChannels(profile, event.session_id);
322
+ if (!channels.length)
323
+ return 0;
324
+ if (Date.now() - lastParentCheck >= 5_000) {
325
+ lastParentCheck = Date.now();
326
+ // 依頼元のClaude processが終わっていたら、本文を別の会話へ流さずに待機を終える。
327
+ if (!channels.some(channel => processIdentity(channel.claude.parent_pid) === channel.claude.parent_started_identity))
328
+ return 0;
329
+ }
330
+ const claimed = channels.flatMap(channel => claimPending(profile, channel.channel_id, "claude_hook"));
331
+ if (claimed.length) {
332
+ await emitClaimed(claimed, "claude_hook", texts => emit(texts.join("\n\n")));
333
+ return 2;
334
+ }
335
+ if (Date.now() >= deadline) {
336
+ const notice = profile.channels?.claude_expiry_notice;
337
+ if (!notice)
338
+ return 0;
339
+ await emit(notice);
340
+ return 2;
341
+ }
342
+ await delay(options.poll_ms ?? 250);
343
+ }
344
+ }
345
+ finally {
346
+ releaseWaiter(index, identity);
347
+ }
348
+ }
349
+ /** Claude CodeのSessionEndで、その会話のchannelを閉じる。未取得の本文は残る。 */
350
+ export function closeClaudeSessionChannels(profile, input) {
351
+ const { session_id } = z.object({ session_id: z.uuid() }).loose().parse(input);
352
+ for (const channel of openClaudeChannels(profile, session_id))
353
+ closeChannel(profile, channel.channel_id, "session_end");
354
+ }
355
+ // ---- Cursor ----
356
+ const CHANNEL_LINE = /^steer_channel=([0-9a-f-]{36})$/i;
357
+ /** tool結果(structuredContentのsteer_channel.channel_id、または本文の`steer_channel=<uuid>`行)からchannel IDを読む。 */
358
+ export function channelIdFromResult(value, depth = 0) {
359
+ if (depth > 3 || value === null || value === undefined)
360
+ return null;
361
+ let parsed = value;
362
+ if (typeof value === "string") {
363
+ try {
364
+ parsed = JSON.parse(value);
365
+ }
366
+ catch {
367
+ parsed = null;
368
+ }
369
+ }
370
+ if (parsed !== null && typeof parsed === "object") {
371
+ const record = parsed;
372
+ const structured = record.structuredContent;
373
+ const carrier = structured !== null && typeof structured === "object" ? structured : record;
374
+ const marker = carrier.steer_channel;
375
+ if (marker !== null && typeof marker === "object") {
376
+ const id = marker.channel_id;
377
+ if (typeof id === "string" && uuid.safeParse(id).success)
378
+ return id;
379
+ }
380
+ if (depth === 0 && Array.isArray(record.content)) {
381
+ for (const entry of record.content) {
382
+ const text = entry !== null && typeof entry === "object" ? entry.text : undefined;
383
+ if (typeof text === "string") {
384
+ const id = channelIdFromResult(text, depth + 1);
385
+ if (id)
386
+ return id;
387
+ }
388
+ }
389
+ }
390
+ }
391
+ if (typeof value === "string") {
392
+ for (const line of value.split("\n")) {
393
+ const match = CHANNEL_LINE.exec(line.trim());
394
+ if (match && uuid.safeParse(match[1]).success)
395
+ return match[1];
396
+ }
397
+ }
398
+ return null;
399
+ }
400
+ /** tool結果へ載せる印。CursorのhookはこれでchannelをCursorの実際の会話へ結ぶ。 */
401
+ export function channelMarker(channel) {
402
+ return { structured: { steer_channel: { channel_id: channel.channel_id } }, text: `steer_channel=${channel.channel_id}` };
403
+ }
404
+ function conversationId(value) {
405
+ if (typeof value !== "string" || value.length === 0 || value.length > 200)
406
+ return null;
407
+ if (value.includes("/") || value.includes("\\") || value.includes(".."))
408
+ return null;
409
+ return value;
410
+ }
411
+ /**
412
+ * Cursorの公式hook(afterMCPExecution・postToolUse・postToolUseFailure)から呼ぶ。
413
+ * dispatch toolの結果にあるchannelをその会話へ結び、tool返りのhookでは結ばれたchannelの本文を差し込み用に返す。
414
+ */
415
+ export async function handleCursorChannelHook(profile, event, emit) {
416
+ const name = event.hook_event_name;
417
+ if (name !== "afterMCPExecution" && name !== "postToolUse" && name !== "postToolUseFailure")
418
+ return false;
419
+ const conv = conversationId(event.conversation_id);
420
+ if (!conv)
421
+ return false;
422
+ const payload = name === "afterMCPExecution" ? event.result_json : event.tool_output;
423
+ const bound = channelIdFromResult(payload);
424
+ const conversations = path.join(channelRoot(profile), "cursor-conversations");
425
+ if (bound && fs.existsSync(channelDir(profile, bound))) {
426
+ const channel = readChannel(profile, bound);
427
+ if (channel.kind === "cursor") {
428
+ const bindFile = path.join(channelDir(profile, bound), "bind.json");
429
+ if (!fs.existsSync(bindFile))
430
+ writeJson0600(bindFile, { conversation_id: conv, at: new Date().toISOString() });
431
+ const bindConv = JSON.parse(fs.readFileSync(bindFile, "utf8")).conversation_id;
432
+ if (bindConv === conv) {
433
+ mkdirs(path.join(conversations, conv));
434
+ fs.writeFileSync(path.join(conversations, conv, bound), "", { mode: 0o600 });
435
+ }
436
+ }
437
+ }
438
+ if (name === "afterMCPExecution")
439
+ return false;
440
+ const index = path.join(conversations, conv);
441
+ if (!fs.existsSync(index))
442
+ return false;
443
+ const claimed = fs.readdirSync(index).filter(id => uuid.safeParse(id).success && !channelClosed(profile, id))
444
+ .flatMap(id => claimPending(profile, id, "cursor_hook"));
445
+ if (!claimed.length)
446
+ return false;
447
+ await emitClaimed(claimed, "cursor_hook", texts => emit(texts.join("\n\n")));
448
+ return true;
449
+ }
450
+ // ---- 背景受信(Cursorのidle時、Grok等) ----
451
+ /** 親の背景process APIへそのまま渡す起動情報。scriptは製品のchannel受信入口の絶対path。 */
452
+ export function channelReceiveProcess(script, channelId, executable = process.execPath) {
453
+ const args = [script, "--channel", uuid.parse(channelId)];
454
+ return { executable, args, windows_start_process_argument_list: process.platform === "win32" ? windowsStartProcessArgumentList(args) : null };
455
+ }
456
+ /**
457
+ * 次に届いた本文を受け取って終わる。受け取った本文はこの時点でemittedになる(出力は呼び出し側が行う)。
458
+ * hookが先に差し込んだ本文は飛ばして、その次を待つ。
459
+ */
460
+ export async function receiveFromChannel(profile, channelId, options = {}) {
461
+ readChannel(profile, channelId);
462
+ const deadline = Date.now() + (options.wait_ms ?? 86_400_000);
463
+ const emit = options.emit ?? (() => undefined);
464
+ for (;;) {
465
+ if (channelClosed(profile, channelId)) {
466
+ const result = { outcome: "closed", channel_id: channelId };
467
+ await emit(result);
468
+ return result;
469
+ }
470
+ const claimed = claimPending(profile, channelId, "receiver");
471
+ if (claimed.length) {
472
+ const result = { outcome: "delivered", channel_id: channelId,
473
+ deliveries: claimed.map(entry => ({ delivery_id: entry.item.delivery_id, text: entry.item.text })) };
474
+ await emitClaimed(claimed, "receiver", () => emit(result));
475
+ return result;
476
+ }
477
+ if (Date.now() >= deadline) {
478
+ const result = { outcome: "timeout", channel_id: channelId };
479
+ await emit(result);
480
+ return result;
481
+ }
482
+ await delay(options.poll_ms ?? 250);
483
+ }
484
+ }
@@ -0,0 +1,20 @@
1
+ import { z } from "zod";
2
+ import type { ProductProfile } from "./profile.js";
3
+ export declare const claudeParentSchema: z.ZodObject<{
4
+ kind: z.ZodLiteral<"claude">;
5
+ request_id: z.ZodString;
6
+ session_id: z.ZodUUID;
7
+ hook_root: z.ZodString;
8
+ }, z.core.$strict>;
9
+ export type ClaudeParent = z.infer<typeof claudeParentSchema>;
10
+ export declare function prepareClaudeHookRequest(input: unknown, root: string): void;
11
+ /** 起動時envのsession IDは/clearで古くなるため、実際のPreToolUseとの相関だけを使う。 */
12
+ export declare function claudeParentFromRequest(profile: ProductProfile, clientName: string | undefined, metadata: unknown, root: string): ClaudeParent | null;
13
+ export declare function verifyClaudeParent(profile: ProductProfile, parent: ClaudeParent): void;
14
+ export declare function bindClaudeParentDelivery(profile: ProductProfile, parent: ClaudeParent, deliveryId: string): void;
15
+ /** SessionEndはその時点の依頼だけを終了する。同じ会話をresumeした新規依頼は別requestになる。 */
16
+ export declare function closeClaudeParentSession(input: unknown, root: string): void;
17
+ export declare function submitClaudeParentAnswer(profile: ProductProfile, parent: ClaudeParent, deliveryId: string, text: string): Promise<{
18
+ queued_submission_id: null;
19
+ }>;
20
+ export declare function runClaudeResultHook(profile: ProductProfile, input: unknown, emit: (text: string) => void | Promise<void>, root: string): Promise<0 | 2>;
@@ -0,0 +1,171 @@
1
+ // Claude Codeの公式hookを受信口にする。待機processはharnessが所有し、親のturnを止めない。
2
+ // PreToolUseが実際の会話(session_id)と親processを記録し、MCP要求のtoolUseIdと結ぶ。
3
+ // PostToolUseのasyncRewake hookが本文の到着を待ち、stderrへ出してexit 2で親を起こす(作業中ならそのturnへ入る)。
4
+ import * as fs from "node:fs";
5
+ import * as path from "node:path";
6
+ import { z } from "zod";
7
+ import { waitForFileState, writeJson0600 } from "./files.js";
8
+ import { readRuntimeProcesses } from "./process.js";
9
+ import { ClaudeDeliveryError } from "./errors.js";
10
+ const requestId = z.string().regex(/^[A-Za-z0-9_-]{1,160}$/);
11
+ const invocationSchema = z.object({
12
+ request_id: requestId, session_id: z.uuid(), agent_id: z.string().nullable(),
13
+ parent_pid: z.number().int().positive(), parent_started_identity: z.string(),
14
+ }).strict();
15
+ export const claudeParentSchema = z.object({
16
+ kind: z.literal("claude"), request_id: requestId, session_id: z.uuid(), hook_root: z.string(),
17
+ }).strict();
18
+ function processIdentity(pid) { return readRuntimeProcesses().find(entry => entry.pid === pid)?.started_identity; }
19
+ function directory(parent) { return path.join(parent.hook_root, parent.request_id); }
20
+ function readInvocation(profile, parent) {
21
+ let value;
22
+ try {
23
+ value = invocationSchema.parse(JSON.parse(fs.readFileSync(path.join(directory(parent), "request.json"), "utf8")));
24
+ }
25
+ catch {
26
+ throw new ClaudeDeliveryError("CLAUDE_PARENT_HOOK_UNAVAILABLE", `親のhook記録がありません。${profile.setup_command}を実行し、Claude Codeのhookを有効にしてください`);
27
+ }
28
+ if (value.request_id !== parent.request_id || value.session_id !== parent.session_id) {
29
+ throw new ClaudeDeliveryError("CLAUDE_PARENT_SESSION_MISMATCH", "要求とhookの会話が一致しません");
30
+ }
31
+ return value;
32
+ }
33
+ function assertOpen(parent) {
34
+ if (fs.existsSync(path.join(directory(parent), "closed.json"))) {
35
+ throw new ClaudeDeliveryError("CLAUDE_PARENT_SESSION_CLOSED", "依頼元の会話は終了しました。回答を別の会話へ送っていません");
36
+ }
37
+ }
38
+ export function prepareClaudeHookRequest(input, root) {
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)
42
+ throw new ClaudeDeliveryError("CLAUDE_PARENT_PROCESS_UNAVAILABLE", "hookを起動した親processを確認できません");
43
+ const dir = path.join(root, event.tool_use_id);
44
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
45
+ writeJson0600(path.join(dir, "request.json"), {
46
+ 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
+ });
49
+ }
50
+ /** 起動時envのsession IDは/clearで古くなるため、実際のPreToolUseとの相関だけを使う。 */
51
+ export function claudeParentFromRequest(profile, clientName, metadata, root) {
52
+ if (clientName !== "claude-code")
53
+ return null;
54
+ const parsed = requestId.safeParse(metadata?.["claudecode/toolUseId"]);
55
+ if (!parsed.success)
56
+ throw new ClaudeDeliveryError("CLAUDE_PARENT_ID_UNAVAILABLE", "MCP要求にtoolUseIdがありません。対応するClaude Codeへ更新してください");
57
+ let invocation;
58
+ try {
59
+ invocation = invocationSchema.parse(JSON.parse(fs.readFileSync(path.join(root, parsed.data, "request.json"), "utf8")));
60
+ }
61
+ catch {
62
+ throw new ClaudeDeliveryError("CLAUDE_PARENT_HOOK_UNAVAILABLE", `親のPreToolUse hookを確認できません。${profile.setup_command}を実行し、hookを有効にしてください`);
63
+ }
64
+ const parent = { kind: "claude", request_id: parsed.data, session_id: invocation.session_id, hook_root: root };
65
+ verifyClaudeParent(profile, parent);
66
+ return parent;
67
+ }
68
+ export function verifyClaudeParent(profile, parent) {
69
+ const invocation = readInvocation(profile, parent);
70
+ if (invocation.agent_id)
71
+ throw new ClaudeDeliveryError("CLAUDE_PARENT_SUBAGENT_UNSUPPORTED", "agent_id付きのClaude会話(--agent起動またはnative subagent)への自動配送には対応していません");
72
+ assertOpen(parent);
73
+ }
74
+ export function bindClaudeParentDelivery(profile, parent, deliveryId) {
75
+ verifyClaudeParent(profile, parent);
76
+ writeJson0600(path.join(directory(parent), "delivery.json"), { delivery_id: z.uuid().parse(deliveryId) });
77
+ }
78
+ /** SessionEndはその時点の依頼だけを終了する。同じ会話をresumeした新規依頼は別requestになる。 */
79
+ export function closeClaudeParentSession(input, root) {
80
+ const { session_id } = z.object({ session_id: z.uuid() }).parse(input);
81
+ if (!fs.existsSync(root))
82
+ return;
83
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
84
+ if (!entry.isDirectory())
85
+ continue;
86
+ const file = path.join(root, entry.name, "request.json");
87
+ if (!fs.existsSync(file))
88
+ continue;
89
+ const invocation = invocationSchema.parse(JSON.parse(fs.readFileSync(file, "utf8")));
90
+ if (invocation.session_id === session_id)
91
+ writeJson0600(path.join(root, entry.name, "closed.json"), { session_id });
92
+ }
93
+ }
94
+ function assertParentAlive(invocation) {
95
+ if (processIdentity(invocation.parent_pid) !== invocation.parent_started_identity) {
96
+ throw new ClaudeDeliveryError("CLAUDE_PARENT_PROCESS_CLOSED", "依頼元のClaude processは終了しました。回答は保存したままです");
97
+ }
98
+ }
99
+ export async function submitClaudeParentAnswer(profile, parent, deliveryId, text) {
100
+ const invocation = readInvocation(profile, parent);
101
+ const dir = directory(parent);
102
+ // 会話終了でも確定本文を失わない。終了判定より先に保存する。
103
+ writeJson0600(path.join(dir, "answer.json"), { delivery_id: deliveryId, text });
104
+ 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);
110
+ return true;
111
+ }
112
+ assertOpen(parent);
113
+ const failed = path.join(dir, "failed.json");
114
+ if (fs.existsSync(failed)) {
115
+ const value = JSON.parse(fs.readFileSync(failed, "utf8"));
116
+ throw new ClaudeDeliveryError("CLAUDE_PARENT_HOOK_FAILED", "親へのhook出力が失敗しました。回答は保存したままです", value.outcome_unknown === true);
117
+ }
118
+ const hookFile = path.join(dir, "hook.json");
119
+ if (fs.existsSync(hookFile)) {
120
+ 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")));
123
+ }
124
+ }
125
+ assertParentAlive(invocation);
126
+ return undefined;
127
+ });
128
+ return { queued_submission_id: null };
129
+ }
130
+ export async function runClaudeResultHook(profile, input, emit, root) {
131
+ const event = z.object({ session_id: z.uuid(), tool_use_id: requestId }).parse(input);
132
+ const parent = { kind: "claude", request_id: event.tool_use_id, session_id: event.session_id, hook_root: root };
133
+ const invocation = readInvocation(profile, parent);
134
+ const dir = directory(parent);
135
+ const binding = path.join(dir, "delivery.json");
136
+ if (!fs.existsSync(binding)) {
137
+ fs.rmSync(dir, { recursive: true });
138
+ return 0;
139
+ }
140
+ const deliveryId = z.uuid().parse(JSON.parse(fs.readFileSync(binding, "utf8")).delivery_id);
141
+ const identity = processIdentity(process.pid);
142
+ if (!identity)
143
+ throw new ClaudeDeliveryError("CLAUDE_PARENT_HOOK_UNAVAILABLE", "受信hookのprocessを確認できません");
144
+ writeJson0600(path.join(dir, "hook.json"), { pid: process.pid, started_identity: identity });
145
+ try {
146
+ const answer = await waitForFileState(dir, () => {
147
+ if (fs.existsSync(path.join(dir, "closed.json")))
148
+ return null;
149
+ assertParentAlive(invocation);
150
+ const file = path.join(dir, "answer.json");
151
+ if (!fs.existsSync(file))
152
+ return undefined;
153
+ const value = z.object({ delivery_id: z.uuid(), text: z.string() }).strict().parse(JSON.parse(fs.readFileSync(file, "utf8")));
154
+ if (value.delivery_id !== deliveryId)
155
+ throw new ClaudeDeliveryError("CLAUDE_PARENT_DELIVERY_MISMATCH", "保存された回答の配送IDが一致しません");
156
+ return value;
157
+ });
158
+ if (!answer)
159
+ return 0;
160
+ assertOpen(parent);
161
+ writeJson0600(path.join(dir, "sending.json"), { delivery_id: deliveryId });
162
+ await emit(answer.text);
163
+ writeJson0600(path.join(dir, "emitted.json"), { delivery_id: deliveryId });
164
+ // Claudeが定めるasyncRewakeの再開信号。子の成功/失敗は本文のoutcomeで区別する。
165
+ return 2;
166
+ }
167
+ catch (error) {
168
+ writeJson0600(path.join(dir, "failed.json"), { outcome_unknown: fs.existsSync(path.join(dir, "sending.json")) });
169
+ throw error;
170
+ }
171
+ }