Skip to content
refs
History
1268 lines · 58.0 KBRaw
1#!/usr/bin/env node
2import { execFileSync, spawn } from "node:child_process";
3import { createHash, randomBytes, randomUUID } from "node:crypto";
4import fs from "node:fs";
5import http from "node:http";
6import net from "node:net";
7import os from "node:os";
8import path from "node:path";
9import readline from "node:readline";
10import { parseArgs } from "node:util";
11
12const VERSION = "0.1.0";
13const HOME = process.env.REFS_HOME || path.join(os.homedir(), ".refs");
14const CREDENTIALS = path.join(HOME, "credentials.json");
15const GIT_TOKENS = path.join(HOME, "git-tokens.json");
16const SOCKET = path.join(HOME, "daemon.sock");
17const LOG = path.join(HOME, "daemon.log");
18const SCRIPT = path.join(HOME, "bin", "refs.mjs");
19const BIN = path.join(HOME, "bin", "refs");
20const MACHINE = (process.env.REFS_MACHINE || os.hostname().split(".")[0]).replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 64) || "machine";
21const LAUNCHD = path.join(os.homedir(), "Library", "LaunchAgents", "dev.refs.daemon.plist");
22const SYSTEMD = path.join(os.homedir(), ".config", "systemd", "user", "refs.service");
23const CLAUDE_SETTINGS = path.join(os.homedir(), ".claude", "settings.json");
24const RUNS = path.join(HOME, "runs.json");
25const OPENCODE_SESSIONS = path.join(HOME, "opencode-sessions.json");
26const OPENCODE_CONFIG = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "opencode");
27const OPENCODE_SERVICE = path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state"), "opencode", "service.json");
28const WORK = path.join(HOME, "work");
29const NETWORK_TIMEOUT_MS = 30_000;
30const MCP_TIMEOUT_MS = 12 * 60 * 1000;
31const SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000;
32const SUBAGENT_TIMEOUT_MS = 60 * 60 * 1000;
33const DEFAULT_TOKEN_LIFETIME_SECONDS = 3600;
34const RECONNECT_MAX_SECONDS = 60;
35const SIGNED_OUT_RETRY_SECONDS = 5 * 60;
36const PING_INTERVAL_MS = 30_000;
37const SUMMARY_LIMIT = 2000;
38const GRANT_SCOPE = "agents git";
39
40class CliError extends Error {}
41
42function fail(message) {
43 throw new CliError(message);
44}
45
46/** Writes through a temporary file and a rename, so a crash never leaves a half-written file behind. */
47function writeFileAtomic(file, data, mode) {
48 fs.mkdirSync(path.dirname(file), { recursive: true });
49 const temporary = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
50 fs.writeFileSync(temporary, data, mode === undefined ? undefined : { mode });
51 fs.renameSync(temporary, file);
52}
53
54function request(url, init = {}, timeoutMs = NETWORK_TIMEOUT_MS) {
55 const timeout = AbortSignal.timeout(timeoutMs);
56 return fetch(url, { ...init, signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout });
57}
58
59function readCredentials() {
60 try {
61 return JSON.parse(fs.readFileSync(CREDENTIALS, "utf8"));
62 } catch {
63 return null;
64 }
65}
66
67function writeCredentials(credentials) {
68 writeFileAtomic(CREDENTIALS, JSON.stringify(credentials, null, 2), 0o600);
69}
70
71function readGitTokens() {
72 try {
73 return JSON.parse(fs.readFileSync(GIT_TOKENS, "utf8"));
74 } catch {
75 return {};
76 }
77}
78
79/** The session tokens of `remote`, one for each agent process that holds a branch there. A token is kept only while its agent runs. */
80function agentTokens(remote) {
81 const held = readGitTokens()[remote];
82 if (!held || typeof held !== "object") return {};
83 return Object.fromEntries(Object.entries(held).filter(([owner]) => alive(Number(owner))));
84}
85
86function saveGitToken(remote, value, owner = process.ppid) {
87 const tokens = readGitTokens();
88 const held = { ...agentTokens(remote) };
89 if (value) held[owner] = value;
90 else delete held[owner];
91 if (Object.keys(held).length) tokens[remote] = held;
92 else delete tokens[remote];
93 writeFileAtomic(GIT_TOKENS, JSON.stringify(tokens, null, 2), 0o600);
94 return Object.keys(held).length;
95}
96
97function alive(pid) {
98 try {
99 process.kill(pid, 0);
100 return true;
101 } catch (error) {
102 return error.code === "EPERM";
103 }
104}
105
106/** The process IDs from this process up to the first process of the machine. */
107function ancestors() {
108 const parents = new Map();
109 try {
110 for (const line of execFileSync("ps", ["-A", "-o", "pid=,ppid="], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).split("\n")) {
111 const [pid, ppid] = line.trim().split(/\s+/).map(Number);
112 if (pid) parents.set(pid, ppid);
113 }
114 } catch {}
115 const chain = [process.pid];
116 for (let pid = process.ppid; pid > 1 && !chain.includes(pid); pid = parents.get(pid) ?? 0) chain.push(pid);
117 return chain;
118}
119
120function gitRemote(url) {
121 return url.replace(/(\.git)?\/?$/, ".git");
122}
123
124/** git's credential helper. Git that an agent runs gets that agent's session token. Git that a person runs gets the person's own sign-in. */
125async function credentialHelper(action) {
126 const fields = Object.fromEntries(
127 fs
128 .readFileSync(0, "utf8")
129 .split("\n")
130 .filter((line) => line.includes("="))
131 .map((line) => [line.slice(0, line.indexOf("=")), line.slice(line.indexOf("=") + 1)]),
132 );
133 if (!fields.path) return;
134 const remote = gitRemote(`${fields.protocol}://${fields.host}/${fields.path}`);
135 const held = agentTokens(remote);
136 const owner = ancestors().find((pid) => held[pid]);
137 const saved = owner && held[owner];
138 if (action === "erase" && saved && fields.password === saved) saveGitToken(remote, null, owner);
139 if (action !== "get") return;
140 if (saved) return process.stdout.write(`username=x-token\npassword=${saved}\n`);
141 const signedIn = readCredentials();
142 if (signedIn?.origin === `${fields.protocol}://${fields.host}` && hasGitScope(signedIn)) process.stdout.write(`username=x-token\npassword=${await token()}\n`);
143}
144
145function hasGitScope(saved) {
146 return saved.scope?.split(" ").includes("git") ?? false;
147}
148
149/** Makes git use the refs sign-in for every repository on `origin`, in place of any other credential helper. */
150function setupGit(origin, add) {
151 const global = (...args) => {
152 try {
153 execFileSync("git", ["config", "--global", ...args], { stdio: "ignore" });
154 } catch {}
155 };
156 global("--unset-all", `credential.${origin}.helper`);
157 global("--unset-all", `credential.${origin}.useHttpPath`);
158 if (!add) return;
159 global("--add", `credential.${origin}.helper`, "");
160 global("--add", `credential.${origin}.helper`, `!"${BIN}" credential`);
161 global(`credential.${origin}.useHttpPath`, "true");
162}
163
164function cloneUrl(cwd) {
165 try {
166 return execFileSync("git", ["-C", cwd, "config", "--get", "remote.origin.url"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
167 } catch {
168 return null;
169 }
170}
171
172function gitConfig(cwd, ...args) {
173 try {
174 execFileSync("git", ["-C", cwd, "config", ...args], { stdio: "ignore" });
175 } catch {}
176}
177
178/** Points the clone at `cwd` to the refs credential helper for `remote`, and drops any session token an older CLI put in its config. */
179function useCredentialHelper(cwd, remote) {
180 const url = cloneUrl(cwd);
181 if (!url || gitRemote(url) !== remote) return;
182 for (const header of new Set([`http.${remote}.extraHeader`, `http.${url}.extraHeader`])) gitConfig(cwd, "--unset-all", header, "refs_agent_");
183 gitConfig(cwd, "--replace-all", `credential.${url}.helper`, "");
184 gitConfig(cwd, "--add", `credential.${url}.helper`, `!"${BIN}" credential`);
185 gitConfig(cwd, `credential.${url}.useHttpPath`, "true");
186}
187
188function dropCredentialHelper(cwd, remote) {
189 if (saveGitToken(remote, null)) return;
190 const url = cloneUrl(cwd);
191 if (!url || gitRemote(url) !== remote) return;
192 gitConfig(cwd, "--unset-all", `credential.${url}.helper`);
193 gitConfig(cwd, "--unset-all", `credential.${url}.useHttpPath`);
194}
195
196/** Takes the session credential out of a refs tool result before the model sees it, and hands it to git. */
197function holdCredential(name, helper, result, cwd) {
198 const refs = result?._meta?.refs;
199 if (!refs) return;
200 delete result._meta.refs;
201 if (result.isError) return;
202 if (!refs.token) return dropCredentialHelper(cwd, refs.remote);
203 if (!helper) return;
204 saveGitToken(refs.remote, refs.token);
205 if (name === "refs_take" || name === "refs_connect") useCredentialHelper(cwd, refs.remote);
206}
207
208function credentials() {
209 return readCredentials() ?? fail("Not signed in. Run `refs setup <origin>`.");
210}
211
212let refreshing = null;
213
214async function token() {
215 const saved = credentials();
216 if (saved.expiresAt - 60 > Date.now() / 1000) return saved.accessToken;
217 refreshing ??= refreshToken(saved).finally(() => (refreshing = null));
218 return refreshing;
219}
220
221async function refreshToken(saved) {
222 const response = await request(`${saved.origin}/oauth/token`, {
223 method: "POST",
224 headers: { "content-type": "application/x-www-form-urlencoded" },
225 body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: saved.refreshToken, client_id: saved.clientId, resource: saved.origin }),
226 });
227 const refreshed = await response.json().catch(() => ({}));
228 if (!refreshed.access_token) fail("Your refs sign-in expired. Run `refs login`.");
229 writeCredentials({ ...saved, accessToken: refreshed.access_token, refreshToken: refreshed.refresh_token ?? saved.refreshToken, expiresAt: Date.now() / 1000 + (refreshed.expires_in ?? DEFAULT_TOKEN_LIFETIME_SECONDS) });
230 return refreshed.access_token;
231}
232
233function normalizeOrigin(value) {
234 const url = new URL(value.includes("://") ? value : `https://${value}`);
235 return url.origin;
236}
237
238function openBrowser(url) {
239 if (process.env.REFS_BROWSER === "none") return;
240 const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
241 spawn(opener, [url], { stdio: "ignore", detached: true }).on("error", () => {}).unref();
242}
243
244async function login(origin) {
245 const server = http.createServer();
246 await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
247 const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
248 const registered = await (
249 await request(`${origin}/oauth/register`, {
250 method: "POST",
251 headers: { "content-type": "application/json" },
252 body: JSON.stringify({ client_name: `refs CLI on ${MACHINE}`, redirect_uris: [redirectUri], grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none" }),
253 })
254 ).json();
255 if (!registered.client_id) fail(`${origin} did not accept the refs CLI as an OAuth client. Is it a refs server?`);
256
257 const verifier = randomBytes(32).toString("base64url");
258 const state = randomBytes(12).toString("base64url");
259 const authorize = new URL(`${origin}/oauth/authorize`);
260 authorize.search = new URLSearchParams({
261 response_type: "code",
262 client_id: registered.client_id,
263 redirect_uri: redirectUri,
264 code_challenge: createHash("sha256").update(verifier).digest("base64url"),
265 code_challenge_method: "S256",
266 state,
267 scope: GRANT_SCOPE,
268 resource: origin,
269 }).toString();
270 console.log(`Sign in to refs in your browser. If it doesn't open, visit:\n\n ${authorize}\n`);
271 openBrowser(authorize.href);
272
273 const code = await new Promise((resolve, reject) => {
274 const timer = setTimeout(() => {
275 server.close();
276 reject(new CliError("Sign-in timed out. Run `refs login` again."));
277 }, SIGN_IN_TIMEOUT_MS);
278 server.on("request", (incoming, response) => {
279 const url = new URL(incoming.url, redirectUri);
280 if (url.pathname !== "/callback") return response.writeHead(404).end();
281 const ok = url.searchParams.get("state") === state && url.searchParams.get("code");
282 response.writeHead(200, { "content-type": "text/html" }).end(ok ? "<p>Signed in to refs. You can close this tab.</p>" : "<p>Sign-in was cancelled.</p>");
283 clearTimeout(timer);
284 server.close();
285 ok ? resolve(url.searchParams.get("code")) : reject(new CliError(`Sign-in failed: ${url.searchParams.get("error") ?? "state mismatch"}.`));
286 });
287 });
288
289 const issued = await (
290 await request(`${origin}/oauth/token`, {
291 method: "POST",
292 headers: { "content-type": "application/x-www-form-urlencoded" },
293 body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirectUri, client_id: registered.client_id, code_verifier: verifier, resource: origin }),
294 })
295 ).json();
296 if (!issued.access_token) fail(`Sign-in failed: ${issued.error_description ?? issued.error ?? "no token"}.`);
297 writeCredentials({ origin, scope: GRANT_SCOPE, clientId: registered.client_id, accessToken: issued.access_token, refreshToken: issued.refresh_token, expiresAt: Date.now() / 1000 + (issued.expires_in ?? DEFAULT_TOKEN_LIFETIME_SECONDS) });
298 setupGit(origin, true);
299 const me = await whoami();
300 console.log(`Signed in to ${origin} as ${me.name}. Git uses this sign-in for ${new URL(origin).host}.`);
301}
302
303async function api(pathname, init = {}) {
304 const { origin } = credentials();
305 return request(`${origin}${pathname}`, { ...init, headers: { authorization: `Bearer ${await token()}`, ...init.headers } });
306}
307
308async function whoami() {
309 const response = await api("/api/cli/whoami");
310 if (!response.ok) fail(`refs refused the sign-in (HTTP ${response.status}). Run \`refs login\`.`);
311 return response.json();
312}
313
314function runtimes() {
315 return ["claude", "opencode", "codex"].filter(installed);
316}
317
318function askDaemon(message, timeoutMs = 1000) {
319 return new Promise((resolve) => {
320 const socket = net.createConnection(SOCKET);
321 const timer = setTimeout(() => (socket.destroy(), resolve(null)), timeoutMs);
322 socket.on("error", () => (clearTimeout(timer), resolve(null)));
323 socket.on("connect", () => {
324 readline.createInterface({ input: socket }).once("line", (line) => {
325 clearTimeout(timer);
326 socket.end();
327 try {
328 resolve(JSON.parse(line));
329 } catch {
330 resolve(null);
331 }
332 });
333 socket.write(JSON.stringify(message) + "\n");
334 });
335 });
336}
337
338async function ensureDaemon() {
339 if (await askDaemon({ type: "status" })) return;
340 fs.mkdirSync(HOME, { recursive: true });
341 const log = fs.openSync(LOG, "a");
342 spawn(process.execPath, [process.argv[1], "daemon"], { detached: true, stdio: ["ignore", log, log] }).unref();
343 for (let attempt = 0; attempt < 30; attempt++) {
344 await new Promise((resolve) => setTimeout(resolve, 100));
345 if (await askDaemon({ type: "status" })) return;
346 }
347}
348
349async function daemon() {
350 const { origin } = credentials();
351 if (await askDaemon({ type: "status" })) fail("The refs daemon is already running.");
352 fs.mkdirSync(HOME, { recursive: true });
353 fs.rmSync(SOCKET, { force: true });
354 const state = { connected: false, since: null };
355
356 net
357 .createServer((connection) => {
358 readline.createInterface({ input: connection }).on("line", (line) => {
359 let message;
360 try {
361 message = JSON.parse(line);
362 } catch {
363 return;
364 }
365 if (message.type === "status") connection.write(JSON.stringify({ origin, machine: MACHINE, version: VERSION, ...state }) + "\n");
366 });
367 })
368 .listen(SOCKET);
369
370 const log = (text) => console.log(`${new Date().toISOString()} ${text}`);
371 let retry = 1;
372 const reconnect = (seconds) => setTimeout(connect, seconds * 1000 * (0.5 + Math.random() / 2));
373 const connect = async () => {
374 let socket;
375 try {
376 socket = new WebSocket(`${origin.replace(/^http/, "ws")}/api/cli/connect`, { headers: { authorization: `Bearer ${await token()}` } });
377 } catch (error) {
378 if (error instanceof CliError) {
379 log(`${error.message} Retrying in ${SIGNED_OUT_RETRY_SECONDS / 60} minutes.`);
380 return reconnect(SIGNED_OUT_RETRY_SECONDS);
381 }
382 log(`cannot connect: ${error.message}`);
383 return reconnect(Math.min((retry *= 2), RECONNECT_MAX_SECONDS));
384 }
385 let ping;
386 socket.addEventListener("open", () => {
387 socket.send(JSON.stringify({ type: "hello", machine: MACHINE, runtimes: runtimes(), version: VERSION }));
388 ping = setInterval(() => socket.send(JSON.stringify({ type: "ping" })), PING_INTERVAL_MS);
389 });
390 socket.addEventListener("message", ({ data }) => {
391 let message;
392 try {
393 message = JSON.parse(String(data));
394 } catch {
395 return log("ignored a malformed message from refs");
396 }
397 if (message.type === "welcome") {
398 retry = 1;
399 Object.assign(state, { connected: true, since: new Date().toISOString() });
400 log(`connected to ${origin} as ${MACHINE}`);
401 }
402 if (message.type === "run") queueRun(message, log);
403 if (message.type === "wake") wakeOpenCode(message, log).catch((error) => log(`could not wake OpenCode for mention ${message.mention}: ${error.message}`));
404 });
405 socket.addEventListener("close", () => {
406 clearInterval(ping);
407 if (state.connected) log("disconnected");
408 Object.assign(state, { connected: false, since: null });
409 reconnect(Math.min((retry *= 2), RECONNECT_MAX_SECONDS));
410 });
411 socket.addEventListener("error", () => {});
412 };
413 for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => (fs.rmSync(SOCKET, { force: true }), process.exit(0)));
414 if (installed("opencode")) watchOpenCode(log);
415 await connect();
416}
417
418function openCodeService() {
419 const service = JSON.parse(fs.readFileSync(OPENCODE_SERVICE, "utf8"));
420 return { url: service.url.replace(/\/$/, ""), authorization: `Basic ${Buffer.from(`opencode:${service.password}`).toString("base64")}` };
421}
422
423function openCodeSessions() {
424 try {
425 return JSON.parse(fs.readFileSync(OPENCODE_SESSIONS, "utf8"));
426 } catch {
427 return {};
428 }
429}
430
431const woken = new Map();
432
433/** Starts a turn in a live OpenCode session through the OpenCode service, so it answers a mention now. */
434async function wakeOpenCode(wake, log) {
435 const service = openCodeService();
436 const response = await request(`${service.url}/api/session/${encodeURIComponent(wake.session)}/prompt`, {
437 method: "POST",
438 headers: { authorization: service.authorization, "content-type": "application/json" },
439 body: JSON.stringify({
440 text: `[refs] ${wake.by} mentioned you on ${mentionPlace(wake)} "${wake.title}" while you were away (mention ${wake.mention}). Your refs updates below have it; answer with refs_reply.`,
441 delivery: "queue",
442 }),
443 });
444 if (!response.ok) throw new Error(`OpenCode answered HTTP ${response.status}`);
445 woken.set(wake.session, { mention: wake.mention, started: false, text: "" });
446 log(`mention ${wake.mention}: started a turn in OpenCode session ${wake.session}`);
447}
448
449/**
450 * Follows the OpenCode service's events and mirrors every tool approval a refs-connected session asks
451 * for to the portal. Whichever answer comes first wins: a portal answer is sent to OpenCode, and an
452 * answer in OpenCode takes the request back off the portal.
453 */
454async function watchOpenCode(log) {
455 const pending = new Map();
456 const decoder = new TextDecoder();
457 for (;;) {
458 try {
459 const service = openCodeService();
460 const response = await fetch(`${service.url}/api/event`, { headers: { authorization: service.authorization, accept: "text/event-stream" } });
461 if (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`);
462 let buffer = "";
463 for await (const chunk of response.body) {
464 buffer += decoder.decode(chunk, { stream: true });
465 for (let end = buffer.indexOf("\n\n"); end >= 0; end = buffer.indexOf("\n\n")) {
466 const data = buffer
467 .slice(0, end)
468 .split("\n")
469 .filter((line) => line.startsWith("data:"))
470 .map((line) => line.slice(5).trim())
471 .join("");
472 buffer = buffer.slice(end + 2);
473 if (!data) continue;
474 try {
475 openCodeEvent(JSON.parse(data), service, pending, log);
476 } catch (error) {
477 log(`ignored an OpenCode event: ${error.message}`);
478 }
479 }
480 }
481 } catch (error) {
482 if (!(error?.code === "ENOENT")) log(`OpenCode event stream stopped: ${error.message}`);
483 }
484 await new Promise((resolve) => setTimeout(resolve, 5000));
485 }
486}
487
488function openCodeEvent(event, service, pending, log) {
489 const data = event.data ?? event.properties ?? {};
490 const turn = woken.get(data.sessionID);
491 if (turn && event.type === "session.execution.started") turn.started = true;
492 if (turn && event.type === "session.text.ended" && typeof data.text === "string" && data.text.trim()) turn.text = data.text.trim();
493 if (turn?.started && (event.type === "session.execution.succeeded" || event.type === "session.execution.failed")) {
494 woken.delete(data.sessionID);
495 const ok = event.type === "session.execution.succeeded";
496 const summary = turn.text || (ok ? "" : String(data.error?.message ?? data.error ?? "the turn failed"));
497 reportRun({ session: openCodeSessions()[data.sessionID], mention: turn.mention, ok, summary }).catch((error) => log(`could not report mention ${turn.mention}: ${error.message}`));
498 }
499 if (event.type === "permission.asked" && openCodeSessions()[data.sessionID] && !pending.has(data.id)) {
500 const controller = new AbortController();
501 pending.set(data.id, controller);
502 log(`OpenCode session ${data.sessionID} asks for ${data.action}: sent to refs`);
503 callTool("opencode", "refs_approve", { client_session: data.sessionID, tool_name: data.action, input: { resources: data.resources, ...(data.metadata ?? {}) }, request_id: data.id }, controller.signal)
504 .then(async (answer) => {
505 if (!pending.delete(data.id)) return;
506 const { behavior, message, expired } = JSON.parse(answer);
507 if (expired || (behavior !== "allow" && behavior !== "deny")) return;
508 await request(`${service.url}/api/session/${encodeURIComponent(data.sessionID)}/permission/${encodeURIComponent(data.id)}/reply`, {
509 method: "POST",
510 headers: { authorization: service.authorization, "content-type": "application/json" },
511 body: JSON.stringify({ decision: behavior === "allow" ? "once" : "reject", ...(message ? { message } : {}) }),
512 });
513 })
514 .catch((error) => pending.delete(data.id) && log(`approval ${data.id} failed: ${error.message}`));
515 }
516 if (event.type === "permission.replied" && pending.has(data.requestID)) {
517 pending.get(data.requestID).abort();
518 pending.delete(data.requestID);
519 callTool("opencode", "refs_approve", { client_session: data.sessionID, tool_name: "", input: {}, request_id: data.requestID, withdraw: true }).catch(() => {});
520 }
521}
522
523const runQueues = new Map();
524
525function queueRun(run, log) {
526 const previous = runQueues.get(run.parent) ?? Promise.resolve();
527 const next = previous
528 .then(() => runSubAgent(run, log))
529 .catch((error) => log(`run for mention ${run.mention} failed: ${error.message}`))
530 .finally(() => runQueues.get(run.parent) === next && runQueues.delete(run.parent));
531 runQueues.set(run.parent, next);
532}
533
534function readRuns() {
535 try {
536 return JSON.parse(fs.readFileSync(RUNS, "utf8"));
537 } catch {
538 return {};
539 }
540}
541
542/** Changes one parent's run record. Reads and writes with no await between them, so concurrent runs never overwrite each other. */
543function updateRun(parent, change) {
544 const runs = readRuns();
545 runs[parent] = change(runs[parent]);
546 writeFileAtomic(RUNS, JSON.stringify(runs, null, 2));
547}
548
549function mentionPlace(mention) {
550 return `pull request #${mention.pull}`;
551}
552
553function subAgentPrompt(run) {
554 const job = run.assigned
555 ? `This mention assigned you ${mentionPlace(run)}. Call refs_take with pull ${run.pull}, check out the branch it names in this directory, and do the whole job: implement it, commit with a decision record (or the trailer "Decision: none") in every commit, and push that branch after each commit. Then answer with refs_reply (mention ${run.mention}) summarising what you did, and call refs_release.`
556 : `Answer with refs_reply (mention ${run.mention}). The repository is checked out in the current directory if you need it.`;
557 return [
558 `Your human mentioned their agent on refs while away from it, and you are answering for that agent. Mention ${run.mention} on ${mentionPlace(run)} "${run.title}":`,
559 "",
560 run.body,
561 "",
562 job,
563 "Work only in this directory. Nobody is watching the terminal: tool approvals go to your human on refs. Finish with a one-paragraph summary of what you did.",
564 ].join("\n");
565}
566
567/**
568 * Answers a mention with a headless Claude Code run: a sub-agent session linked to the mentioned one,
569 * in its own clone, resuming the same conversation on later mentions, with every tool approval sent
570 * to the portal. The parent session hears how it went at its next turn.
571 */
572async function runSubAgent(run, log) {
573 const known = readRuns()[run.parent];
574 const conversation = known?.conversation ?? randomUUID();
575 const dir = known?.dir ?? path.join(WORK, run.repo, run.parent.slice(0, 8));
576 log(`mention ${run.mention} on ${run.repo} ${mentionPlace(run)}: starting a sub-agent`);
577
578 const init = await mcpRequest({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", clientInfo: { name: "claude-code" }, capabilities: {} } });
579 const connection = init.headers.get("mcp-session-id");
580 const connected = await (
581 await mcpRequest({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "refs_connect", arguments: { repo: run.repo, client_session: conversation, machine: MACHINE, parent: run.parent, credentials: "helper" } } }, connection)
582 ).json();
583 const rules = connected.result?.content?.[0]?.text ?? "";
584 const child = connected.result?._meta?.session;
585 if (connected.result?.isError || !child) throw new CliError(rules || "refs did not start a sub-agent session");
586
587 const { remote, token: sessionToken } = connected.result._meta?.refs ?? {};
588 if (!sessionToken) throw new CliError("refs gave no git credential for the sub-agent");
589 if (!fs.existsSync(dir)) {
590 fs.mkdirSync(path.dirname(dir), { recursive: true });
591 const header = { GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: `http.${remote}.extraHeader`, GIT_CONFIG_VALUE_0: `Authorization: Bearer ${sessionToken}` };
592 execFileSync("git", ["clone", "-q", remote, dir], { stdio: "ignore", env: { ...process.env, ...header } });
593 }
594 updateRun(run.parent, (current) => ({ conversation, dir, child, started: current?.started === true }));
595
596 const config = path.join(HOME, "runs", `${conversation}.mcp.json`);
597 fs.mkdirSync(path.dirname(config), { recursive: true });
598 fs.writeFileSync(config, JSON.stringify({ mcpServers: { refs: { command: process.execPath, args: [process.argv[1], "mcp"], env: { REFS_CLIENT_SESSION: conversation, REFS_HOME: HOME } } } }));
599 const args = [
600 "-p",
601 subAgentPrompt(run),
602 ...(known?.started ? ["--resume", conversation] : ["--session-id", conversation]),
603 "--mcp-config",
604 config,
605 "--strict-mcp-config",
606 "--permission-prompt-tool",
607 "mcp__refs__refs_approve",
608 "--allowedTools",
609 "mcp__refs",
610 "Read",
611 "Glob",
612 "Grep",
613 "--append-system-prompt",
614 rules,
615 "--output-format",
616 "json",
617 ...(process.env.REFS_SUBAGENT_MODEL ? ["--model", process.env.REFS_SUBAGENT_MODEL] : []),
618 ];
619 const { code, stdout, stderr } = await new Promise((resolve) => {
620 const agent = spawn("claude", args, { cwd: dir, stdio: ["ignore", "pipe", "pipe"] });
621 let stdout = "";
622 let stderr = "";
623 const limit = setTimeout(() => {
624 stderr += `\nThe sub-agent ran longer than ${SUBAGENT_TIMEOUT_MS / 60_000} minutes and was stopped.`;
625 agent.kill("SIGTERM");
626 }, SUBAGENT_TIMEOUT_MS);
627 agent.stdout.on("data", (chunk) => (stdout += chunk));
628 agent.stderr.on("data", (chunk) => (stderr += chunk));
629 agent.on("error", (error) => (clearTimeout(limit), resolve({ code: -1, stdout, stderr: error.message })));
630 agent.on("exit", (code) => (clearTimeout(limit), resolve({ code, stdout, stderr })));
631 });
632 let result = {};
633 try {
634 result = JSON.parse(stdout);
635 } catch {}
636 const ok = code === 0 && !result.is_error;
637 if (result.session_id) updateRun(run.parent, (current) => ({ ...current, started: true }));
638 log(`mention ${run.mention}: sub-agent ${ok ? "finished" : `failed (exit ${code})`}`);
639 const summary = String(result.result ?? stderr ?? "").trim().slice(0, SUMMARY_LIMIT);
640 await reportRun({ session: child, mention: run.mention, ok, summary });
641}
642
643async function reportRun(report) {
644 for (let attempt = 1; ; attempt++) {
645 try {
646 const response = await api("/api/cli/runs/finished", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ...report, summary: report.summary.slice(0, SUMMARY_LIMIT) }) });
647 if (response.ok || response.status === 404) return;
648 const error = new Error(`HTTP ${response.status}`);
649 if (response.status < 500 && response.status !== 429) throw new CliError(`refs refused the run report (${error.message}).`);
650 throw error;
651 } catch (error) {
652 if (error instanceof CliError || attempt === 5) throw error;
653 await new Promise((resolve) => setTimeout(resolve, attempt * 2000));
654 }
655 }
656}
657
658async function mcpRequest(body, session, signal) {
659 const send = async (bearer) =>
660 request(`${credentials().origin}/mcp`, {
661 method: "POST",
662 headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json", accept: "application/json, text/event-stream", ...(session ? { "mcp-session-id": session } : {}) },
663 body: JSON.stringify(body),
664 signal,
665 }, MCP_TIMEOUT_MS);
666 return send(await token());
667}
668
669/**
670 * The MCP server outside a refs clone: it answers on the spot, offers no tools and never calls refs, so a project that
671 * doesn't use refs never waits on it or sees its errors. The refs hooks' calls to refs_events get an empty answer.
672 */
673function localMcp() {
674 const write = (message) => process.stdout.write(JSON.stringify(message) + "\n");
675 const answers = {
676 initialize: (params) => ({ protocolVersion: params?.protocolVersion ?? "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "refs", version: VERSION } }),
677 ping: () => ({}),
678 "tools/list": () => ({ tools: [] }),
679 "tools/call": () => ({ content: [] }),
680 };
681 const lines = readline.createInterface({ input: process.stdin });
682 lines.on("line", (line) => {
683 let message;
684 try {
685 message = JSON.parse(line);
686 } catch {
687 return;
688 }
689 if (message.id === undefined) return;
690 const answer = answers[message.method];
691 write(answer ? { jsonrpc: "2.0", id: message.id, result: answer(message.params) } : { jsonrpc: "2.0", id: message.id, error: { code: -32601, message: `refs has no ${message.method} outside a refs clone.` } });
692 });
693 lines.on("close", () => process.exit(0));
694}
695
696async function mcp() {
697 const cwd = process.cwd();
698 const saved = readCredentials();
699 const clone = saved && repoOf(cwd, saved.origin);
700 if (!clone) return localMcp();
701 ensureDaemon().catch(() => {});
702 let session = null;
703 const write = (message) => process.stdout.write(JSON.stringify(message) + "\n");
704 const lines = readline.createInterface({ input: process.stdin });
705 lines.on("line", async (line) => {
706 let message;
707 try {
708 message = JSON.parse(line);
709 } catch {
710 return;
711 }
712 if (message.method === "tools/call" && message.params?.name === "refs_connect") message.params.arguments = { ...message.params.arguments, machine: MACHINE };
713 if (message.method === "tools/call" && process.env.REFS_CLIENT_SESSION) message.params.arguments = { client_session: process.env.REFS_CLIENT_SESSION, ...message.params.arguments };
714 const name = message.method === "tools/call" ? message.params?.name : null;
715 const helper = Boolean(clone) && (name === "refs_take" || name === "refs_release" || (name === "refs_connect" && message.params.arguments?.repo === clone));
716 if (helper) message.params.arguments = { ...message.params.arguments, credentials: "helper" };
717 try {
718 const response = await mcpRequest(message, session);
719 session ??= response.headers.get("mcp-session-id");
720 if (response.status === 200) {
721 const answer = await response.json();
722 if (name) holdCredential(name, helper, answer.result, cwd);
723 write(answer);
724 } else if (message.id !== undefined && response.status !== 202 && response.status !== 204)
725 write({ jsonrpc: "2.0", id: message.id, error: { code: -32000, message: `refs answered HTTP ${response.status}. Run \`refs status\`.` } });
726 } catch (error) {
727 if (message.id !== undefined) write({ jsonrpc: "2.0", id: message.id, error: { code: -32000, message: error.message } });
728 }
729 });
730 lines.on("close", async () => {
731 if (session) {
732 await request(`${credentials().origin}/mcp`, { method: "DELETE", headers: { authorization: `Bearer ${await token()}`, "mcp-session-id": session } }).catch(() => {});
733 }
734 process.exit(0);
735 });
736}
737
738function repoOf(cwd, origin) {
739 const match = (cloneUrl(cwd) ?? "").match(/^(https?:\/\/[^/]+)\/([A-Za-z0-9._-]+\/[A-Za-z0-9._-]+?)(?:\.git)?\/?$/);
740 return match && match[1] === origin ? match[2] : null;
741}
742
743async function connectSession(runtime, clientSession, cwd) {
744 const saved = readCredentials();
745 const repo = saved && repoOf(cwd, saved.origin);
746 if (!repo) return null;
747 await ensureDaemon();
748 const init = await mcpRequest({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", clientInfo: { name: runtime }, capabilities: {} } });
749 const connection = init.headers.get("mcp-session-id");
750 const connected = await (
751 await mcpRequest({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "refs_connect", arguments: { repo, client_session: clientSession, machine: MACHINE, credentials: "helper" } } }, connection)
752 ).json();
753 const text = connected.result?.content?.[0]?.text ?? "";
754 const id = connected.result?._meta?.session;
755 if (connected.result?.isError || !id) return { error: `[refs] Could not connect to ${saved.origin}: ${text || "no answer"}` };
756 const me = await whoami();
757 const daemonState = await askDaemon({ type: "status" });
758 const banner = `[refs] Connected to ${new URL(saved.origin).host} as ${me.name} · ${MACHINE} · ${repo} · session ${id.slice(0, 4)}${daemonState?.connected ? "" : " (daemon offline: run `refs status`)"}`;
759 return { id, banner, text, connection };
760}
761
762async function callTool(runtime, name, args, signal) {
763 const init = await mcpRequest({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", clientInfo: { name: runtime }, capabilities: {} } });
764 const answer = await (await mcpRequest({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name, arguments: args } }, init.headers.get("mcp-session-id"), signal)).json();
765 return answer.result?.content?.[0]?.text ?? "";
766}
767
768async function sessionStart() {
769 const input = JSON.parse(fs.readFileSync(0, "utf8") || "{}");
770 const session = await connectSession("claude-code", input.session_id, input.cwd ?? process.cwd());
771 if (!session) return;
772 if (session.error) return console.log(JSON.stringify({ systemMessage: session.error }));
773 console.log(JSON.stringify({ systemMessage: session.banner, hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: `${session.banner}\n\n${session.text}` } }));
774}
775
776async function sessionEnd() {
777 const input = JSON.parse(fs.readFileSync(0, "utf8") || "{}");
778 const saved = readCredentials();
779 if (input.session_id && saved && repoOf(input.cwd ?? process.cwd(), saved.origin)) await callTool("claude-code", "refs_events", { event: "SessionEnd", client_session: input.session_id });
780}
781
782/** Claude Code's UserPromptSubmit and PostToolUse hook: outside a refs clone it exits silently, so other projects never see a refs error. */
783async function events() {
784 const input = JSON.parse(fs.readFileSync(0, "utf8") || "{}");
785 const saved = readCredentials();
786 if (!input.session_id || !saved || !repoOf(input.cwd ?? process.cwd(), saved.origin)) return;
787 const updates = await callTool("claude-code", "refs_events", { event: input.hook_event_name, client_session: input.session_id });
788 if (updates) console.log(updates);
789}
790
791/** OpenCode's refs plugin calls this before each prompt: the first one connects the session, every one gets the updates. */
792async function openCodePrompt() {
793 const input = JSON.parse(fs.readFileSync(0, "utf8") || "{}");
794 if (!input.session_id || !readCredentials() || !repoOf(input.cwd ?? process.cwd(), readCredentials().origin)) return;
795 const known = openCodeSessions();
796 const parts = [];
797 if (!known[input.session_id]) {
798 const session = await connectSession("opencode", input.session_id, input.cwd);
799 if (session?.error) return console.log(session.error);
800 known[input.session_id] = session.id;
801 writeFileAtomic(OPENCODE_SESSIONS, JSON.stringify(known, null, 2));
802 parts.push(`${session.banner}\n\n${session.text}`);
803 }
804 const updates = await callTool("opencode", "refs_events", { client_session: input.session_id });
805 if (updates && !/^(No new updates|You are offline)/.test(updates)) parts.push(updates);
806 if (parts.length) console.log(parts.join("\n\n"));
807}
808
809
810function claude(args) {
811 return execFileSync("claude", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
812}
813
814function isRefsHook(hook) {
815 return (hook.type === "mcp_tool" && /^(plugin:refs:)?refs$/.test(hook.server ?? "")) || /refs\/bin\/refs|git\.useref\.dev/.test(hook.command ?? "");
816}
817
818function editClaudeHooks(add) {
819 const settings = fs.existsSync(CLAUDE_SETTINGS) ? JSON.parse(fs.readFileSync(CLAUDE_SETTINGS, "utf8")) : {};
820 const hooks = settings.hooks ?? {};
821 for (const event of Object.keys(hooks)) {
822 hooks[event] = hooks[event].map((entry) => ({ ...entry, hooks: (entry.hooks ?? []).filter((hook) => !isRefsHook(hook)) })).filter((entry) => entry.hooks.length);
823 if (!hooks[event].length) delete hooks[event];
824 }
825 if (add) {
826 const updates = [{ type: "command", command: `"${BIN}" hook events` }];
827 (hooks.SessionStart ??= []).push({ hooks: [{ type: "command", command: `"${BIN}" hook session-start` }] });
828 (hooks.SessionEnd ??= []).push({ hooks: [{ type: "command", command: `"${BIN}" hook session-end` }] });
829 (hooks.UserPromptSubmit ??= []).push({ hooks: updates });
830 (hooks.PostToolUse ??= []).push({ matcher: "Bash", hooks: updates });
831 }
832 if (Object.keys(hooks).length) settings.hooks = hooks;
833 else delete settings.hooks;
834 fs.mkdirSync(path.dirname(CLAUDE_SETTINGS), { recursive: true });
835 fs.writeFileSync(CLAUDE_SETTINGS, JSON.stringify(settings, null, 2) + "\n");
836}
837
838function installService() {
839 if (process.env.REFS_NO_SERVICE) return ensureDaemon();
840 if (process.platform === "darwin") {
841 const uid = String(process.getuid());
842 fs.mkdirSync(path.dirname(LAUNCHD), { recursive: true });
843 fs.writeFileSync(
844 LAUNCHD,
845 `<?xml version="1.0" encoding="UTF-8"?>
846<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
847<plist version="1.0"><dict>
848 <key>Label</key><string>dev.refs.daemon</string>
849 <key>ProgramArguments</key><array><string>${BIN}</string><string>daemon</string></array>
850 <key>RunAtLoad</key><true/>
851 <key>KeepAlive</key><true/>
852 <key>EnvironmentVariables</key><dict><key>PATH</key><string>${(process.env.PATH ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;")}</string></dict>
853 <key>StandardOutPath</key><string>${LOG}</string>
854 <key>StandardErrorPath</key><string>${LOG}</string>
855</dict></plist>
856`,
857 );
858 try {
859 execFileSync("launchctl", ["bootout", `gui/${uid}`, LAUNCHD], { stdio: "ignore" });
860 } catch {}
861 execFileSync("launchctl", ["bootstrap", `gui/${uid}`, LAUNCHD]);
862 return;
863 }
864 if (process.platform === "linux") {
865 fs.mkdirSync(path.dirname(SYSTEMD), { recursive: true });
866 fs.writeFileSync(SYSTEMD, `[Unit]\nDescription=refs daemon\n\n[Service]\nEnvironment="PATH=${process.env.PATH ?? ""}"\nExecStart=${BIN} daemon\nRestart=always\n\n[Install]\nWantedBy=default.target\n`);
867 execFileSync("systemctl", ["--user", "daemon-reload"]);
868 execFileSync("systemctl", ["--user", "enable", "--now", "refs.service"]);
869 return;
870 }
871 return ensureDaemon();
872}
873
874function restartService() {
875 try {
876 if (process.platform === "darwin" && fs.existsSync(LAUNCHD)) execFileSync("launchctl", ["kickstart", "-k", `gui/${process.getuid()}/dev.refs.daemon`], { stdio: "ignore" });
877 else if (process.platform === "linux" && fs.existsSync(SYSTEMD)) execFileSync("systemctl", ["--user", "restart", "refs.service"], { stdio: "ignore" });
878 } catch {}
879}
880
881function removeService() {
882 if (process.platform === "darwin" && fs.existsSync(LAUNCHD)) {
883 try {
884 execFileSync("launchctl", ["bootout", `gui/${process.getuid()}`, LAUNCHD], { stdio: "ignore" });
885 } catch {}
886 fs.rmSync(LAUNCHD, { force: true });
887 }
888 if (process.platform === "linux" && fs.existsSync(SYSTEMD)) {
889 try {
890 execFileSync("systemctl", ["--user", "disable", "--now", "refs.service"], { stdio: "ignore" });
891 } catch {}
892 fs.rmSync(SYSTEMD, { force: true });
893 }
894}
895
896function installed(name) {
897 try {
898 execFileSync("sh", ["-c", `command -v ${name}`], { stdio: "ignore" });
899 return true;
900 } catch {
901 return false;
902 }
903}
904
905function setupClaude() {
906 for (const args of [["plugin", "uninstall", "refs@refs"], ["plugin", "marketplace", "remove", "refs"], ["mcp", "remove", "refs", "--scope", "user"]]) {
907 try {
908 claude(args);
909 } catch {}
910 }
911 claude(["mcp", "add", "--scope", "user", "refs", "--", BIN, "mcp"]);
912 editClaudeHooks(true);
913}
914
915function openCodePlugin() {
916 return `import { execFile } from "node:child_process";
917
918const BIN = ${JSON.stringify(BIN)};
919const ENV = { ...process.env, PATH: ${JSON.stringify(process.env.PATH ?? "")} };
920
921function refs(args, input) {
922 return new Promise((resolve) => {
923 const child = execFile(BIN, args, { env: ENV, timeout: 60 * 1000 }, (error, stdout) => resolve(error ? "" : stdout.trim()));
924 child.stdin.end(JSON.stringify(input));
925 });
926}
927
928export default {
929 id: "refs",
930 setup: async (ctx) => {
931 await ctx.session.hook("prompt", async (event) => {
932 const prompt = event.prompt;
933 const text = typeof prompt?.text === "string" ? prompt.text : "";
934 const extra = await refs(["hook", "opencode-prompt"], { session_id: event.sessionID, cwd: ctx.location.directory });
935 if (extra && prompt) prompt.text = text ? text + "\\n\\n" + extra : extra;
936 });
937 await ctx.tool.hook("execute.before", (event) => {
938 if (/^refs[_.]/.test(event.tool) && event.input && typeof event.input === "object") event.input = { ...event.input, client_session: event.sessionID };
939 });
940 },
941};
942`;
943}
944
945function editOpenCode(add) {
946 const file = path.join(OPENCODE_CONFIG, "opencode.json");
947 const config = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : { $schema: "https://opencode.ai/config.json" };
948 config.mcp ??= {};
949 delete config.mcp.refs;
950 if (config.mcp.servers) delete config.mcp.servers.refs;
951 if (add) (config.mcp.servers ??= {}).refs = { type: "local", command: [BIN, "mcp"], environment: { PATH: process.env.PATH ?? "" }, codemode: false };
952 if (config.mcp.servers && !Object.keys(config.mcp.servers).length) delete config.mcp.servers;
953 fs.mkdirSync(OPENCODE_CONFIG, { recursive: true });
954 fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\n");
955 const plugin = path.join(OPENCODE_CONFIG, "plugins", "refs.js");
956 if (add) {
957 fs.mkdirSync(path.dirname(plugin), { recursive: true });
958 fs.writeFileSync(plugin, openCodePlugin());
959 } else fs.rmSync(plugin, { force: true });
960}
961
962async function setup(originArg) {
963 const saved = readCredentials();
964 const origin = normalizeOrigin(originArg ?? saved?.origin ?? fail("Usage: refs setup <origin>, for example refs setup useref.dev"));
965 const agents = [installed("claude") && "Claude Code", installed("opencode") && "OpenCode"].filter(Boolean);
966 if (!agents.length) fail("Neither Claude Code nor OpenCode is installed. Install one, then run `refs setup` again.");
967 if (!saved || saved.origin !== origin || !hasGitScope(saved)) await login(origin);
968 if (agents.includes("Claude Code")) setupClaude();
969 if (agents.includes("OpenCode")) editOpenCode(true);
970 await installService();
971 console.log(`refs is set up for ${agents.join(" and ")} on ${MACHINE}. Git signs in to ${new URL(origin).host} as you, and every new session in a clone of its repositories connects by itself.`);
972 if (agents.includes("OpenCode")) console.log("Restart OpenCode's background service to load refs: opencode service restart");
973}
974
975async function status() {
976 const saved = readCredentials();
977 if (!saved) return console.log("Not signed in. Run `refs setup <origin>`.");
978 const me = await whoami().catch((error) => ({ name: `unknown (${error.message})` }));
979 const daemonState = await askDaemon({ type: "status" });
980 console.log(`refs ${VERSION} on ${MACHINE}`);
981 console.log(`Signed in to ${saved.origin} as ${me.name}`);
982 console.log(daemonState ? `Daemon running, ${daemonState.connected ? `connected since ${daemonState.since}` : "not connected yet"}` : "Daemon not running. Run `refs setup` to install it as a service.");
983}
984
985async function update() {
986 const { origin } = credentials();
987 const response = await request(`${origin}/cli/refs.mjs`);
988 if (!response.ok) fail(`Could not download the CLI from ${origin} (HTTP ${response.status}).`);
989 const script = await response.text();
990 const expected = response.headers.get("x-refs-sha256");
991 if (expected && createHash("sha256").update(script).digest("hex") !== expected) fail("The downloaded CLI does not match its checksum. Nothing was changed. Try again.");
992 const candidate = path.join(path.dirname(SCRIPT), "refs.download.mjs");
993 fs.writeFileSync(candidate, script);
994 try {
995 execFileSync(process.execPath, ["--check", candidate], { stdio: "ignore" });
996 } catch {
997 fs.rmSync(candidate, { force: true });
998 fail("The downloaded CLI is not valid JavaScript. Nothing was changed. Try again.");
999 }
1000 fs.renameSync(candidate, SCRIPT);
1001 if (installed("claude")) execFileSync(BIN, ["hook", "refresh-claude"], { stdio: "ignore" });
1002 if (installed("opencode") && fs.existsSync(path.join(OPENCODE_CONFIG, "plugins", "refs.js"))) execFileSync(BIN, ["hook", "refresh-opencode"], { stdio: "ignore" });
1003 restartService();
1004 console.log(`Updated refs from ${origin} and restarted the daemon.`);
1005}
1006
1007function uninstall() {
1008 removeService();
1009 const saved = readCredentials();
1010 if (saved) setupGit(saved.origin, false);
1011 try {
1012 claude(["mcp", "remove", "refs", "--scope", "user"]);
1013 } catch {}
1014 editClaudeHooks(false);
1015 if (fs.existsSync(path.join(OPENCODE_CONFIG, "opencode.json"))) editOpenCode(false);
1016 if (fs.existsSync(CREDENTIALS) || fs.existsSync(SCRIPT) || HOME === path.join(os.homedir(), ".refs")) fs.rmSync(HOME, { recursive: true, force: true });
1017 else console.log(`${HOME} does not look like a refs home, so it was left in place.`);
1018 console.log("refs is uninstalled: the daemon, the Claude Code and OpenCode setup, and ~/.refs are gone.");
1019}
1020
1021const FLAGS = {
1022 repo: { type: "string", short: "R" },
1023 json: { type: "boolean" },
1024 closed: { type: "boolean" },
1025 title: { type: "string", short: "t" },
1026 body: { type: "string", short: "b" },
1027 base: { type: "string", short: "B" },
1028 "log-failed": { type: "boolean" },
1029 public: { type: "boolean" },
1030 description: { type: "string", short: "d" },
1031 empty: { type: "boolean" },
1032 clone: { type: "boolean" },
1033};
1034
1035function options(argv) {
1036 try {
1037 return parseArgs({ args: argv, options: FLAGS, allowPositionals: true });
1038 } catch (error) {
1039 fail(error.message);
1040 }
1041}
1042
1043function git(...argv) {
1044 return execFileSync("git", argv, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
1045}
1046
1047function targetRepo(values) {
1048 return values.repo ?? repoOf(process.cwd(), credentials().origin) ?? fail("Run this in a clone of a refs repository, or pass -R <namespace>/<repo>.");
1049}
1050
1051async function repoApi(repo, pathname, body) {
1052 const init = body ? { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) } : {};
1053 const response = await api(`/api/cli/repos${repo ? `/${repo}/${pathname}` : ""}`, init);
1054 const answer = await response.json().catch(() => ({}));
1055 if (!response.ok) fail(answer.error ?? `refs answered HTTP ${response.status}.`);
1056 return answer;
1057}
1058
1059function show(values, data, print) {
1060 if (values.json) console.log(JSON.stringify(data, null, 2));
1061 else print(data);
1062}
1063
1064function number(value, what) {
1065 return /^\d+$/.test(value ?? "") ? value : fail(`Give the ${what} number.`);
1066}
1067
1068async function pullNumber(repo, value) {
1069 if (value) return number(value, "pull request");
1070 const branch = git("symbolic-ref", "--short", "HEAD");
1071 const open = (await repoApi(repo, "pulls?state=open")).items.find((pull) => pull.head === branch);
1072 return open?.number ?? fail(`No open pull request from ${branch}. Give the pull request number.`);
1073}
1074
1075function mergeLine(pull) {
1076 if (pull.status !== "open") return `Merge: ${pull.status}.`;
1077 const merge = pull.mergeability;
1078 return merge?.state === "clean" ? "Merge: no conflicts." : merge?.state === "conflicts" ? `Merge: conflicts in ${merge.paths.join(", ")}.` : `Merge: unknown (${merge?.reason ?? "no answer"}).`;
1079}
1080
1081function confirm(question) {
1082 const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
1083 return new Promise((resolve) => prompt.question(`${question} [y/N] `, (answer) => (prompt.close(), resolve(/^y(es)?$/i.test(answer.trim())))));
1084}
1085
1086const pr = {
1087 async list(values) {
1088 const repo = targetRepo(values);
1089 show(values, await repoApi(repo, `pulls?state=${values.closed ? "closed" : "open"}`), ({ items }) => {
1090 if (!items.length) return console.log(`No ${values.closed ? "closed" : "open"} pull requests in ${repo}.`);
1091 for (const pull of items) console.log(`#${pull.number}\t${pull.status}\t${pull.head} → ${pull.base}\t${pull.title}\t${pull.author.name}${pull.agent ? ` (${pull.agent})` : ""}`);
1092 });
1093 },
1094 async view(values, [value]) {
1095 const repo = targetRepo(values);
1096 const pull = await repoApi(repo, `pulls/${await pullNumber(repo, value)}`);
1097 show(values, pull, () => {
1098 console.log(`#${pull.number} ${pull.title}`);
1099 console.log(`${pull.status} · ${pull.head} → ${pull.base} · by ${pull.author.name}${pull.agent ? ` (${pull.agent})` : ""}`);
1100 console.log(`${credentials().origin}/${repo}/pulls/${pull.number}`);
1101 console.log(mergeLine(pull));
1102 console.log(`Review threads not resolved: ${pull.threads}`);
1103 console.log(pull.checks.length ? `Checks: run ${pull.checks[0].id} ${pull.checks[0].state}` : "Checks: no runs");
1104 if (pull.body) console.log(`\n${pull.body}`);
1105 });
1106 },
1107 async create(values) {
1108 const repo = targetRepo(values);
1109 if (!values.title) fail("Give a title with --title.");
1110 const head = git("symbolic-ref", "--short", "HEAD");
1111 const pull = await repoApi(repo, "pulls", { title: values.title, body: values.body ?? "", base: values.base, head });
1112 show(values, pull, () => console.log(`Opened pull request #${pull.number}: ${credentials().origin}/${repo}/pulls/${pull.number}`));
1113 },
1114 async checkout(values, [value]) {
1115 const repo = targetRepo(values);
1116 const { head } = await repoApi(repo, `pulls/${number(value, "pull request")}`);
1117 git("fetch", "origin", `refs/heads/${head}:refs/remotes/origin/${head}`);
1118 git("checkout", "-B", head, "--track", `origin/${head}`);
1119 console.log(`Switched to ${head}.`);
1120 },
1121 async checks(values, [value]) {
1122 const repo = targetRepo(values);
1123 const { checks } = await repoApi(repo, `pulls/${await pullNumber(repo, value)}`);
1124 show(values, checks, () => {
1125 if (!checks.length) return console.log("No CI runs.");
1126 for (const run of checks) console.log(`${run.id}\t${run.state}\t${run.sha.slice(0, 7)}\t${run.trigger}\t${run.branch}`);
1127 });
1128 const latest = checks[0]?.state;
1129 if (latest && !["succeeded", "queued", "running", "waiting_image", "waiting_approval"].includes(latest)) process.exitCode = 1;
1130 },
1131 async merge(values, [value]) {
1132 const repo = targetRepo(values);
1133 const pull = await repoApi(repo, `pulls/${number(value, "pull request")}`);
1134 if (!process.stdin.isTTY) fail("refs pr merge asks for confirmation in a terminal, so only a person can merge. Merge on the pull request page instead.");
1135 if (!(await confirm(`Merge #${pull.number} "${pull.title}", ${pull.head} into ${pull.base}?`))) return console.log("Not merged.");
1136 const { commit } = await repoApi(repo, `pulls/${pull.number}/merge`, {});
1137 console.log(`Merged #${pull.number} into ${pull.base} as ${commit.slice(0, 7)}.`);
1138 },
1139};
1140
1141const task = {
1142 async list(values) {
1143 const repo = targetRepo(values);
1144 show(values, await repoApi(repo, `tasks?state=${values.closed ? "closed" : "open"}`), ({ page }) => {
1145 if (!page.items.length) return console.log(`No ${values.closed ? "closed" : "open"} tasks in ${repo}.`);
1146 for (const item of page.items) console.log(`#${item.number}\t${item.status}\t${item.title}\t${item.assignee?.name ?? ""}\t${item.labels.map((label) => label.name).join(", ")}`);
1147 });
1148 },
1149 async view(values, [value]) {
1150 const repo = targetRepo(values);
1151 const item = await repoApi(repo, `tasks/${number(value, "task")}`);
1152 show(values, item, () => {
1153 console.log(`#${item.number} ${item.title}`);
1154 console.log(`${item.status} · by ${item.author.name}${item.assignee ? ` · assigned to ${item.assignee.name}` : ""}${item.labels.length ? ` · ${item.labels.map((label) => label.name).join(", ")}` : ""}`);
1155 console.log(`${credentials().origin}/${item.repo}/tasks/${item.number}`);
1156 if (item.body) console.log(`\n${item.body}`);
1157 });
1158 },
1159 async create(values) {
1160 const repo = targetRepo(values);
1161 if (!values.title) fail("Give a title with --title.");
1162 const item = await repoApi(repo, "tasks", { title: values.title, body: values.body ?? "" });
1163 show(values, item, () => console.log(`Created task #${item.number}: ${credentials().origin}/${repo}/tasks/${item.number}`));
1164 },
1165};
1166
1167const ci = {
1168 async view(values, [id]) {
1169 const repo = targetRepo(values);
1170 const run = await repoApi(repo, `runs/${encodeURIComponent(id ?? fail("Give the run id, from refs pr checks."))}`);
1171 const failed = run.jobs.filter((job) => job.state === "failed" || job.state === "timed_out");
1172 const logs = values["log-failed"] ? await Promise.all(failed.map((job) => repoApi(repo, `runs/${run.id}/logs/${encodeURIComponent(job.name)}`))) : [];
1173 show(values, values["log-failed"] ? { ...run, logs: Object.fromEntries(failed.map((job, index) => [job.name, logs[index].steps])) } : run, () => {
1174 console.log(`Run ${run.id} ${run.state} · ${run.branch} ${run.sha.slice(0, 7)} · ${run.trigger}${run.trusted ? "" : " · untrusted"}`);
1175 for (const job of run.jobs) console.log(` ${job.state}\t${job.name}${job.failedStep === null ? "" : ` (step ${job.failedStep}: ${job.steps[job.failedStep - 1] ?? "setup"})`}`);
1176 failed.forEach((job, index) => {
1177 if (!logs[index]) return;
1178 console.log(`\n--- ${job.name} ---`);
1179 for (const step of logs[index].steps) console.log(step.text);
1180 });
1181 });
1182 },
1183};
1184
1185function group(name, verbs) {
1186 return () => {
1187 const { values, positionals } = options(args);
1188 const [verb, ...rest] = positionals;
1189 const run = verbs[verb] ?? fail(`Usage: refs ${name} ${Object.keys(verbs).join("|")}`);
1190 return run(values, rest);
1191 };
1192}
1193
1194const [command, ...args] = process.argv.slice(2);
1195const commands = {
1196 setup: () => setup(args[0]),
1197 login: async () => login(normalizeOrigin(args[0] ?? credentials().origin)),
1198 logout: () => {
1199 const saved = readCredentials();
1200 if (saved) setupGit(saved.origin, false);
1201 fs.rmSync(CREDENTIALS, { force: true });
1202 console.log("Signed out.");
1203 },
1204 status,
1205 daemon,
1206 mcp,
1207 credential: () => credentialHelper(args[0]),
1208 hook: () => {
1209 const hook = { "session-start": sessionStart, "session-end": sessionEnd, events, "opencode-prompt": openCodePrompt, "refresh-opencode": () => editOpenCode(true), "refresh-claude": () => editClaudeHooks(true) }[args[0]];
1210 return hook ? hook() : fail(`Unknown hook ${args[0]}.`);
1211 },
1212 update,
1213 uninstall,
1214 version: () => console.log(VERSION),
1215 repo: group("repo", {
1216 async create(values, [name]) {
1217 const [owner, repoName] = (name ?? fail("Usage: refs repo create [<namespace>/]<name> [--public] [--description <d>] [--empty] [--clone]")).includes("/") ? name.split("/") : [undefined, name];
1218 const repo = await repoApi(null, null, { owner, name: repoName, description: values.description ?? "", visibility: values.public ? "public" : "private", setUp: !values.empty });
1219 show(values, repo, () => console.log(`Created ${repo.visibility} repository ${repo.name}: ${credentials().origin}/${repo.name}`));
1220 if (values.clone) execFileSync("git", ["clone", repo.cloneUrl], { stdio: ["ignore", "inherit", "inherit"] });
1221 },
1222 clone: (values, [name, dir]) => execFileSync("git", ["clone", `${credentials().origin}/${name ?? fail("Usage: refs repo clone <namespace>/<repo> [directory]")}.git`, ...(dir ? [dir] : [])], { stdio: "inherit" }),
1223 }),
1224 browse: () => {
1225 const { values, positionals } = options(args);
1226 const url = `${credentials().origin}/${targetRepo(values)}${positionals[0] ? `/pulls/${number(positionals[0], "pull request")}` : ""}`;
1227 openBrowser(url);
1228 console.log(url);
1229 },
1230 pr: group("pr", pr),
1231 task: group("task", task),
1232 run: group("run", ci),
1233};
1234
1235const run = commands[command];
1236if (!run) {
1237 console.log(`refs ${VERSION}: connect your coding agents to refs, and work with its repositories.
1238
1239Setup
1240 refs setup <origin> sign in for Git and agents, set up Claude Code and OpenCode, and start the daemon
1241 refs status show sign-in and daemon state
1242 refs login [origin] sign in again
1243 refs logout forget the sign-in
1244 refs update download the latest CLI from your refs
1245 refs uninstall remove the daemon, the agent setup and ~/.refs
1246 refs version show the version
1247
1248Repositories (in a clone, or with -R <namespace>/<repo>; add --json for machine-readable output)
1249 refs repo create [<namespace>/]<name> [--public] [--description <d>] [--empty] [--clone]
1250 private and set up for agents unless told otherwise
1251 refs repo clone <namespace>/<repo> [dir]
1252 refs browse [number] open the repository or a pull request in the browser
1253 refs pr list [--closed]
1254 refs pr view [number] the pull request of the current branch without a number
1255 refs pr create --title <t> [--body <b>] [--base <branch>]
1256 refs pr checkout <number>
1257 refs pr checks [number] exits 1 when the latest run failed
1258 refs pr merge <number> asks for confirmation in a terminal
1259 refs task list [--closed]
1260 refs task view <number>
1261 refs task create --title <t> [--body <b>]
1262 refs run view <id> [--log-failed]`);
1263 process.exit(command ? 1 : 0);
1264}
1265Promise.resolve().then(run).catch((error) => {
1266 console.error(error instanceof CliError ? error.message : error);
1267 process.exit(1);
1268});