Skip to content
refs
History
186 lines · 11.1 KBRaw
1import { captureWorkEvent } from "./analytics.ts";
2import { now } from "./auth.ts";
3import type { Actor } from "./contract/actor.ts";
4import type { MentionState } from "./contract/views.ts";
5import { recordEvent, repoStream } from "./events.ts";
6import { branchProblem } from "@refs/protocol";
7import { escapeHtml } from "./markdown.ts";
8import type { PullRecord } from "./pulls.ts";
9import { startAgentRuns } from "./agent-runs.ts";
10
11/** Where a mention was made: a pull request. Agents are mentioned only on pull requests and their review threads. */
12export interface MentionSubject {
13 readonly repoId: string;
14 readonly title: string;
15 readonly pull: number;
16 /** The pull request's head branch, which assigning on the pull request hands over. */
17 readonly branch: string;
18}
19
20export const onPull = (pull: Pick<PullRecord, "repo_id" | "title" | "number" | "head_ref">): MentionSubject => ({ repoId: pull.repo_id, title: pull.title, pull: pull.number, branch: pull.head_ref });
21
22const MENTION = /@agent\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/g;
23const MAX_MENTION_BODY = 4000;
24/** The runtime the refs daemon answers a mention for with a headless sub-agent run. */
25const SUBAGENT_RUNTIME = "claude-code";
26/** The runtime the refs daemon answers a mention for by starting a turn in the live session. */
27const WAKEABLE_RUNTIME = "opencode";
28const MAX_REASON = 300;
29
30export function mentionedSessions(text: string): string[] {
31 return [...new Set([...text.matchAll(MENTION)].map((match) => match[1]))];
32}
33
34/**
35 * Delivers `text` to every live session it newly mentions on the subject's repository, skipping sessions
36 * `before` already mentioned. With `assign`, each of them also takes the pull request's head branch. When a human mentions
37 * their own agent and that agent's machine is connected, the machine's refs daemon acts on it at once:
38 * for Claude Code it starts a sub-agent run, for OpenCode it starts a turn in the live session.
39 * The agent's reply goes back to the pull request; with `thread`, into that review thread.
40 * The comment is already saved, so a failure here is logged, not thrown: failing the request would make the human post it again.
41 */
42export async function deliverMentions(env: Env, ctx: Pick<ExecutionContext, "waitUntil">, actor: Actor, subject: MentionSubject, text: string, comment: number | null, options: MentionOptions = {}): Promise<void> {
43 try {
44 await sendMentions(env, ctx, actor, subject, text, comment, options);
45 } catch (error) {
46 console.error(`mentions not delivered for comment ${comment ?? "none"} in repo ${subject.repoId}`, error);
47 }
48}
49
50type MentionOptions = { before?: string; assign?: boolean; thread?: number };
51
52async function sendMentions(env: Env, ctx: Pick<ExecutionContext, "waitUntil">, actor: Actor, subject: MentionSubject, text: string, comment: number | null, options: MentionOptions): Promise<void> {
53 const { pull } = subject;
54 const db = env.DB;
55 const already = new Set(mentionedSessions(options.before ?? ""));
56 if (actor.kind === "agent") already.add(actor.sessionId);
57 await startAgentRuns(env, actor, subject, text, options.before ?? "", comment, options.thread).catch((error) => console.error(`hosted agents not started for comment ${comment ?? "none"}`, error));
58 const fresh = mentionedSessions(text).filter((session) => !already.has(session));
59 if (!fresh.length) return;
60 const { results } = await db
61 .prepare(
62 `SELECT s.id, s.user_id, s.machine, s.runtime, s.client_session, s.parent_session IS NULL AS top
63 FROM agent_sessions s
64 WHERE s.id IN (SELECT value FROM json_each(?)) AND s.repo_id = ? AND s.ended_at IS NULL AND s.expires_at > ?`,
65 )
66 .bind(JSON.stringify(fresh), subject.repoId, now())
67 .all<{ id: string; user_id: string; machine: string | null; runtime: string; client_session: string | null; top: number }>();
68 const at = now();
69 const stream = repoStream(subject.repoId);
70 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 }>())!;
71 const assign = options.assign === true && branchProblem(subject.branch, repo.default_branch) === null;
72 const owner = actor.kind === "human" ? actor.person.id : null;
73 const ours = (session: (typeof results)[number]) => session.user_id === owner && Boolean(session.top) && session.machine !== null;
74 const online = owner && results.some(ours) ? new Set(await env.USER_HUB.get(env.USER_HUB.idFromName(owner)).connected()) : new Set<string>();
75 const statements: D1PreparedStatement[] = [];
76 const runs: { userId: string; machine: string; index: number; session: string }[] = [];
77 const wakes: { userId: string; machine: string; index: number; clientSession: string }[] = [];
78 for (const session of results) {
79 const reachable = ours(session) && online.has(session.machine!);
80 const run = reachable && session.runtime === SUBAGENT_RUNTIME;
81 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));
82 if (run) runs.push({ userId: session.user_id, machine: session.machine!, index: statements.length, session: session.id });
83 const wake = reachable && session.runtime === WAKEABLE_RUNTIME && session.client_session !== null;
84 if (wake) wakes.push({ userId: session.user_id, machine: session.machine!, index: statements.length, clientSession: session.client_session! });
85 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));
86 }
87 if (!statements.length) return;
88 const written = await db.batch(statements);
89 if (actor.kind === "human") {
90 const channel = options.thread ? "thread" : "pull";
91 captureWorkEvent(env, ctx, actor, { name: "agent.directed", repoId: subject.repoId, namespaceId: repo.namespace_id, branch: subject.branch, channel, assigned: assign });
92 }
93 await Promise.all([
94 ...runs.map(async ({ userId, machine, index, session }) => {
95 const mention = written[index].meta.last_row_id;
96 const dispatched = await env.USER_HUB.get(env.USER_HUB.idFromName(userId)).dispatch(machine, {
97 type: "run",
98 parent: session,
99 mention: String(mention),
100 repo: repo.name,
101 pull,
102 title: subject.title,
103 body: text.slice(0, MAX_MENTION_BODY),
104 assigned: assign,
105 });
106 if (!dispatched) await db.prepare("UPDATE events SET data = json_set(data, '$.run', json('false')) WHERE id = ?").bind(mention).run();
107 }),
108 ...wakes.map(async ({ userId, machine, index, clientSession }) => {
109 const mention = written[index].meta.last_row_id;
110 const dispatched = await env.USER_HUB.get(env.USER_HUB.idFromName(userId)).dispatch(machine, {
111 type: "wake",
112 session: clientSession,
113 mention: String(mention),
114 pull,
115 title: subject.title,
116 by: actor.kind === "human" ? actor.person.name : "someone",
117 });
118 if (!dispatched) await db.prepare("UPDATE events SET data = json_remove(data, '$.wake') WHERE id = ?").bind(mention).run();
119 }),
120 ]);
121}
122
123interface AgentName {
124 id: string;
125 runtime: string;
126 person: string;
127 live: number;
128}
129
130/** Turns every `@agent/<session>` in rendered HTML into a chip naming the agent and its human. */
131export async function decorateMentions(db: D1Database, html: string, hosted: readonly string[] = []): Promise<string> {
132 if (hosted.length) {
133 const known = new Set(hosted);
134 html = html.replace(/(^|[\s>(])@([a-z][a-z0-9-]{1,31})(?![\w/-])/g, (token, lead: string, handle: string) => (known.has(handle) ? `${lead}<span class="agent-mention" data-live="true" title="An agent that refs runs">@${handle}</span>` : token));
135 }
136 const sessions = mentionedSessions(html);
137 if (!sessions.length) return html;
138 const { results } = await db
139 .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(?))")
140 .bind(now(), JSON.stringify(sessions))
141 .all<AgentName>();
142 const names = new Map(results.map((row) => [row.id, row]));
143 return html.replace(MENTION, (token, id: string) => {
144 const agent = names.get(id);
145 if (!agent) return token;
146 return `<span class="agent-mention" data-live="${agent.live ? "true" : "false"}" title="Agent session ${id}">@${escapeHtml(agent.runtime)} · ${escapeHtml(agent.person)} · ${id.slice(0, 4)}</span>`;
147 });
148}
149
150/**
151 * Where each mention on a pull request stands: picked up by the agent, or, when a sub-agent answers it,
152 * how that run is going. `comment` is null for the description.
153 */
154export async function mentionStates(db: D1Database, repoId: string, pull: number): Promise<MentionState[]> {
155 const { results } = await db
156 .prepare(
157 `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,
158 (coalesce(json_extract(e.data, '$.run'), 0) OR coalesce(json_extract(e.data, '$.wake'), 0)) AS run,
159 (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,
160 (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,
161 EXISTS (SELECT 1 FROM permission_requests p JOIN agent_sessions c ON c.id = p.session_id
162 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
163 FROM events e JOIN agent_sessions s ON s.id = json_extract(e.data, '$.session') JOIN users u ON u.id = s.user_id
164 WHERE e.stream = ? AND e.kind = 'agent.mentioned' AND json_extract(e.data, '$.pull') = ? ORDER BY e.id`,
165 )
166 .bind(now(), repoStream(repoId), pull)
167 .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 }>();
168 return results.map((row) => ({
169 comment: row.comment === null ? null : String(row.comment),
170 agent: `${row.runtime} · ${row.person} · ${row.session.slice(0, 4)}`,
171 reason: row.finished === 0 ? (row.summary || "no reason given").slice(0, MAX_REASON) : null,
172 state: row.run
173 ? row.finished !== null
174 ? row.finished
175 ? "answered"
176 : "failed"
177 : row.asking
178 ? "approval"
179 : "working"
180 : row.delivered_through !== null && row.delivered_through >= row.id
181 ? "delivered"
182 : row.live
183 ? "waiting"
184 : "offline",
185 }));
186}