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