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