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