#!/usr/bin/env node import { execFileSync, spawn } from "node:child_process"; import { createHash, randomBytes, randomUUID } from "node:crypto"; import fs from "node:fs"; import http from "node:http"; import net from "node:net"; import os from "node:os"; import path from "node:path"; import readline from "node:readline"; const VERSION = "0.1.0"; const HOME = process.env.REFS_HOME || path.join(os.homedir(), ".refs"); const CREDENTIALS = path.join(HOME, "credentials.json"); const GIT_TOKENS = path.join(HOME, "git-tokens.json"); const SOCKET = path.join(HOME, "daemon.sock"); const LOG = path.join(HOME, "daemon.log"); const SCRIPT = path.join(HOME, "bin", "refs.mjs"); const BIN = path.join(HOME, "bin", "refs"); const MACHINE = (process.env.REFS_MACHINE || os.hostname().split(".")[0]).replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 64) || "machine"; const LAUNCHD = path.join(os.homedir(), "Library", "LaunchAgents", "dev.refs.daemon.plist"); const SYSTEMD = path.join(os.homedir(), ".config", "systemd", "user", "refs.service"); const CLAUDE_SETTINGS = path.join(os.homedir(), ".claude", "settings.json"); const RUNS = path.join(HOME, "runs.json"); const OPENCODE_SESSIONS = path.join(HOME, "opencode-sessions.json"); const OPENCODE_CONFIG = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "opencode"); const OPENCODE_SERVICE = path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state"), "opencode", "service.json"); const WORK = path.join(HOME, "work"); const NETWORK_TIMEOUT_MS = 30_000; const MCP_TIMEOUT_MS = 12 * 60 * 1000; const SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000; const SUBAGENT_TIMEOUT_MS = 60 * 60 * 1000; const DEFAULT_TOKEN_LIFETIME_SECONDS = 3600; const RECONNECT_MAX_SECONDS = 60; const SIGNED_OUT_RETRY_SECONDS = 5 * 60; const PING_INTERVAL_MS = 30_000; const SUMMARY_LIMIT = 2000; class CliError extends Error {} function fail(message) { throw new CliError(message); } /** Writes through a temporary file and a rename, so a crash never leaves a half-written file behind. */ function writeFileAtomic(file, data, mode) { fs.mkdirSync(path.dirname(file), { recursive: true }); const temporary = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`; fs.writeFileSync(temporary, data, mode === undefined ? undefined : { mode }); fs.renameSync(temporary, file); } function request(url, init = {}, timeoutMs = NETWORK_TIMEOUT_MS) { const timeout = AbortSignal.timeout(timeoutMs); return fetch(url, { ...init, signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout }); } function readCredentials() { try { return JSON.parse(fs.readFileSync(CREDENTIALS, "utf8")); } catch { return null; } } function writeCredentials(credentials) { writeFileAtomic(CREDENTIALS, JSON.stringify(credentials, null, 2), 0o600); } function readGitTokens() { try { return JSON.parse(fs.readFileSync(GIT_TOKENS, "utf8")); } catch { return {}; } } function saveGitToken(remote, value) { const tokens = readGitTokens(); if (value) tokens[remote] = value; else delete tokens[remote]; writeFileAtomic(GIT_TOKENS, JSON.stringify(tokens, null, 2), 0o600); } function gitRemote(url) { return url.replace(/(\.git)?\/?$/, ".git"); } /** git's credential helper: answers `get` for a refs remote with the session token the MCP proxy holds for it. */ function credentialHelper(action) { const fields = Object.fromEntries( fs .readFileSync(0, "utf8") .split("\n") .filter((line) => line.includes("=")) .map((line) => [line.slice(0, line.indexOf("=")), line.slice(line.indexOf("=") + 1)]), ); if (!fields.path) return; const remote = gitRemote(`${fields.protocol}://${fields.host}/${fields.path}`); const saved = readGitTokens()[remote]; if (action === "get" && saved) process.stdout.write(`username=x-token\npassword=${saved}\n`); if (action === "erase" && saved && fields.password === saved) saveGitToken(remote, null); } function cloneUrl(cwd) { try { return execFileSync("git", ["-C", cwd, "config", "--get", "remote.origin.url"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); } catch { return null; } } function gitConfig(cwd, ...args) { try { execFileSync("git", ["-C", cwd, "config", ...args], { stdio: "ignore" }); } catch {} } /** Points the clone at `cwd` to the refs credential helper for `remote`, and drops any session token an older CLI put in its config. */ function useCredentialHelper(cwd, remote) { const url = cloneUrl(cwd); if (!url || gitRemote(url) !== remote) return; for (const header of new Set([`http.${remote}.extraHeader`, `http.${url}.extraHeader`])) gitConfig(cwd, "--unset-all", header, "refs_agent_"); gitConfig(cwd, "--replace-all", `credential.${url}.helper`, ""); gitConfig(cwd, "--add", `credential.${url}.helper`, `!"${BIN}" credential`); gitConfig(cwd, `credential.${url}.useHttpPath`, "true"); } function dropCredentialHelper(cwd, remote) { saveGitToken(remote, null); const url = cloneUrl(cwd); if (!url || gitRemote(url) !== remote) return; gitConfig(cwd, "--unset-all", `credential.${url}.helper`); gitConfig(cwd, "--unset-all", `credential.${url}.useHttpPath`); } /** Takes the session credential out of a refs tool result before the model sees it, and hands it to git. */ function holdCredential(name, helper, result, cwd) { const refs = result?._meta?.refs; if (!refs) return; delete result._meta.refs; if (result.isError) return; if (!refs.token) return dropCredentialHelper(cwd, refs.remote); if (!helper) return; saveGitToken(refs.remote, refs.token); if (name === "refs_take" || name === "refs_connect") useCredentialHelper(cwd, refs.remote); } function credentials() { return readCredentials() ?? fail("Not signed in. Run `refs setup `."); } let refreshing = null; async function token() { const saved = credentials(); if (saved.expiresAt - 60 > Date.now() / 1000) return saved.accessToken; refreshing ??= refreshToken(saved).finally(() => (refreshing = null)); return refreshing; } async function refreshToken(saved) { const response = await request(`${saved.origin}/oauth/token`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: saved.refreshToken, client_id: saved.clientId, resource: saved.origin }), }); const refreshed = await response.json().catch(() => ({})); if (!refreshed.access_token) fail("Your refs sign-in expired. Run `refs login`."); writeCredentials({ ...saved, accessToken: refreshed.access_token, refreshToken: refreshed.refresh_token ?? saved.refreshToken, expiresAt: Date.now() / 1000 + (refreshed.expires_in ?? DEFAULT_TOKEN_LIFETIME_SECONDS) }); return refreshed.access_token; } function normalizeOrigin(value) { const url = new URL(value.includes("://") ? value : `https://${value}`); return url.origin; } function openBrowser(url) { if (process.env.REFS_BROWSER === "none") return; const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open"; spawn(opener, [url], { stdio: "ignore", detached: true }).on("error", () => {}).unref(); } async function login(origin) { const server = http.createServer(); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const redirectUri = `http://127.0.0.1:${server.address().port}/callback`; const registered = await ( await request(`${origin}/oauth/register`, { method: "POST", headers: { "content-type": "application/json" }, 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" }), }) ).json(); if (!registered.client_id) fail(`${origin} did not accept the refs CLI as an OAuth client. Is it a refs server?`); const verifier = randomBytes(32).toString("base64url"); const state = randomBytes(12).toString("base64url"); const authorize = new URL(`${origin}/oauth/authorize`); authorize.search = new URLSearchParams({ response_type: "code", client_id: registered.client_id, redirect_uri: redirectUri, code_challenge: createHash("sha256").update(verifier).digest("base64url"), code_challenge_method: "S256", state, scope: "agents", resource: origin, }).toString(); console.log(`Sign in to refs in your browser. If it doesn't open, visit:\n\n ${authorize}\n`); openBrowser(authorize.href); const code = await new Promise((resolve, reject) => { const timer = setTimeout(() => { server.close(); reject(new CliError("Sign-in timed out. Run `refs login` again.")); }, SIGN_IN_TIMEOUT_MS); server.on("request", (incoming, response) => { const url = new URL(incoming.url, redirectUri); if (url.pathname !== "/callback") return response.writeHead(404).end(); const ok = url.searchParams.get("state") === state && url.searchParams.get("code"); response.writeHead(200, { "content-type": "text/html" }).end(ok ? "

