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