forkit-cli 0.0.0-stage → 0.2.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.
- package/forkit-hook.mjs +241 -0
- package/forkit.mjs +651 -0
- package/package.json +18 -4
- package/README.md +0 -3
package/forkit-hook.mjs
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Forkit capture hook for Claude Code.
|
|
4
|
+
*
|
|
5
|
+
* Reads one hook event on stdin and sends a small summary to Forkit, so the
|
|
6
|
+
* team inbox shows this session without Claude having to report anything.
|
|
7
|
+
* It never blocks or breaks Claude: it prints nothing, gives up after a few
|
|
8
|
+
* seconds, and always exits 0.
|
|
9
|
+
*
|
|
10
|
+
* Config: FORKIT_API_KEY and FORKIT_URL, or ~/.config/forkit/config.json
|
|
11
|
+
* (written by `forkit init`). FORKIT_CAPTURE=full (default) | minimal | off.
|
|
12
|
+
*
|
|
13
|
+
* Permission requests (the PermissionRequest hook): the request goes to Forkit,
|
|
14
|
+
* where a rule, the orchestrator or a person answers it. The hook waits up to
|
|
15
|
+
* FORKIT_PERMISSION_WAIT seconds (default 90); with no answer it prints nothing
|
|
16
|
+
* and Claude asks in the terminal as usual. Only in full mode, since deciding
|
|
17
|
+
* needs the command; FORKIT_PERMISSIONS=off turns this part off.
|
|
18
|
+
* full prompts, commands, Claude's final message per turn, file paths, states
|
|
19
|
+
* minimal file paths and states only, no prompt or command text
|
|
20
|
+
* off nothing
|
|
21
|
+
*/
|
|
22
|
+
import { execFileSync } from 'node:child_process';
|
|
23
|
+
import { readFileSync, openSync, readSync, fstatSync, closeSync, realpathSync } from 'node:fs';
|
|
24
|
+
import { homedir } from 'node:os';
|
|
25
|
+
import { join, relative, isAbsolute, resolve, dirname, basename } from 'node:path';
|
|
26
|
+
|
|
27
|
+
const TIMEOUT_MS = 2500;
|
|
28
|
+
|
|
29
|
+
function config() {
|
|
30
|
+
let file = {};
|
|
31
|
+
try { file = JSON.parse(readFileSync(join(homedir(), '.config', 'forkit', 'config.json'), 'utf8')); } catch { /* none */ }
|
|
32
|
+
return {
|
|
33
|
+
key: process.env.FORKIT_API_KEY || file.keys?.['claude-code'] || file.api_key,
|
|
34
|
+
url: (process.env.FORKIT_URL || file.url || 'https://forkit-mcp.com').replace(/\/+$/, ''),
|
|
35
|
+
mode: process.env.FORKIT_CAPTURE || file.capture || 'full',
|
|
36
|
+
permissions: (process.env.FORKIT_PERMISSIONS || file.permissions || 'on') !== 'off',
|
|
37
|
+
waitSeconds: Math.max(0, Number(process.env.FORKIT_PERMISSION_WAIT ?? file.permission_wait ?? 90) || 0),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function git(cwd, args) {
|
|
42
|
+
try {
|
|
43
|
+
return execFileSync('git', args, { cwd, timeout: 1500, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim() || undefined;
|
|
44
|
+
} catch { return undefined; }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** owner/name from git@github.com:owner/name.git or https://host/owner/name(.git). */
|
|
48
|
+
export function repoName(remote) {
|
|
49
|
+
if (!remote) return undefined;
|
|
50
|
+
const m = /[:/]([^/:]+\/[^/]+?)(?:\.git)?\/?$/.exec(remote.trim());
|
|
51
|
+
return m ? m[1] : undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function gitInfo(cwd) {
|
|
55
|
+
const root = git(cwd, ['rev-parse', '--show-toplevel']);
|
|
56
|
+
if (!root) return {};
|
|
57
|
+
return {
|
|
58
|
+
root,
|
|
59
|
+
repo: repoName(git(cwd, ['remote', 'get-url', 'origin'])),
|
|
60
|
+
branch: git(cwd, ['rev-parse', '--abbrev-ref', 'HEAD']),
|
|
61
|
+
head_sha: git(cwd, ['rev-parse', 'HEAD']),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Last assistant text in the transcript, reading only its tail. */
|
|
66
|
+
function lastAssistantText(path) {
|
|
67
|
+
if (!path) return undefined;
|
|
68
|
+
try {
|
|
69
|
+
const fd = openSync(path, 'r');
|
|
70
|
+
const size = fstatSync(fd).size;
|
|
71
|
+
const len = Math.min(size, 256 * 1024);
|
|
72
|
+
const buf = Buffer.alloc(len);
|
|
73
|
+
readSync(fd, buf, 0, len, size - len);
|
|
74
|
+
closeSync(fd);
|
|
75
|
+
const lines = buf.toString('utf8').split('\n').reverse();
|
|
76
|
+
for (const line of lines) {
|
|
77
|
+
if (!line.includes('"assistant"')) continue;
|
|
78
|
+
try {
|
|
79
|
+
const entry = JSON.parse(line);
|
|
80
|
+
if (entry.type !== 'assistant') continue;
|
|
81
|
+
const content = entry.message?.content;
|
|
82
|
+
const text = Array.isArray(content)
|
|
83
|
+
? content.filter(c => c?.type === 'text').map(c => c.text).join('\n').trim()
|
|
84
|
+
: typeof content === 'string' ? content.trim() : '';
|
|
85
|
+
if (text) return text;
|
|
86
|
+
} catch { /* partial first line */ }
|
|
87
|
+
}
|
|
88
|
+
} catch { /* unreadable transcript */ }
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Resolves symlinks, so /var/... and /private/var/... (macOS) or a symlinked
|
|
94
|
+
* projects folder compare equal. The file may not exist yet (a Write), so the
|
|
95
|
+
* nearest existing parent is resolved and the rest appended.
|
|
96
|
+
*/
|
|
97
|
+
function real(p) {
|
|
98
|
+
let head = p;
|
|
99
|
+
const tail = [];
|
|
100
|
+
for (let i = 0; i < 64; i++) {
|
|
101
|
+
try { return join(realpathSync(head), ...tail.reverse()); } catch { /* not there yet */ }
|
|
102
|
+
const parent = dirname(head);
|
|
103
|
+
if (parent === head) break;
|
|
104
|
+
tail.push(basename(head));
|
|
105
|
+
head = parent;
|
|
106
|
+
}
|
|
107
|
+
return p;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Paths inside the repo only, relative to its root; nothing from elsewhere on disk. */
|
|
111
|
+
export function repoPath(root, cwd, file) {
|
|
112
|
+
if (!root || typeof file !== 'string') return undefined;
|
|
113
|
+
const abs = isAbsolute(file) ? file : resolve(cwd, file);
|
|
114
|
+
const rel = relative(real(root), real(abs));
|
|
115
|
+
return rel && !rel.startsWith('..') && !isAbsolute(rel) ? rel.split('\\').join('/') : undefined;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Turns one Claude Code hook input into zero or more Forkit capture events. */
|
|
119
|
+
export function toEvents(input, info, mode) {
|
|
120
|
+
const full = mode === 'full';
|
|
121
|
+
const cwd = input.cwd || process.cwd();
|
|
122
|
+
const where = info.repo ? ` in ${info.repo}` : '';
|
|
123
|
+
switch (input.hook_event_name) {
|
|
124
|
+
case 'SessionStart':
|
|
125
|
+
return input.source === 'resume' || input.source === 'compact' || input.source === 'clear'
|
|
126
|
+
? [] : [{ event: 'start', title: `Claude Code session${where}` }];
|
|
127
|
+
case 'UserPromptSubmit': {
|
|
128
|
+
const prompt = input.prompt ?? input.user_prompt;
|
|
129
|
+
return [{ event: 'prompt', body: full && typeof prompt === 'string' ? prompt : undefined }];
|
|
130
|
+
}
|
|
131
|
+
case 'PostToolUse': {
|
|
132
|
+
const tool = input.tool_name;
|
|
133
|
+
const ti = input.tool_input || {};
|
|
134
|
+
if (tool === 'Bash') {
|
|
135
|
+
if (!full || typeof ti.command !== 'string') return [];
|
|
136
|
+
const res = input.tool_response ?? input.tool_result ?? {};
|
|
137
|
+
const exit = typeof res.exit_code === 'number' ? res.exit_code : typeof res.exitCode === 'number' ? res.exitCode : undefined;
|
|
138
|
+
return [{ event: 'command', command: ti.command, exit_code: exit }];
|
|
139
|
+
}
|
|
140
|
+
const p = repoPath(info.root, cwd, ti.file_path ?? ti.notebook_path);
|
|
141
|
+
return p ? [{ event: 'files', paths: [p] }] : [];
|
|
142
|
+
}
|
|
143
|
+
case 'Notification': {
|
|
144
|
+
const msg = typeof input.message === 'string' ? input.message : '';
|
|
145
|
+
// Permission prompts stop Claude until someone answers; "waiting for your input" just means the turn ended.
|
|
146
|
+
const needsYou = input.notification_type === 'permission_prompt' || /permission|approve|allow/i.test(msg);
|
|
147
|
+
return needsYou ? [{ event: 'waiting', body: msg || 'Claude needs your permission' }] : [];
|
|
148
|
+
}
|
|
149
|
+
case 'Stop': {
|
|
150
|
+
const text = full ? lastAssistantText(input.transcript_path) : undefined;
|
|
151
|
+
return [...(text ? [{ event: 'message', body: text }] : []), { event: 'idle' }];
|
|
152
|
+
}
|
|
153
|
+
case 'SessionEnd':
|
|
154
|
+
return [{ event: 'end' }];
|
|
155
|
+
default:
|
|
156
|
+
return [];
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** What the decision is about: the command, the file (repo-relative, or ~/… outside it), the URL. */
|
|
161
|
+
export function permissionSubject(input, info) {
|
|
162
|
+
const ti = input.tool_input || {};
|
|
163
|
+
if (input.tool_name === 'Bash' && typeof ti.command === 'string') return ti.command;
|
|
164
|
+
const file = ti.file_path ?? ti.notebook_path ?? ti.path;
|
|
165
|
+
if (typeof file === 'string') {
|
|
166
|
+
const rel = repoPath(info.root, input.cwd || process.cwd(), file);
|
|
167
|
+
if (rel) return rel;
|
|
168
|
+
const home = homedir();
|
|
169
|
+
return file.startsWith(`${home}/`) ? `~/${file.slice(home.length + 1)}` : file;
|
|
170
|
+
}
|
|
171
|
+
if (typeof ti.url === 'string') return ti.url;
|
|
172
|
+
return JSON.stringify(ti).slice(0, 500);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function call(cfg, path, body, timeoutMs) {
|
|
176
|
+
const res = await fetch(`${cfg.url}${path}`, {
|
|
177
|
+
method: body === undefined ? 'GET' : 'POST',
|
|
178
|
+
headers: { Authorization: `Bearer ${cfg.key}`, 'Content-Type': 'application/json', 'User-Agent': 'forkit-claude-code/0.2' },
|
|
179
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
180
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
181
|
+
});
|
|
182
|
+
return res.ok ? res.json() : null;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Asks Forkit and waits for an answer. Returns the hook output to print, or
|
|
187
|
+
* null for "no answer": Claude then shows its own prompt.
|
|
188
|
+
*/
|
|
189
|
+
export async function askForkit(cfg, input, info, refs) {
|
|
190
|
+
const subject = permissionSubject(input, info);
|
|
191
|
+
const asked = await call(cfg, '/api/v1/permissions', {
|
|
192
|
+
source: 'claude-code', session_id: input.session_id, tool: input.tool_name, subject,
|
|
193
|
+
input: input.tool_input, ...refs,
|
|
194
|
+
}, 4000).catch(() => null);
|
|
195
|
+
if (!asked?.id) return null;
|
|
196
|
+
let r = asked;
|
|
197
|
+
const deadline = Date.now() + cfg.waitSeconds * 1000;
|
|
198
|
+
while (r && r.state === 'pending') {
|
|
199
|
+
const left = Math.floor((deadline - Date.now()) / 1000);
|
|
200
|
+
if (left < 1) break;
|
|
201
|
+
const wait = Math.min(left, 110);
|
|
202
|
+
r = await call(cfg, `/api/v1/permissions/${encodeURIComponent(asked.id)}/wait?timeout=${wait}`, undefined, (wait + 10) * 1000).catch(() => null);
|
|
203
|
+
}
|
|
204
|
+
if (r?.decision === 'allow' || r?.decision === 'deny') {
|
|
205
|
+
const decision = r.decision === 'allow' ? { behavior: 'allow' } : { behavior: 'deny', message: r.message };
|
|
206
|
+
return { hookSpecificOutput: { hookEventName: 'PermissionRequest', decision } };
|
|
207
|
+
}
|
|
208
|
+
// Nobody answered in time: say so, and let Claude ask in its terminal.
|
|
209
|
+
await call(cfg, `/api/v1/permissions/${encodeURIComponent(asked.id)}/withdraw`, {}, 3000).catch(() => null);
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function main() {
|
|
214
|
+
const cfg = config();
|
|
215
|
+
const { key, url, mode } = cfg;
|
|
216
|
+
if (!key || mode === 'off') return;
|
|
217
|
+
let raw = '';
|
|
218
|
+
for await (const chunk of process.stdin) raw += chunk;
|
|
219
|
+
const input = JSON.parse(raw);
|
|
220
|
+
if (!input.session_id) return;
|
|
221
|
+
const info = gitInfo(input.cwd || process.cwd());
|
|
222
|
+
const refs = { repo: info.repo, branch: info.branch === 'HEAD' ? undefined : info.branch, head_sha: info.head_sha };
|
|
223
|
+
if (input.hook_event_name === 'PermissionRequest') {
|
|
224
|
+
if (mode !== 'full' || !cfg.permissions || !input.tool_name) return;
|
|
225
|
+
const out = await askForkit(cfg, input, info, refs);
|
|
226
|
+
if (out) process.stdout.write(JSON.stringify(out));
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
for (const ev of toEvents(input, info, mode)) {
|
|
230
|
+
await fetch(`${url}/api/v1/capture`, {
|
|
231
|
+
method: 'POST',
|
|
232
|
+
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json', 'User-Agent': 'forkit-claude-code/0.1' },
|
|
233
|
+
body: JSON.stringify({ source: 'claude-code', session_id: input.session_id, ...refs, ...ev }),
|
|
234
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith('forkit-hook.mjs')) {
|
|
240
|
+
main().catch(() => {}).finally(() => process.exit(0));
|
|
241
|
+
}
|
package/forkit.mjs
ADDED
|
@@ -0,0 +1,651 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* forkit: one inbox for every coding agent, from the terminal.
|
|
4
|
+
*
|
|
5
|
+
* forkit init [--url URL] [--yes] sign in, create agent keys, connect Claude Code and Codex
|
|
6
|
+
* forkit login | logout | whoami sign this terminal in as you (a code you confirm in the browser)
|
|
7
|
+
* forkit watch live inbox: answer, allow or deny with one key
|
|
8
|
+
* forkit inbox [--json] what needs you, once
|
|
9
|
+
* forkit ask [--tool Bash] -- <cmd> ask Forkit for permission (any agent); --run runs it if allowed
|
|
10
|
+
* forkit run [--title T] -- <cmd> run an agent and report its session
|
|
11
|
+
* forkit notify '<json>' Codex: notify = ["forkit", "notify"]
|
|
12
|
+
*
|
|
13
|
+
* Config: ~/.config/forkit/config.json (mode 600). Environment: FORKIT_API_KEY,
|
|
14
|
+
* FORKIT_URL, FORKIT_CAPTURE=full|minimal|off, FORKIT_PERMISSION_WAIT (seconds).
|
|
15
|
+
*/
|
|
16
|
+
import { spawn, execFileSync, spawnSync } from 'node:child_process';
|
|
17
|
+
import { readFileSync, writeFileSync, mkdirSync, chmodSync, copyFileSync, existsSync } from 'node:fs';
|
|
18
|
+
import { homedir } from 'node:os';
|
|
19
|
+
import { join, basename, dirname } from 'node:path';
|
|
20
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
21
|
+
import { fileURLToPath } from 'node:url';
|
|
22
|
+
import { createInterface } from 'node:readline';
|
|
23
|
+
|
|
24
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
25
|
+
const DEFAULT_URL = 'https://forkit-mcp.com';
|
|
26
|
+
const configDir = () => join(homedir(), '.config', 'forkit');
|
|
27
|
+
const configFile = () => join(configDir(), 'config.json');
|
|
28
|
+
|
|
29
|
+
function readConfig() {
|
|
30
|
+
try { return JSON.parse(readFileSync(configFile(), 'utf8')); } catch { return {}; }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function writeConfig(next) {
|
|
34
|
+
mkdirSync(configDir(), { recursive: true, mode: 0o700 });
|
|
35
|
+
writeFileSync(configFile(), JSON.stringify(next, null, 2), { mode: 0o600 });
|
|
36
|
+
chmodSync(configFile(), 0o600);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function config(source) {
|
|
40
|
+
const file = readConfig();
|
|
41
|
+
return {
|
|
42
|
+
key: process.env.FORKIT_API_KEY || (source && file.keys?.[source]) || file.api_key,
|
|
43
|
+
url: (process.env.FORKIT_URL || file.url || DEFAULT_URL).replace(/\/+$/, ''),
|
|
44
|
+
mode: process.env.FORKIT_CAPTURE || file.capture || 'full',
|
|
45
|
+
session: process.env.FORKIT_SESSION_TOKEN || file.session?.token,
|
|
46
|
+
file,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function flag(argv, name) {
|
|
51
|
+
const i = argv.indexOf(name);
|
|
52
|
+
return i === -1 ? undefined : argv[i + 1];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const out = (s = '') => process.stdout.write(`${s}\n`);
|
|
56
|
+
const err = (s) => process.stderr.write(`${s}\n`);
|
|
57
|
+
|
|
58
|
+
// ── git ──────────────────────────────────────────────────────────────────
|
|
59
|
+
|
|
60
|
+
function git(args) {
|
|
61
|
+
try {
|
|
62
|
+
return execFileSync('git', args, { timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim() || undefined;
|
|
63
|
+
} catch { return undefined; }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function repoName(remote) {
|
|
67
|
+
if (!remote) return undefined;
|
|
68
|
+
const m = /[:/]([^/:]+\/[^/]+?)(?:\.git)?\/?$/.exec(remote.trim());
|
|
69
|
+
return m ? m[1] : undefined;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function refs() {
|
|
73
|
+
const branch = git(['rev-parse', '--abbrev-ref', 'HEAD']);
|
|
74
|
+
return {
|
|
75
|
+
repo: repoName(git(['remote', 'get-url', 'origin'])),
|
|
76
|
+
branch: branch === 'HEAD' ? undefined : branch,
|
|
77
|
+
head_sha: git(['rev-parse', 'HEAD']),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function lines(text) { return text ? text.split('\n').filter(Boolean) : []; }
|
|
82
|
+
|
|
83
|
+
/** Files changed since `startSha`, plus untracked files that weren't there at the start. */
|
|
84
|
+
function changedFiles(startSha, untrackedBefore) {
|
|
85
|
+
const tracked = startSha ? lines(git(['diff', '--name-only', startSha])) : lines(git(['diff', '--name-only', 'HEAD']));
|
|
86
|
+
const untracked = lines(git(['ls-files', '--others', '--exclude-standard'])).filter(f => !untrackedBefore.has(f));
|
|
87
|
+
return [...new Set([...tracked, ...untracked])].slice(0, 500);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// ── HTTP ─────────────────────────────────────────────────────────────────
|
|
91
|
+
|
|
92
|
+
/** Agent calls: never throw, never block the agent for long. */
|
|
93
|
+
async function send(cfg, body, path = '/api/v1/capture') {
|
|
94
|
+
if (!cfg.key || cfg.mode === 'off') return null;
|
|
95
|
+
try {
|
|
96
|
+
const res = await fetch(`${cfg.url}${path}`, {
|
|
97
|
+
method: 'POST',
|
|
98
|
+
headers: { Authorization: `Bearer ${cfg.key}`, 'Content-Type': 'application/json', 'User-Agent': 'forkit-cli/0.2' },
|
|
99
|
+
body: JSON.stringify(body),
|
|
100
|
+
signal: AbortSignal.timeout(4000),
|
|
101
|
+
});
|
|
102
|
+
if (!res.ok) {
|
|
103
|
+
err(`forkit: ${res.status} ${(await res.text()).slice(0, 200)}`);
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
return await res.json();
|
|
107
|
+
} catch (e) {
|
|
108
|
+
err(`forkit: could not reach ${cfg.url} (${e?.message ?? e})`);
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Calls made as the person signed in with `forkit login`. */
|
|
114
|
+
async function me(cfg, path, body, timeoutMs = 15000) {
|
|
115
|
+
if (!cfg.session) throw Object.assign(new Error('Not signed in. Run `forkit login` first.'), { status: 401 });
|
|
116
|
+
const res = await fetch(`${cfg.url}${path}`, {
|
|
117
|
+
method: body === undefined ? 'GET' : 'POST',
|
|
118
|
+
headers: { Authorization: `Bearer ${cfg.session}`, Accept: 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'forkit-cli/0.2' },
|
|
119
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
120
|
+
redirect: 'manual',
|
|
121
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
122
|
+
});
|
|
123
|
+
const text = await res.text();
|
|
124
|
+
let json = null;
|
|
125
|
+
try { json = text ? JSON.parse(text) : null; } catch { /* not JSON */ }
|
|
126
|
+
if (!res.ok) {
|
|
127
|
+
const message = res.status === 401 || res.status === 302 ? 'Your terminal session ended. Run `forkit login` again.' : json?.error || `Forkit answered ${res.status}`;
|
|
128
|
+
throw Object.assign(new Error(message), { status: res.status });
|
|
129
|
+
}
|
|
130
|
+
return json;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function sourceFor(cmd) {
|
|
134
|
+
const name = basename(cmd).toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 40);
|
|
135
|
+
return /^[a-z0-9]/.test(name) ? name : 'cli';
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// ── run / notify (passive capture) ───────────────────────────────────────
|
|
139
|
+
|
|
140
|
+
async function run(argv) {
|
|
141
|
+
const sep = argv.indexOf('--');
|
|
142
|
+
const opts = sep === -1 ? [] : argv.slice(0, sep);
|
|
143
|
+
const cmd = sep === -1 ? argv : argv.slice(sep + 1);
|
|
144
|
+
const title = flag(opts, '--title');
|
|
145
|
+
if (cmd.length === 0) {
|
|
146
|
+
err('usage: forkit run [--title "what this is for"] -- <command> [args...]');
|
|
147
|
+
process.exit(2);
|
|
148
|
+
}
|
|
149
|
+
const source = sourceFor(cmd[0]);
|
|
150
|
+
const cfg = config(source);
|
|
151
|
+
if (!cfg.key) err('forkit: no API key (run `forkit init` or set FORKIT_API_KEY); running without reporting.');
|
|
152
|
+
|
|
153
|
+
const session = randomUUID();
|
|
154
|
+
const start = refs();
|
|
155
|
+
const untrackedBefore = new Set(lines(git(['ls-files', '--others', '--exclude-standard'])));
|
|
156
|
+
const where = start.repo ? ` in ${start.repo}` : '';
|
|
157
|
+
const base = { source, session_id: session };
|
|
158
|
+
const started = await send(cfg, { ...base, ...start, event: 'start', title: title ?? `${cmd[0]}${where}` });
|
|
159
|
+
if (started) err(`forkit: reporting to ${cfg.url}/threads/${started.thread_id}`);
|
|
160
|
+
|
|
161
|
+
// The terminal sends Ctrl-C to the whole process group; let the child decide what it means.
|
|
162
|
+
const ignore = () => {};
|
|
163
|
+
process.on('SIGINT', ignore);
|
|
164
|
+
process.on('SIGTERM', ignore);
|
|
165
|
+
const child = spawn(cmd[0], cmd.slice(1), {
|
|
166
|
+
stdio: 'inherit',
|
|
167
|
+
env: { ...process.env, FORKIT_SESSION: session, FORKIT_SOURCE: source },
|
|
168
|
+
});
|
|
169
|
+
const code = await new Promise(resolve => {
|
|
170
|
+
child.on('error', e => { err(`forkit: ${e.message}`); resolve(127); });
|
|
171
|
+
child.on('exit', (c, signal) => resolve(c ?? (signal ? 128 : 1)));
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
const end = refs();
|
|
175
|
+
const files = changedFiles(start.head_sha, untrackedBefore);
|
|
176
|
+
if (files.length) await send(cfg, { ...base, ...end, event: 'files', paths: files });
|
|
177
|
+
if (cfg.mode === 'full') await send(cfg, { ...base, ...end, event: 'command', command: cmd.join(' '), exit_code: code });
|
|
178
|
+
await send(cfg, { ...base, ...end, event: 'end' });
|
|
179
|
+
process.exit(code);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Codex calls this after each turn with a JSON payload as the last argument. */
|
|
183
|
+
async function notify(argv) {
|
|
184
|
+
let payload = {};
|
|
185
|
+
try { payload = JSON.parse(argv[argv.length - 1] ?? '{}'); } catch { return; }
|
|
186
|
+
if (payload.type && payload.type !== 'agent-turn-complete') return;
|
|
187
|
+
const source = process.env.FORKIT_SOURCE || 'codex';
|
|
188
|
+
const cfg = config(source);
|
|
189
|
+
const session = process.env.FORKIT_SESSION || payload['thread-id'] || payload.thread_id
|
|
190
|
+
|| createHash('sha256').update(`${process.cwd()}:${new Date().toISOString().slice(0, 10)}`).digest('hex').slice(0, 32);
|
|
191
|
+
const base = { source, session_id: String(session), ...refs() };
|
|
192
|
+
const message = payload['last-assistant-message'] ?? payload.last_assistant_message;
|
|
193
|
+
if (cfg.mode === 'full' && typeof message === 'string' && message.trim()) await send(cfg, { ...base, event: 'message', body: message });
|
|
194
|
+
await send(cfg, { ...base, event: 'idle' });
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ── ask: permission for any agent ────────────────────────────────────────
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Exit codes: 0 allowed, 1 denied, 2 no answer in time (or Forkit unreachable).
|
|
201
|
+
* With --run, an allowed command runs and its exit code is returned.
|
|
202
|
+
*/
|
|
203
|
+
async function ask(argv) {
|
|
204
|
+
const sep = argv.indexOf('--');
|
|
205
|
+
const opts = sep === -1 ? argv : argv.slice(0, sep);
|
|
206
|
+
const cmd = sep === -1 ? [] : argv.slice(sep + 1);
|
|
207
|
+
if (!cmd.length) {
|
|
208
|
+
err('usage: forkit ask [--tool Bash] [--wait 90] [--title T] [--run] -- <command> [args...]');
|
|
209
|
+
process.exit(2);
|
|
210
|
+
}
|
|
211
|
+
const source = process.env.FORKIT_SOURCE || 'cli';
|
|
212
|
+
const cfg = config(source);
|
|
213
|
+
if (!cfg.key) { err('forkit: no API key (run `forkit init` or set FORKIT_API_KEY).'); process.exit(2); }
|
|
214
|
+
const waitSeconds = Number(flag(opts, '--wait') ?? process.env.FORKIT_PERMISSION_WAIT ?? 90);
|
|
215
|
+
const subject = cmd.join(' ');
|
|
216
|
+
const asked = await send({ ...cfg, mode: 'full' }, {
|
|
217
|
+
source, session_id: process.env.FORKIT_SESSION || randomUUID(), tool: flag(opts, '--tool') || 'Bash', subject,
|
|
218
|
+
title: flag(opts, '--title'), ...refs(),
|
|
219
|
+
}, '/api/v1/permissions');
|
|
220
|
+
if (!asked?.id) process.exit(2);
|
|
221
|
+
let r = asked;
|
|
222
|
+
if (r.state === 'pending') err(`forkit: waiting for an answer (${cfg.url}/threads/${r.thread_id})`);
|
|
223
|
+
const deadline = Date.now() + waitSeconds * 1000;
|
|
224
|
+
while (r && r.state === 'pending') {
|
|
225
|
+
const left = Math.floor((deadline - Date.now()) / 1000);
|
|
226
|
+
if (left < 1) break;
|
|
227
|
+
const wait = Math.min(left, 110);
|
|
228
|
+
try {
|
|
229
|
+
const res = await fetch(`${cfg.url}/api/v1/permissions/${asked.id}/wait?timeout=${wait}`, {
|
|
230
|
+
headers: { Authorization: `Bearer ${cfg.key}` }, signal: AbortSignal.timeout((wait + 10) * 1000),
|
|
231
|
+
});
|
|
232
|
+
r = res.ok ? await res.json() : null;
|
|
233
|
+
} catch { r = null; }
|
|
234
|
+
}
|
|
235
|
+
if (r?.decision === 'allow') {
|
|
236
|
+
err(`forkit: ${r.message}`);
|
|
237
|
+
if (opts.includes('--run')) {
|
|
238
|
+
const child = spawnSync(cmd[0], cmd.slice(1), { stdio: 'inherit' });
|
|
239
|
+
process.exit(child.status ?? 1);
|
|
240
|
+
}
|
|
241
|
+
process.exit(0);
|
|
242
|
+
}
|
|
243
|
+
if (r?.decision === 'deny') { err(`forkit: ${r.message}`); process.exit(1); }
|
|
244
|
+
await send({ ...cfg, mode: 'full' }, {}, `/api/v1/permissions/${asked.id}/withdraw`);
|
|
245
|
+
err('forkit: no answer in time');
|
|
246
|
+
process.exit(2);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// ── login ────────────────────────────────────────────────────────────────
|
|
250
|
+
|
|
251
|
+
function openBrowser(url) {
|
|
252
|
+
const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
|
|
253
|
+
const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
|
|
254
|
+
try { spawn(cmd, args, { stdio: 'ignore', detached: true }).unref(); return true; } catch { return false; }
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async function login(argv, { quiet = false } = {}) {
|
|
258
|
+
const file = readConfig();
|
|
259
|
+
const url = (flag(argv, '--url') || process.env.FORKIT_URL || file.url || DEFAULT_URL).replace(/\/+$/, '');
|
|
260
|
+
const start = await fetch(`${url}/api/cli/login/start`, { method: 'POST', signal: AbortSignal.timeout(10000) }).then(r => (r.ok ? r.json() : null)).catch(() => null);
|
|
261
|
+
if (!start?.device_code) { err(`forkit: could not reach ${url}`); process.exit(1); }
|
|
262
|
+
out(`\n Your code: ${start.user_code}\n\n Confirm it in the browser: ${start.verification_url}\n`);
|
|
263
|
+
if (!argv.includes('--no-browser') && !process.env.FORKIT_NO_BROWSER) openBrowser(start.verification_url);
|
|
264
|
+
const until = Date.now() + start.expires_in * 1000;
|
|
265
|
+
while (Date.now() < until) {
|
|
266
|
+
await new Promise(r => setTimeout(r, (start.interval || 2) * 1000));
|
|
267
|
+
const res = await fetch(`${url}/api/cli/login/poll`, {
|
|
268
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ device_code: start.device_code }), signal: AbortSignal.timeout(10000),
|
|
269
|
+
}).catch(() => null);
|
|
270
|
+
if (!res) continue;
|
|
271
|
+
const body = await res.json().catch(() => ({}));
|
|
272
|
+
if (body.status === 'approved') {
|
|
273
|
+
writeConfig({ ...readConfig(), url, session: { token: body.token, login: body.login, workspace: body.workspace } });
|
|
274
|
+
if (!quiet) out(`Signed in as ${body.login} in ${body.workspace.name}.`);
|
|
275
|
+
return body;
|
|
276
|
+
}
|
|
277
|
+
if (body.status === 'expired') break;
|
|
278
|
+
}
|
|
279
|
+
err('forkit: the code expired. Run `forkit login` again.');
|
|
280
|
+
process.exit(1);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function logout() {
|
|
284
|
+
const { session, ...rest } = readConfig();
|
|
285
|
+
writeConfig(rest);
|
|
286
|
+
out(session ? 'Signed out of this terminal.' : 'This terminal was not signed in.');
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function whoami() {
|
|
290
|
+
const cfg = config();
|
|
291
|
+
try {
|
|
292
|
+
const inbox = await me(cfg, '/api/me/inbox');
|
|
293
|
+
out(`${inbox.user.login} in ${inbox.workspace.name} (${cfg.url})`);
|
|
294
|
+
} catch (e) { err(`forkit: ${e.message}`); process.exit(1); }
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// ── inbox and watch ──────────────────────────────────────────────────────
|
|
298
|
+
|
|
299
|
+
const color = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
300
|
+
const paint = (code) => (s) => (color ? `\x1b[${code}m${s}\x1b[0m` : String(s));
|
|
301
|
+
const C = { dim: paint('2'), bold: paint('1'), ask: paint('38;2;245;165;36'), review: paint('38;2;122;162;255'), ok: paint('38;2;61;214;140'), bad: paint('38;2;255;99;105'), inv: paint('7') };
|
|
302
|
+
const LABEL = { waiting: 'waiting', review: 'review', blocked: 'blocked' };
|
|
303
|
+
|
|
304
|
+
function ago(iso) {
|
|
305
|
+
const m = Math.floor((Date.now() - new Date(iso).getTime()) / 60000);
|
|
306
|
+
if (m < 1) return 'now';
|
|
307
|
+
if (m < 60) return `${m}m`;
|
|
308
|
+
const h = Math.floor(m / 60);
|
|
309
|
+
return h < 24 ? `${h}h` : `${Math.floor(h / 24)}d`;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function stateTag(t) {
|
|
313
|
+
if (t.permission) return C.ask('permission');
|
|
314
|
+
return t.state === 'waiting' ? C.ask(LABEL.waiting) : t.state === 'review' ? C.review(LABEL.review) : C.bad(LABEL.blocked);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function headline(t) {
|
|
318
|
+
return t.permission ? `${t.agent} wants to ${t.permission.verb}: ${t.permission.subject}` : t.question;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async function inbox(argv) {
|
|
322
|
+
const cfg = config();
|
|
323
|
+
let data;
|
|
324
|
+
try { data = await me(cfg, '/api/me/inbox'); } catch (e) { err(`forkit: ${e.message}`); process.exit(1); }
|
|
325
|
+
if (argv.includes('--json')) return out(JSON.stringify(data, null, 2));
|
|
326
|
+
out(`${data.workspace.name} · ${data.needs_you.length} need${data.needs_you.length === 1 ? 's' : ''} you · ${data.in_progress} in progress`);
|
|
327
|
+
for (const t of data.needs_you) out(` ● ${t.state.padEnd(7)} ${t.agent.padEnd(12)} ${headline(t)} ${t.url}`);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function width() { return Math.max(40, process.stdout.columns || 100); }
|
|
331
|
+
function clip(s, n) { s = String(s).replace(/\s+/g, ' '); return s.length > n ? `${s.slice(0, n - 1)}…` : s; }
|
|
332
|
+
|
|
333
|
+
async function watch() {
|
|
334
|
+
const cfg = config();
|
|
335
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) return inbox([]);
|
|
336
|
+
if (!cfg.session) { err('forkit: not signed in. Run `forkit login` first.'); process.exit(1); }
|
|
337
|
+
|
|
338
|
+
let data = null;
|
|
339
|
+
let error = null;
|
|
340
|
+
let cursor = 0;
|
|
341
|
+
let flash = '';
|
|
342
|
+
let seen = null;
|
|
343
|
+
let busy = false;
|
|
344
|
+
let prompting = false;
|
|
345
|
+
|
|
346
|
+
const items = () => data?.needs_you ?? [];
|
|
347
|
+
const draw = () => {
|
|
348
|
+
if (prompting) return;
|
|
349
|
+
const w = width();
|
|
350
|
+
const rows = [];
|
|
351
|
+
const n = items().length;
|
|
352
|
+
rows.push(`${C.bold('forkit watch')} ${C.dim(data ? `${data.workspace.name} · ${data.user.login}` : cfg.url)}`);
|
|
353
|
+
rows.push(data ? `${n ? C.ask(`${n} need${n === 1 ? 's' : ''} you`) : C.ok('nothing needs you')}${C.dim(` · ${data.in_progress} in progress`)}` : C.dim('loading…'));
|
|
354
|
+
if (error) rows.push(C.bad(error));
|
|
355
|
+
rows.push('');
|
|
356
|
+
items().forEach((t, i) => {
|
|
357
|
+
const on = i === cursor;
|
|
358
|
+
const line = `${on ? '›' : ' '} ${stateTag(t)} ${C.dim(clip(t.agent + (t.owner && !t.mine ? ` · ${t.owner}` : ''), 22))} ${clip(headline(t), w - 40)} ${C.dim(ago(t.last_event_at))}`;
|
|
359
|
+
rows.push(on ? C.bold(line) : line);
|
|
360
|
+
if (on) {
|
|
361
|
+
if (t.repo) rows.push(C.dim(` ${[t.repo, t.branch].filter(Boolean).join(' · ')}`));
|
|
362
|
+
if (t.permission?.sensitive) rows.push(C.bad(` ${t.permission.sensitive} always needs a person: allow once or deny.`));
|
|
363
|
+
rows.push(` ${actionsFor(t).map(([k, label]) => `${C.inv(` ${k} `)} ${label}`).join(' ')}`);
|
|
364
|
+
rows.push('');
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
if (!n && data) rows.push(C.dim(' Your agents are working. This updates by itself; you get a bell when one needs you.'));
|
|
368
|
+
rows.push('');
|
|
369
|
+
if (flash) rows.push(flash);
|
|
370
|
+
rows.push(C.dim('j/k move · o open in browser · r refresh · q quit'));
|
|
371
|
+
process.stdout.write(`\x1b[H\x1b[2J${rows.join('\n')}\n`);
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
const refresh = async () => {
|
|
375
|
+
try {
|
|
376
|
+
data = await me(cfg, '/api/me/inbox');
|
|
377
|
+
error = null;
|
|
378
|
+
const ids = data.needs_you.map(t => t.id);
|
|
379
|
+
if (seen && ids.some(id => !seen.includes(id))) process.stdout.write('\x07');
|
|
380
|
+
seen = ids;
|
|
381
|
+
cursor = Math.min(cursor, Math.max(0, ids.length - 1));
|
|
382
|
+
} catch (e) {
|
|
383
|
+
error = e.message;
|
|
384
|
+
if (e.status === 401) { cleanup(); err(`forkit: ${e.message}`); process.exit(1); }
|
|
385
|
+
}
|
|
386
|
+
draw();
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
const question = (q) => new Promise(resolve => {
|
|
390
|
+
prompting = true;
|
|
391
|
+
process.stdin.setRawMode(false);
|
|
392
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
393
|
+
rl.question(`\n${q} `, (answer) => {
|
|
394
|
+
rl.close();
|
|
395
|
+
process.stdin.setRawMode(true);
|
|
396
|
+
process.stdin.resume();
|
|
397
|
+
prompting = false;
|
|
398
|
+
resolve(answer.trim());
|
|
399
|
+
});
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
const act = async (fn, done) => {
|
|
403
|
+
if (busy) return;
|
|
404
|
+
busy = true;
|
|
405
|
+
try { await fn(); flash = C.ok(done); } catch (e) { flash = C.bad(e.message); }
|
|
406
|
+
busy = false;
|
|
407
|
+
await refresh();
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
function actionsFor(t) {
|
|
411
|
+
if (t.permission) {
|
|
412
|
+
if (!t.permission.can_answer) return [['o', `open (only ${t.owner ?? 'its person'} or an owner can answer)`]];
|
|
413
|
+
return t.permission.sensitive
|
|
414
|
+
? [['a', 'allow once'], ['d', 'deny'], ['o', 'open']]
|
|
415
|
+
: [['a', 'allow once'], ['h', 'allow for an hour'], ['r', `always: ${t.permission.pattern}`], ['d', 'deny'], ['o', 'open']];
|
|
416
|
+
}
|
|
417
|
+
if (t.state === 'review') return [['y', 'approve'], ['c', 'ask for changes'], ['o', 'open']];
|
|
418
|
+
const opts = (t.options ?? []).slice(0, 5).map((o, i) => [String(i + 1), o]);
|
|
419
|
+
return [...opts, ['m', 'reply'], ['o', 'open']];
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
const onKey = async (key) => {
|
|
423
|
+
if (prompting) return;
|
|
424
|
+
flash = '';
|
|
425
|
+
const t = items()[cursor];
|
|
426
|
+
if (key === '\u0003' || key === 'q') { cleanup(); process.exit(0); }
|
|
427
|
+
if (key === 'j' || key === '\x1b[B') { cursor = Math.min(cursor + 1, Math.max(0, items().length - 1)); return draw(); }
|
|
428
|
+
if (key === 'k' || key === '\x1b[A') { cursor = Math.max(cursor - 1, 0); return draw(); }
|
|
429
|
+
if (key === 'r') return refresh();
|
|
430
|
+
if (!t) return draw();
|
|
431
|
+
if (key === 'o') { openBrowser(t.url); flash = C.dim(`opened ${t.url}`); return draw(); }
|
|
432
|
+
const p = t.permission;
|
|
433
|
+
if (p && p.can_answer) {
|
|
434
|
+
const decide = (decision, extra, done) => act(() => me(cfg, `/api/me/permissions/${p.id}/decide`, { decision, ...extra }), done);
|
|
435
|
+
if (key === 'a') return decide('once', {}, `Allowed once: ${clip(p.subject, 60)}`);
|
|
436
|
+
if (key === 'h' && !p.sensitive) return decide('hour', {}, 'Allowed for an hour');
|
|
437
|
+
if (key === 'r' && !p.sensitive) return decide('rule', { pattern: p.pattern }, `Always allowed: ${p.pattern}`);
|
|
438
|
+
if (key === 'd') { const note = await question('Why? (optional, the agent sees it)'); return decide('deny', { note }, 'Denied'); }
|
|
439
|
+
return draw();
|
|
440
|
+
}
|
|
441
|
+
if (t.state === 'review') {
|
|
442
|
+
if (key === 'y') return act(() => me(cfg, `/api/me/threads/${t.id}/review`, { decision: 'approve', expected_seq: t.last_seq }), 'Approved');
|
|
443
|
+
if (key === 'c') {
|
|
444
|
+
const note = await question('What should change?');
|
|
445
|
+
if (!note) return draw();
|
|
446
|
+
return act(() => me(cfg, `/api/me/threads/${t.id}/review`, { decision: 'changes', body: note, expected_seq: t.last_seq }), 'Sent back with your note');
|
|
447
|
+
}
|
|
448
|
+
return draw();
|
|
449
|
+
}
|
|
450
|
+
if (/^[1-5]$/.test(key) && t.options?.[Number(key) - 1]) {
|
|
451
|
+
const o = t.options[Number(key) - 1];
|
|
452
|
+
return act(() => me(cfg, `/api/me/threads/${t.id}/reply`, { body: o }), `Answered “${o}”`);
|
|
453
|
+
}
|
|
454
|
+
if (key === 'm') {
|
|
455
|
+
const body = await question('Your answer:');
|
|
456
|
+
if (!body) return draw();
|
|
457
|
+
return act(() => me(cfg, `/api/me/threads/${t.id}/reply`, { body }), 'Answer sent');
|
|
458
|
+
}
|
|
459
|
+
draw();
|
|
460
|
+
};
|
|
461
|
+
|
|
462
|
+
const cleanup = () => {
|
|
463
|
+
clearInterval(timer);
|
|
464
|
+
try { process.stdin.setRawMode(false); } catch { /* not a TTY */ }
|
|
465
|
+
process.stdout.write('\x1b[?25h\x1b[?1049l');
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
process.stdout.write('\x1b[?1049h\x1b[?25l');
|
|
469
|
+
process.stdin.setRawMode(true);
|
|
470
|
+
process.stdin.setEncoding('utf8');
|
|
471
|
+
process.stdin.on('data', (k) => { onKey(k); });
|
|
472
|
+
process.stdout.on('resize', draw);
|
|
473
|
+
process.on('exit', cleanup);
|
|
474
|
+
const timer = setInterval(refresh, Number(process.env.FORKIT_WATCH_MS) || 3000);
|
|
475
|
+
await refresh();
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// ── init ─────────────────────────────────────────────────────────────────
|
|
479
|
+
|
|
480
|
+
function onPath(bin) {
|
|
481
|
+
const r = spawnSync(process.platform === 'win32' ? 'where' : 'which', [bin], { stdio: 'ignore' });
|
|
482
|
+
return r.status === 0;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
async function confirm(q, yes) {
|
|
486
|
+
if (yes || !process.stdin.isTTY) return yes;
|
|
487
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
488
|
+
const answer = await new Promise(resolve => rl.question(`${q} [Y/n] `, resolve));
|
|
489
|
+
rl.close();
|
|
490
|
+
return !/^n/i.test(answer.trim());
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function backup(path) {
|
|
494
|
+
if (!existsSync(path)) return null;
|
|
495
|
+
const to = `${path}.forkit-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`;
|
|
496
|
+
copyFileSync(path, to);
|
|
497
|
+
return to;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
const HOOK_EVENTS = ['SessionStart', 'UserPromptSubmit', 'PostToolUse', 'PermissionRequest', 'Notification', 'Stop', 'SessionEnd'];
|
|
501
|
+
|
|
502
|
+
/** Adds Forkit's hooks to Claude Code's settings, leaving everything else as it was. */
|
|
503
|
+
export function mergeClaudeHooks(settings, hookPath) {
|
|
504
|
+
const next = { ...settings, hooks: { ...(settings.hooks ?? {}) } };
|
|
505
|
+
const command = `node "${hookPath}"`;
|
|
506
|
+
let added = 0;
|
|
507
|
+
for (const event of HOOK_EVENTS) {
|
|
508
|
+
const groups = Array.isArray(next.hooks[event]) ? [...next.hooks[event]] : [];
|
|
509
|
+
const present = groups.some(g => (g.hooks ?? []).some(h => typeof h.command === 'string' && h.command.includes('forkit-hook.mjs')));
|
|
510
|
+
if (present) continue;
|
|
511
|
+
const timeout = event === 'PermissionRequest' ? 900 : event === 'Stop' ? 8 : 5;
|
|
512
|
+
groups.push({ ...(event === 'PostToolUse' ? { matcher: 'Bash|Edit|Write|MultiEdit|NotebookEdit' } : {}), hooks: [{ type: 'command', command, timeout }] });
|
|
513
|
+
next.hooks[event] = groups;
|
|
514
|
+
added += 1;
|
|
515
|
+
}
|
|
516
|
+
return { settings: next, added };
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/** Sets Codex's notify command, unless the person already has one of their own. */
|
|
520
|
+
export function mergeCodexNotify(toml, cliPath) {
|
|
521
|
+
const line = `notify = ["node", ${JSON.stringify(cliPath)}, "notify"]`;
|
|
522
|
+
const existing = /^\s*notify\s*=.*$/m.exec(toml);
|
|
523
|
+
if (existing) return existing[0].includes('forkit') ? { toml, changed: false, conflict: false } : { toml, changed: false, conflict: true, existing: existing[0].trim() };
|
|
524
|
+
// Top-level keys must come before the first [table].
|
|
525
|
+
return { toml: `${line}\n${toml}`, changed: true, conflict: false };
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
async function init(argv) {
|
|
529
|
+
const yes = argv.includes('--yes') || argv.includes('-y');
|
|
530
|
+
const positional = argv.filter((a, i) => !a.startsWith('-') && argv[i - 1] !== '--url' && argv[i - 1] !== '--agents');
|
|
531
|
+
// Old form: forkit init <api-key> just saves the key.
|
|
532
|
+
if (positional[0]) {
|
|
533
|
+
const next = { ...readConfig(), api_key: positional[0] };
|
|
534
|
+
const url = flag(argv, '--url');
|
|
535
|
+
if (url) next.url = url;
|
|
536
|
+
writeConfig(next);
|
|
537
|
+
return out(`Saved to ${configFile()}`);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
let cfg = config();
|
|
541
|
+
if (flag(argv, '--url')) { writeConfig({ ...readConfig(), url: flag(argv, '--url').replace(/\/+$/, '') }); cfg = config(); }
|
|
542
|
+
out(`Setting up Forkit (${cfg.url})\n`);
|
|
543
|
+
|
|
544
|
+
// 1. You, in this terminal.
|
|
545
|
+
let signedIn = null;
|
|
546
|
+
if (cfg.session) signedIn = await me(cfg, '/api/me/inbox').catch(() => null);
|
|
547
|
+
if (!signedIn) {
|
|
548
|
+
out('First, sign this terminal in.');
|
|
549
|
+
await login(argv, { quiet: true });
|
|
550
|
+
cfg = config();
|
|
551
|
+
signedIn = await me(cfg, '/api/me/inbox');
|
|
552
|
+
}
|
|
553
|
+
out(`✓ Signed in as ${signedIn.user.login} in ${signedIn.workspace.name}`);
|
|
554
|
+
|
|
555
|
+
// 2. One key per agent on this machine, so each shows up under its own name.
|
|
556
|
+
const requested = flag(argv, '--agents')?.split(',').map(s => s.trim()).filter(Boolean);
|
|
557
|
+
const agents = requested ?? [onPath('claude') && 'claude-code', onPath('codex') && 'codex'].filter(Boolean);
|
|
558
|
+
if (!agents.length) agents.push('claude-code');
|
|
559
|
+
const keys = { ...(cfg.file.keys ?? {}) };
|
|
560
|
+
for (const name of agents) {
|
|
561
|
+
if (keys[name]) { out(`✓ ${name} already has a key`); continue; }
|
|
562
|
+
const created = await me(cfg, '/api/keys', { name });
|
|
563
|
+
keys[name] = created.key;
|
|
564
|
+
out(`✓ Created a key for ${name}`);
|
|
565
|
+
}
|
|
566
|
+
writeConfig({ ...readConfig(), keys, api_key: readConfig().api_key ?? keys[agents[0]] });
|
|
567
|
+
|
|
568
|
+
// 3. Stable copies of the hook and this CLI, so the agents' settings point at files that stay put.
|
|
569
|
+
const bin = join(configDir(), 'bin');
|
|
570
|
+
mkdirSync(bin, { recursive: true });
|
|
571
|
+
const hookSource = [join(here, 'forkit-hook.mjs'), join(here, '..', 'claude-code', 'forkit', 'hooks', 'forkit-hook.mjs')].find(existsSync);
|
|
572
|
+
const cliCopy = join(bin, 'forkit.mjs');
|
|
573
|
+
copyFileSync(fileURLToPath(import.meta.url), cliCopy);
|
|
574
|
+
chmodSync(cliCopy, 0o755);
|
|
575
|
+
|
|
576
|
+
// 4. Claude Code: hooks in ~/.claude/settings.json.
|
|
577
|
+
if (agents.includes('claude-code')) {
|
|
578
|
+
if (!hookSource) out('! Could not find forkit-hook.mjs next to this CLI; skipped Claude Code.');
|
|
579
|
+
else {
|
|
580
|
+
const hookCopy = join(bin, 'forkit-hook.mjs');
|
|
581
|
+
copyFileSync(hookSource, hookCopy);
|
|
582
|
+
const path = join(homedir(), '.claude', 'settings.json');
|
|
583
|
+
let settings = {};
|
|
584
|
+
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
|
+
if (settings) {
|
|
586
|
+
const merged = mergeClaudeHooks(settings, hookCopy);
|
|
587
|
+
if (!merged.added) out('✓ Claude Code already reports to Forkit');
|
|
588
|
+
else if (await confirm(`Add Forkit's hooks to ${path}? (a backup is kept)`, yes)) {
|
|
589
|
+
const saved = backup(path);
|
|
590
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
591
|
+
writeFileSync(path, JSON.stringify(merged.settings, null, 2));
|
|
592
|
+
out(`✓ Claude Code connected: permission requests and sessions go to Forkit${saved ? ` (backup: ${basename(saved)})` : ''}`);
|
|
593
|
+
} else out('– Skipped Claude Code');
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
// 5. Codex: notify in ~/.codex/config.toml.
|
|
599
|
+
if (agents.includes('codex')) {
|
|
600
|
+
const path = join(homedir(), '.codex', 'config.toml');
|
|
601
|
+
const toml = existsSync(path) ? readFileSync(path, 'utf8') : '';
|
|
602
|
+
const merged = mergeCodexNotify(toml, cliCopy);
|
|
603
|
+
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
|
+
else if (!merged.changed) out('✓ Codex already reports to Forkit');
|
|
605
|
+
else if (await confirm(`Set Codex's notify command in ${path}? (a backup is kept)`, yes)) {
|
|
606
|
+
const saved = backup(path);
|
|
607
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
608
|
+
writeFileSync(path, merged.toml);
|
|
609
|
+
out(`✓ Codex connected: each finished turn goes to Forkit${saved ? ` (backup: ${basename(saved)})` : ''}`);
|
|
610
|
+
} else out('– Skipped Codex');
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
out(`\nDone. Run ${C.bold('forkit watch')} to answer your agents from this terminal, or open ${cfg.url}/inbox.`);
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// ── main ─────────────────────────────────────────────────────────────────
|
|
617
|
+
|
|
618
|
+
const HELP = `forkit: one inbox for every coding agent
|
|
619
|
+
|
|
620
|
+
forkit init [--url URL] [--yes] sign in, create agent keys, connect Claude Code and Codex
|
|
621
|
+
forkit login | logout | whoami sign this terminal in as you
|
|
622
|
+
forkit watch live inbox: answer, allow or deny with one key
|
|
623
|
+
forkit inbox [--json] what needs you, once
|
|
624
|
+
forkit ask [--tool T] [--run] -- cmd ask permission for a command (exit 0 allowed, 1 denied, 2 no answer)
|
|
625
|
+
forkit run [--title T] -- <command> run an agent and report its session
|
|
626
|
+
forkit notify '<json>' Codex hook: notify = ["forkit", "notify"]
|
|
627
|
+
|
|
628
|
+
Environment: FORKIT_API_KEY, FORKIT_URL, FORKIT_CAPTURE=full|minimal|off, FORKIT_PERMISSION_WAIT
|
|
629
|
+
`;
|
|
630
|
+
|
|
631
|
+
const { realpathSync } = await import('node:fs');
|
|
632
|
+
const real = (p) => { try { return realpathSync(p); } catch { return p; } };
|
|
633
|
+
const isMain = !!process.argv[1] && real(fileURLToPath(import.meta.url)) === real(process.argv[1]);
|
|
634
|
+
if (isMain) {
|
|
635
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
636
|
+
try {
|
|
637
|
+
if (command === 'run') await run(rest);
|
|
638
|
+
else if (command === 'notify') await notify(rest);
|
|
639
|
+
else if (command === 'init') await init(rest);
|
|
640
|
+
else if (command === 'login') await login(rest);
|
|
641
|
+
else if (command === 'logout') logout();
|
|
642
|
+
else if (command === 'whoami') await whoami();
|
|
643
|
+
else if (command === 'watch') await watch();
|
|
644
|
+
else if (command === 'inbox') await inbox(rest);
|
|
645
|
+
else if (command === 'ask') await ask(rest);
|
|
646
|
+
else out(HELP);
|
|
647
|
+
} catch (e) {
|
|
648
|
+
err(`forkit: ${e.message}`);
|
|
649
|
+
process.exit(1);
|
|
650
|
+
}
|
|
651
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "forkit-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "One inbox for every coding agent: report sessions, answer permission requests, and watch your agents from the terminal.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"forkit": "forkit.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"forkit.mjs",
|
|
11
|
+
"forkit-hook.mjs"
|
|
12
|
+
],
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=18.17"
|
|
15
|
+
},
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"scripts": {
|
|
18
|
+
"prepack": "cp ../claude-code/forkit/hooks/forkit-hook.mjs ./forkit-hook.mjs"
|
|
19
|
+
}
|
|
20
|
+
}
|
package/README.md
DELETED