import { captureWorkEvent } from "./analytics.ts"; import { now } from "./auth.ts"; import type { Actor } from "./contract/actor.ts"; import type { MentionState } from "./contract/views.ts"; import { recordEvent, repoStream } from "./events.ts"; import { branchProblem } from "@refs/protocol"; import { escapeHtml } from "./markdown.ts"; import type { PullRecord } from "./pulls.ts"; import { startAgentRuns } from "./agent-runs.ts"; /** Where a mention was made: a pull request. Agents are mentioned only on pull requests and their review threads. */ export interface MentionSubject { readonly repoId: string; readonly title: string; readonly pull: number; /** The pull request's head branch, which assigning on the pull request hands over. */ readonly branch: string; } export const onPull = (pull: Pick): MentionSubject => ({ repoId: pull.repo_id, title: pull.title, pull: pull.number, branch: pull.head_ref }); const MENTION = /@agent\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/g; const MAX_MENTION_BODY = 4000; /** The runtime the refs daemon answers a mention for with a headless sub-agent run. */ const SUBAGENT_RUNTIME = "claude-code"; /** The runtime the refs daemon answers a mention for by starting a turn in the live session. */ const WAKEABLE_RUNTIME = "opencode"; const MAX_REASON = 300; export function mentionedSessions(text: string): string[] { return [...new Set([...text.matchAll(MENTION)].map((match) => match[1]))]; } /** * Delivers `text` to every live session it newly mentions on the subject's repository, skipping sessions * `before` already mentioned. With `assign`, each of them also takes the pull request's head branch. When a human mentions * their own agent and that agent's machine is connected, the machine's refs daemon acts on it at once: * for Claude Code it starts a sub-agent run, for OpenCode it starts a turn in the live session. * The agent's reply goes back to the pull request; with `thread`, into that review thread. * The comment is already saved, so a failure here is logged, not thrown: failing the request would make the human post it again. */ export async function deliverMentions(env: Env, ctx: Pick, actor: Actor, subject: MentionSubject, text: string, comment: number | null, options: MentionOptions = {}): Promise { try { await sendMentions(env, ctx, actor, subject, text, comment, options); } catch (error) { console.error(`mentions not delivered for comment ${comment ?? "none"} in repo ${subject.repoId}`, error); } } type MentionOptions = { before?: string; assign?: boolean; thread?: number }; async function sendMentions(env: Env, ctx: Pick, actor: Actor, subject: MentionSubject, text: string, comment: number | null, options: MentionOptions): Promise { const { pull } = subject; const db = env.DB; const already = new Set(mentionedSessions(options.before ?? "")); if (actor.kind === "agent") already.add(actor.sessionId); await startAgentRuns(env, actor, subject, text, options.before ?? "", comment, options.thread).catch((error) => console.error(`hosted agents not started for comment ${comment ?? "none"}`, error)); const fresh = mentionedSessions(text).filter((session) => !already.has(session)); if (!fresh.length) return; const { results } = await db .prepare( `SELECT s.id, s.user_id, s.machine, s.runtime, s.client_session, s.parent_session IS NULL AS top FROM agent_sessions s WHERE s.id IN (SELECT value FROM json_each(?)) AND s.repo_id = ? AND s.ended_at IS NULL AND s.expires_at > ?`, ) .bind(JSON.stringify(fresh), subject.repoId, now()) .all<{ id: string; user_id: string; machine: string | null; runtime: string; client_session: string | null; top: number }>(); const at = now(); const stream = repoStream(subject.repoId); const repo = (await db.prepare("SELECT n.slug || '/' || r.name AS name, r.namespace_id, r.default_branch FROM repos r JOIN namespaces n ON n.id = r.namespace_id WHERE r.id = ?").bind(subject.repoId).first<{ name: string; namespace_id: string; default_branch: string }>())!; const assign = options.assign === true && branchProblem(subject.branch, repo.default_branch) === null; const owner = actor.kind === "human" ? actor.person.id : null; const ours = (session: (typeof results)[number]) => session.user_id === owner && Boolean(session.top) && session.machine !== null; const online = owner && results.some(ours) ? new Set(await env.USER_HUB.get(env.USER_HUB.idFromName(owner)).connected()) : new Set(); const statements: D1PreparedStatement[] = []; const runs: { userId: string; machine: string; index: number; session: string }[] = []; const wakes: { userId: string; machine: string; index: number; clientSession: string }[] = []; for (const session of results) { const reachable = ours(session) && online.has(session.machine!); const run = reachable && session.runtime === SUBAGENT_RUNTIME; if (assign) statements.push(db.prepare("UPDATE agent_sessions SET branch = ? WHERE id = ? AND ended_at IS NULL").bind(subject.branch, session.id), recordEvent(db, actor, stream, "session.tasked", { session: session.id, branch: subject.branch }, at)); if (run) runs.push({ userId: session.user_id, machine: session.machine!, index: statements.length, session: session.id }); const wake = reachable && session.runtime === WAKEABLE_RUNTIME && session.client_session !== null; if (wake) wakes.push({ userId: session.user_id, machine: session.machine!, index: statements.length, clientSession: session.client_session! }); statements.push(recordEvent(db, actor, stream, "agent.mentioned", { session: session.id, title: subject.title, comment, body: text.slice(0, MAX_MENTION_BODY), assigned: assign, run, ...(wake ? { wake } : {}), pull, ...(options.thread ? { thread: options.thread } : {}) }, at)); } if (!statements.length) return; const written = await db.batch(statements); if (actor.kind === "human") { const channel = options.thread ? "thread" : "pull"; captureWorkEvent(env, ctx, actor, { name: "agent.directed", repoId: subject.repoId, namespaceId: repo.namespace_id, branch: subject.branch, channel, assigned: assign }); } await Promise.all([ ...runs.map(async ({ userId, machine, index, session }) => { const mention = written[index].meta.last_row_id; const dispatched = await env.USER_HUB.get(env.USER_HUB.idFromName(userId)).dispatch(machine, { type: "run", parent: session, mention: String(mention), repo: repo.name, pull, title: subject.title, body: text.slice(0, MAX_MENTION_BODY), assigned: assign, }); if (!dispatched) await db.prepare("UPDATE events SET data = json_set(data, '$.run', json('false')) WHERE id = ?").bind(mention).run(); }), ...wakes.map(async ({ userId, machine, index, clientSession }) => { const mention = written[index].meta.last_row_id; const dispatched = await env.USER_HUB.get(env.USER_HUB.idFromName(userId)).dispatch(machine, { type: "wake", session: clientSession, mention: String(mention), pull, title: subject.title, by: actor.kind === "human" ? actor.person.name : "someone", }); if (!dispatched) await db.prepare("UPDATE events SET data = json_remove(data, '$.wake') WHERE id = ?").bind(mention).run(); }), ]); } interface AgentName { id: string; runtime: string; person: string; live: number; } /** Turns every `@agent/` in rendered HTML into a chip naming the agent and its human. */ export async function decorateMentions(db: D1Database, html: string, hosted: readonly string[] = []): Promise { if (hosted.length) { const known = new Set(hosted); html = html.replace(/(^|[\s>(])@([a-z][a-z0-9-]{1,31})(?![\w/-])/g, (token, lead: string, handle: string) => (known.has(handle) ? `${lead}@${handle}` : token)); } const sessions = mentionedSessions(html); if (!sessions.length) return html; const { results } = await db .prepare("SELECT s.id, s.runtime, u.name AS person, (s.ended_at IS NULL AND s.expires_at > ?) AS live FROM agent_sessions s JOIN users u ON u.id = s.user_id WHERE s.id IN (SELECT value FROM json_each(?))") .bind(now(), JSON.stringify(sessions)) .all(); const names = new Map(results.map((row) => [row.id, row])); return html.replace(MENTION, (token, id: string) => { const agent = names.get(id); if (!agent) return token; return `@${escapeHtml(agent.runtime)} · ${escapeHtml(agent.person)} · ${id.slice(0, 4)}`; }); } /** * Where each mention on a pull request stands: picked up by the agent, or, when a sub-agent answers it, * how that run is going. `comment` is null for the description. */ export async function mentionStates(db: D1Database, repoId: string, pull: number): Promise { const { results } = await db .prepare( `SELECT e.id, json_extract(e.data, '$.comment') AS comment, s.id AS session, s.runtime, u.name AS person, s.delivered_through, (s.ended_at IS NULL AND s.expires_at > ?) AS live, (coalesce(json_extract(e.data, '$.run'), 0) OR coalesce(json_extract(e.data, '$.wake'), 0)) AS run, (SELECT json_extract(f.data, '$.ok') FROM events f WHERE f.stream = e.stream AND f.kind = 'agent.run_finished' AND json_extract(f.data, '$.mention') = CAST(e.id AS TEXT) LIMIT 1) AS finished, (SELECT json_extract(f.data, '$.summary') FROM events f WHERE f.stream = e.stream AND f.kind = 'agent.run_finished' AND json_extract(f.data, '$.mention') = CAST(e.id AS TEXT) LIMIT 1) AS summary, EXISTS (SELECT 1 FROM permission_requests p JOIN agent_sessions c ON c.id = p.session_id WHERE p.repo_id = s.repo_id AND p.decided_at IS NULL AND p.created_at >= e.created_at AND (c.parent_session = s.id OR c.id = s.id) AND c.ended_at IS NULL) AS asking FROM events e JOIN agent_sessions s ON s.id = json_extract(e.data, '$.session') JOIN users u ON u.id = s.user_id WHERE e.stream = ? AND e.kind = 'agent.mentioned' AND json_extract(e.data, '$.pull') = ? ORDER BY e.id`, ) .bind(now(), repoStream(repoId), pull) .all<{ id: number; comment: number | null; session: string; runtime: string; person: string; delivered_through: number | null; live: number; run: number; finished: number | null; summary: string | null; asking: number }>(); return results.map((row) => ({ comment: row.comment === null ? null : String(row.comment), agent: `${row.runtime} · ${row.person} · ${row.session.slice(0, 4)}`, reason: row.finished === 0 ? (row.summary || "no reason given").slice(0, MAX_REASON) : null, state: row.run ? row.finished !== null ? row.finished ? "answered" : "failed" : row.asking ? "approval" : "working" : row.delivered_through !== null && row.delivered_through >= row.id ? "delivered" : row.live ? "waiting" : "offline", })); }