Signed in to refs. You can close this tab.

" : "

Sign-in was cancelled.

"); clearTimeout(timer); server.close(); ok ? resolve(url.searchParams.get("code")) : reject(new CliError(`Sign-in failed: ${url.searchParams.get("error") ?? "state mismatch"}.`)); }); }); const issued = await ( await request(`${origin}/oauth/token`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirectUri, client_id: registered.client_id, code_verifier: verifier, resource: origin }), }) ).json(); if (!issued.access_token) fail(`Sign-in failed: ${issued.error_description ?? issued.error ?? "no token"}.`); writeCredentials({ origin, clientId: registered.client_id, accessToken: issued.access_token, refreshToken: issued.refresh_token, expiresAt: Date.now() / 1000 + (issued.expires_in ?? DEFAULT_TOKEN_LIFETIME_SECONDS) }); const me = await whoami(); console.log(`Signed in to ${origin} as ${me.name}.`); } async function api(pathname, init = {}) { const { origin } = credentials(); return request(`${origin}${pathname}`, { ...init, headers: { authorization: `Bearer ${await token()}`, ...init.headers } }); } async function whoami() { const response = await api("/api/cli/whoami"); if (!response.ok) fail(`refs refused the sign-in (HTTP ${response.status}). Run \`refs login\`.`); return response.json(); } function runtimes() { return ["claude", "opencode", "codex"].filter(installed); } function askDaemon(message, timeoutMs = 1000) { return new Promise((resolve) => { const socket = net.createConnection(SOCKET); const timer = setTimeout(() => (socket.destroy(), resolve(null)), timeoutMs); socket.on("error", () => (clearTimeout(timer), resolve(null))); socket.on("connect", () => { readline.createInterface({ input: socket }).once("line", (line) => { clearTimeout(timer); socket.end(); try { resolve(JSON.parse(line)); } catch { resolve(null); } }); socket.write(JSON.stringify(message) + "\n"); }); }); } async function ensureDaemon() { if (await askDaemon({ type: "status" })) return; fs.mkdirSync(HOME, { recursive: true }); const log = fs.openSync(LOG, "a"); spawn(process.execPath, [process.argv[1], "daemon"], { detached: true, stdio: ["ignore", log, log] }).unref(); for (let attempt = 0; attempt < 30; attempt++) { await new Promise((resolve) => setTimeout(resolve, 100)); if (await askDaemon({ type: "status" })) return; } } async function daemon() { const { origin } = credentials(); if (await askDaemon({ type: "status" })) fail("The refs daemon is already running."); fs.mkdirSync(HOME, { recursive: true }); fs.rmSync(SOCKET, { force: true }); const state = { connected: false, since: null }; net .createServer((connection) => { readline.createInterface({ input: connection }).on("line", (line) => { let message; try { message = JSON.parse(line); } catch { return; } if (message.type === "status") connection.write(JSON.stringify({ origin, machine: MACHINE, version: VERSION, ...state }) + "\n"); }); }) .listen(SOCKET); const log = (text) => console.log(`${new Date().toISOString()} ${text}`); let retry = 1; const reconnect = (seconds) => setTimeout(connect, seconds * 1000 * (0.5 + Math.random() / 2)); const connect = async () => { let socket; try { socket = new WebSocket(`${origin.replace(/^http/, "ws")}/api/cli/connect`, { headers: { authorization: `Bearer ${await token()}` } }); } catch (error) { if (error instanceof CliError) { log(`${error.message} Retrying in ${SIGNED_OUT_RETRY_SECONDS / 60} minutes.`); return reconnect(SIGNED_OUT_RETRY_SECONDS); } log(`cannot connect: ${error.message}`); return reconnect(Math.min((retry *= 2), RECONNECT_MAX_SECONDS)); } let ping; socket.addEventListener("open", () => { socket.send(JSON.stringify({ type: "hello", machine: MACHINE, runtimes: runtimes(), version: VERSION })); ping = setInterval(() => socket.send(JSON.stringify({ type: "ping" })), PING_INTERVAL_MS); }); socket.addEventListener("message", ({ data }) => { let message; try { message = JSON.parse(String(data)); } catch { return log("ignored a malformed message from refs"); } if (message.type === "welcome") { retry = 1; Object.assign(state, { connected: true, since: new Date().toISOString() }); log(`connected to ${origin} as ${MACHINE}`); } if (message.type === "run") queueRun(message, log); if (message.type === "wake") wakeOpenCode(message, log).catch((error) => log(`could not wake OpenCode for mention ${message.mention}: ${error.message}`)); }); socket.addEventListener("close", () => { clearInterval(ping); if (state.connected) log("disconnected"); Object.assign(state, { connected: false, since: null }); reconnect(Math.min((retry *= 2), RECONNECT_MAX_SECONDS)); }); socket.addEventListener("error", () => {}); }; for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => (fs.rmSync(SOCKET, { force: true }), process.exit(0))); if (installed("opencode")) watchOpenCode(log); await connect(); } function openCodeService() { const service = JSON.parse(fs.readFileSync(OPENCODE_SERVICE, "utf8")); return { url: service.url.replace(/\/$/, ""), authorization: `Basic ${Buffer.from(`opencode:${service.password}`).toString("base64")}` }; } function openCodeSessions() { try { return JSON.parse(fs.readFileSync(OPENCODE_SESSIONS, "utf8")); } catch { return {}; } } const woken = new Map(); /** Starts a turn in a live OpenCode session through the OpenCode service, so it answers a mention now. */ async function wakeOpenCode(wake, log) { const service = openCodeService(); const response = await request(`${service.url}/api/session/${encodeURIComponent(wake.session)}/prompt`, { method: "POST", headers: { authorization: service.authorization, "content-type": "application/json" }, body: JSON.stringify({ 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.`, delivery: "queue", }), }); if (!response.ok) throw new Error(`OpenCode answered HTTP ${response.status}`); woken.set(wake.session, { mention: wake.mention, started: false, text: "" }); log(`mention ${wake.mention}: started a turn in OpenCode session ${wake.session}`); } /** * Follows the OpenCode service's events and mirrors every tool approval a refs-connected session asks * for to the portal. Whichever answer comes first wins: a portal answer is sent to OpenCode, and an * answer in OpenCode takes the request back off the portal. */ async function watchOpenCode(log) { const pending = new Map(); const decoder = new TextDecoder(); for (;;) { try { const service = openCodeService(); const response = await fetch(`${service.url}/api/event`, { headers: { authorization: service.authorization, accept: "text/event-stream" } }); if (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`); let buffer = ""; for await (const chunk of response.body) { buffer += decoder.decode(chunk, { stream: true }); for (let end = buffer.indexOf("\n\n"); end >= 0; end = buffer.indexOf("\n\n")) { const data = buffer .slice(0, end) .split("\n") .filter((line) => line.startsWith("data:")) .map((line) => line.slice(5).trim()) .join(""); buffer = buffer.slice(end + 2); if (!data) continue; try { openCodeEvent(JSON.parse(data), service, pending, log); } catch (error) { log(`ignored an OpenCode event: ${error.message}`); } } } } catch (error) { if (!(error?.code === "ENOENT")) log(`OpenCode event stream stopped: ${error.message}`); } await new Promise((resolve) => setTimeout(resolve, 5000)); } } function openCodeEvent(event, service, pending, log) { const data = event.data ?? event.properties ?? {}; const turn = woken.get(data.sessionID); if (turn && event.type === "session.execution.started") turn.started = true; if (turn && event.type === "session.text.ended" && typeof data.text === "string" && data.text.trim()) turn.text = data.text.trim(); if (turn?.started && (event.type === "session.execution.succeeded" || event.type === "session.execution.failed")) { woken.delete(data.sessionID); const ok = event.type === "session.execution.succeeded"; const summary = turn.text || (ok ? "" : String(data.error?.message ?? data.error ?? "the turn failed")); reportRun({ session: openCodeSessions()[data.sessionID], mention: turn.mention, ok, summary }).catch((error) => log(`could not report mention ${turn.mention}: ${error.message}`)); } if (event.type === "permission.asked" && openCodeSessions()[data.sessionID] && !pending.has(data.id)) { const controller = new AbortController(); pending.set(data.id, controller); log(`OpenCode session ${data.sessionID} asks for ${data.action}: sent to refs`); callTool("opencode", "refs_approve", { client_session: data.sessionID, tool_name: data.action, input: { resources: data.resources, ...(data.metadata ?? {}) }, request_id: data.id }, controller.signal) .then(async (answer) => { if (!pending.delete(data.id)) return; const { behavior, message, expired } = JSON.parse(answer); if (expired || (behavior !== "allow" && behavior !== "deny")) return; await request(`${service.url}/api/session/${encodeURIComponent(data.sessionID)}/permission/${encodeURIComponent(data.id)}/reply`, { method: "POST", headers: { authorization: service.authorization, "content-type": "application/json" }, body: JSON.stringify({ decision: behavior === "allow" ? "once" : "reject", ...(message ? { message } : {}) }), }); }) .catch((error) => pending.delete(data.id) && log(`approval ${data.id} failed: ${error.message}`)); } if (event.type === "permission.replied" && pending.has(data.requestID)) { pending.get(data.requestID).abort(); pending.delete(data.requestID); callTool("opencode", "refs_approve", { client_session: data.sessionID, tool_name: "", input: {}, request_id: data.requestID, withdraw: true }).catch(() => {}); } } const runQueues = new Map(); function queueRun(run, log) { const previous = runQueues.get(run.parent) ?? Promise.resolve(); const next = previous .then(() => runSubAgent(run, log)) .catch((error) => log(`run for mention ${run.mention} failed: ${error.message}`)) .finally(() => runQueues.get(run.parent) === next && runQueues.delete(run.parent)); runQueues.set(run.parent, next); } function readRuns() { try { return JSON.parse(fs.readFileSync(RUNS, "utf8")); } catch { return {}; } } /** Changes one parent's run record. Reads and writes with no await between them, so concurrent runs never overwrite each other. */ function updateRun(parent, change) { const runs = readRuns(); runs[parent] = change(runs[parent]); writeFileAtomic(RUNS, JSON.stringify(runs, null, 2)); } function mentionPlace(mention) { return `pull request #${mention.pull}`; } function subAgentPrompt(run) { const job = run.assigned ? `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.` : `Answer with refs_reply (mention ${run.mention}). The repository is checked out in the current directory if you need it.`; return [ `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}":`, "", run.body, "", job, "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.", ].join("\n"); } /** * Answers a mention with a headless Claude Code run: a sub-agent session linked to the mentioned one, * in its own clone, resuming the same conversation on later mentions, with every tool approval sent * to the portal. The parent session hears how it went at its next turn. */ async function runSubAgent(run, log) { const known = readRuns()[run.parent]; const conversation = known?.conversation ?? randomUUID(); const dir = known?.dir ?? path.join(WORK, run.repo, run.parent.slice(0, 8)); log(`mention ${run.mention} on ${run.repo} ${mentionPlace(run)}: starting a sub-agent`); const init = await mcpRequest({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", clientInfo: { name: "claude-code" }, capabilities: {} } }); const connection = init.headers.get("mcp-session-id"); const connected = await ( 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) ).json(); const rules = connected.result?.content?.[0]?.text ?? ""; const child = connected.result?._meta?.session; if (connected.result?.isError || !child) throw new CliError(rules || "refs did not start a sub-agent session"); const { remote, token: sessionToken } = connected.result._meta?.refs ?? {}; if (!sessionToken) throw new CliError("refs gave no git credential for the sub-agent"); if (!fs.existsSync(dir)) { fs.mkdirSync(path.dirname(dir), { recursive: true }); const header = { GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: `http.${remote}.extraHeader`, GIT_CONFIG_VALUE_0: `Authorization: Bearer ${sessionToken}` }; execFileSync("git", ["clone", "-q", remote, dir], { stdio: "ignore", env: { ...process.env, ...header } }); } updateRun(run.parent, (current) => ({ conversation, dir, child, started: current?.started === true })); const config = path.join(HOME, "runs", `${conversation}.mcp.json`); fs.mkdirSync(path.dirname(config), { recursive: true }); fs.writeFileSync(config, JSON.stringify({ mcpServers: { refs: { command: process.execPath, args: [process.argv[1], "mcp"], env: { REFS_CLIENT_SESSION: conversation, REFS_HOME: HOME } } } })); const args = [ "-p", subAgentPrompt(run), ...(known?.started ? ["--resume", conversation] : ["--session-id", conversation]), "--mcp-config", config, "--strict-mcp-config", "--permission-prompt-tool", "mcp__refs__refs_approve", "--allowedTools", "mcp__refs", "Read", "Glob", "Grep", "--append-system-prompt", rules, "--output-format", "json", ...(process.env.REFS_SUBAGENT_MODEL ? ["--model", process.env.REFS_SUBAGENT_MODEL] : []), ]; const { code, stdout, stderr } = await new Promise((resolve) => { const agent = spawn("claude", args, { cwd: dir, stdio: ["ignore", "pipe", "pipe"] }); let stdout = ""; let stderr = ""; const limit = setTimeout(() => { stderr += `\nThe sub-agent ran longer than ${SUBAGENT_TIMEOUT_MS / 60_000} minutes and was stopped.`; agent.kill("SIGTERM"); }, SUBAGENT_TIMEOUT_MS); agent.stdout.on("data", (chunk) => (stdout += chunk)); agent.stderr.on("data", (chunk) => (stderr += chunk)); agent.on("error", (error) => (clearTimeout(limit), resolve({ code: -1, stdout, stderr: error.message }))); agent.on("exit", (code) => (clearTimeout(limit), resolve({ code, stdout, stderr }))); }); let result = {}; try { result = JSON.parse(stdout); } catch {} const ok = code === 0 && !result.is_error; if (result.session_id) updateRun(run.parent, (current) => ({ ...current, started: true })); log(`mention ${run.mention}: sub-agent ${ok ? "finished" : `failed (exit ${code})`}`); const summary = String(result.result ?? stderr ?? "").trim().slice(0, SUMMARY_LIMIT); await reportRun({ session: child, mention: run.mention, ok, summary }); } async function reportRun(report) { for (let attempt = 1; ; attempt++) { try { 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) }) }); if (response.ok || response.status === 404) return; const error = new Error(`HTTP ${response.status}`); if (response.status < 500 && response.status !== 429) throw new CliError(`refs refused the run report (${error.message}).`); throw error; } catch (error) { if (error instanceof CliError || attempt === 5) throw error; await new Promise((resolve) => setTimeout(resolve, attempt * 2000)); } } } async function mcpRequest(body, session, signal) { const send = async (bearer) => request(`${credentials().origin}/mcp`, { method: "POST", headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json", accept: "application/json, text/event-stream", ...(session ? { "mcp-session-id": session } : {}) }, body: JSON.stringify(body), signal, }, MCP_TIMEOUT_MS); return send(await token()); } /** * The MCP server outside a refs clone: it answers on the spot, offers no tools and never calls refs, so a project that * doesn't use refs never waits on it or sees its errors. The refs hooks' calls to refs_events get an empty answer. */ function localMcp() { const write = (message) => process.stdout.write(JSON.stringify(message) + "\n"); const answers = { initialize: (params) => ({ protocolVersion: params?.protocolVersion ?? "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "refs", version: VERSION } }), ping: () => ({}), "tools/list": () => ({ tools: [] }), "tools/call": () => ({ content: [] }), }; const lines = readline.createInterface({ input: process.stdin }); lines.on("line", (line) => { let message; try { message = JSON.parse(line); } catch { return; } if (message.id === undefined) return; const answer = answers[message.method]; 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.` } }); }); lines.on("close", () => process.exit(0)); } async function mcp() { const cwd = process.cwd(); const saved = readCredentials(); const clone = saved && repoOf(cwd, saved.origin); if (!clone) return localMcp(); ensureDaemon().catch(() => {}); let session = null; const write = (message) => process.stdout.write(JSON.stringify(message) + "\n"); const lines = readline.createInterface({ input: process.stdin }); lines.on("line", async (line) => { let message; try { message = JSON.parse(line); } catch { return; } if (message.method === "tools/call" && message.params?.name === "refs_connect") message.params.arguments = { ...message.params.arguments, machine: MACHINE }; if (message.method === "tools/call" && process.env.REFS_CLIENT_SESSION) message.params.arguments = { client_session: process.env.REFS_CLIENT_SESSION, ...message.params.arguments }; const name = message.method === "tools/call" ? message.params?.name : null; const helper = Boolean(clone) && (name === "refs_take" || name === "refs_release" || (name === "refs_connect" && message.params.arguments?.repo === clone)); if (helper) message.params.arguments = { ...message.params.arguments, credentials: "helper" }; try { const response = await mcpRequest(message, session); session ??= response.headers.get("mcp-session-id"); if (response.status === 200) { const answer = await response.json(); if (name) holdCredential(name, helper, answer.result, cwd); write(answer); } else if (message.id !== undefined && response.status !== 202 && response.status !== 204) write({ jsonrpc: "2.0", id: message.id, error: { code: -32000, message: `refs answered HTTP ${response.status}. Run \`refs status\`.` } }); } catch (error) { if (message.id !== undefined) write({ jsonrpc: "2.0", id: message.id, error: { code: -32000, message: error.message } }); } }); lines.on("close", async () => { if (session) { await request(`${credentials().origin}/mcp`, { method: "DELETE", headers: { authorization: `Bearer ${await token()}`, "mcp-session-id": session } }).catch(() => {}); } process.exit(0); }); } function repoOf(cwd, origin) { try { const remote = execFileSync("git", ["-C", cwd, "config", "--get", "remote.origin.url"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); const match = remote.match(/^(https?:\/\/[^/]+)\/([A-Za-z0-9._-]+\/[A-Za-z0-9._-]+?)(?:\.git)?\/?$/); return match && match[1] === origin ? match[2] : null; } catch { return null; } } async function connectSession(runtime, clientSession, cwd) { const saved = readCredentials(); const repo = saved && repoOf(cwd, saved.origin); if (!repo) return null; await ensureDaemon(); const init = await mcpRequest({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", clientInfo: { name: runtime }, capabilities: {} } }); const connection = init.headers.get("mcp-session-id"); const connected = await ( await mcpRequest({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "refs_connect", arguments: { repo, client_session: clientSession, machine: MACHINE, credentials: "helper" } } }, connection) ).json(); const text = connected.result?.content?.[0]?.text ?? ""; const id = connected.result?._meta?.session; if (connected.result?.isError || !id) return { error: `[refs] Could not connect to ${saved.origin}: ${text || "no answer"}` }; const me = await whoami(); const daemonState = await askDaemon({ type: "status" }); 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`)"}`; return { id, banner, text, connection }; } async function callTool(runtime, name, args, signal) { const init = await mcpRequest({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", clientInfo: { name: runtime }, capabilities: {} } }); 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(); return answer.result?.content?.[0]?.text ?? ""; } async function sessionStart() { const input = JSON.parse(fs.readFileSync(0, "utf8") || "{}"); const session = await connectSession("claude-code", input.session_id, input.cwd ?? process.cwd()); if (!session) return; if (session.error) return console.log(JSON.stringify({ systemMessage: session.error })); console.log(JSON.stringify({ systemMessage: session.banner, hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: `${session.banner}\n\n${session.text}` } })); } async function sessionEnd() { const input = JSON.parse(fs.readFileSync(0, "utf8") || "{}"); const saved = readCredentials(); 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 }); } /** OpenCode's refs plugin calls this before each prompt: the first one connects the session, every one gets the updates. */ async function openCodePrompt() { const input = JSON.parse(fs.readFileSync(0, "utf8") || "{}"); if (!input.session_id || !readCredentials() || !repoOf(input.cwd ?? process.cwd(), readCredentials().origin)) return; let known = {}; try { known = JSON.parse(fs.readFileSync(OPENCODE_SESSIONS, "utf8")); } catch {} const parts = []; if (!known[input.session_id]) { const session = await connectSession("opencode", input.session_id, input.cwd); if (session?.error) return console.log(session.error); known[input.session_id] = session.id; writeFileAtomic(OPENCODE_SESSIONS, JSON.stringify(known, null, 2)); parts.push(`${session.banner}\n\n${session.text}`); } const updates = await callTool("opencode", "refs_events", { client_session: input.session_id }); if (updates && !/^(No new updates|You are offline)/.test(updates)) parts.push(updates); if (parts.length) console.log(parts.join("\n\n")); } function claude(args) { return execFileSync("claude", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); } function isRefsHook(hook) { return (hook.type === "mcp_tool" && /^(plugin:refs:)?refs$/.test(hook.server ?? "")) || /refs\/bin\/refs|git\.useref\.dev/.test(hook.command ?? ""); } function editClaudeHooks(add) { const settings = fs.existsSync(CLAUDE_SETTINGS) ? JSON.parse(fs.readFileSync(CLAUDE_SETTINGS, "utf8")) : {}; const hooks = settings.hooks ?? {}; for (const event of Object.keys(hooks)) { hooks[event] = hooks[event].map((entry) => ({ ...entry, hooks: (entry.hooks ?? []).filter((hook) => !isRefsHook(hook)) })).filter((entry) => entry.hooks.length); if (!hooks[event].length) delete hooks[event]; } if (add) { const updates = [{ type: "mcp_tool", server: "refs", tool: "refs_events", input: { event: "${hook_event_name}", client_session: "${session_id}" } }]; (hooks.SessionStart ??= []).push({ hooks: [{ type: "command", command: `"${BIN}" hook session-start` }] }); (hooks.SessionEnd ??= []).push({ hooks: [{ type: "command", command: `"${BIN}" hook session-end` }] }); (hooks.UserPromptSubmit ??= []).push({ hooks: updates }); (hooks.PostToolUse ??= []).push({ matcher: "Bash", hooks: updates }); } if (Object.keys(hooks).length) settings.hooks = hooks; else delete settings.hooks; fs.mkdirSync(path.dirname(CLAUDE_SETTINGS), { recursive: true }); fs.writeFileSync(CLAUDE_SETTINGS, JSON.stringify(settings, null, 2) + "\n"); } function installService() { if (process.env.REFS_NO_SERVICE) return ensureDaemon(); if (process.platform === "darwin") { const uid = String(process.getuid()); fs.mkdirSync(path.dirname(LAUNCHD), { recursive: true }); fs.writeFileSync( LAUNCHD, ` Labeldev.refs.daemon ProgramArguments${BIN}daemon RunAtLoad KeepAlive EnvironmentVariablesPATH${(process.env.PATH ?? "").replace(/&/g, "&").replace(/ StandardOutPath${LOG} StandardErrorPath${LOG} `, ); try { execFileSync("launchctl", ["bootout", `gui/${uid}`, LAUNCHD], { stdio: "ignore" }); } catch {} execFileSync("launchctl", ["bootstrap", `gui/${uid}`, LAUNCHD]); return; } if (process.platform === "linux") { fs.mkdirSync(path.dirname(SYSTEMD), { recursive: true }); 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`); execFileSync("systemctl", ["--user", "daemon-reload"]); execFileSync("systemctl", ["--user", "enable", "--now", "refs.service"]); return; } return ensureDaemon(); } function restartService() { try { if (process.platform === "darwin" && fs.existsSync(LAUNCHD)) execFileSync("launchctl", ["kickstart", "-k", `gui/${process.getuid()}/dev.refs.daemon`], { stdio: "ignore" }); else if (process.platform === "linux" && fs.existsSync(SYSTEMD)) execFileSync("systemctl", ["--user", "restart", "refs.service"], { stdio: "ignore" }); } catch {} } function removeService() { if (process.platform === "darwin" && fs.existsSync(LAUNCHD)) { try { execFileSync("launchctl", ["bootout", `gui/${process.getuid()}`, LAUNCHD], { stdio: "ignore" }); } catch {} fs.rmSync(LAUNCHD, { force: true }); } if (process.platform === "linux" && fs.existsSync(SYSTEMD)) { try { execFileSync("systemctl", ["--user", "disable", "--now", "refs.service"], { stdio: "ignore" }); } catch {} fs.rmSync(SYSTEMD, { force: true }); } } function installed(name) { try { execFileSync("sh", ["-c", `command -v ${name}`], { stdio: "ignore" }); return true; } catch { return false; } } function setupClaude() { for (const args of [["plugin", "uninstall", "refs@refs"], ["plugin", "marketplace", "remove", "refs"], ["mcp", "remove", "refs", "--scope", "user"]]) { try { claude(args); } catch {} } claude(["mcp", "add", "--scope", "user", "refs", "--", BIN, "mcp"]); editClaudeHooks(true); } function openCodePlugin() { return `import { execFile } from "node:child_process"; const BIN = ${JSON.stringify(BIN)}; const ENV = { ...process.env, PATH: ${JSON.stringify(process.env.PATH ?? "")} }; function refs(args, input) { return new Promise((resolve) => { const child = execFile(BIN, args, { env: ENV, timeout: 60 * 1000 }, (error, stdout) => resolve(error ? "" : stdout.trim())); child.stdin.end(JSON.stringify(input)); }); } export default { id: "refs", setup: async (ctx) => { await ctx.session.hook("prompt", async (event) => { const prompt = event.prompt; const text = typeof prompt?.text === "string" ? prompt.text : ""; const extra = await refs(["hook", "opencode-prompt"], { session_id: event.sessionID, cwd: ctx.location.directory }); if (extra && prompt) prompt.text = text ? text + "\\n\\n" + extra : extra; }); await ctx.tool.hook("execute.before", (event) => { if (/^refs[_.]/.test(event.tool) && event.input && typeof event.input === "object") event.input = { ...event.input, client_session: event.sessionID }; }); }, }; `; } function editOpenCode(add) { const file = path.join(OPENCODE_CONFIG, "opencode.json"); const config = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : { $schema: "https://opencode.ai/config.json" }; config.mcp ??= {}; delete config.mcp.refs; if (config.mcp.servers) delete config.mcp.servers.refs; if (add) (config.mcp.servers ??= {}).refs = { type: "local", command: [BIN, "mcp"], environment: { PATH: process.env.PATH ?? "" }, codemode: false }; if (config.mcp.servers && !Object.keys(config.mcp.servers).length) delete config.mcp.servers; fs.mkdirSync(OPENCODE_CONFIG, { recursive: true }); fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\n"); const plugin = path.join(OPENCODE_CONFIG, "plugins", "refs.js"); if (add) { fs.mkdirSync(path.dirname(plugin), { recursive: true }); fs.writeFileSync(plugin, openCodePlugin()); } else fs.rmSync(plugin, { force: true }); } async function setup(originArg) { const saved = readCredentials(); const origin = normalizeOrigin(originArg ?? saved?.origin ?? fail("Usage: refs setup , for example refs setup useref.dev")); const agents = [installed("claude") && "Claude Code", installed("opencode") && "OpenCode"].filter(Boolean); if (!agents.length) fail("Neither Claude Code nor OpenCode is installed. Install one, then run `refs setup` again."); if (!saved || saved.origin !== origin) await login(origin); if (agents.includes("Claude Code")) setupClaude(); if (agents.includes("OpenCode")) editOpenCode(true); await installService(); console.log(`refs is set up for ${agents.join(" and ")} on ${MACHINE}. Every new session in a clone of a ${new URL(origin).host} repository connects by itself.`); if (agents.includes("OpenCode")) console.log("Restart OpenCode's background service to load refs: opencode service restart"); } async function status() { const saved = readCredentials(); if (!saved) return console.log("Not signed in. Run `refs setup `."); const me = await whoami().catch((error) => ({ name: `unknown (${error.message})` })); const daemonState = await askDaemon({ type: "status" }); console.log(`refs ${VERSION} on ${MACHINE}`); console.log(`Signed in to ${saved.origin} as ${me.name}`); 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."); } async function update() { const { origin } = credentials(); const response = await request(`${origin}/cli/refs.mjs`); if (!response.ok) fail(`Could not download the CLI from ${origin} (HTTP ${response.status}).`); const script = await response.text(); const expected = response.headers.get("x-refs-sha256"); if (expected && createHash("sha256").update(script).digest("hex") !== expected) fail("The downloaded CLI does not match its checksum. Nothing was changed. Try again."); const candidate = path.join(path.dirname(SCRIPT), "refs.download.mjs"); fs.writeFileSync(candidate, script); try { execFileSync(process.execPath, ["--check", candidate], { stdio: "ignore" }); } catch { fs.rmSync(candidate, { force: true }); fail("The downloaded CLI is not valid JavaScript. Nothing was changed. Try again."); } fs.renameSync(candidate, SCRIPT); if (installed("claude")) execFileSync(BIN, ["hook", "refresh-claude"], { stdio: "ignore" }); if (installed("opencode") && fs.existsSync(path.join(OPENCODE_CONFIG, "plugins", "refs.js"))) execFileSync(BIN, ["hook", "refresh-opencode"], { stdio: "ignore" }); restartService(); console.log(`Updated refs from ${origin} and restarted the daemon.`); } function uninstall() { removeService(); try { claude(["mcp", "remove", "refs", "--scope", "user"]); } catch {} editClaudeHooks(false); if (fs.existsSync(path.join(OPENCODE_CONFIG, "opencode.json"))) editOpenCode(false); if (fs.existsSync(CREDENTIALS) || fs.existsSync(SCRIPT) || HOME === path.join(os.homedir(), ".refs")) fs.rmSync(HOME, { recursive: true, force: true }); else console.log(`${HOME} does not look like a refs home, so it was left in place.`); console.log("refs is uninstalled: the daemon, the Claude Code and OpenCode setup, and ~/.refs are gone."); } const [command, ...args] = process.argv.slice(2); const commands = { setup: () => setup(args[0]), login: async () => login(normalizeOrigin(args[0] ?? credentials().origin)), logout: () => (fs.rmSync(CREDENTIALS, { force: true }), console.log("Signed out.")), status, daemon, mcp, credential: () => credentialHelper(args[0]), hook: () => { const hook = { "session-start": sessionStart, "session-end": sessionEnd, "opencode-prompt": openCodePrompt, "refresh-opencode": () => editOpenCode(true), "refresh-claude": () => editClaudeHooks(true) }[args[0]]; return hook ? hook() : fail(`Unknown hook ${args[0]}.`); }, update, uninstall, version: () => console.log(VERSION), }; const run = commands[command]; if (!run) { console.log(`refs ${VERSION}: connect your coding agents to refs. refs setup sign in, set up Claude Code and OpenCode, and start the daemon refs status show sign-in and daemon state refs update download the latest CLI from your refs refs logout forget the sign-in refs uninstall remove the daemon, the agent setup and ~/.refs`); process.exit(command ? 1 : 0); } Promise.resolve(run()).catch((error) => { console.error(error instanceof CliError ? error.message : error); process.exit(1); });