989 lines · 44.6 KBRaw
| 1 | #!/usr/bin/env node |
| 2 | import { execFileSync, spawn } from "node:child_process"; |
| 3 | import { createHash, randomBytes, randomUUID } from "node:crypto"; |
| 4 | import fs from "node:fs"; |
| 5 | import http from "node:http"; |
| 6 | import net from "node:net"; |
| 7 | import os from "node:os"; |
| 8 | import path from "node:path"; |
| 9 | import readline from "node:readline"; |
| 10 | |
| 11 | const VERSION = "0.1.0"; |
| 12 | const HOME = process.env.REFS_HOME || path.join(os.homedir(), ".refs"); |
| 13 | const CREDENTIALS = path.join(HOME, "credentials.json"); |
| 14 | const GIT_TOKENS = path.join(HOME, "git-tokens.json"); |
| 15 | const SOCKET = path.join(HOME, "daemon.sock"); |
| 16 | const LOG = path.join(HOME, "daemon.log"); |
| 17 | const SCRIPT = path.join(HOME, "bin", "refs.mjs"); |
| 18 | const BIN = path.join(HOME, "bin", "refs"); |
| 19 | const MACHINE = (process.env.REFS_MACHINE || os.hostname().split(".")[0]).replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 64) || "machine"; |
| 20 | const LAUNCHD = path.join(os.homedir(), "Library", "LaunchAgents", "dev.refs.daemon.plist"); |
| 21 | const SYSTEMD = path.join(os.homedir(), ".config", "systemd", "user", "refs.service"); |
| 22 | const CLAUDE_SETTINGS = path.join(os.homedir(), ".claude", "settings.json"); |
| 23 | const RUNS = path.join(HOME, "runs.json"); |
| 24 | const OPENCODE_SESSIONS = path.join(HOME, "opencode-sessions.json"); |
| 25 | const OPENCODE_CONFIG = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "opencode"); |
| 26 | const OPENCODE_SERVICE = path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state"), "opencode", "service.json"); |
| 27 | const WORK = path.join(HOME, "work"); |
| 28 | const NETWORK_TIMEOUT_MS = 30_000; |
| 29 | const MCP_TIMEOUT_MS = 12 * 60 * 1000; |
| 30 | const SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000; |
| 31 | const SUBAGENT_TIMEOUT_MS = 60 * 60 * 1000; |
| 32 | const DEFAULT_TOKEN_LIFETIME_SECONDS = 3600; |
| 33 | const RECONNECT_MAX_SECONDS = 60; |
| 34 | const SIGNED_OUT_RETRY_SECONDS = 5 * 60; |
| 35 | const PING_INTERVAL_MS = 30_000; |
| 36 | const SUMMARY_LIMIT = 2000; |
| 37 | |
| 38 | class CliError extends Error {} |
| 39 | |
| 40 | function fail(message) { |
| 41 | throw new CliError(message); |
| 42 | } |
| 43 | |
| 44 | /** Writes through a temporary file and a rename, so a crash never leaves a half-written file behind. */ |
| 45 | function writeFileAtomic(file, data, mode) { |
| 46 | fs.mkdirSync(path.dirname(file), { recursive: true }); |
| 47 | const temporary = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`; |
| 48 | fs.writeFileSync(temporary, data, mode === undefined ? undefined : { mode }); |
| 49 | fs.renameSync(temporary, file); |
| 50 | } |
| 51 | |
| 52 | function request(url, init = {}, timeoutMs = NETWORK_TIMEOUT_MS) { |
| 53 | const timeout = AbortSignal.timeout(timeoutMs); |
| 54 | return fetch(url, { ...init, signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout }); |
| 55 | } |
| 56 | |
| 57 | function readCredentials() { |
| 58 | try { |
| 59 | return JSON.parse(fs.readFileSync(CREDENTIALS, "utf8")); |
| 60 | } catch { |
| 61 | return null; |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | function writeCredentials(credentials) { |
| 66 | writeFileAtomic(CREDENTIALS, JSON.stringify(credentials, null, 2), 0o600); |
| 67 | } |
| 68 | |
| 69 | function readGitTokens() { |
| 70 | try { |
| 71 | return JSON.parse(fs.readFileSync(GIT_TOKENS, "utf8")); |
| 72 | } catch { |
| 73 | return {}; |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | function saveGitToken(remote, value) { |
| 78 | const tokens = readGitTokens(); |
| 79 | if (value) tokens[remote] = value; |
| 80 | else delete tokens[remote]; |
| 81 | writeFileAtomic(GIT_TOKENS, JSON.stringify(tokens, null, 2), 0o600); |
| 82 | } |
| 83 | |
| 84 | function gitRemote(url) { |
| 85 | return url.replace(/(\.git)?\/?$/, ".git"); |
| 86 | } |
| 87 | |
| 88 | /** git's credential helper: answers `get` for a refs remote with the session token the MCP proxy holds for it. */ |
| 89 | function credentialHelper(action) { |
| 90 | const fields = Object.fromEntries( |
| 91 | fs |
| 92 | .readFileSync(0, "utf8") |
| 93 | .split("\n") |
| 94 | .filter((line) => line.includes("=")) |
| 95 | .map((line) => [line.slice(0, line.indexOf("=")), line.slice(line.indexOf("=") + 1)]), |
| 96 | ); |
| 97 | if (!fields.path) return; |
| 98 | const remote = gitRemote(`${fields.protocol}://${fields.host}/${fields.path}`); |
| 99 | const saved = readGitTokens()[remote]; |
| 100 | if (action === "get" && saved) process.stdout.write(`username=x-token\npassword=${saved}\n`); |
| 101 | if (action === "erase" && saved && fields.password === saved) saveGitToken(remote, null); |
| 102 | } |
| 103 | |
| 104 | function cloneUrl(cwd) { |
| 105 | try { |
| 106 | return execFileSync("git", ["-C", cwd, "config", "--get", "remote.origin.url"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); |
| 107 | } catch { |
| 108 | return null; |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | function gitConfig(cwd, ...args) { |
| 113 | try { |
| 114 | execFileSync("git", ["-C", cwd, "config", ...args], { stdio: "ignore" }); |
| 115 | } catch {} |
| 116 | } |
| 117 | |
| 118 | /** Points the clone at `cwd` to the refs credential helper for `remote`, and drops any session token an older CLI put in its config. */ |
| 119 | function useCredentialHelper(cwd, remote) { |
| 120 | const url = cloneUrl(cwd); |
| 121 | if (!url || gitRemote(url) !== remote) return; |
| 122 | for (const header of new Set([`http.${remote}.extraHeader`, `http.${url}.extraHeader`])) gitConfig(cwd, "--unset-all", header, "refs_agent_"); |
| 123 | gitConfig(cwd, "--replace-all", `credential.${url}.helper`, ""); |
| 124 | gitConfig(cwd, "--add", `credential.${url}.helper`, `!"${BIN}" credential`); |
| 125 | gitConfig(cwd, `credential.${url}.useHttpPath`, "true"); |
| 126 | } |
| 127 | |
| 128 | function dropCredentialHelper(cwd, remote) { |
| 129 | saveGitToken(remote, null); |
| 130 | const url = cloneUrl(cwd); |
| 131 | if (!url || gitRemote(url) !== remote) return; |
| 132 | gitConfig(cwd, "--unset-all", `credential.${url}.helper`); |
| 133 | gitConfig(cwd, "--unset-all", `credential.${url}.useHttpPath`); |
| 134 | } |
| 135 | |
| 136 | /** Takes the session credential out of a refs tool result before the model sees it, and hands it to git. */ |
| 137 | function holdCredential(name, helper, result, cwd) { |
| 138 | const refs = result?._meta?.refs; |
| 139 | if (!refs) return; |
| 140 | delete result._meta.refs; |
| 141 | if (result.isError) return; |
| 142 | if (!refs.token) return dropCredentialHelper(cwd, refs.remote); |
| 143 | if (!helper) return; |
| 144 | saveGitToken(refs.remote, refs.token); |
| 145 | if (name === "refs_take" || name === "refs_connect") useCredentialHelper(cwd, refs.remote); |
| 146 | } |
| 147 | |
| 148 | function credentials() { |
| 149 | return readCredentials() ?? fail("Not signed in. Run `refs setup <origin>`."); |
| 150 | } |
| 151 | |
| 152 | let refreshing = null; |
| 153 | |
| 154 | async function token() { |
| 155 | const saved = credentials(); |
| 156 | if (saved.expiresAt - 60 > Date.now() / 1000) return saved.accessToken; |
| 157 | refreshing ??= refreshToken(saved).finally(() => (refreshing = null)); |
| 158 | return refreshing; |
| 159 | } |
| 160 | |
| 161 | async function refreshToken(saved) { |
| 162 | const response = await request(`${saved.origin}/oauth/token`, { |
| 163 | method: "POST", |
| 164 | headers: { "content-type": "application/x-www-form-urlencoded" }, |
| 165 | body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: saved.refreshToken, client_id: saved.clientId, resource: saved.origin }), |
| 166 | }); |
| 167 | const refreshed = await response.json().catch(() => ({})); |
| 168 | if (!refreshed.access_token) fail("Your refs sign-in expired. Run `refs login`."); |
| 169 | writeCredentials({ ...saved, accessToken: refreshed.access_token, refreshToken: refreshed.refresh_token ?? saved.refreshToken, expiresAt: Date.now() / 1000 + (refreshed.expires_in ?? DEFAULT_TOKEN_LIFETIME_SECONDS) }); |
| 170 | return refreshed.access_token; |
| 171 | } |
| 172 | |
| 173 | function normalizeOrigin(value) { |
| 174 | const url = new URL(value.includes("://") ? value : `https://${value}`); |
| 175 | return url.origin; |
| 176 | } |
| 177 | |
| 178 | function openBrowser(url) { |
| 179 | if (process.env.REFS_BROWSER === "none") return; |
| 180 | const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open"; |
| 181 | spawn(opener, [url], { stdio: "ignore", detached: true }).on("error", () => {}).unref(); |
| 182 | } |
| 183 | |
| 184 | async function login(origin) { |
| 185 | const server = http.createServer(); |
| 186 | await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); |
| 187 | const redirectUri = `http://127.0.0.1:${server.address().port}/callback`; |
| 188 | const registered = await ( |
| 189 | await request(`${origin}/oauth/register`, { |
| 190 | method: "POST", |
| 191 | headers: { "content-type": "application/json" }, |
| 192 | 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" }), |
| 193 | }) |
| 194 | ).json(); |
| 195 | if (!registered.client_id) fail(`${origin} did not accept the refs CLI as an OAuth client. Is it a refs server?`); |
| 196 | |
| 197 | const verifier = randomBytes(32).toString("base64url"); |
| 198 | const state = randomBytes(12).toString("base64url"); |
| 199 | const authorize = new URL(`${origin}/oauth/authorize`); |
| 200 | authorize.search = new URLSearchParams({ |
| 201 | response_type: "code", |
| 202 | client_id: registered.client_id, |
| 203 | redirect_uri: redirectUri, |
| 204 | code_challenge: createHash("sha256").update(verifier).digest("base64url"), |
| 205 | code_challenge_method: "S256", |
| 206 | state, |
| 207 | scope: "agents", |
| 208 | resource: origin, |
| 209 | }).toString(); |
| 210 | console.log(`Sign in to refs in your browser. If it doesn't open, visit:\n\n ${authorize}\n`); |
| 211 | openBrowser(authorize.href); |
| 212 | |
| 213 | const code = await new Promise((resolve, reject) => { |
| 214 | const timer = setTimeout(() => { |
| 215 | server.close(); |
| 216 | reject(new CliError("Sign-in timed out. Run `refs login` again.")); |
| 217 | }, SIGN_IN_TIMEOUT_MS); |
| 218 | server.on("request", (incoming, response) => { |
| 219 | const url = new URL(incoming.url, redirectUri); |
| 220 | if (url.pathname !== "/callback") return response.writeHead(404).end(); |
| 221 | const ok = url.searchParams.get("state") === state && url.searchParams.get("code"); |
| 222 | 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>"); |
| 223 | clearTimeout(timer); |
| 224 | server.close(); |
| 225 | ok ? resolve(url.searchParams.get("code")) : reject(new CliError(`Sign-in failed: ${url.searchParams.get("error") ?? "state mismatch"}.`)); |
| 226 | }); |
| 227 | }); |
| 228 | |
| 229 | const issued = await ( |
| 230 | await request(`${origin}/oauth/token`, { |
| 231 | method: "POST", |
| 232 | headers: { "content-type": "application/x-www-form-urlencoded" }, |
| 233 | body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirectUri, client_id: registered.client_id, code_verifier: verifier, resource: origin }), |
| 234 | }) |
| 235 | ).json(); |
| 236 | if (!issued.access_token) fail(`Sign-in failed: ${issued.error_description ?? issued.error ?? "no token"}.`); |
| 237 | 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) }); |
| 238 | const me = await whoami(); |
| 239 | console.log(`Signed in to ${origin} as ${me.name}.`); |
| 240 | } |
| 241 | |
| 242 | async function api(pathname, init = {}) { |
| 243 | const { origin } = credentials(); |
| 244 | return request(`${origin}${pathname}`, { ...init, headers: { authorization: `Bearer ${await token()}`, ...init.headers } }); |
| 245 | } |
| 246 | |
| 247 | async function whoami() { |
| 248 | const response = await api("/api/cli/whoami"); |
| 249 | if (!response.ok) fail(`refs refused the sign-in (HTTP ${response.status}). Run \`refs login\`.`); |
| 250 | return response.json(); |
| 251 | } |
| 252 | |
| 253 | function runtimes() { |
| 254 | return ["claude", "opencode", "codex"].filter(installed); |
| 255 | } |
| 256 | |
| 257 | function askDaemon(message, timeoutMs = 1000) { |
| 258 | return new Promise((resolve) => { |
| 259 | const socket = net.createConnection(SOCKET); |
| 260 | const timer = setTimeout(() => (socket.destroy(), resolve(null)), timeoutMs); |
| 261 | socket.on("error", () => (clearTimeout(timer), resolve(null))); |
| 262 | socket.on("connect", () => { |
| 263 | readline.createInterface({ input: socket }).once("line", (line) => { |
| 264 | clearTimeout(timer); |
| 265 | socket.end(); |
| 266 | try { |
| 267 | resolve(JSON.parse(line)); |
| 268 | } catch { |
| 269 | resolve(null); |
| 270 | } |
| 271 | }); |
| 272 | socket.write(JSON.stringify(message) + "\n"); |
| 273 | }); |
| 274 | }); |
| 275 | } |
| 276 | |
| 277 | async function ensureDaemon() { |
| 278 | if (await askDaemon({ type: "status" })) return; |
| 279 | fs.mkdirSync(HOME, { recursive: true }); |
| 280 | const log = fs.openSync(LOG, "a"); |
| 281 | spawn(process.execPath, [process.argv[1], "daemon"], { detached: true, stdio: ["ignore", log, log] }).unref(); |
| 282 | for (let attempt = 0; attempt < 30; attempt++) { |
| 283 | await new Promise((resolve) => setTimeout(resolve, 100)); |
| 284 | if (await askDaemon({ type: "status" })) return; |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | async function daemon() { |
| 289 | const { origin } = credentials(); |
| 290 | if (await askDaemon({ type: "status" })) fail("The refs daemon is already running."); |
| 291 | fs.mkdirSync(HOME, { recursive: true }); |
| 292 | fs.rmSync(SOCKET, { force: true }); |
| 293 | const state = { connected: false, since: null }; |
| 294 | |
| 295 | net |
| 296 | .createServer((connection) => { |
| 297 | readline.createInterface({ input: connection }).on("line", (line) => { |
| 298 | let message; |
| 299 | try { |
| 300 | message = JSON.parse(line); |
| 301 | } catch { |
| 302 | return; |
| 303 | } |
| 304 | if (message.type === "status") connection.write(JSON.stringify({ origin, machine: MACHINE, version: VERSION, ...state }) + "\n"); |
| 305 | }); |
| 306 | }) |
| 307 | .listen(SOCKET); |
| 308 | |
| 309 | const log = (text) => console.log(`${new Date().toISOString()} ${text}`); |
| 310 | let retry = 1; |
| 311 | const reconnect = (seconds) => setTimeout(connect, seconds * 1000 * (0.5 + Math.random() / 2)); |
| 312 | const connect = async () => { |
| 313 | let socket; |
| 314 | try { |
| 315 | socket = new WebSocket(`${origin.replace(/^http/, "ws")}/api/cli/connect`, { headers: { authorization: `Bearer ${await token()}` } }); |
| 316 | } catch (error) { |
| 317 | if (error instanceof CliError) { |
| 318 | log(`${error.message} Retrying in ${SIGNED_OUT_RETRY_SECONDS / 60} minutes.`); |
| 319 | return reconnect(SIGNED_OUT_RETRY_SECONDS); |
| 320 | } |
| 321 | log(`cannot connect: ${error.message}`); |
| 322 | return reconnect(Math.min((retry *= 2), RECONNECT_MAX_SECONDS)); |
| 323 | } |
| 324 | let ping; |
| 325 | socket.addEventListener("open", () => { |
| 326 | socket.send(JSON.stringify({ type: "hello", machine: MACHINE, runtimes: runtimes(), version: VERSION })); |
| 327 | ping = setInterval(() => socket.send(JSON.stringify({ type: "ping" })), PING_INTERVAL_MS); |
| 328 | }); |
| 329 | socket.addEventListener("message", ({ data }) => { |
| 330 | let message; |
| 331 | try { |
| 332 | message = JSON.parse(String(data)); |
| 333 | } catch { |
| 334 | return log("ignored a malformed message from refs"); |
| 335 | } |
| 336 | if (message.type === "welcome") { |
| 337 | retry = 1; |
| 338 | Object.assign(state, { connected: true, since: new Date().toISOString() }); |
| 339 | log(`connected to ${origin} as ${MACHINE}`); |
| 340 | } |
| 341 | if (message.type === "run") queueRun(message, log); |
| 342 | if (message.type === "wake") wakeOpenCode(message, log).catch((error) => log(`could not wake OpenCode for mention ${message.mention}: ${error.message}`)); |
| 343 | }); |
| 344 | socket.addEventListener("close", () => { |
| 345 | clearInterval(ping); |
| 346 | if (state.connected) log("disconnected"); |
| 347 | Object.assign(state, { connected: false, since: null }); |
| 348 | reconnect(Math.min((retry *= 2), RECONNECT_MAX_SECONDS)); |
| 349 | }); |
| 350 | socket.addEventListener("error", () => {}); |
| 351 | }; |
| 352 | for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => (fs.rmSync(SOCKET, { force: true }), process.exit(0))); |
| 353 | if (installed("opencode")) watchOpenCode(log); |
| 354 | await connect(); |
| 355 | } |
| 356 | |
| 357 | function openCodeService() { |
| 358 | const service = JSON.parse(fs.readFileSync(OPENCODE_SERVICE, "utf8")); |
| 359 | return { url: service.url.replace(/\/$/, ""), authorization: `Basic ${Buffer.from(`opencode:${service.password}`).toString("base64")}` }; |
| 360 | } |
| 361 | |
| 362 | function openCodeSessions() { |
| 363 | try { |
| 364 | return JSON.parse(fs.readFileSync(OPENCODE_SESSIONS, "utf8")); |
| 365 | } catch { |
| 366 | return {}; |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | const woken = new Map(); |
| 371 | |
| 372 | /** Starts a turn in a live OpenCode session through the OpenCode service, so it answers a mention now. */ |
| 373 | async function wakeOpenCode(wake, log) { |
| 374 | const service = openCodeService(); |
| 375 | const response = await request(`${service.url}/api/session/${encodeURIComponent(wake.session)}/prompt`, { |
| 376 | method: "POST", |
| 377 | headers: { authorization: service.authorization, "content-type": "application/json" }, |
| 378 | body: JSON.stringify({ |
| 379 | 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.`, |
| 380 | delivery: "queue", |
| 381 | }), |
| 382 | }); |
| 383 | if (!response.ok) throw new Error(`OpenCode answered HTTP ${response.status}`); |
| 384 | woken.set(wake.session, { mention: wake.mention, started: false, text: "" }); |
| 385 | log(`mention ${wake.mention}: started a turn in OpenCode session ${wake.session}`); |
| 386 | } |
| 387 | |
| 388 | /** |
| 389 | * Follows the OpenCode service's events and mirrors every tool approval a refs-connected session asks |
| 390 | * for to the portal. Whichever answer comes first wins: a portal answer is sent to OpenCode, and an |
| 391 | * answer in OpenCode takes the request back off the portal. |
| 392 | */ |
| 393 | async function watchOpenCode(log) { |
| 394 | const pending = new Map(); |
| 395 | const decoder = new TextDecoder(); |
| 396 | for (;;) { |
| 397 | try { |
| 398 | const service = openCodeService(); |
| 399 | const response = await fetch(`${service.url}/api/event`, { headers: { authorization: service.authorization, accept: "text/event-stream" } }); |
| 400 | if (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`); |
| 401 | let buffer = ""; |
| 402 | for await (const chunk of response.body) { |
| 403 | buffer += decoder.decode(chunk, { stream: true }); |
| 404 | for (let end = buffer.indexOf("\n\n"); end >= 0; end = buffer.indexOf("\n\n")) { |
| 405 | const data = buffer |
| 406 | .slice(0, end) |
| 407 | .split("\n") |
| 408 | .filter((line) => line.startsWith("data:")) |
| 409 | .map((line) => line.slice(5).trim()) |
| 410 | .join(""); |
| 411 | buffer = buffer.slice(end + 2); |
| 412 | if (!data) continue; |
| 413 | try { |
| 414 | openCodeEvent(JSON.parse(data), service, pending, log); |
| 415 | } catch (error) { |
| 416 | log(`ignored an OpenCode event: ${error.message}`); |
| 417 | } |
| 418 | } |
| 419 | } |
| 420 | } catch (error) { |
| 421 | if (!(error?.code === "ENOENT")) log(`OpenCode event stream stopped: ${error.message}`); |
| 422 | } |
| 423 | await new Promise((resolve) => setTimeout(resolve, 5000)); |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | function openCodeEvent(event, service, pending, log) { |
| 428 | const data = event.data ?? event.properties ?? {}; |
| 429 | const turn = woken.get(data.sessionID); |
| 430 | if (turn && event.type === "session.execution.started") turn.started = true; |
| 431 | if (turn && event.type === "session.text.ended" && typeof data.text === "string" && data.text.trim()) turn.text = data.text.trim(); |
| 432 | if (turn?.started && (event.type === "session.execution.succeeded" || event.type === "session.execution.failed")) { |
| 433 | woken.delete(data.sessionID); |
| 434 | const ok = event.type === "session.execution.succeeded"; |
| 435 | const summary = turn.text || (ok ? "" : String(data.error?.message ?? data.error ?? "the turn failed")); |
| 436 | reportRun({ session: openCodeSessions()[data.sessionID], mention: turn.mention, ok, summary }).catch((error) => log(`could not report mention ${turn.mention}: ${error.message}`)); |
| 437 | } |
| 438 | if (event.type === "permission.asked" && openCodeSessions()[data.sessionID] && !pending.has(data.id)) { |
| 439 | const controller = new AbortController(); |
| 440 | pending.set(data.id, controller); |
| 441 | log(`OpenCode session ${data.sessionID} asks for ${data.action}: sent to refs`); |
| 442 | callTool("opencode", "refs_approve", { client_session: data.sessionID, tool_name: data.action, input: { resources: data.resources, ...(data.metadata ?? {}) }, request_id: data.id }, controller.signal) |
| 443 | .then(async (answer) => { |
| 444 | if (!pending.delete(data.id)) return; |
| 445 | const { behavior, message, expired } = JSON.parse(answer); |
| 446 | if (expired || (behavior !== "allow" && behavior !== "deny")) return; |
| 447 | await request(`${service.url}/api/session/${encodeURIComponent(data.sessionID)}/permission/${encodeURIComponent(data.id)}/reply`, { |
| 448 | method: "POST", |
| 449 | headers: { authorization: service.authorization, "content-type": "application/json" }, |
| 450 | body: JSON.stringify({ decision: behavior === "allow" ? "once" : "reject", ...(message ? { message } : {}) }), |
| 451 | }); |
| 452 | }) |
| 453 | .catch((error) => pending.delete(data.id) && log(`approval ${data.id} failed: ${error.message}`)); |
| 454 | } |
| 455 | if (event.type === "permission.replied" && pending.has(data.requestID)) { |
| 456 | pending.get(data.requestID).abort(); |
| 457 | pending.delete(data.requestID); |
| 458 | callTool("opencode", "refs_approve", { client_session: data.sessionID, tool_name: "", input: {}, request_id: data.requestID, withdraw: true }).catch(() => {}); |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | const runQueues = new Map(); |
| 463 | |
| 464 | function queueRun(run, log) { |
| 465 | const previous = runQueues.get(run.parent) ?? Promise.resolve(); |
| 466 | const next = previous |
| 467 | .then(() => runSubAgent(run, log)) |
| 468 | .catch((error) => log(`run for mention ${run.mention} failed: ${error.message}`)) |
| 469 | .finally(() => runQueues.get(run.parent) === next && runQueues.delete(run.parent)); |
| 470 | runQueues.set(run.parent, next); |
| 471 | } |
| 472 | |
| 473 | function readRuns() { |
| 474 | try { |
| 475 | return JSON.parse(fs.readFileSync(RUNS, "utf8")); |
| 476 | } catch { |
| 477 | return {}; |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | /** Changes one parent's run record. Reads and writes with no await between them, so concurrent runs never overwrite each other. */ |
| 482 | function updateRun(parent, change) { |
| 483 | const runs = readRuns(); |
| 484 | runs[parent] = change(runs[parent]); |
| 485 | writeFileAtomic(RUNS, JSON.stringify(runs, null, 2)); |
| 486 | } |
| 487 | |
| 488 | function mentionPlace(mention) { |
| 489 | return `pull request #${mention.pull}`; |
| 490 | } |
| 491 | |
| 492 | function subAgentPrompt(run) { |
| 493 | const job = run.assigned |
| 494 | ? `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.` |
| 495 | : `Answer with refs_reply (mention ${run.mention}). The repository is checked out in the current directory if you need it.`; |
| 496 | return [ |
| 497 | `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}":`, |
| 498 | "", |
| 499 | run.body, |
| 500 | "", |
| 501 | job, |
| 502 | "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.", |
| 503 | ].join("\n"); |
| 504 | } |
| 505 | |
| 506 | /** |
| 507 | * Answers a mention with a headless Claude Code run: a sub-agent session linked to the mentioned one, |
| 508 | * in its own clone, resuming the same conversation on later mentions, with every tool approval sent |
| 509 | * to the portal. The parent session hears how it went at its next turn. |
| 510 | */ |
| 511 | async function runSubAgent(run, log) { |
| 512 | const known = readRuns()[run.parent]; |
| 513 | const conversation = known?.conversation ?? randomUUID(); |
| 514 | const dir = known?.dir ?? path.join(WORK, run.repo, run.parent.slice(0, 8)); |
| 515 | log(`mention ${run.mention} on ${run.repo} ${mentionPlace(run)}: starting a sub-agent`); |
| 516 | |
| 517 | const init = await mcpRequest({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", clientInfo: { name: "claude-code" }, capabilities: {} } }); |
| 518 | const connection = init.headers.get("mcp-session-id"); |
| 519 | const connected = await ( |
| 520 | 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) |
| 521 | ).json(); |
| 522 | const rules = connected.result?.content?.[0]?.text ?? ""; |
| 523 | const child = connected.result?._meta?.session; |
| 524 | if (connected.result?.isError || !child) throw new CliError(rules || "refs did not start a sub-agent session"); |
| 525 | |
| 526 | const { remote, token: sessionToken } = connected.result._meta?.refs ?? {}; |
| 527 | if (!sessionToken) throw new CliError("refs gave no git credential for the sub-agent"); |
| 528 | if (!fs.existsSync(dir)) { |
| 529 | fs.mkdirSync(path.dirname(dir), { recursive: true }); |
| 530 | const header = { GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: `http.${remote}.extraHeader`, GIT_CONFIG_VALUE_0: `Authorization: Bearer ${sessionToken}` }; |
| 531 | execFileSync("git", ["clone", "-q", remote, dir], { stdio: "ignore", env: { ...process.env, ...header } }); |
| 532 | } |
| 533 | updateRun(run.parent, (current) => ({ conversation, dir, child, started: current?.started === true })); |
| 534 | |
| 535 | const config = path.join(HOME, "runs", `${conversation}.mcp.json`); |
| 536 | fs.mkdirSync(path.dirname(config), { recursive: true }); |
| 537 | fs.writeFileSync(config, JSON.stringify({ mcpServers: { refs: { command: process.execPath, args: [process.argv[1], "mcp"], env: { REFS_CLIENT_SESSION: conversation, REFS_HOME: HOME } } } })); |
| 538 | const args = [ |
| 539 | "-p", |
| 540 | subAgentPrompt(run), |
| 541 | ...(known?.started ? ["--resume", conversation] : ["--session-id", conversation]), |
| 542 | "--mcp-config", |
| 543 | config, |
| 544 | "--strict-mcp-config", |
| 545 | "--permission-prompt-tool", |
| 546 | "mcp__refs__refs_approve", |
| 547 | "--allowedTools", |
| 548 | "mcp__refs", |
| 549 | "Read", |
| 550 | "Glob", |
| 551 | "Grep", |
| 552 | "--append-system-prompt", |
| 553 | rules, |
| 554 | "--output-format", |
| 555 | "json", |
| 556 | ...(process.env.REFS_SUBAGENT_MODEL ? ["--model", process.env.REFS_SUBAGENT_MODEL] : []), |
| 557 | ]; |
| 558 | const { code, stdout, stderr } = await new Promise((resolve) => { |
| 559 | const agent = spawn("claude", args, { cwd: dir, stdio: ["ignore", "pipe", "pipe"] }); |
| 560 | let stdout = ""; |
| 561 | let stderr = ""; |
| 562 | const limit = setTimeout(() => { |
| 563 | stderr += `\nThe sub-agent ran longer than ${SUBAGENT_TIMEOUT_MS / 60_000} minutes and was stopped.`; |
| 564 | agent.kill("SIGTERM"); |
| 565 | }, SUBAGENT_TIMEOUT_MS); |
| 566 | agent.stdout.on("data", (chunk) => (stdout += chunk)); |
| 567 | agent.stderr.on("data", (chunk) => (stderr += chunk)); |
| 568 | agent.on("error", (error) => (clearTimeout(limit), resolve({ code: -1, stdout, stderr: error.message }))); |
| 569 | agent.on("exit", (code) => (clearTimeout(limit), resolve({ code, stdout, stderr }))); |
| 570 | }); |
| 571 | let result = {}; |
| 572 | try { |
| 573 | result = JSON.parse(stdout); |
| 574 | } catch {} |
| 575 | const ok = code === 0 && !result.is_error; |
| 576 | if (result.session_id) updateRun(run.parent, (current) => ({ ...current, started: true })); |
| 577 | log(`mention ${run.mention}: sub-agent ${ok ? "finished" : `failed (exit ${code})`}`); |
| 578 | const summary = String(result.result ?? stderr ?? "").trim().slice(0, SUMMARY_LIMIT); |
| 579 | await reportRun({ session: child, mention: run.mention, ok, summary }); |
| 580 | } |
| 581 | |
| 582 | async function reportRun(report) { |
| 583 | for (let attempt = 1; ; attempt++) { |
| 584 | try { |
| 585 | 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) }) }); |
| 586 | if (response.ok || response.status === 404) return; |
| 587 | const error = new Error(`HTTP ${response.status}`); |
| 588 | if (response.status < 500 && response.status !== 429) throw new CliError(`refs refused the run report (${error.message}).`); |
| 589 | throw error; |
| 590 | } catch (error) { |
| 591 | if (error instanceof CliError || attempt === 5) throw error; |
| 592 | await new Promise((resolve) => setTimeout(resolve, attempt * 2000)); |
| 593 | } |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | async function mcpRequest(body, session, signal) { |
| 598 | const send = async (bearer) => |
| 599 | request(`${credentials().origin}/mcp`, { |
| 600 | method: "POST", |
| 601 | headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json", accept: "application/json, text/event-stream", ...(session ? { "mcp-session-id": session } : {}) }, |
| 602 | body: JSON.stringify(body), |
| 603 | signal, |
| 604 | }, MCP_TIMEOUT_MS); |
| 605 | return send(await token()); |
| 606 | } |
| 607 | |
| 608 | /** |
| 609 | * The MCP server outside a refs clone: it answers on the spot, offers no tools and never calls refs, so a project that |
| 610 | * doesn't use refs never waits on it or sees its errors. The refs hooks' calls to refs_events get an empty answer. |
| 611 | */ |
| 612 | function localMcp() { |
| 613 | const write = (message) => process.stdout.write(JSON.stringify(message) + "\n"); |
| 614 | const answers = { |
| 615 | initialize: (params) => ({ protocolVersion: params?.protocolVersion ?? "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "refs", version: VERSION } }), |
| 616 | ping: () => ({}), |
| 617 | "tools/list": () => ({ tools: [] }), |
| 618 | "tools/call": () => ({ content: [] }), |
| 619 | }; |
| 620 | const lines = readline.createInterface({ input: process.stdin }); |
| 621 | lines.on("line", (line) => { |
| 622 | let message; |
| 623 | try { |
| 624 | message = JSON.parse(line); |
| 625 | } catch { |
| 626 | return; |
| 627 | } |
| 628 | if (message.id === undefined) return; |
| 629 | const answer = answers[message.method]; |
| 630 | 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.` } }); |
| 631 | }); |
| 632 | lines.on("close", () => process.exit(0)); |
| 633 | } |
| 634 | |
| 635 | async function mcp() { |
| 636 | const cwd = process.cwd(); |
| 637 | const saved = readCredentials(); |
| 638 | const clone = saved && repoOf(cwd, saved.origin); |
| 639 | if (!clone) return localMcp(); |
| 640 | ensureDaemon().catch(() => {}); |
| 641 | let session = null; |
| 642 | const write = (message) => process.stdout.write(JSON.stringify(message) + "\n"); |
| 643 | const lines = readline.createInterface({ input: process.stdin }); |
| 644 | lines.on("line", async (line) => { |
| 645 | let message; |
| 646 | try { |
| 647 | message = JSON.parse(line); |
| 648 | } catch { |
| 649 | return; |
| 650 | } |
| 651 | if (message.method === "tools/call" && message.params?.name === "refs_connect") message.params.arguments = { ...message.params.arguments, machine: MACHINE }; |
| 652 | if (message.method === "tools/call" && process.env.REFS_CLIENT_SESSION) message.params.arguments = { client_session: process.env.REFS_CLIENT_SESSION, ...message.params.arguments }; |
| 653 | const name = message.method === "tools/call" ? message.params?.name : null; |
| 654 | const helper = Boolean(clone) && (name === "refs_take" || name === "refs_release" || (name === "refs_connect" && message.params.arguments?.repo === clone)); |
| 655 | if (helper) message.params.arguments = { ...message.params.arguments, credentials: "helper" }; |
| 656 | try { |
| 657 | const response = await mcpRequest(message, session); |
| 658 | session ??= response.headers.get("mcp-session-id"); |
| 659 | if (response.status === 200) { |
| 660 | const answer = await response.json(); |
| 661 | if (name) holdCredential(name, helper, answer.result, cwd); |
| 662 | write(answer); |
| 663 | } else if (message.id !== undefined && response.status !== 202 && response.status !== 204) |
| 664 | write({ jsonrpc: "2.0", id: message.id, error: { code: -32000, message: `refs answered HTTP ${response.status}. Run \`refs status\`.` } }); |
| 665 | } catch (error) { |
| 666 | if (message.id !== undefined) write({ jsonrpc: "2.0", id: message.id, error: { code: -32000, message: error.message } }); |
| 667 | } |
| 668 | }); |
| 669 | lines.on("close", async () => { |
| 670 | if (session) { |
| 671 | await request(`${credentials().origin}/mcp`, { method: "DELETE", headers: { authorization: `Bearer ${await token()}`, "mcp-session-id": session } }).catch(() => {}); |
| 672 | } |
| 673 | process.exit(0); |
| 674 | }); |
| 675 | } |
| 676 | |
| 677 | function repoOf(cwd, origin) { |
| 678 | try { |
| 679 | const remote = execFileSync("git", ["-C", cwd, "config", "--get", "remote.origin.url"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); |
| 680 | const match = remote.match(/^(https?:\/\/[^/]+)\/([A-Za-z0-9._-]+\/[A-Za-z0-9._-]+?)(?:\.git)?\/?$/); |
| 681 | return match && match[1] === origin ? match[2] : null; |
| 682 | } catch { |
| 683 | return null; |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | async function connectSession(runtime, clientSession, cwd) { |
| 688 | const saved = readCredentials(); |
| 689 | const repo = saved && repoOf(cwd, saved.origin); |
| 690 | if (!repo) return null; |
| 691 | await ensureDaemon(); |
| 692 | const init = await mcpRequest({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", clientInfo: { name: runtime }, capabilities: {} } }); |
| 693 | const connection = init.headers.get("mcp-session-id"); |
| 694 | const connected = await ( |
| 695 | await mcpRequest({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "refs_connect", arguments: { repo, client_session: clientSession, machine: MACHINE, credentials: "helper" } } }, connection) |
| 696 | ).json(); |
| 697 | const text = connected.result?.content?.[0]?.text ?? ""; |
| 698 | const id = connected.result?._meta?.session; |
| 699 | if (connected.result?.isError || !id) return { error: `[refs] Could not connect to ${saved.origin}: ${text || "no answer"}` }; |
| 700 | const me = await whoami(); |
| 701 | const daemonState = await askDaemon({ type: "status" }); |
| 702 | 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`)"}`; |
| 703 | return { id, banner, text, connection }; |
| 704 | } |
| 705 | |
| 706 | async function callTool(runtime, name, args, signal) { |
| 707 | const init = await mcpRequest({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", clientInfo: { name: runtime }, capabilities: {} } }); |
| 708 | 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(); |
| 709 | return answer.result?.content?.[0]?.text ?? ""; |
| 710 | } |
| 711 | |
| 712 | async function sessionStart() { |
| 713 | const input = JSON.parse(fs.readFileSync(0, "utf8") || "{}"); |
| 714 | const session = await connectSession("claude-code", input.session_id, input.cwd ?? process.cwd()); |
| 715 | if (!session) return; |
| 716 | if (session.error) return console.log(JSON.stringify({ systemMessage: session.error })); |
| 717 | console.log(JSON.stringify({ systemMessage: session.banner, hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: `${session.banner}\n\n${session.text}` } })); |
| 718 | } |
| 719 | |
| 720 | async function sessionEnd() { |
| 721 | const input = JSON.parse(fs.readFileSync(0, "utf8") || "{}"); |
| 722 | const saved = readCredentials(); |
| 723 | 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 }); |
| 724 | } |
| 725 | |
| 726 | /** OpenCode's refs plugin calls this before each prompt: the first one connects the session, every one gets the updates. */ |
| 727 | async function openCodePrompt() { |
| 728 | const input = JSON.parse(fs.readFileSync(0, "utf8") || "{}"); |
| 729 | if (!input.session_id || !readCredentials() || !repoOf(input.cwd ?? process.cwd(), readCredentials().origin)) return; |
| 730 | let known = {}; |
| 731 | try { |
| 732 | known = JSON.parse(fs.readFileSync(OPENCODE_SESSIONS, "utf8")); |
| 733 | } catch {} |
| 734 | const parts = []; |
| 735 | if (!known[input.session_id]) { |
| 736 | const session = await connectSession("opencode", input.session_id, input.cwd); |
| 737 | if (session?.error) return console.log(session.error); |
| 738 | known[input.session_id] = session.id; |
| 739 | writeFileAtomic(OPENCODE_SESSIONS, JSON.stringify(known, null, 2)); |
| 740 | parts.push(`${session.banner}\n\n${session.text}`); |
| 741 | } |
| 742 | const updates = await callTool("opencode", "refs_events", { client_session: input.session_id }); |
| 743 | if (updates && !/^(No new updates|You are offline)/.test(updates)) parts.push(updates); |
| 744 | if (parts.length) console.log(parts.join("\n\n")); |
| 745 | } |
| 746 | |
| 747 | |
| 748 | function claude(args) { |
| 749 | return execFileSync("claude", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); |
| 750 | } |
| 751 | |
| 752 | function isRefsHook(hook) { |
| 753 | return (hook.type === "mcp_tool" && /^(plugin:refs:)?refs$/.test(hook.server ?? "")) || /refs\/bin\/refs|git\.useref\.dev/.test(hook.command ?? ""); |
| 754 | } |
| 755 | |
| 756 | function editClaudeHooks(add) { |
| 757 | const settings = fs.existsSync(CLAUDE_SETTINGS) ? JSON.parse(fs.readFileSync(CLAUDE_SETTINGS, "utf8")) : {}; |
| 758 | const hooks = settings.hooks ?? {}; |
| 759 | for (const event of Object.keys(hooks)) { |
| 760 | hooks[event] = hooks[event].map((entry) => ({ ...entry, hooks: (entry.hooks ?? []).filter((hook) => !isRefsHook(hook)) })).filter((entry) => entry.hooks.length); |
| 761 | if (!hooks[event].length) delete hooks[event]; |
| 762 | } |
| 763 | if (add) { |
| 764 | const updates = [{ type: "mcp_tool", server: "refs", tool: "refs_events", input: { event: "${hook_event_name}", client_session: "${session_id}" } }]; |
| 765 | (hooks.SessionStart ??= []).push({ hooks: [{ type: "command", command: `"${BIN}" hook session-start` }] }); |
| 766 | (hooks.SessionEnd ??= []).push({ hooks: [{ type: "command", command: `"${BIN}" hook session-end` }] }); |
| 767 | (hooks.UserPromptSubmit ??= []).push({ hooks: updates }); |
| 768 | (hooks.PostToolUse ??= []).push({ matcher: "Bash", hooks: updates }); |
| 769 | } |
| 770 | if (Object.keys(hooks).length) settings.hooks = hooks; |
| 771 | else delete settings.hooks; |
| 772 | fs.mkdirSync(path.dirname(CLAUDE_SETTINGS), { recursive: true }); |
| 773 | fs.writeFileSync(CLAUDE_SETTINGS, JSON.stringify(settings, null, 2) + "\n"); |
| 774 | } |
| 775 | |
| 776 | function installService() { |
| 777 | if (process.env.REFS_NO_SERVICE) return ensureDaemon(); |
| 778 | if (process.platform === "darwin") { |
| 779 | const uid = String(process.getuid()); |
| 780 | fs.mkdirSync(path.dirname(LAUNCHD), { recursive: true }); |
| 781 | fs.writeFileSync( |
| 782 | LAUNCHD, |
| 783 | `<?xml version="1.0" encoding="UTF-8"?> |
| 784 | <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> |
| 785 | <plist version="1.0"><dict> |
| 786 | <key>Label</key><string>dev.refs.daemon</string> |
| 787 | <key>ProgramArguments</key><array><string>${BIN}</string><string>daemon</string></array> |
| 788 | <key>RunAtLoad</key><true/> |
| 789 | <key>KeepAlive</key><true/> |
| 790 | <key>EnvironmentVariables</key><dict><key>PATH</key><string>${(process.env.PATH ?? "").replace(/&/g, "&").replace(/</g, "<")}</string></dict> |
| 791 | <key>StandardOutPath</key><string>${LOG}</string> |
| 792 | <key>StandardErrorPath</key><string>${LOG}</string> |
| 793 | </dict></plist> |
| 794 | `, |
| 795 | ); |
| 796 | try { |
| 797 | execFileSync("launchctl", ["bootout", `gui/${uid}`, LAUNCHD], { stdio: "ignore" }); |
| 798 | } catch {} |
| 799 | execFileSync("launchctl", ["bootstrap", `gui/${uid}`, LAUNCHD]); |
| 800 | return; |
| 801 | } |
| 802 | if (process.platform === "linux") { |
| 803 | fs.mkdirSync(path.dirname(SYSTEMD), { recursive: true }); |
| 804 | 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`); |
| 805 | execFileSync("systemctl", ["--user", "daemon-reload"]); |
| 806 | execFileSync("systemctl", ["--user", "enable", "--now", "refs.service"]); |
| 807 | return; |
| 808 | } |
| 809 | return ensureDaemon(); |
| 810 | } |
| 811 | |
| 812 | function restartService() { |
| 813 | try { |
| 814 | if (process.platform === "darwin" && fs.existsSync(LAUNCHD)) execFileSync("launchctl", ["kickstart", "-k", `gui/${process.getuid()}/dev.refs.daemon`], { stdio: "ignore" }); |
| 815 | else if (process.platform === "linux" && fs.existsSync(SYSTEMD)) execFileSync("systemctl", ["--user", "restart", "refs.service"], { stdio: "ignore" }); |
| 816 | } catch {} |
| 817 | } |
| 818 | |
| 819 | function removeService() { |
| 820 | if (process.platform === "darwin" && fs.existsSync(LAUNCHD)) { |
| 821 | try { |
| 822 | execFileSync("launchctl", ["bootout", `gui/${process.getuid()}`, LAUNCHD], { stdio: "ignore" }); |
| 823 | } catch {} |
| 824 | fs.rmSync(LAUNCHD, { force: true }); |
| 825 | } |
| 826 | if (process.platform === "linux" && fs.existsSync(SYSTEMD)) { |
| 827 | try { |
| 828 | execFileSync("systemctl", ["--user", "disable", "--now", "refs.service"], { stdio: "ignore" }); |
| 829 | } catch {} |
| 830 | fs.rmSync(SYSTEMD, { force: true }); |
| 831 | } |
| 832 | } |
| 833 | |
| 834 | function installed(name) { |
| 835 | try { |
| 836 | execFileSync("sh", ["-c", `command -v ${name}`], { stdio: "ignore" }); |
| 837 | return true; |
| 838 | } catch { |
| 839 | return false; |
| 840 | } |
| 841 | } |
| 842 | |
| 843 | function setupClaude() { |
| 844 | for (const args of [["plugin", "uninstall", "refs@refs"], ["plugin", "marketplace", "remove", "refs"], ["mcp", "remove", "refs", "--scope", "user"]]) { |
| 845 | try { |
| 846 | claude(args); |
| 847 | } catch {} |
| 848 | } |
| 849 | claude(["mcp", "add", "--scope", "user", "refs", "--", BIN, "mcp"]); |
| 850 | editClaudeHooks(true); |
| 851 | } |
| 852 | |
| 853 | function openCodePlugin() { |
| 854 | return `import { execFile } from "node:child_process"; |
| 855 | |
| 856 | const BIN = ${JSON.stringify(BIN)}; |
| 857 | const ENV = { ...process.env, PATH: ${JSON.stringify(process.env.PATH ?? "")} }; |
| 858 | |
| 859 | function refs(args, input) { |
| 860 | return new Promise((resolve) => { |
| 861 | const child = execFile(BIN, args, { env: ENV, timeout: 60 * 1000 }, (error, stdout) => resolve(error ? "" : stdout.trim())); |
| 862 | child.stdin.end(JSON.stringify(input)); |
| 863 | }); |
| 864 | } |
| 865 | |
| 866 | export default { |
| 867 | id: "refs", |
| 868 | setup: async (ctx) => { |
| 869 | await ctx.session.hook("prompt", async (event) => { |
| 870 | const prompt = event.prompt; |
| 871 | const text = typeof prompt?.text === "string" ? prompt.text : ""; |
| 872 | const extra = await refs(["hook", "opencode-prompt"], { session_id: event.sessionID, cwd: ctx.location.directory }); |
| 873 | if (extra && prompt) prompt.text = text ? text + "\\n\\n" + extra : extra; |
| 874 | }); |
| 875 | await ctx.tool.hook("execute.before", (event) => { |
| 876 | if (/^refs[_.]/.test(event.tool) && event.input && typeof event.input === "object") event.input = { ...event.input, client_session: event.sessionID }; |
| 877 | }); |
| 878 | }, |
| 879 | }; |
| 880 | `; |
| 881 | } |
| 882 | |
| 883 | function editOpenCode(add) { |
| 884 | const file = path.join(OPENCODE_CONFIG, "opencode.json"); |
| 885 | const config = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : { $schema: "https://opencode.ai/config.json" }; |
| 886 | config.mcp ??= {}; |
| 887 | delete config.mcp.refs; |
| 888 | if (config.mcp.servers) delete config.mcp.servers.refs; |
| 889 | if (add) (config.mcp.servers ??= {}).refs = { type: "local", command: [BIN, "mcp"], environment: { PATH: process.env.PATH ?? "" }, codemode: false }; |
| 890 | if (config.mcp.servers && !Object.keys(config.mcp.servers).length) delete config.mcp.servers; |
| 891 | fs.mkdirSync(OPENCODE_CONFIG, { recursive: true }); |
| 892 | fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\n"); |
| 893 | const plugin = path.join(OPENCODE_CONFIG, "plugins", "refs.js"); |
| 894 | if (add) { |
| 895 | fs.mkdirSync(path.dirname(plugin), { recursive: true }); |
| 896 | fs.writeFileSync(plugin, openCodePlugin()); |
| 897 | } else fs.rmSync(plugin, { force: true }); |
| 898 | } |
| 899 | |
| 900 | async function setup(originArg) { |
| 901 | const saved = readCredentials(); |
| 902 | const origin = normalizeOrigin(originArg ?? saved?.origin ?? fail("Usage: refs setup <origin>, for example refs setup useref.dev")); |
| 903 | const agents = [installed("claude") && "Claude Code", installed("opencode") && "OpenCode"].filter(Boolean); |
| 904 | if (!agents.length) fail("Neither Claude Code nor OpenCode is installed. Install one, then run `refs setup` again."); |
| 905 | if (!saved || saved.origin !== origin) await login(origin); |
| 906 | if (agents.includes("Claude Code")) setupClaude(); |
| 907 | if (agents.includes("OpenCode")) editOpenCode(true); |
| 908 | await installService(); |
| 909 | 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.`); |
| 910 | if (agents.includes("OpenCode")) console.log("Restart OpenCode's background service to load refs: opencode service restart"); |
| 911 | } |
| 912 | |
| 913 | async function status() { |
| 914 | const saved = readCredentials(); |
| 915 | if (!saved) return console.log("Not signed in. Run `refs setup <origin>`."); |
| 916 | const me = await whoami().catch((error) => ({ name: `unknown (${error.message})` })); |
| 917 | const daemonState = await askDaemon({ type: "status" }); |
| 918 | console.log(`refs ${VERSION} on ${MACHINE}`); |
| 919 | console.log(`Signed in to ${saved.origin} as ${me.name}`); |
| 920 | 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."); |
| 921 | } |
| 922 | |
| 923 | async function update() { |
| 924 | const { origin } = credentials(); |
| 925 | const response = await request(`${origin}/cli/refs.mjs`); |
| 926 | if (!response.ok) fail(`Could not download the CLI from ${origin} (HTTP ${response.status}).`); |
| 927 | const script = await response.text(); |
| 928 | const expected = response.headers.get("x-refs-sha256"); |
| 929 | if (expected && createHash("sha256").update(script).digest("hex") !== expected) fail("The downloaded CLI does not match its checksum. Nothing was changed. Try again."); |
| 930 | const candidate = path.join(path.dirname(SCRIPT), "refs.download.mjs"); |
| 931 | fs.writeFileSync(candidate, script); |
| 932 | try { |
| 933 | execFileSync(process.execPath, ["--check", candidate], { stdio: "ignore" }); |
| 934 | } catch { |
| 935 | fs.rmSync(candidate, { force: true }); |
| 936 | fail("The downloaded CLI is not valid JavaScript. Nothing was changed. Try again."); |
| 937 | } |
| 938 | fs.renameSync(candidate, SCRIPT); |
| 939 | if (installed("claude")) execFileSync(BIN, ["hook", "refresh-claude"], { stdio: "ignore" }); |
| 940 | if (installed("opencode") && fs.existsSync(path.join(OPENCODE_CONFIG, "plugins", "refs.js"))) execFileSync(BIN, ["hook", "refresh-opencode"], { stdio: "ignore" }); |
| 941 | restartService(); |
| 942 | console.log(`Updated refs from ${origin} and restarted the daemon.`); |
| 943 | } |
| 944 | |
| 945 | function uninstall() { |
| 946 | removeService(); |
| 947 | try { |
| 948 | claude(["mcp", "remove", "refs", "--scope", "user"]); |
| 949 | } catch {} |
| 950 | editClaudeHooks(false); |
| 951 | if (fs.existsSync(path.join(OPENCODE_CONFIG, "opencode.json"))) editOpenCode(false); |
| 952 | if (fs.existsSync(CREDENTIALS) || fs.existsSync(SCRIPT) || HOME === path.join(os.homedir(), ".refs")) fs.rmSync(HOME, { recursive: true, force: true }); |
| 953 | else console.log(`${HOME} does not look like a refs home, so it was left in place.`); |
| 954 | console.log("refs is uninstalled: the daemon, the Claude Code and OpenCode setup, and ~/.refs are gone."); |
| 955 | } |
| 956 | |
| 957 | const [command, ...args] = process.argv.slice(2); |
| 958 | const commands = { |
| 959 | setup: () => setup(args[0]), |
| 960 | login: async () => login(normalizeOrigin(args[0] ?? credentials().origin)), |
| 961 | logout: () => (fs.rmSync(CREDENTIALS, { force: true }), console.log("Signed out.")), |
| 962 | status, |
| 963 | daemon, |
| 964 | mcp, |
| 965 | credential: () => credentialHelper(args[0]), |
| 966 | hook: () => { |
| 967 | const hook = { "session-start": sessionStart, "session-end": sessionEnd, "opencode-prompt": openCodePrompt, "refresh-opencode": () => editOpenCode(true), "refresh-claude": () => editClaudeHooks(true) }[args[0]]; |
| 968 | return hook ? hook() : fail(`Unknown hook ${args[0]}.`); |
| 969 | }, |
| 970 | update, |
| 971 | uninstall, |
| 972 | version: () => console.log(VERSION), |
| 973 | }; |
| 974 | |
| 975 | const run = commands[command]; |
| 976 | if (!run) { |
| 977 | console.log(`refs ${VERSION}: connect your coding agents to refs. |
| 978 | |
| 979 | refs setup <origin> sign in, set up Claude Code and OpenCode, and start the daemon |
| 980 | refs status show sign-in and daemon state |
| 981 | refs update download the latest CLI from your refs |
| 982 | refs logout forget the sign-in |
| 983 | refs uninstall remove the daemon, the agent setup and ~/.refs`); |
| 984 | process.exit(command ? 1 : 0); |
| 985 | } |
| 986 | Promise.resolve(run()).catch((error) => { |
| 987 | console.error(error instanceof CliError ? error.message : error); |
| 988 | process.exit(1); |
| 989 | }); |