forkit-cli 0.2.1 → 0.3.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 (3) hide show
  1. package/forkit-hook.mjs +514 -26
  2. package/forkit.mjs +568 -9
  3. package/package.json +1 -1
package/forkit.mjs CHANGED
@@ -15,10 +15,11 @@
15
15
  */
16
16
  import { spawn, execFileSync, spawnSync } from 'node:child_process';
17
17
  import { readFileSync, writeFileSync, mkdirSync, chmodSync, copyFileSync, existsSync } from 'node:fs';
18
- import { homedir } from 'node:os';
18
+ import { homedir, tmpdir } from 'node:os';
19
19
  import { join, basename, dirname } from 'node:path';
20
20
  import { randomUUID, createHash } from 'node:crypto';
21
21
  import { fileURLToPath } from 'node:url';
22
+ import { repoCredentialHelper, REPO_HOSTS, mergeCheck, mergeReason } from './forkit-hook.mjs';
22
23
  import { createInterface } from 'node:readline';
23
24
 
24
25
  const here = dirname(fileURLToPath(import.meta.url));
@@ -497,7 +498,10 @@ function backup(path) {
497
498
  return to;
498
499
  }
499
500
 
500
- const HOOK_EVENTS = ['SessionStart', 'UserPromptSubmit', 'PostToolUse', 'PermissionRequest', 'Notification', 'Stop', 'SessionEnd'];
501
+ const HOOK_EVENTS = ['SessionStart', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'PermissionRequest', 'Notification', 'Stop', 'SessionEnd'];
502
+
503
+ // PreToolUse only runs before an edit, to ask whether another agent has claimed the file.
504
+ const HOOK_MATCHER = { PreToolUse: 'Edit|Write|MultiEdit|NotebookEdit', PostToolUse: 'Bash|Edit|Write|MultiEdit|NotebookEdit' };
501
505
 
502
506
  // PermissionRequest and Stop can wait for a person; UserPromptSubmit and SessionStart read replies before reporting.
503
507
  const HOOK_TIMEOUT = { PermissionRequest: 900, Stop: 900, UserPromptSubmit: 15, SessionStart: 15 };
@@ -508,9 +512,9 @@ const isForkitHook = h => typeof h?.command === 'string' && h.command.includes('
508
512
  * Adds Forkit's hooks to Claude Code's settings, leaving everything else as it
509
513
  * was. An older Forkit hook with a shorter timeout than it now needs is raised.
510
514
  */
511
- export function mergeClaudeHooks(settings, hookPath) {
515
+ export function mergeClaudeHooks(settings, hookPath, hookCommand) {
512
516
  const next = { ...settings, hooks: { ...(settings.hooks ?? {}) } };
513
- const command = `node "${hookPath}"`;
517
+ const command = hookCommand ?? `node "${hookPath}"`;
514
518
  let added = 0;
515
519
  let updated = 0;
516
520
  for (const event of HOOK_EVENTS) {
@@ -527,7 +531,7 @@ export function mergeClaudeHooks(settings, hookPath) {
527
531
  }));
528
532
  continue;
529
533
  }
530
- groups.push({ ...(event === 'PostToolUse' ? { matcher: 'Bash|Edit|Write|MultiEdit|NotebookEdit' } : {}), hooks: [{ type: 'command', command, timeout }] });
534
+ groups.push({ ...(HOOK_MATCHER[event] ? { matcher: HOOK_MATCHER[event] } : {}), hooks: [{ type: 'command', command, timeout }] });
531
535
  next.hooks[event] = groups;
532
536
  added += 1;
533
537
  }
