forkit-cli 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/forkit-hook.mjs +134 -8
- package/forkit.mjs +41 -7
- package/package.json +1 -1
package/forkit-hook.mjs
CHANGED
|
@@ -4,8 +4,9 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Reads one hook event on stdin and sends a small summary to Forkit, so the
|
|
6
6
|
* team inbox shows this session without Claude having to report anything.
|
|
7
|
-
* It never
|
|
8
|
-
*
|
|
7
|
+
* It never breaks Claude: every call gives up after a few seconds and it always
|
|
8
|
+
* exits 0. It prints only what Claude Code acts on: a permission answer, a
|
|
9
|
+
* teammate's reply, or a notice that the key was refused.
|
|
9
10
|
*
|
|
10
11
|
* Config: FORKIT_API_KEY and FORKIT_URL, or ~/.config/forkit/config.json
|
|
11
12
|
* (written by `forkit init`). FORKIT_CAPTURE=full (default) | minimal | off.
|
|
@@ -15,12 +16,19 @@
|
|
|
15
16
|
* FORKIT_PERMISSION_WAIT seconds (default 90); with no answer it prints nothing
|
|
16
17
|
* and Claude asks in the terminal as usual. Only in full mode, since deciding
|
|
17
18
|
* needs the command; FORKIT_PERMISSIONS=off turns this part off.
|
|
19
|
+
* Questions and answers: when Claude's turn ends by asking something, the
|
|
20
|
+
* thread goes to "waiting" so it reaches a person. The Stop hook then waits up
|
|
21
|
+
* to FORKIT_REPLY_WAIT seconds (default 90) for an answer from the inbox; if
|
|
22
|
+
* one comes, Claude carries on with it. Answers that arrive later are handed
|
|
23
|
+
* to Claude with the next prompt, and replies posted mid-turn when the turn
|
|
24
|
+
* ends. A refused key shows a notice in Claude Code on each prompt until fixed.
|
|
25
|
+
*
|
|
18
26
|
* full prompts, commands, Claude's final message per turn, file paths, states
|
|
19
27
|
* minimal file paths and states only, no prompt or command text
|
|
20
28
|
* off nothing
|
|
21
29
|
*/
|
|
22
30
|
import { execFileSync } from 'node:child_process';
|
|
23
|
-
import { readFileSync, openSync, readSync, fstatSync, closeSync, realpathSync } from 'node:fs';
|
|
31
|
+
import { readFileSync, writeFileSync, mkdirSync, openSync, readSync, fstatSync, closeSync, realpathSync } from 'node:fs';
|
|
24
32
|
import { homedir } from 'node:os';
|
|
25
33
|
import { join, relative, isAbsolute, resolve, dirname, basename } from 'node:path';
|
|
26
34
|
|
|
@@ -35,9 +43,64 @@ function config() {
|
|
|
35
43
|
mode: process.env.FORKIT_CAPTURE || file.capture || 'full',
|
|
36
44
|
permissions: (process.env.FORKIT_PERMISSIONS || file.permissions || 'on') !== 'off',
|
|
37
45
|
waitSeconds: Math.max(0, Number(process.env.FORKIT_PERMISSION_WAIT ?? file.permission_wait ?? 90) || 0),
|
|
46
|
+
replyWait: replyWaitSeconds(process.env.FORKIT_REPLY_WAIT ?? file.reply_wait),
|
|
38
47
|
};
|
|
39
48
|
}
|
|
40
49
|
|
|
50
|
+
/** How long a turn that ends with a question waits for an answer: default 90 s, never past the 900 s Stop hook timeout. */
|
|
51
|
+
export function replyWaitSeconds(raw) {
|
|
52
|
+
if (raw === undefined || raw === null || raw === '') return 90;
|
|
53
|
+
const n = Number(raw);
|
|
54
|
+
return Number.isFinite(n) ? Math.min(Math.max(0, Math.floor(n)), 840) : 0;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ── What Claude last saw of its thread, per session ─────────────────────
|
|
58
|
+
|
|
59
|
+
function sessionFile(sessionId) {
|
|
60
|
+
return join(homedir(), '.config', 'forkit', 'sessions', `${String(sessionId).replace(/[^A-Za-z0-9_-]/g, '_')}.json`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function readSession(sessionId) {
|
|
64
|
+
try { return JSON.parse(readFileSync(sessionFile(sessionId), 'utf8')); } catch { return null; }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function writeSession(sessionId, state) {
|
|
68
|
+
try {
|
|
69
|
+
mkdirSync(dirname(sessionFile(sessionId)), { recursive: true });
|
|
70
|
+
writeFileSync(sessionFile(sessionId), JSON.stringify(state));
|
|
71
|
+
} catch { /* never in Claude's way */ }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The question a message ends with, or undefined. Only the last sentence of
|
|
76
|
+
* the last line counts, so "Why did it fail? Fixed it." is not a question.
|
|
77
|
+
*/
|
|
78
|
+
export function endingQuestion(text) {
|
|
79
|
+
if (typeof text !== 'string') return undefined;
|
|
80
|
+
const lines = text.trim().split('\n').map(l => l.trim()).filter(Boolean);
|
|
81
|
+
const last = (lines.at(-1) ?? '').replace(/[*_`]+/g, '').trim();
|
|
82
|
+
if (!last.endsWith('?')) return undefined;
|
|
83
|
+
const sentence = last.split(/(?<=[.!?])\s+/).filter(Boolean).at(-1) ?? last;
|
|
84
|
+
return sentence.length > 300 ? `${sentence.slice(0, 297)}...` : sentence;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** A person's messages and review decisions; never permission answers, agents or GitHub. */
|
|
88
|
+
export function personReplies(events) {
|
|
89
|
+
return (events ?? []).filter(e => {
|
|
90
|
+
if (e?.actor_kind !== 'user' || !e.body) return false;
|
|
91
|
+
if (e.type === 'message') return true;
|
|
92
|
+
if (e.type !== 'decision') return false;
|
|
93
|
+
const data = typeof e.data === 'string' ? (() => { try { return JSON.parse(e.data); } catch { return null; } })() : e.data;
|
|
94
|
+
return !data?.permission;
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function formatReplies(replies) {
|
|
99
|
+
return replies.map(e => `${e.actor_name || 'A teammate'}: ${e.body}`).join('\n');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export const REVOKED_MESSAGE = "Forkit: this agent's key was refused (revoked, you left the workspace, or your account isn't approved), so this session isn't reaching your team. Run npx forkit-cli init to reconnect.";
|
|
103
|
+
|
|
41
104
|
function git(cwd, args) {
|
|
42
105
|
try {
|
|
43
106
|
return execFileSync('git', args, { cwd, timeout: 1500, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim() || undefined;
|
|
@@ -148,7 +211,9 @@ export function toEvents(input, info, mode) {
|
|
|
148
211
|
}
|
|
149
212
|
case 'Stop': {
|
|
150
213
|
const text = full ? lastAssistantText(input.transcript_path) : undefined;
|
|
151
|
-
|
|
214
|
+
// A turn that ends by asking the person something needs them; anything else just ended.
|
|
215
|
+
const question = endingQuestion(text);
|
|
216
|
+
return [...(text ? [{ event: 'message', body: text }] : []), question ? { event: 'waiting', body: question } : { event: 'idle' }];
|
|
152
217
|
}
|
|
153
218
|
case 'SessionEnd':
|
|
154
219
|
return [{ event: 'end' }];
|
|
@@ -226,14 +291,75 @@ async function main() {
|
|
|
226
291
|
if (out) process.stdout.write(JSON.stringify(out));
|
|
227
292
|
return;
|
|
228
293
|
}
|
|
229
|
-
|
|
230
|
-
|
|
294
|
+
const event = input.hook_event_name;
|
|
295
|
+
const out = {};
|
|
296
|
+
let session = readSession(input.session_id);
|
|
297
|
+
// Only events Claude has actually been given count as seen. Capture responses never move this
|
|
298
|
+
// (a person's reply posted mid-turn sits below the thread's latest number), and it is saved only
|
|
299
|
+
// after the output is written, so a hook killed by its timeout loses nothing.
|
|
300
|
+
let seen = session?.seq ?? 0;
|
|
301
|
+
const readReplies = async () => {
|
|
302
|
+
const t = await call(cfg, `/api/v1/threads/${encodeURIComponent(session.thread_id)}?after=${seen}`, undefined, TIMEOUT_MS).catch(() => null);
|
|
303
|
+
if (!t) return [];
|
|
304
|
+
seen = Math.max(seen, ...(t.events ?? []).map(e => e.seq));
|
|
305
|
+
return personReplies(t.events);
|
|
306
|
+
};
|
|
307
|
+
const handBack = event === 'UserPromptSubmit' || event === 'SessionStart' || (event === 'Stop' && !input.stop_hook_active);
|
|
308
|
+
|
|
309
|
+
// Replies a person left since Claude last looked, read before this turn's own events.
|
|
310
|
+
if (handBack && session?.thread_id) {
|
|
311
|
+
const replies = await readReplies();
|
|
312
|
+
if (replies.length && event === 'Stop') {
|
|
313
|
+
out.decision = 'block';
|
|
314
|
+
out.reason = `A teammate wrote to you in Forkit while you worked. ${formatReplies(replies)}\nTake that into account before you finish.`;
|
|
315
|
+
} else if (replies.length) {
|
|
316
|
+
out.hookSpecificOutput = { hookEventName: event, additionalContext: `Messages from your team in Forkit since your last turn:\n${formatReplies(replies)}` };
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
const events = toEvents(input, info, mode);
|
|
321
|
+
let refused = false;
|
|
322
|
+
let state = null;
|
|
323
|
+
for (const ev of events) {
|
|
324
|
+
const res = await fetch(`${url}/api/v1/capture`, {
|
|
231
325
|
method: 'POST',
|
|
232
|
-
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json', 'User-Agent': 'forkit-claude-code/0.
|
|
326
|
+
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json', 'User-Agent': 'forkit-claude-code/0.2' },
|
|
233
327
|
body: JSON.stringify({ source: 'claude-code', session_id: input.session_id, ...refs, ...ev }),
|
|
234
328
|
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
235
|
-
});
|
|
329
|
+
}).catch(() => null);
|
|
330
|
+
if (res?.status === 401 || res?.status === 403) { refused = true; break; }
|
|
331
|
+
const r = res?.ok ? await res.json().catch(() => null) : null;
|
|
332
|
+
if (r?.thread_id && r.thread_id !== session?.thread_id) {
|
|
333
|
+
// A new thread (first event, or a person resolved the old one): nothing in it is a reply yet.
|
|
334
|
+
session = { thread_id: r.thread_id };
|
|
335
|
+
seen = r.last_seq;
|
|
336
|
+
}
|
|
337
|
+
if (r?.state) state = r.state;
|
|
338
|
+
}
|
|
339
|
+
if (refused && (event === 'SessionStart' || event === 'UserPromptSubmit')) out.systemMessage = REVOKED_MESSAGE;
|
|
340
|
+
|
|
341
|
+
// The turn ended on a question and the thread really is waiting: wait a while for an answer, and if one comes, Claude carries on with it.
|
|
342
|
+
if (event === 'Stop' && !out.decision && state === 'waiting' && !input.stop_hook_active && cfg.replyWait > 0 && session?.thread_id) {
|
|
343
|
+
const deadline = Date.now() + cfg.replyWait * 1000;
|
|
344
|
+
for (;;) {
|
|
345
|
+
const left = Math.floor((deadline - Date.now()) / 1000);
|
|
346
|
+
if (left < 1) break;
|
|
347
|
+
const wait = Math.min(left, 110);
|
|
348
|
+
const r = await call(cfg, `/api/v1/threads/${encodeURIComponent(session.thread_id)}/wait?after=${seen}&timeout=${wait}`, undefined, (wait + 10) * 1000).catch(() => null);
|
|
349
|
+
if (!r) break;
|
|
350
|
+
const replies = personReplies(r.events);
|
|
351
|
+
seen = Math.max(seen, ...(r.events ?? []).map(e => e.seq));
|
|
352
|
+
if (replies.length) {
|
|
353
|
+
out.decision = 'block';
|
|
354
|
+
out.reason = `Your question was answered in Forkit. ${formatReplies(replies)}\nContinue with that answer.`;
|
|
355
|
+
break;
|
|
356
|
+
}
|
|
357
|
+
if (r.thread?.state && r.thread.state !== 'waiting') break; // someone closed it or the agent moved on
|
|
358
|
+
}
|
|
236
359
|
}
|
|
360
|
+
|
|
361
|
+
if (Object.keys(out).length) process.stdout.write(JSON.stringify(out));
|
|
362
|
+
if (session?.thread_id) writeSession(input.session_id, { thread_id: session.thread_id, seq: seen });
|
|
237
363
|
}
|
|
238
364
|
|
|
239
365
|
if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith('forkit-hook.mjs')) {
|
package/forkit.mjs
CHANGED
|
@@ -499,23 +499,44 @@ function backup(path) {
|
|
|
499
499
|
|
|
500
500
|
const HOOK_EVENTS = ['SessionStart', 'UserPromptSubmit', 'PostToolUse', 'PermissionRequest', 'Notification', 'Stop', 'SessionEnd'];
|
|
501
501
|
|
|
502
|
-
|
|
502
|
+
// PermissionRequest and Stop can wait for a person; UserPromptSubmit and SessionStart read replies before reporting.
|
|
503
|
+
const HOOK_TIMEOUT = { PermissionRequest: 900, Stop: 900, UserPromptSubmit: 15, SessionStart: 15 };
|
|
504
|
+
|
|
505
|
+
const isForkitHook = h => typeof h?.command === 'string' && h.command.includes('forkit-hook.mjs');
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Adds Forkit's hooks to Claude Code's settings, leaving everything else as it
|
|
509
|
+
* was. An older Forkit hook with a shorter timeout than it now needs is raised.
|
|
510
|
+
*/
|
|
503
511
|
export function mergeClaudeHooks(settings, hookPath) {
|
|
504
512
|
const next = { ...settings, hooks: { ...(settings.hooks ?? {}) } };
|
|
505
513
|
const command = `node "${hookPath}"`;
|
|
506
514
|
let added = 0;
|
|
515
|
+
let updated = 0;
|
|
507
516
|
for (const event of HOOK_EVENTS) {
|
|
517
|
+
const timeout = HOOK_TIMEOUT[event] ?? 5;
|
|
508
518
|
const groups = Array.isArray(next.hooks[event]) ? [...next.hooks[event]] : [];
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
519
|
+
if (groups.some(g => (g.hooks ?? []).some(isForkitHook))) {
|
|
520
|
+
next.hooks[event] = groups.map(g => ({
|
|
521
|
+
...g,
|
|
522
|
+
hooks: (g.hooks ?? []).map(h => {
|
|
523
|
+
if (!isForkitHook(h) || (h.timeout ?? 0) >= timeout) return h;
|
|
524
|
+
updated += 1;
|
|
525
|
+
return { ...h, timeout };
|
|
526
|
+
}),
|
|
527
|
+
}));
|
|
528
|
+
continue;
|
|
529
|
+
}
|
|
512
530
|
groups.push({ ...(event === 'PostToolUse' ? { matcher: 'Bash|Edit|Write|MultiEdit|NotebookEdit' } : {}), hooks: [{ type: 'command', command, timeout }] });
|
|
513
531
|
next.hooks[event] = groups;
|
|
514
532
|
added += 1;
|
|
515
533
|
}
|
|
516
|
-
return { settings: next, added };
|
|
534
|
+
return { settings: next, added, updated };
|
|
517
535
|
}
|
|
518
536
|
|
|
537
|
+
/** Without a terminal nothing can be asked, so init says how to finish instead of pretending it did. */
|
|
538
|
+
export const NO_TERMINAL_HINT = 'No terminal to ask in, so nothing was connected. Run npx forkit-cli init --yes to connect Claude Code and Codex.';
|
|
539
|
+
|
|
519
540
|
/** Sets Codex's notify command, unless the person already has one of their own. */
|
|
520
541
|
export function mergeCodexNotify(toml, cliPath) {
|
|
521
542
|
const line = `notify = ["node", ${JSON.stringify(cliPath)}, "notify"]`;
|
|
@@ -527,6 +548,8 @@ export function mergeCodexNotify(toml, cliPath) {
|
|
|
527
548
|
|
|
528
549
|
async function init(argv) {
|
|
529
550
|
const yes = argv.includes('--yes') || argv.includes('-y');
|
|
551
|
+
const canAsk = Boolean(process.stdin.isTTY);
|
|
552
|
+
let skippedForNoTerminal = false;
|
|
530
553
|
const positional = argv.filter((a, i) => !a.startsWith('-') && argv[i - 1] !== '--url' && argv[i - 1] !== '--agents');
|
|
531
554
|
// Old form: forkit init <api-key> just saves the key.
|
|
532
555
|
if (positional[0]) {
|
|
@@ -584,7 +607,12 @@ async function init(argv) {
|
|
|
584
607
|
try { settings = JSON.parse(readFileSync(path, 'utf8')); } catch (e) { if (existsSync(path)) { out(`! ${path} isn't valid JSON; skipped Claude Code. Fix it and run forkit init again.`); settings = null; } }
|
|
585
608
|
if (settings) {
|
|
586
609
|
const merged = mergeClaudeHooks(settings, hookCopy);
|
|
587
|
-
if (!merged.added
|
|
610
|
+
if (!merged.added && merged.updated) {
|
|
611
|
+
const saved = backup(path);
|
|
612
|
+
writeFileSync(path, JSON.stringify(merged.settings, null, 2));
|
|
613
|
+
out(`✓ Claude Code's Forkit hooks updated${saved ? ` (backup: ${basename(saved)})` : ''}`);
|
|
614
|
+
} else if (!merged.added) out('✓ Claude Code already reports to Forkit');
|
|
615
|
+
else if (!yes && !canAsk) { skippedForNoTerminal = true; out('– Skipped Claude Code'); }
|
|
588
616
|
else if (await confirm(`Add Forkit's hooks to ${path}? (a backup is kept)`, yes)) {
|
|
589
617
|
const saved = backup(path);
|
|
590
618
|
mkdirSync(dirname(path), { recursive: true });
|
|
@@ -602,6 +630,7 @@ async function init(argv) {
|
|
|
602
630
|
const merged = mergeCodexNotify(toml, cliCopy);
|
|
603
631
|
if (merged.conflict) out(`! Codex already has its own notify command (${merged.existing}). Left it alone; to use Forkit, set notify = ["node", "${cliCopy}", "notify"].`);
|
|
604
632
|
else if (!merged.changed) out('✓ Codex already reports to Forkit');
|
|
633
|
+
else if (!yes && !canAsk) { skippedForNoTerminal = true; out('– Skipped Codex'); }
|
|
605
634
|
else if (await confirm(`Set Codex's notify command in ${path}? (a backup is kept)`, yes)) {
|
|
606
635
|
const saved = backup(path);
|
|
607
636
|
mkdirSync(dirname(path), { recursive: true });
|
|
@@ -610,6 +639,11 @@ async function init(argv) {
|
|
|
610
639
|
} else out('– Skipped Codex');
|
|
611
640
|
}
|
|
612
641
|
|
|
642
|
+
if (skippedForNoTerminal) {
|
|
643
|
+
out(`\n${NO_TERMINAL_HINT}`);
|
|
644
|
+
process.exitCode = 1;
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
613
647
|
out(`\nDone. Run ${C.bold('forkit watch')} to answer your agents from this terminal, or open ${cfg.url}/inbox.`);
|
|
614
648
|
}
|
|
615
649
|
|
|
@@ -625,7 +659,7 @@ const HELP = `forkit: one inbox for every coding agent
|
|
|
625
659
|
forkit run [--title T] -- <command> run an agent and report its session
|
|
626
660
|
forkit notify '<json>' Codex hook: notify = ["forkit", "notify"]
|
|
627
661
|
|
|
628
|
-
Environment: FORKIT_API_KEY, FORKIT_URL, FORKIT_CAPTURE=full|minimal|off, FORKIT_PERMISSION_WAIT
|
|
662
|
+
Environment: FORKIT_API_KEY, FORKIT_URL, FORKIT_CAPTURE=full|minimal|off, FORKIT_PERMISSION_WAIT, FORKIT_REPLY_WAIT (seconds, max 840)
|
|
629
663
|
`;
|
|
630
664
|
|
|
631
665
|
const { realpathSync } = await import('node:fs');
|
package/package.json
CHANGED