@@ -537,6 +541,47 @@ export function mergeClaudeHooks(settings, hookPath) {
537
541
  /** Without a terminal nothing can be asked, so init says how to finish instead of pretending it did. */
538
542
  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
543
 
544
+ // Codex's hooks use the same script as Claude Code's, told which agent is calling.
545
+ // SessionEnd may run for 3 s at most; edits arrive as apply_patch.
546
+ const CODEX_HOOKS = {
547
+ SessionStart: { timeout: 30 },
548
+ UserPromptSubmit: { timeout: 15 },
549
+ PreToolUse: { timeout: 5, matcher: 'apply_patch|Edit|Write' },
550
+ PostToolUse: { timeout: 5, matcher: 'Bash|apply_patch' },
551
+ PermissionRequest: { timeout: 900 },
552
+ Stop: { timeout: 900 },
553
+ SessionEnd: { timeout: 3 },
554
+ };
555
+
556
+ /** Adds Forkit's hooks to Codex's hooks.json, leaving everything else as it was. */
557
+ export function mergeCodexHooks(config, hookPath) {
558
+ const next = { ...config, hooks: { ...(config.hooks ?? {}) } };
559
+ const command = `node "${hookPath}" --source codex`;
560
+ let added = 0;
561
+ for (const [event, { timeout, matcher }] of Object.entries(CODEX_HOOKS)) {
562
+ const groups = Array.isArray(next.hooks[event]) ? [...next.hooks[event]] : [];
563
+ if (groups.some(g => (g.hooks ?? []).some(isForkitHook))) continue;
564
+ groups.push({ ...(matcher ? { matcher } : {}), hooks: [{ type: 'command', command, timeout }] });
565
+ next.hooks[event] = groups;
566
+ added += 1;
567
+ }
568
+ return { config: next, added };
569
+ }
570
+
571
+ /** Whether this Codex runs hooks. They are on by default from 0.133; older ones only have notify. */
572
+ export function codexHasHooks(versionText) {
573
+ const m = /(\d+)\.(\d+)\.(\d+)/.exec(versionText ?? '');
574
+ return m ? Number(m[1]) > 0 || Number(m[2]) >= 133 : false;
575
+ }
576
+
577
+ /** Takes Forkit's own notify line out once hooks report the same turns; anyone else's notify stays. */
578
+ export function removeForkitNotify(toml) {
579
+ const existing = /^\s*notify\s*=.*\n?/m.exec(toml);
580
+ // Only the line forkit init wrote itself: node, this CLI's file, "notify". A person's own script under a folder named forkit stays.
581
+ if (!existing || !/=\s*\[\s*"node"\s*,\s*"[^"]*forkit\.mjs"\s*,\s*"notify"\s*\]/.test(existing[0])) return { toml, changed: false };
582
+ return { toml: toml.replace(existing[0], ''), changed: true };
583
+ }
584
+
540
585
  /** Sets Codex's notify command, unless the person already has one of their own. */
541
586
  export function mergeCodexNotify(toml, cliPath) {
542
587
  const line = `notify = ["node", ${JSON.stringify(cliPath)}, "notify"]`;
@@ -546,7 +591,471 @@ export function mergeCodexNotify(toml, cliPath) {
546
591
  return { toml: `${line}\n${toml}`, changed: true, conflict: false };
547
592
  }
548
593
 
594
+ /**
595
+ * Setup for a machine nobody sits at: a sandbox image, a CI runner. No sign-in,
596
+ * no key and no question. It only installs the hooks; each agent's key arrives
597
+ * at run time in FORKIT_API_KEY (one of a fan-out's keys). With --project the
598
+ * hooks go into this repository's .claude/, to be committed, and nothing is
599
+ * written to the home directory.
600
+ */
601
+ async function initSandbox(argv) {
602
+ const hookSource = [join(here, 'forkit-hook.mjs'), join(here, '..', 'claude-code', 'forkit', 'hooks', 'forkit-hook.mjs')].find(existsSync);
603
+ if (!hookSource) throw new Error('Could not find forkit-hook.mjs next to this CLI.');
604
+ const project = argv.includes('--project');
605
+ const url = flag(argv, '--url')?.replace(/\/+$/, '');
606
+ const dir = project ? join(process.cwd(), '.claude') : join(homedir(), '.claude');
607
+ const path = join(dir, 'settings.json');
608
+ let settings = {};
609
+ try { settings = JSON.parse(readFileSync(path, 'utf8')); } catch { if (existsSync(path)) throw new Error(`${path} isn't valid JSON. Fix it and run this again.`); }
610
+ mkdirSync(dir, { recursive: true });
611
+ let command;
612
+ if (project) {
613
+ copyFileSync(hookSource, join(dir, 'forkit-hook.mjs'));
614
+ command = 'node "$CLAUDE_PROJECT_DIR/.claude/forkit-hook.mjs"';
615
+ } else {
616
+ const bin = join(configDir(), 'bin');
617
+ mkdirSync(bin, { recursive: true });
618
+ copyFileSync(hookSource, join(bin, 'forkit-hook.mjs'));
619
+ copyFileSync(fileURLToPath(import.meta.url), join(bin, 'forkit.mjs'));
620
+ command = `node "${join(bin, 'forkit-hook.mjs')}"`;
621
+ // No terminal here, so an unanswered permission request is refused, whichever key the agent is given.
622
+ writeConfig({ ...readConfig(), ...(url ? { url } : {}), on_timeout: 'deny' });
623
+ }
624
+ const merged = mergeClaudeHooks(settings, null, command);
625
+ if (merged.added || merged.updated) writeFileSync(path, JSON.stringify(merged.settings, null, 2));
626
+ out(`✓ Claude Code hooks ${merged.added || merged.updated ? 'written to' : 'already in'} ${path}`);
627
+ // Agents of a fan-out with a repository: git asks Forkit for a fresh token, for Artifacts hosts only.
628
+ // The empty entry first keeps any other helper (a keychain) from storing a token that expires in minutes.
629
+ if (!project && onPath('git')) {
630
+ const key = `credential.${REPO_HOSTS}.helper`;
631
+ const g = (args) => spawnSync('git', ['config', '--global', ...args], { stdio: 'ignore' }).status === 0;
632
+ const ok = g(['--unset-all', key]) || true;
633
+ if (ok && g(['--add', key, '']) && g(['--add', key, repoCredentialHelper(url ?? config().url)])) out(`✓ git asks Forkit for repository logins (${REPO_HOSTS})`);
634
+ }
635
+ if (project) out(` Commit .claude/settings.json and .claude/forkit-hook.mjs. Claude Code runs them in any checkout, with no trust question under -p.`);
636
+ out(`
637
+ Each agent needs its own key at run time:
638
+ FORKIT_API_KEY one key of a fan-out (forkit fanout create --name NAME --agents N)${url || project ? '' : '\n FORKIT_URL only if not https://forkit-mcp.com'}
639
+ Start Claude Code without --bare: bare mode runs no hooks, so Forkit would see nothing.
640
+ Codex is not set up by this command: its hooks must be trusted once in a terminal (/hooks).`);
641
+ }
642
+
643
+ async function fanoutCall(cfg, path, body, method) {
644
+ if (!cfg.key) throw new Error('No API key. Set FORKIT_API_KEY to the key of the agent that starts the fan-out, or run `forkit init`.');
645
+ const res = await fetch(`${cfg.url}${path}`, {
646
+ method: method ?? (body === undefined ? 'GET' : 'POST'),
647
+ headers: { Authorization: `Bearer ${cfg.key}`, 'Content-Type': 'application/json', 'User-Agent': 'forkit-cli/0.3' },
648
+ body: body === undefined ? undefined : JSON.stringify(body),
649
+ signal: AbortSignal.timeout(60_000),
650
+ });
651
+ const json = await res.json().catch(() => null);
652
+ if (!res.ok) throw new Error(json?.error || `Forkit answered ${res.status}`);
653
+ return json;
654
+ }
655
+
656
+ /**
657
+ * forkit fanout collect ID [DIR] [--merge]: every agent's work in one local repository. The base is
658
+ * cloned and each fork that was pushed to becomes a branch agent/<name>; with --merge they are merged
659
+ * one by one into fanout/<name>, and agents whose work conflicts are listed and left as branches.
660
+ * Each fetch uses a 15-minute read token passed for that command only, never written to disk.
661
+ */
662
+ async function collect(cfg, rest) {
663
+ const id = rest.find(a => !a.startsWith('-'));
664
+ if (!id) throw new Error('Usage: forkit fanout collect FANOUT_ID [DIR] [--merge]');
665
+ const dir = rest.filter(a => !a.startsWith('-'))[1];
666
+ const list = await fanoutCall(cfg, `/api/v1/fanouts/${encodeURIComponent(id)}/repos`);
667
+ const target = dir ?? list.fanout.name;
668
+ const token = async repo => (await fanoutCall(cfg, `/api/v1/fanouts/${encodeURIComponent(id)}/repos/token`, { repo })).token;
669
+ const git = (args, opts = {}) => spawnSync('git', args, { stdio: opts.quiet ? 'ignore' : ['ignore', 'inherit', 'inherit'], cwd: opts.cwd });
670
+ const authed = (t) => ['-c', 'credential.helper=', '-c', `http.extraHeader=Authorization: Bearer ${t}`];
671
+ const branch = list.base.branch;
672
+ if (git([...authed(await token(list.base.repo)), 'clone', '--quiet', ...(branch ? ['--branch', branch] : []), list.base.remote, target]).status !== 0) throw new Error('could not clone the base repository');
673
+ const pushed = list.agents.filter(a => a.head_sha);
674
+ const fetched = [];
675
+ for (const a of pushed) {
676
+ const ok = git([...authed(await token(a.repo)), 'fetch', '--quiet', a.remote, `${branch ?? 'HEAD'}:refs/heads/agent/${a.agent}`], { cwd: target }).status === 0;
677
+ if (ok) fetched.push(a.agent); else err(`! could not fetch ${a.agent}'s work`);
678
+ }
679
+ err(`${fetched.length} of ${list.agents.length} agents pushed work; each is a branch agent/<name> in ${target}.`);
680
+ if (!rest.includes('--merge') || !fetched.length) return undefined;
681
+ const into = `fanout/${list.fanout.name}`;
682
+ git(['checkout', '--quiet', '-b', into], { cwd: target });
683
+ const conflicts = [];
684
+ for (const name of fetched) {
685
+ const r = git(['-c', 'user.name=Forkit', '-c', 'user.email=forkit@users.noreply.forkit-mcp.com', 'merge', '--no-edit', '--quiet', `agent/${name}`], { cwd: target, quiet: true });
686
+ if (r.status !== 0) { git(['merge', '--abort'], { cwd: target, quiet: true }); conflicts.push(name); }
687
+ }
688
+ err(`Merged ${fetched.length - conflicts.length} into ${into}.${conflicts.length ? ` Conflicts, left as branches: ${conflicts.join(', ')}.` : ''}`);
689
+ if (conflicts.length) process.exitCode = 3;
690
+ return undefined;
691
+ }
692
+
693
+ /** forkit fanout create|add|list|stop: keys for agents this agent starts elsewhere. */
694
+ async function fanout(argv) {
695
+ const [sub, ...rest] = argv;
696
+ const cfg = config();
697
+ const num = name => (flag(rest, name) === undefined ? undefined : Number(flag(rest, name)));
698
+ if (sub === 'create') {
699
+ const name = flag(rest, '--name');
700
+ const agents = num('--agents');
701
+ if (!name || !agents) throw new Error('Usage: forkit fanout create --name NAME --agents N [--max-agents N] [--ttl SECONDS] [--parent THREAD] [--max-tool-calls N]');
702
+ // --repo-from DIR: the code is pushed from that checkout (any private repository); --repo URL: a public one is imported.
703
+ const from = flag(rest, '--repo-from');
704
+ let branch = flag(rest, '--branch');
705
+ if (from) {
706
+ branch ??= spawnSync('git', ['-C', from, 'rev-parse', '--abbrev-ref', 'HEAD'], { encoding: 'utf8' }).stdout?.trim();
707
+ if (!branch || branch === 'HEAD') throw new Error(`${from} is not a git checkout on a branch (or give --branch)`);
708
+ }
709
+ // The keys are printed once, as JSON on stdout, for the script that starts the sandboxes. Nothing else is printed there.
710
+ const made = await fanoutCall(cfg, '/api/v1/fanouts', {
711
+ name, agents, max_agents: num('--max-agents'), ttl_seconds: num('--ttl'),
712
+ parent_thread_id: flag(rest, '--parent') ?? process.env.FORKIT_PARENT_THREAD, max_tool_calls: num('--max-tool-calls'),
713
+ repo: from ? { push: true, branch } : flag(rest, '--repo') ? { url: flag(rest, '--repo'), branch } : undefined,
714
+ max_cost_usd: num('--max-cost'), repo_keep_days: num('--keep-days'), shadow: rest.includes('--shadow') || undefined,
715
+ });
716
+ if (from) {
717
+ const base = await fanoutCall(cfg, `/api/v1/fanouts/${encodeURIComponent(made.id)}/repos/base`, {});
718
+ // The token is passed for this one push, never written to the checkout's config.
719
+ const pushed = spawnSync('git', ['-C', from, '-c', 'credential.helper=', '-c', `http.extraHeader=Authorization: Bearer ${base.token}`,
720
+ 'push', '--quiet', base.remote, `HEAD:refs/heads/${base.branch}`], { stdio: ['ignore', 'ignore', 'inherit'] });
721
+ if (pushed.status !== 0) throw new Error(`could not push ${from} to the fan-out's repository; the fan-out ${made.id} was started: stop it with forkit fanout stop ${made.id}`);
722
+ await fanoutCall(cfg, `/api/v1/fanouts/${encodeURIComponent(made.id)}/repos/ready`, {});
723
+ made.repo = { ...made.repo, state: 'ready' };
724
+ err(`Pushed ${from} (${base.branch}) to the fan-out's repository; its agents can clone it now.`);
725
+ }
726
+ return out(JSON.stringify(made, null, 2));
727
+ }
728
+ if (sub === 'add') {
729
+ const agents = num('--agents');
730
+ if (!rest[0] || rest[0].startsWith('-') || !agents) throw new Error('Usage: forkit fanout add FANOUT_ID --agents N');
731
+ return out(JSON.stringify(await fanoutCall(cfg, `/api/v1/fanouts/${encodeURIComponent(rest[0])}/keys`, { agents }), null, 2));
732
+ }
733
+ if (sub === 'stop') {
734
+ if (!rest[0]) throw new Error('Usage: forkit fanout stop FANOUT_ID');
735
+ const f = await fanoutCall(cfg, `/api/v1/fanouts/${encodeURIComponent(rest[0])}/stop`, {});
736
+ return out(`Stopped ${f.name}: each of its agents is told to stop on its next step.`);
737
+ }
738
+ if (sub === 'list' || sub === undefined) {
739
+ const { fanouts } = await fanoutCall(cfg, '/api/v1/fanouts');
740
+ if (rest.includes('--json')) return out(JSON.stringify(fanouts, null, 2));
741
+ if (!fanouts.length) return out('No fan-outs started by this agent.');
742
+ for (const f of fanouts) {
743
+ const state = f.live ? `until ${f.expires_at}` : f.stop_reason ?? 'time limit reached';
744
+ const cost = f.cost_usd || f.max_cost_usd ? ` ~$${Number(f.cost_usd ?? 0).toFixed(2)}${f.max_cost_usd ? ` of $${Number(f.max_cost_usd).toFixed(2)}` : ''}${f.budget_warning ? ' (over 80%)' : ''}` : '';
745
+ out(`${f.id} ${f.name} ${f.sessions} of ${f.minted} agents at work ${f.tool_calls}${f.max_tool_calls ? ` of ${f.max_tool_calls}` : ''} tool calls${cost} ${state}`);
746
+ }
747
+ return undefined;
748
+ }
749
+ if (sub === 'collect') return collect(cfg, rest);
750
+ if (sub === 'clean') {
751
+ if (!rest[0]) throw new Error('Usage: forkit fanout clean FANOUT_ID');
752
+ const r = await fanoutCall(cfg, `/api/v1/fanouts/${encodeURIComponent(rest[0])}/clean`, {});
753
+ return out(`Deleted ${r.deleted} repositories of ${rest[0]}.`);
754
+ }
755
+ throw new Error('Usage: forkit fanout create | add | list | stop | collect | clean');
756
+ }
757
+
758
+ /**
759
+ * forkit repo clone|credential|info: the agent's own fork of its fan-out's repository.
760
+ * `clone` writes a git credential helper into the clone that asks Forkit for a fresh 15-minute
761
+ * token on each git operation, so no long-lived token is ever written to disk.
762
+ */
763
+ async function askRepo(cfg, { wait = 60 } = {}) {
764
+ if (!cfg.key) throw new Error('No API key. A fan-out agent gets its key in FORKIT_API_KEY.');
765
+ const until = Date.now() + wait * 1000;
766
+ for (;;) {
767
+ const res = await fetch(`${cfg.url}/api/v1/repo`, {
768
+ method: 'POST', headers: { Authorization: `Bearer ${cfg.key}`, 'User-Agent': 'forkit-cli/0.3' }, signal: AbortSignal.timeout(30_000),
769
+ });
770
+ const json = await res.json().catch(() => null);
771
+ if (res.ok) return json;
772
+ // Still being imported or forked: asked again shortly.
773
+ if (res.status === 409 && Date.now() < until) { await new Promise(r => setTimeout(r, 3000)); continue; }
774
+ throw new Error(json?.error || `Forkit answered ${res.status}`);
775
+ }
776
+ }
777
+
778
+ async function repo(argv) {
779
+ const [sub, ...rest] = argv;
780
+ const cfg = config();
781
+ if (sub === 'credential') {
782
+ // git calls: <helper> get|store|erase, with key=value lines on stdin. Only "get" is answered.
783
+ if (rest[0] !== 'get') return undefined;
784
+ const input = readFileSync(0, 'utf8');
785
+ const host = /^host=(.*)$/m.exec(input)?.[1] ?? '';
786
+ if (!/\.artifacts\.cloudflare\.net$/.test(host) && !/^(localhost|127\.0\.0\.1)(:\d+)?$/.test(host)) return undefined;
787
+ const r = await askRepo(cfg, { wait: 30 });
788
+ // Basic auth: any user name; the password is the token without its ?expires= suffix.
789
+ return out(`username=x\npassword=${String(r.token).split('?')[0]}\n`);
790
+ }
791
+ if (sub === 'clone') {
792
+ const r = await askRepo(cfg);
793
+ const dir = rest.find(a => !a.startsWith('-')) ?? r.repo;
794
+ const self = fileURLToPath(import.meta.url);
795
+ const helper = `!"${process.execPath}" "${self}" repo credential`;
796
+ const git = (args, opts = {}) => {
797
+ const p = spawnSync('git', args, { stdio: 'inherit', ...opts });
798
+ if (p.status !== 0) throw new Error(`git ${args[0]} failed`);
799
+ };
800
+ // The helper replaces any other for this clone (the empty value resets the list first).
801
+ git(['-c', 'credential.helper=', '-c', `credential.helper=${helper}`, 'clone', ...(r.branch ? ['--branch', r.branch] : []), r.remote, dir]);
802
+ git(['config', 'credential.helper', ''], { cwd: dir });
803
+ git(['config', '--add', 'credential.helper', helper], { cwd: dir });
804
+ err(`Cloned your fork into ${dir}. Push to it as usual: Forkit records each push on your thread.`);
805
+ return undefined;
806
+ }
807
+ if (sub === 'info' || sub === undefined) {
808
+ const { token, ...r } = await askRepo(cfg);
809
+ void token;
810
+ return out(JSON.stringify(r, null, 2));
811
+ }
812
+ throw new Error('Usage: forkit repo clone [DIR] | info');
813
+ }
814
+
815
+ /**
816
+ * forkit usage: what a session used, for agents whose tool has no hook. Token counts, or the cost the tool
817
+ * itself knows, or both; --json reads a provider's usage object from stdin ({ prompt_tokens, … }).
818
+ */
819
+ async function usage(argv) {
820
+ const cfg = config(process.env.FORKIT_SOURCE);
821
+ if (!cfg.key) throw new Error('No API key (run `forkit init` or set FORKIT_API_KEY).');
822
+ const session = flag(argv, '--session') ?? process.env.FORKIT_SESSION;
823
+ const model = flag(argv, '--model');
824
+ if (!session || !model) throw new Error('Usage: forkit usage --model MODEL [--input N] [--output N] [--cache-read N] [--cache-write N] [--cost USD] [--session ID] [--json < usage.json]\n(inside `forkit run` the session is already known)');
825
+ const num = name => (flag(argv, name) === undefined ? undefined : Number(flag(argv, name)));
826
+ let row = { model, input: num('--input'), output: num('--output'), cache_read: num('--cache-read'), cache_write: num('--cache-write'), cost_usd: num('--cost') };
827
+ if (argv.includes('--json')) {
828
+ const given = JSON.parse(readFileSync(0, 'utf8'));
829
+ row = { ...(given.usage ?? given), model, ...Object.fromEntries(Object.entries(row).filter(([, v]) => v !== undefined)) };
830
+ }
831
+ const res = await fetch(`${cfg.url}/api/v1/usage`, {
832
+ method: 'POST', headers: { Authorization: `Bearer ${cfg.key}`, 'Content-Type': 'application/json', 'User-Agent': 'forkit-cli/0.3' },
833
+ body: JSON.stringify({ source: flag(argv, '--source') ?? process.env.FORKIT_SOURCE ?? 'cli', session_id: session, usage: [row] }),
834
+ signal: AbortSignal.timeout(15_000),
835
+ });
836
+ const body = await res.json().catch(() => null);
837
+ if (!res.ok) throw new Error(body?.error || `Forkit answered ${res.status}`);
838
+ if (!body.recorded) throw new Error('Forkit does not know this session yet; report again in a moment.');
839
+ out(`Recorded. This session so far: about $${Number(body.cost_usd ?? 0).toFixed(2)}${body.estimated ? ' (a model without a known price was priced high)' : ''}${body.fanout?.stopped ? `. Its fan-out was ${body.fanout.reason}: stop working.` : ''}`);
840
+ if (body.fanout?.stopped) process.exitCode = 4;
841
+ }
842
+
843
+ /**
844
+ * forkit share --to AGENT [-m TEXT] [--reply-to ID] [-- PATHS…]: send another agent your change itself, as a patch on a
845
+ * Forkit message (tracked edits since HEAD, and new files). It applies it to its own checkout with `forkit apply ID`.
846
+ * Agents in separate checkouts cannot see each other's edits; a patch lets one make a change for both, and the other
847
+ * check it and make the very same change, so the two merge cleanly.
848
+ */
849
+ async function share(argv) {
850
+ const cfg = config(process.env.FORKIT_SOURCE);
851
+ if (!cfg.key) throw new Error('No API key (run `forkit init` or set FORKIT_API_KEY).');
852
+ const to = flag(argv, '--to');
853
+ if (!to) throw new Error('Usage: forkit share --to AGENT [-m TEXT] [--reply-to MESSAGE_ID] [-- PATHS…]');
854
+ const dash = argv.indexOf('--');
855
+ const paths = dash >= 0 ? argv.slice(dash + 1) : [];
856
+ const git = (args) => spawnSync('git', args, { encoding: 'utf8', maxBuffer: 50 * 1024 * 1024 });
857
+ if (git(['rev-parse', '--is-inside-work-tree']).status !== 0) throw new Error('Run this inside the git checkout whose change you are sharing.');
858
+ let patch = git(['diff', 'HEAD', '--', ...paths]).stdout ?? '';
859
+ const untracked = (git(['ls-files', '--others', '--exclude-standard', '--', ...paths]).stdout ?? '').split('\n').filter(Boolean);
860
+ for (const f of untracked) patch += git(['diff', '--no-index', '--', '/dev/null', f]).stdout ?? '';
861
+ if (!patch.trim()) throw new Error('There is no change to share here (nothing differs from HEAD).');
862
+ const replyTo = flag(argv, '--reply-to');
863
+ const body = flag(argv, '-m') ?? flag(argv, '--message') ?? 'My change, as a patch.';
864
+ const res = await fetch(`${cfg.url}/api/v1/messages`, {
865
+ method: 'POST', headers: { Authorization: `Bearer ${cfg.key}`, 'Content-Type': 'application/json', 'User-Agent': 'forkit-cli/0.3' },
866
+ body: JSON.stringify({ type: replyTo ? 'answer' : 'handoff', to, body, patch, ...(replyTo ? { in_reply_to: replyTo } : {}) }),
867
+ signal: AbortSignal.timeout(30_000),
868
+ });
869
+ const sent = await res.json().catch(() => null);
870
+ if (!res.ok) throw new Error(sent?.error || `Forkit answered ${res.status}`);
871
+ const files = [...new Set([...patch.matchAll(/^diff --git a\/(\S+) b\//gm)].map(m => m[1]))];
872
+ out(`Sent ${sent.id ?? '(queued)'} to ${to} with a patch changing ${files.join(', ')}. They apply it with: forkit apply ${sent.id ?? '<id>'}`);
873
+ }
874
+
875
+ /**
876
+ * forkit apply MESSAGE_ID [--check]: apply the patch another agent sent you to this checkout (git apply --3way).
877
+ * --check only says whether it applies. A patch that is already applied is reported, not applied twice (exit 3).
878
+ */
879
+ async function applyPatch(argv) {
880
+ const cfg = config(process.env.FORKIT_SOURCE);
881
+ if (!cfg.key) throw new Error('No API key (run `forkit init` or set FORKIT_API_KEY).');
882
+ const id = argv.find(a => /^am-[0-9a-f]+$/.test(a));
883
+ if (!id) throw new Error('Usage: forkit apply MESSAGE_ID [--check]');
884
+ const res = await fetch(`${cfg.url}/api/v1/messages/${id}/patch`, {
885
+ headers: { Authorization: `Bearer ${cfg.key}`, 'User-Agent': 'forkit-cli/0.3' }, signal: AbortSignal.timeout(30_000),
886
+ });
887
+ if (!res.ok) throw new Error((await res.json().catch(() => null))?.error || `Forkit answered ${res.status}`);
888
+ const patch = await res.text();
889
+ const file = join(tmpdir(), `forkit-${id}.patch`);
890
+ writeFileSync(file, patch);
891
+ const git = (args) => spawnSync('git', args, { encoding: 'utf8' });
892
+ const files = [...new Set([...patch.matchAll(/^diff --git a\/(\S+) b\//gm)].map(m => m[1]))].join(', ');
893
+ if (git(['apply', '--reverse', '--check', file]).status === 0) {
894
+ out(`${id} is already applied here (${files}).`);
895
+ process.exitCode = 3;
896
+ return;
897
+ }
898
+ if (argv.includes('--check')) {
899
+ const r = git(['apply', '--check', file]);
900
+ if (r.status !== 0) throw new Error(`${id} does not apply cleanly here: ${(r.stderr || '').trim()}`);
901
+ out(`${id} applies cleanly here (${files}). Nothing was changed.`);
902
+ return;
903
+ }
904
+ const r = git(['apply', '--3way', '--whitespace=nowarn', file]);
905
+ if (r.status !== 0) throw new Error(`${id} did not apply cleanly (${files}): ${(r.stderr || '').trim()}\nConflicting parts are marked in the files; resolve them, or ask the sender.`);
906
+ out(`Applied ${id}: ${files}. Check it with git diff.`);
907
+ }
908
+
909
+ /**
910
+ * forkit check-merge [--exclude PATH…]: would this checkout's change merge with the other agents' of the fan-out?
911
+ * Sends the change since HEAD (and new files) to Forkit, which compares it with each peer's latest. Exit 0 when it
912
+ * would merge, 1 when it would conflict (where, and with whom, is printed), 2 when it could not be checked.
913
+ */
914
+ async function checkMergeCmd(argv) {
915
+ const cfg = config(process.env.FORKIT_SOURCE);
916
+ if (!cfg.key) throw new Error('No API key (run `forkit init` or set FORKIT_API_KEY).');
917
+ const exclude = argv.flatMap((a, i) => (a === '--exclude' && argv[i + 1] ? [argv[i + 1]] : []));
918
+ const r = await mergeCheck(cfg, process.cwd(), exclude);
919
+ if (!r) { err('Could not check: run this inside the git checkout of a fan-out agent.'); process.exitCode = 2; return; }
920
+ const waiting = r.waiting_for?.length ? ` Not sent yet by: ${r.waiting_for.join(', ')} (they are checked when they do).` : '';
921
+ const other = r.different_base?.length ? ` Started from another commit, so not compared: ${r.different_base.join(', ')}.` : '';
922
+ if (r.clean) { out(`Your change would merge with ${r.checked_against?.length ? r.checked_against.join(', ') : 'nobody yet'}.${waiting}${other}`); return; }
923
+ out(mergeReason(r) + waiting + other);
924
+ process.exitCode = 1;
925
+ }
926
+
927
+ /**
928
+ * forkit factory …: saved fan-outs (see the server's src/db/factories.ts).
929
+ * create --name N --prompt-file F [--agents N] [--max-cost USD] [--max-tool-calls N] [--ttl S] [--repo URL | --push] [--branch B]
930
+ * [--shadow] [--schedule "daily 06:30"] [--keep-days N] → the factory and its webhook address, shown once
931
+ * list | show NAME | delete NAME
932
+ * run NAME [--items-file F | --input-file F] ask for a run (one agent per item)
933
+ * work NAME --exec CMD [--once] [--repo-from DIR] [--dir DIR] the runner: picks up waiting runs and starts the agents
934
+ * verdict RUN good|bad [--note TEXT]
935
+ * asks FANOUT_ID what a shadow run's agents would have asked a person
936
+ *
937
+ * `work` is a reference runner. For each agent it runs CMD through the shell in an empty folder, with FORKIT_API_KEY,
938
+ * FORKIT_URL, FORKIT_PROMPT, FORKIT_TITLE and FORKIT_AGENT set, for example:
939
+ * forkit factory work updates --exec 'claude -p "$FORKIT_PROMPT" --settings ~/agent-settings.json'
940
+ * Forkit never runs an agent itself: this is the part your team operates.
941
+ */
942
+ async function factory(argv) {
943
+ const [sub, ...rest] = argv;
944
+ const cfg = config();
945
+ const call = (path, body, method) => fanoutCall(cfg, path, body, method);
946
+ const num = name => (flag(rest, name) === undefined ? undefined : Number(flag(rest, name)));
947
+ const first = rest.find(a => !a.startsWith('-') && rest[rest.indexOf(a) - 1]?.startsWith('--') !== true) ?? rest.find(a => !a.startsWith('-'));
948
+ const readJson = (file) => JSON.parse(readFileSync(file, 'utf8'));
949
+
950
+ if (sub === 'create') {
951
+ const name = flag(rest, '--name');
952
+ const promptFile = flag(rest, '--prompt-file');
953
+ const prompt = promptFile ? readFileSync(promptFile, 'utf8') : flag(rest, '--prompt');
954
+ if (!name || !prompt) throw new Error('Usage: forkit factory create --name NAME --prompt-file FILE [--agents N] [--max-cost USD] [--repo URL | --push] [--shadow] [--schedule "daily 06:30"]');
955
+ const repo = rest.includes('--push') ? { push: true, branch: flag(rest, '--branch') } : flag(rest, '--repo') ? { url: flag(rest, '--repo'), branch: flag(rest, '--branch') } : undefined;
956
+ const made = await call('/api/v1/factories', {
957
+ name, prompt, description: flag(rest, '--description'), agents: num('--agents'), ttl_seconds: num('--ttl'), max_tool_calls: num('--max-tool-calls'),
958
+ max_cost_usd: num('--max-cost'), repo_keep_days: num('--keep-days'), repo, shadow: rest.includes('--shadow') || undefined, schedule: flag(rest, '--schedule'),
959
+ });
960
+ out(JSON.stringify(made, null, 2));
961
+ return err(`\nIts webhook address is shown this once. Anything that can POST to it asks for a run; it starts nothing by itself.`);
962
+ }
963
+ if (sub === 'list' || sub === undefined) {
964
+ const { factories } = await call('/api/v1/factories');
965
+ if (rest.includes('--json')) return out(JSON.stringify(factories, null, 2));
966
+ if (!factories.length) return out('No factories in this workspace.');
967
+ for (const f of factories) out(`${f.name} ${f.agents} agent${f.agents === 1 ? '' : 's'}${f.shadow ? ' shadow' : ''}${f.schedule ? ` ${f.schedule}` : ''}${f.max_cost_usd ? ` up to $${f.max_cost_usd}` : ''}${f.enabled ? '' : ' (off)'}`);
968
+ return undefined;
969
+ }
970
+ if (sub === 'show') {
971
+ if (!first) throw new Error('Usage: forkit factory show NAME');
972
+ const s = await call(`/api/v1/factories/${encodeURIComponent(first)}`);
973
+ if (rest.includes('--json')) return out(JSON.stringify(s, null, 2));
974
+ out(`${s.factory.name}: ${s.runs} run${s.runs === 1 ? '' : 's'} (${s.finished} finished, ${s.failed} failed, ${s.waiting} waiting, ${s.running} running)`);
975
+ out(` judged: ${s.good} good, ${s.bad} bad${s.pass_rate === null ? '' : ` → ${Math.round(s.pass_rate * 100)}% good`}`);
976
+ out(` cost: about $${Number(s.cost_usd).toFixed(2)} in all${s.cost_per_run_usd === null ? '' : `, $${Number(s.cost_per_run_usd).toFixed(2)} a run`}${s.seconds_per_run === null ? '' : `; ${s.seconds_per_run} s a run`}`);
977
+ for (const r of s.recent.slice(0, 10)) out(` ${r.id} ${r.state} ${r.source}${r.verdict ? ` ${r.verdict}` : ''}${r.cost_usd ? ` $${Number(r.cost_usd).toFixed(2)}` : ''}${r.summary ? ` ${r.summary}` : ''}`);
978
+ return undefined;
979
+ }
980
+ if (sub === 'delete') {
981
+ if (!first) throw new Error('Usage: forkit factory delete NAME');
982
+ await call(`/api/v1/factories/${encodeURIComponent(first)}`, undefined, 'DELETE');
983
+ return out(`Deleted ${first}. Its webhook address no longer works.`);
984
+ }
985
+ if (sub === 'run') {
986
+ if (!first) throw new Error('Usage: forkit factory run NAME [--items-file FILE | --input-file FILE]');
987
+ const input = flag(rest, '--items-file') ? { items: readJson(flag(rest, '--items-file')) } : flag(rest, '--input-file') ? readJson(flag(rest, '--input-file')) : {};
988
+ const r = await call(`/api/v1/factories/${encodeURIComponent(first)}/runs`, input);
989
+ return out(`Asked for a run of ${first}: ${r.id}. A runner picks it up (forkit factory work ${first} --exec …).`);
990
+ }
991
+ if (sub === 'verdict') {
992
+ const [run, verdict] = rest.filter(a => !a.startsWith('-') && a !== flag(rest, '--note'));
993
+ if (!run || !verdict) throw new Error('Usage: forkit factory verdict RUN_ID good|bad [--note TEXT]');
994
+ await call(`/api/v1/factory-runs/${encodeURIComponent(run)}/verdict`, { verdict, note: flag(rest, '--note') });
995
+ return out(`Marked ${run} ${verdict}.`);
996
+ }
997
+ if (sub === 'asks') {
998
+ if (!first) throw new Error('Usage: forkit factory asks FANOUT_ID');
999
+ const { asks } = await call(`/api/v1/fanouts/${encodeURIComponent(first)}/asks`);
1000
+ if (!asks.length) return out('Nothing would have reached a person.');
1001
+ out('A real run would have asked a person:');
1002
+ for (const a of asks) out(` ${a.agents} agent${a.agents === 1 ? '' : 's'} ${a.tool}: ${a.subject} rule: ${a.suggested_rule}`);
1003
+ return undefined;
1004
+ }
1005
+ if (sub === 'work') {
1006
+ const exec = flag(rest, '--exec');
1007
+ if (!first || !exec) throw new Error('Usage: forkit factory work NAME --exec \'claude -p "$FORKIT_PROMPT" …\' [--once] [--repo-from DIR] [--dir DIR]');
1008
+ const base = flag(rest, '--dir') ?? join(homedir(), '.forkit', 'runs');
1009
+ const from = flag(rest, '--repo-from');
1010
+ const say = s => err(`[${new Date().toISOString().slice(11, 19)}] ${s}`);
1011
+ for (;;) {
1012
+ const { run } = await call(`/api/v1/factories/${encodeURIComponent(first)}/next`);
1013
+ if (!run) {
1014
+ if (rest.includes('--once')) return say('nothing is waiting');
1015
+ await new Promise(r => setTimeout(r, 5000));
1016
+ continue;
1017
+ }
1018
+ const started = await call(`/api/v1/factory-runs/${encodeURIComponent(run.id)}/start`, {});
1019
+ say(`run ${run.id}: ${started.agents.length} agent${started.agents.length === 1 ? '' : 's'}${started.fanout.shadow ? ' (shadow)' : ''}, fan-out ${started.fanout.id}`);
1020
+ // A repository the starting agent pushes (any private one).
1021
+ if (started.fanout.repo?.source === 'push') {
1022
+ if (!from) { await call(`/api/v1/factory-runs/${encodeURIComponent(run.id)}/finish`, { failed: true, summary: 'the runner was started without --repo-from' }); throw new Error('This factory pushes its repository: start the runner with --repo-from DIR'); }
1023
+ const target = await call(`/api/v1/fanouts/${encodeURIComponent(started.fanout.id)}/repos/base`, {});
1024
+ const pushed = spawnSync('git', ['-C', from, '-c', 'credential.helper=', '-c', `http.extraHeader=Authorization: Bearer ${target.token}`, 'push', '--quiet', target.remote, `HEAD:refs/heads/${target.branch}`], { stdio: ['ignore', 'ignore', 'inherit'] });
1025
+ if (pushed.status !== 0) { await call(`/api/v1/factory-runs/${encodeURIComponent(run.id)}/finish`, { failed: true, summary: 'could not push the starting code' }); throw new Error('could not push the starting code'); }
1026
+ await call(`/api/v1/fanouts/${encodeURIComponent(started.fanout.id)}/repos/ready`, {});
1027
+ }
1028
+ const codes = await Promise.all(started.agents.map(a => new Promise(resolve => {
1029
+ const dir = join(base, run.id, a.name);
1030
+ mkdirSync(dir, { recursive: true });
1031
+ const child = spawn(exec, {
1032
+ cwd: dir, shell: true, stdio: ['ignore', 'pipe', 'pipe'],
1033
+ env: { ...process.env, FORKIT_API_KEY: a.key, FORKIT_URL: cfg.url, FORKIT_PROMPT: a.prompt, FORKIT_TITLE: a.title, FORKIT_AGENT: a.name },
1034
+ });
1035
+ let last = '';
1036
+ const keep = d => { const t = String(d).trim().split('\n').at(-1); if (t) last = t; };
1037
+ child.stdout.on('data', keep);
1038
+ child.stderr.on('data', keep);
1039
+ child.on('close', code => { say(`${a.name} ended (${code}): ${last.slice(0, 120)}`); resolve(code); });
1040
+ child.on('error', () => resolve(127));
1041
+ })));
1042
+ const ok = codes.filter(c => c === 0).length;
1043
+ const done = await call(`/api/v1/factory-runs/${encodeURIComponent(run.id)}/finish`, { summary: `${ok} of ${codes.length} agents finished`, failed: ok === 0 });
1044
+ say(`run ${run.id} ${done.state}: ${ok} of ${codes.length} agents finished, about $${Number(done.cost_usd).toFixed(2)}`);
1045
+ if (started.fanout.shadow) {
1046
+ const { asks } = await call(`/api/v1/fanouts/${encodeURIComponent(started.fanout.id)}/asks`);
1047
+ for (const a of asks) say(`would ask a person: ${a.agents}× ${a.tool}: ${a.subject}`);
1048
+ if (!asks.length) say('nothing would have reached a person');
1049
+ }
1050
+ out(JSON.stringify({ run: run.id, fanout: started.fanout.id, state: done.state, agents: codes.length, finished: ok, cost_usd: done.cost_usd }));
1051
+ if (rest.includes('--once')) return undefined;
1052
+ }
1053
+ }
1054
+ throw new Error('Usage: forkit factory create | list | show | run | work | verdict | asks | delete');
1055
+ }
1056
+
549
1057
  async function init(argv) {
1058
+ if (argv.includes('--sandbox')) return initSandbox(argv);
550
1059
  const yes = argv.includes('--yes') || argv.includes('-y');
551
1060
  const canAsk = Boolean(process.stdin.isTTY);
552
1061
  let skippedForNoTerminal = false;
@@ -623,8 +1132,35 @@ async function init(argv) {
623
1132
  }
624
1133
  }
625
1134
 
626
- // 5. Codex: notify in ~/.codex/config.toml.
627
- if (agents.includes('codex')) {
1135
+ // 5. Codex: hooks in ~/.codex/hooks.json when this Codex runs them; otherwise notify in config.toml.
1136
+ let codexVersion = '';
1137
+ try { codexVersion = execFileSync('codex', ['--version'], { timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).toString(); } catch { /* not on PATH */ }
1138
+ // FORKIT_CODEX=hooks|notify overrides what the installed Codex version suggests.
1139
+ const codexMode = process.env.FORKIT_CODEX;
1140
+ const useCodexHooks = agents.includes('codex') && hookSource && (codexMode ? codexMode === 'hooks' : codexHasHooks(codexVersion));
1141
+ if (useCodexHooks) {
1142
+ const hookCopy = join(bin, 'forkit-hook.mjs');
1143
+ copyFileSync(hookSource, hookCopy);
1144
+ const path = join(homedir(), '.codex', 'hooks.json');
1145
+ let current = {};
1146
+ try { current = JSON.parse(readFileSync(path, 'utf8')); } catch (e) { if (existsSync(path)) { out(`! ${path} isn't valid JSON; skipped Codex. Fix it and run forkit init again.`); current = null; } }
1147
+ if (current) {
1148
+ const merged = mergeCodexHooks(current, hookCopy);
1149
+ if (!merged.added) out('✓ Codex already reports to Forkit');
1150
+ else if (!yes && !canAsk) { skippedForNoTerminal = true; out('– Skipped Codex'); }
1151
+ else if (await confirm(`Add Forkit's hooks to ${path}? (a backup is kept)`, yes)) {
1152
+ const saved = backup(path);
1153
+ mkdirSync(dirname(path), { recursive: true });
1154
+ writeFileSync(path, JSON.stringify(merged.config, null, 2));
1155
+ // The hooks now report each turn, so Forkit's older notify line would report it twice.
1156
+ const tomlPath = join(homedir(), '.codex', 'config.toml');
1157
+ const cleaned = removeForkitNotify(existsSync(tomlPath) ? readFileSync(tomlPath, 'utf8') : '');
1158
+ if (cleaned.changed) { backup(tomlPath); writeFileSync(tomlPath, cleaned.toml); }
1159
+ out(`✓ Codex connected: permission requests, questions and sessions go to Forkit${saved ? ` (backup: ${basename(saved)})` : ''}`);
1160
+ out(` One step left: open Codex and run ${C.bold('/hooks')} to trust Forkit's hooks. Codex skips hooks it hasn't been shown.`);
1161
+ } else out('– Skipped Codex');
1162
+ }
1163
+ } else if (agents.includes('codex')) {
628
1164
  const path = join(homedir(), '.codex', 'config.toml');
629
1165
  const toml = existsSync(path) ? readFileSync(path, 'utf8') : '';
630
1166
  const merged = mergeCodexNotify(toml, cliCopy);
@@ -658,8 +1194,24 @@ const HELP = `forkit: one inbox for every coding agent
658
1194
  forkit ask [--tool T] [--run] -- cmd ask permission for a command (exit 0 allowed, 1 denied, 2 no answer)
659
1195
  forkit run [--title T] -- <command> run an agent and report its session
660
1196
  forkit notify '<json>' Codex hook: notify = ["forkit", "notify"]
661
-
662
- Environment: FORKIT_API_KEY, FORKIT_URL, FORKIT_CAPTURE=full|minimal|off, FORKIT_PERMISSION_WAIT, FORKIT_REPLY_WAIT (seconds, max 840)
1197
+ forkit init --sandbox [--project] hooks only, nothing asked: for a sandbox image or CI (--project: into this repo's .claude/)
1198
+ forkit fanout create --name N --agents N [--ttl S] [--parent THREAD] [--max-tool-calls N] [--max-cost USD] [--keep-days N]
1199
+ keys for agents this agent starts elsewhere, printed once as JSON
1200
+ forkit fanout list | add ID --agents N | stop ID
1201
+ forkit usage --model M [--input N --output N | --cost USD] report what a session used, for any model or tool
1202
+ forkit share --to AGENT [-m TEXT] [-- PATHS] send another agent your change itself, as a patch on a message
1203
+ forkit apply MESSAGE_ID [--check] apply a patch another agent sent you to this checkout
1204
+ forkit check-merge [--exclude PATH] would your change merge with the other agents' of your fan-out?
1205
+ forkit factory create | list | show | run | work | verdict | asks | delete
1206
+ a saved fan-out, run on request, by webhook or on a schedule; work is the runner
1207
+ forkit fanout create ... --shadow a shadow run: what would need a person is refused and listed
1208
+ forkit fanout create ... --repo URL [--branch B] each agent works in its own fork of URL (public repositories)
1209
+ forkit repo clone [DIR] | info (a fan-out's agent) clone your fork; git asks Forkit for a fresh token each time
1210
+ forkit fanout collect ID [DIR] [--merge] every agent's pushed work as branches agent/<name>; --merge into fanout/<name>
1211
+ forkit fanout clean ID delete the fan-out's repositories now (kept 7 days after it ends otherwise)
1212
+ forkit fanout create ... --repo-from DIR [--branch B] any private repository: pushed from your checkout, no token given to Forkit
1213
+
1214
+ Environment: FORKIT_API_KEY, FORKIT_URL, FORKIT_CAPTURE=full|minimal|off, FORKIT_PERMISSION_WAIT, FORKIT_REPLY_WAIT (seconds, max 840), FORKIT_PARENT_THREAD (the planner thread that started this session), FORKIT_ON_TIMEOUT=deny (no terminal: refuse what nobody answered)
663
1215
  `;
664
1216
 
665
1217
  const { realpathSync } = await import('node:fs');
@@ -677,6 +1229,13 @@ if (isMain) {
677
1229
  else if (command === 'watch') await watch();
678
1230
  else if (command === 'inbox') await inbox(rest);
679
1231
  else if (command === 'ask') await ask(rest);
1232
+ else if (command === 'fanout') await fanout(rest);
1233
+ else if (command === 'repo') await repo(rest);
1234
+ else if (command === 'usage') await usage(rest);
1235
+ else if (command === 'share') await share(rest);
1236
+ else if (command === 'apply') await applyPatch(rest);
1237
+ else if (command === 'check-merge') await checkMergeCmd(rest);
1238
+ else if (command === 'factory') await factory(rest);
680
1239
  else out(HELP);
681
1240
  } catch (e) {
682
1241
  err(`forkit: ${e.message}`);