Skip to content
refs
History
475 lines · 30.3 KBRaw
1import { branchProblem, describeDeliveries, hookOutput, type Delivery } from "@refs/protocol";
2import { captureWorkEvent } from "./analytics.ts";
3import { createAgentSession, now, randomToken, rotateAgentToken, type AgentSessionRow } from "./auth.ts";
4import type { Actor, Person } from "./contract/actor.ts";
5import type { Verdict } from "./permissions.ts";
6import { DELIVERABLE_KINDS, framesFor, type DeliverableRow } from "./deliveries.ts";
7import { recordEvent, repoStream } from "./events.ts";
8import { agentActor, resolveActor } from "./identity.ts";
9import { Policy } from "./policy.ts";
10import { findRepoRecord, findRepoRecordById, namespacePolicy, repoFacts, type RepoRecord } from "./repos.ts";
11import { deliverMentions, onPull } from "./mentions.ts";
12import { commentOnPull, findPull, findThread, mentionText, setThreadStatus, threadMentionText } from "./pulls.ts";
13import { bodyError } from "./text.ts";
14import { agentRepo } from "./handles/refs.ts";
15
16const MAX_INSTRUCTION_LENGTH = 10_000;
17const REQUEST_ID = /^[A-Za-z0-9_-]{1,64}$/;
18const MAX_PREVIEW = 4000;
19const DELIVERY_BATCH = 200;
20
21/** A failure the agent can act on. Its message becomes the tool result. */
22export class AgentError extends Error {}
23
24function fail(message: string): never {
25 throw new AgentError(message);
26}
27
28interface SessionRow extends AgentSessionRow {
29 parent_session: string | null;
30 mcp_session: string | null;
31 ended_at: number | null;
32 delivered_through: number | null;
33 started: number | null;
34}
35
36const SELECT_SESSION = `SELECT s.id, s.runtime, s.parent_session, s.mcp_session, s.expires_at, s.ended_at, s.delivered_through, s.branch, r.id AS repo_id, (SELECT slug FROM namespaces WHERE id = r.namespace_id) || '/' || r.name AS repo_name,
37 u.id AS user_id, u.email, u.name, s.started_event AS started
38 FROM agent_sessions s JOIN users u ON u.id = s.user_id JOIN repos r ON r.id = s.repo_id`;
39
40/**
41 * Hands over the session's updates since its cursor, and moves the cursor past them. The cursor moves only from the
42 * value this call read, so when two calls race, one of them gets the updates and the other gets none.
43 */
44async function drainDeliveries(db: D1Database, row: SessionRow): Promise<Delivery[]> {
45 const cursor = row.delivered_through ?? row.started ?? 0;
46 const { results } = await db
47 .prepare(
48 `SELECT e.id, e.kind, e.data, e.session_id, coalesce(s.runtime, u.name) AS actor FROM events e LEFT JOIN agent_sessions s ON s.id = e.session_id LEFT JOIN users u ON u.id = e.actor_id
49 WHERE e.id > ? AND e.stream = ? AND e.kind IN (${DELIVERABLE_KINDS.map(() => "?").join(", ")}) ORDER BY e.id LIMIT ${DELIVERY_BATCH}`,
50 )
51 .bind(cursor, repoStream(row.repo_id), ...DELIVERABLE_KINDS)
52 .all<DeliverableRow>();
53 if (!results.length) return [];
54 const { meta } = await db
55 .prepare("UPDATE agent_sessions SET delivered_through = ?1 WHERE id = ?2 AND coalesce(delivered_through, started_event, 0) = ?3")
56 .bind(results[results.length - 1].id, row.id, cursor)
57 .run();
58 if (!meta.changes) return [];
59 const recipient = { session: row.id, branchRef: row.branch === null ? null : `refs/heads/${row.branch}` };
60 return results.flatMap((event) => framesFor(event, recipient));
61}
62
63function machineName(value: unknown): string | null {
64 return typeof value === "string" && /^[A-Za-z0-9._-]{1,64}$/.test(value) ? value : null;
65}
66
67/** What `refs_take` hands the session: a branch by name, or a pull request's head branch. */
68async function workTarget(db: D1Database, repo: RepoRecord, target: unknown): Promise<{ branch: string; what: string }> {
69 const { branch, pull } = (target ?? {}) as { branch?: unknown; pull?: unknown };
70 if ([branch, pull].filter((value) => value !== undefined && value !== null).length !== 1) fail("Give exactly one of branch or pull.");
71 if (branch !== undefined && branch !== null) {
72 if (typeof branch !== "string") fail("branch must be a branch name.");
73 const problem = branchProblem(branch, repo.default_branch);
74 if (problem) fail(problem);
75 return { branch, what: `branch ${branch}` };
76 }
77 if (!Number.isInteger(pull) || (pull as number) < 1) fail("pull must be a pull request number.");
78 const record = await findPull(db, repo.id, pull as number);
79 if (!record) fail(`No pull request #${pull} in ${repo.full_name}.`);
80 if (record.status !== "open") fail(`Pull request #${record.number} is ${record.status}.`);
81 const problem = branchProblem(record.head_ref, repo.default_branch);
82 if (problem) fail(problem);
83 return { branch: record.head_ref, what: `pull request #${record.number}: ${record.title}, on branch ${record.head_ref}` };
84}
85
86/** What the session works on, for the texts that report it. */
87function working(row: AgentSessionRow): string {
88 return row.branch === null ? "idle" : `branch ${row.branch}`;
89}
90
91const RULES = `Rules for working here:
92- Work on one branch at a time, and never the default branch. refs_take gives you a pull request's branch, or any branch you name. If git in this clone authenticates as this session, pushing a new branch while you have none also claims it. You may push only your branch: \`git push origin HEAD:<branch>\`.
93- Never force-push. If a push is rejected, run \`git pull --rebase\` and push again.
94- People review your work through its decisions, so record only a choice that the owner of the work would want to make themselves. All three must be true. You made the choice: the request, AGENTS.md and the earlier decisions did not. A reasonable person could choose differently. A later change is expensive: it changes what users or other agents can do, the stored data, a public interface, security, privacy or cost, or it adds a hosted service or a storage place. A choice against the request, AGENTS.md or an earlier decision is always a decision.
95- Do not record what you built, how the code works, a number that one edit can change, a choice that the person made, or a decision that is already recorded. Most commits have no decision, and they need no trailer. Most pull requests have zero to three.
96- Put each decision in a \`decision\` block at the end of the commit message. A block needs decision (one or two short sentences), reason (a list of " - item" lines) and to_reverse (what a later change costs, and who pays). If the answer to to_reverse is "a small edit", delete the block. Optional lists: alternatives_considered, assumptions, affected_components, evidence, supersedes (a decision id, or <full commit hash>#<block number>). \`rejected\` takes " name: reason" lines. Write for a reader who does not code, the way you tell a colleague: full sentences of 20 words or fewer, in the active voice. Say who does what, and give the real case ("a password or an API key", not "sensitive data"). Each reason is one full sentence. Write to_reverse as what people must do if the decision changes later. Put code and file names only in affected_components and evidence. Full format: <origin>/llms.txt.
97- refs refuses a push that has a decision block that is not valid, and explains why in the push output. Fix the last commit with \`git commit --amend\` and push again. Push after every commit.
98- Updates (pushes by others, instructions from humans, stop) reach you as "[refs] Updates" in your context. If your client has no refs hooks, call refs_events before every push.
99- Humans and other agents reach you with mentions. Answer them, and report on assigned work, with refs_reply.
100- Call refs_release when the work is done; you stay online, idle. Call refs_end only to go offline.
101- Your session outlives reconnects. If refs says you are offline, call refs_connect again with the same client_session, or with resume set to your session id.`;
102
103/**
104 * A tool's answer. `refs` carries the session's git credential outside the text, so the refs CLI can hand it to
105 * git through its credential helper; with `credentials: "helper"` the text then leaves the token out.
106 */
107/** What `refs_connect` receives, unchecked: it arrives from an MCP client as JSON. */
108export interface ConnectInput {
109 readonly repo: unknown;
110 readonly resume?: unknown;
111 readonly machine?: unknown;
112 readonly parent?: unknown;
113 readonly credentials?: unknown;
114}
115
116export interface Answer {
117 text: string;
118 refs?: { remote: string; token?: string };
119 /** The session the answer is about, for clients that act on it without reading the text. */
120 session?: string;
121}
122
123/**
124 * One MCP connection's view of its agent session. A session acts for the human who authorized the
125 * client over OAuth, on one repository, and outlives the connection: it belongs to the client's
126 * conversation (`clientSession`, sent by Claude Code's hooks), so a reconnect picks it back up.
127 */
128export function agentSessions(env: Env, ctx: Pick<ExecutionContext, "waitUntil">, userId: string, mcpSession: string, runtime: string, origin: string, clientSession: string | null = null, grantId: string | null = null) {
129 const db = env.DB;
130
131 function live(row: SessionRow | null): row is SessionRow {
132 return row !== null && row.ended_at === null && row.expires_at > now();
133 }
134
135 async function liveWhere(condition: string, value: string): Promise<SessionRow | null> {
136 return db
137 .prepare(`${SELECT_SESSION} WHERE s.user_id = ? AND ${condition} AND s.ended_at IS NULL AND s.expires_at > ? ORDER BY s.created_at DESC LIMIT 1`)
138 .bind(userId, value, now())
139 .first<SessionRow>();
140 }
141
142 async function reattach(row: SessionRow): Promise<SessionRow> {
143 await db
144 .prepare("UPDATE agent_sessions SET mcp_session = ?, client_session = coalesce(?, client_session), last_seen_at = ?, status = 'running' WHERE id = ? AND user_id = ?")
145 .bind(mcpSession, clientSession, now(), row.id, userId)
146 .run();
147 return row;
148 }
149
150 async function current(): Promise<SessionRow | null> {
151 const carried = clientSession ? await liveWhere("s.client_session = ?", clientSession) : null;
152 if (carried) return carried.mcp_session === mcpSession ? carried : reattach(carried);
153 return db.prepare(`${SELECT_SESSION} WHERE s.user_id = ? AND s.mcp_session = ? ORDER BY s.created_at DESC LIMIT 1`).bind(userId, mcpSession).first<SessionRow>();
154 }
155
156 async function active(): Promise<SessionRow> {
157 const row = await current();
158 if (!live(row)) fail(`You are offline${row ? ": your session ended or expired" : ""}. Call refs_connect with this repository's full name (<namespace>/<repo>).`);
159 return row;
160 }
161
162 async function endRow(row: SessionRow, actor: Actor, outcome: "finished" | "failed", reason: string): Promise<void> {
163 const at = now();
164 await db.batch([
165 db.prepare("UPDATE agent_sessions SET status = ?, ended_at = ? WHERE id = ? AND ended_at IS NULL").bind(outcome, at, row.id),
166 recordEvent(db, actor, repoStream(row.repo_id), "session.ended", { session: row.id, outcome, reason }, at),
167 ]);
168 }
169
170 return {
171 /** Marks the session as seen, which is what keeps it listed as online. Writes at most once a minute. */
172 async touch(): Promise<void> {
173 await db
174 .prepare("UPDATE agent_sessions SET last_seen_at = ?1, status = 'running' WHERE user_id = ?2 AND mcp_session = ?3 AND ended_at IS NULL AND (last_seen_at IS NULL OR last_seen_at < ?1 - 60 OR status != 'running')")
175 .bind(now(), userId, mcpSession)
176 .run();
177 },
178
179 /** Takes the connection offline without ending its session, so the client can pick it back up. */
180 async detach(): Promise<void> {
181 await db.prepare("UPDATE agent_sessions SET mcp_session = NULL, last_seen_at = 0 WHERE user_id = ? AND mcp_session = ? AND ended_at IS NULL").bind(userId, mcpSession).run();
182 },
183
184 async connect({ repo: repoName, resume, machine, parent, credentials }: ConnectInput): Promise<Answer> {
185 if (typeof repoName !== "string" || !repoName) fail("repo must be the repository's full name, as in <origin>/<namespace>/<repo>.git.");
186 const user = await db.prepare("SELECT id, email, name FROM users WHERE id = ?").bind(userId).first<Person>();
187 if (!user) fail("The human who authorized this client no longer exists. Sign in again.");
188 const repo = await findRepoRecord(db, repoName);
189 const policy = repo && (await namespacePolicy(db, new Policy({ kind: "human", person: user, via: "token" }, null), repo.namespace_id));
190 if (!repo || !policy || !policy.canSeeRepo(repoFacts(repo))) fail(`No repository named "${repoName}".`);
191 if (!policy.canWriteRepo(repoFacts(repo))) fail(`${user.name} cannot push to ${repo.full_name}.`);
192
193 const bound = await current();
194 const previous = !live(bound) && typeof resume === "string" && resume ? ((await liveWhere("s.id = ?", resume)) ?? bound) : bound;
195 if (live(previous) && previous.repo_id === repo.id) {
196 await reattach(previous);
197 if (machineName(machine)) await db.prepare("UPDATE agent_sessions SET machine = ? WHERE id = ?").bind(machineName(machine), previous.id).run();
198 const text = [
199 `You are back online on ${repo.full_name} as session ${previous.id}, ${working(previous)}. Humans can mention you as @agent/${previous.id}.`,
200 "Your git setup is unchanged, and mentions sent to you while you were away are waiting in refs_events.",
201 "",
202 RULES.replace("<origin>", origin),
203 ].join("\n");
204 return { text, session: previous.id };
205 }
206 if (live(previous)) await endRow(previous, agentActor(previous), "finished", "Moved to another repository.");
207
208 const parentRow = typeof parent === "string" && parent ? await liveWhere("s.id = ?", parent) : null;
209 if (parent && parentRow?.repo_id !== repo.id) fail("parent must be one of your live sessions on this repository.");
210 const session = await createAgentSession(db, { userId: user.id, repoId: repo.id, runtime, mcpSession, clientSession, machine: machineName(machine), parent: parentRow?.id ?? null, grantId });
211 const actor = agentActor({ id: session.id, runtime, expires_at: session.expiresAt, branch: null, repo_id: repo.id, repo_name: repo.full_name, user_id: user.id, email: user.email, name: user.name });
212 await db.batch([
213 session.insert,
214 recordEvent(db, actor, repoStream(repo.id), "session.started", { runtime }, now()),
215 db.prepare("UPDATE agent_sessions SET started_event = (SELECT max(id) FROM events WHERE stream = ?1 AND kind = 'session.started' AND session_id = ?2) WHERE id = ?2").bind(repoStream(repo.id), session.id),
216 ]);
217 captureWorkEvent(env, ctx, actor, { name: "agent.connected", repoId: repo.id, namespaceId: repo.namespace_id });
218
219 const remote = `${origin}/${repo.full_name}.git`;
220 const git =
221 credentials === "helper"
222 ? ["Leave this clone's git configuration alone: refs_take gives you push access when you take a branch."]
223 : [
224 "If you are already in a clone of the repository, leave its git configuration alone: refs_take gives you push access when you take a branch.",
225 "If you have no clone yet, clone it with this session's token:",
226 ` git clone -c "http.${remote}.extraHeader=Authorization: Bearer ${session.token}" ${remote}`,
227 "Never print, log or commit a token.",
228 ];
229 const text = [`You are online on ${repo.full_name} as ${user.name}'s agent, idle (session ${session.id}). Humans can mention you as @agent/${session.id}.`, "", ...git, "", RULES.replace("<origin>", origin)].join("\n");
230 return { text, refs: { remote, token: session.token }, session: session.id };
231 },
232
233 async take(target: unknown, credentials?: unknown): Promise<Answer> {
234 const row = await active();
235 const repo = (await findRepoRecordById(db, row.repo_id))!;
236 const work = await workTarget(db, repo, target);
237 await db.batch([
238 db.prepare("UPDATE agent_sessions SET branch = ? WHERE id = ? AND ended_at IS NULL").bind(work.branch, row.id),
239 recordEvent(db, agentActor(row), repoStream(row.repo_id), "session.tasked", { session: row.id, branch: work.branch }, now()),
240 ]);
241 captureWorkEvent(env, ctx, agentActor(row), { name: "task.taken", repoId: row.repo_id, namespaceId: repo.namespace_id, branch: work.branch });
242 const { branch } = work;
243 const token = await rotateAgentToken(db, row.id);
244 const remote = `${origin}/${row.repo_name}.git`;
245 const git =
246 credentials === "helper"
247 ? ["git in this clone already authenticates as this session, through the refs credential helper. Do not configure git credentials yourself."]
248 : [
249 "Point git at this session, in your clone of the repository:",
250 ` git config --replace-all http.${remote}.extraHeader "Authorization: Bearer ${token}"`,
251 "This replaces any token refs gave you before. Never print, log or commit it.",
252 ];
253 const text = [
254 `You took ${work.what}. You may push only ${branch}.`,
255 ...git,
256 `Check out the branch: \`git fetch origin\`, then \`git checkout -B ${branch} origin/${branch}\` if it exists, otherwise \`git checkout -b ${branch}\`.`,
257 `Push with \`git push origin HEAD:${branch}\`. Call refs_release when the work is done.`,
258 ].join("\n");
259 return { text, refs: { remote, token } };
260 },
261
262 async release(): Promise<string> {
263 const row = await active();
264 if (row.branch === null) return "You have no branch.";
265 await db.batch([
266 db.prepare("UPDATE agent_sessions SET branch = NULL WHERE id = ?").bind(row.id),
267 recordEvent(db, agentActor(row), repoStream(row.repo_id), "session.tasked", { session: row.id, branch: null }, now()),
268 ]);
269 return `Released ${working(row)}. You are still online on ${row.repo_name}, with no branch. git in this clone still pushes as this session: push a new branch to claim it, or take work with refs_take.`;
270 },
271
272 /**
273 * Posts where the mention was made: the pull request, or the review thread. With `addressedIn`, a
274 * reply in a review thread also marks the thread addressed by that commit; only a human can resolve it.
275 */
276 async reply(mention: unknown, body: unknown, addressedIn?: unknown): Promise<string> {
277 const row = await active();
278 const text = typeof body === "string" ? body.trim() : "";
279 if (!text) fail("body must be the comment to post.");
280 const tooLong = bodyError(text, "The reply");
281 if (tooLong) fail(tooLong);
282 if (addressedIn !== undefined && addressedIn !== null && (typeof addressedIn !== "string" || !/^[0-9a-f]{40}$/.test(addressedIn))) fail("addressed_in must be the full 40-character hash of the commit that addresses the thread (git rev-parse HEAD).");
283 if (mention === undefined || mention === null) fail("mention must be the id of the mention you answer.");
284 const event = await db
285 .prepare("SELECT json_extract(data, '$.session') AS session, json_extract(data, '$.pull') AS pull, json_extract(data, '$.thread') AS thread FROM events WHERE id = ? AND stream = ? AND kind = 'agent.mentioned'")
286 .bind(Number(mention), repoStream(row.repo_id))
287 .first<{ session: string; pull: number | null; thread: number | null }>();
288 if (!event || (event.session !== row.id && event.session !== row.parent_session)) fail(`Mention ${mention} was not addressed to you.`);
289 if (event.pull === null) fail(`Mention ${mention} was made on a task. Agents answer only on pull requests now.`);
290 const repo = (await findRepoRecordById(db, row.repo_id))!;
291 const actor = agentActor(row);
292 const pull = await findPull(db, repo.id, event.pull);
293 if (!pull) fail(`Pull request #${event.pull} no longer exists in ${repo.full_name}.`);
294 const thread = event.thread !== null ? await findThread(db, pull.id, event.thread) : null;
295 if (addressedIn && !thread) fail("addressed_in only applies when answering a mention in a review thread.");
296 if (thread) {
297 if (addressedIn) {
298 if (thread.status === "resolved") fail(`Review thread ${thread.id} is already resolved.`);
299 const storage = await env.ARTIFACTS.get(repo.artifacts_name);
300 const commit = await Promise.resolve()
301 .then(() => storage.readCommit(addressedIn as string))
302 .catch(() => null);
303 if (!commit) fail(`Commit ${addressedIn} is not in ${repo.full_name}. Push it first.`);
304 }
305 const comment = await commentOnPull(db, actor, pull, text, undefined, thread.id);
306 if (addressedIn) await setThreadStatus(db, actor, pull, thread, "addressed", addressedIn as string);
307 await deliverMentions(env, ctx, actor, onPull(pull), threadMentionText(pull, origin, thread, text), comment, { thread: thread.id });
308 const link = `${origin}/${repo.full_name}/pulls/${pull.number}`;
309 return addressedIn ? `Replied in review thread ${thread.id} and marked it addressed by ${(addressedIn as string).slice(0, 7)}; a human confirms and resolves it: ${link}` : `Replied in review thread ${thread.id}: ${link}`;
310 }
311 const comment = await commentOnPull(db, actor, pull, text);
312 await deliverMentions(env, ctx, actor, onPull(pull), mentionText(pull, origin, text), comment);
313 return `Posted your comment on pull request #${pull.number}: ${origin}/${repo.full_name}/pulls/${pull.number}`;
314 },
315
316 /** Opens a pull request from the branch the session holds, under the same checks as the compare page. */
317 async openPull(title: unknown, body: unknown, base: unknown, head: unknown): Promise<string> {
318 const row = await active();
319 if (typeof title !== "string" || !title.trim()) fail("title must be the pull request's title.");
320 if (row.branch === null) fail("Take a branch with refs_take, push it, then open its pull request.");
321 const record = (await findRepoRecordById(db, row.repo_id))!;
322 const repo = await agentRepo(env, ctx, origin, agentActor(row), row.repo_name);
323 const outcome = await repo.openPull({
324 title,
325 body: typeof body === "string" ? body : "",
326 base: typeof base === "string" && base ? base : record.default_branch,
327 head: typeof head === "string" && head ? head : row.branch,
328 });
329 if (!outcome.ok) fail(outcome.problem.message);
330 return `Opened pull request #${outcome.value.number}: ${origin}/${row.repo_name}/pulls/${outcome.value.number}`;
331 },
332
333 /**
334 * Claude Code's `--permission-prompt-tool`: records the approval the agent needs, waits for its
335 * human to answer on the portal, and returns the verdict in the shape Claude Code expects.
336 */
337 async approve(toolName: unknown, input: unknown, givenId?: unknown, withdraw = false): Promise<string> {
338 const row = await active();
339 const requestId = typeof givenId === "string" && REQUEST_ID.test(givenId) ? givenId : randomToken(4);
340 if (withdraw) {
341 const at = now();
342 const [{ meta }] = await db.batch([
343 db.prepare("UPDATE permission_requests SET behavior = 'withdrawn', decided_at = ? WHERE session_id = ? AND request_id = ? AND decided_at IS NULL").bind(at, row.id, requestId),
344 recordEvent(db, agentActor(row), repoStream(row.repo_id), "agent.permission_decided", { session: row.id, request_id: requestId, behavior: "withdrawn" }, at),
345 ]);
346 if (meta.changes) await env.REPO_HUB.get(env.REPO_HUB.idFromName(row.repo_id)).decide(row.id, requestId, "withdrawn");
347 return "Withdrawn.";
348 }
349 const hash = await inputHash(input);
350 const stored = await db
351 .prepare("SELECT behavior, input_hash FROM permission_requests WHERE session_id = ? AND request_id = ?")
352 .bind(row.id, requestId)
353 .first<{ behavior: Verdict | null; input_hash: string | null }>();
354 if (!stored) {
355 const request = {
356 session: row.id,
357 request_id: requestId,
358 tool: String(toolName ?? "a tool").slice(0, 200),
359 description: "",
360 preview: JSON.stringify(input ?? {}, null, 2).slice(0, MAX_PREVIEW),
361 };
362 const at = now();
363 await db.batch([
364 db
365 .prepare("INSERT OR IGNORE INTO permission_requests (session_id, request_id, repo_id, tool, description, preview, created_at, input_hash) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
366 .bind(row.id, requestId, row.repo_id, request.tool, request.description, request.preview, at, hash),
367 recordEvent(db, agentActor(row), repoStream(row.repo_id), "agent.permission_requested", request, at),
368 ]);
369 }
370 const behavior = stored?.behavior ?? (await env.REPO_HUB.get(env.REPO_HUB.idFromName(row.repo_id)).awaitDecision(row.repo_id, row.id, requestId));
371 return verdict(behavior, (stored ? stored.input_hash : hash) === hash, input);
372 },
373
374 async end(outcome: "finished" | "failed", reason: string): Promise<string | Answer> {
375 const row = await current();
376 if (!live(row)) return "You are already offline.";
377 await endRow(row, agentActor(row), outcome, reason);
378 return { text: `You are offline. Session ${row.id} ended as ${outcome}, and its git token no longer works.`, refs: { remote: `${origin}/${row.repo_name}.git` } };
379 },
380
381 async status(): Promise<string> {
382 const row = await current();
383 if (!live(row)) return "Offline. In a clone of a refs repository, call refs_connect with the repository's full name (<namespace>/<repo>).";
384 return `Online on ${row.repo_name} as session ${row.id}, ${working(row) === "idle" ? "idle" : `on ${working(row)}`}.`;
385 },
386
387 /** Hands over every update since the last call. With `hookEvent`, answers in hook JSON for that Claude Code hook event; SessionEnd takes the session offline. */
388 async events(hookEvent?: string): Promise<string> {
389 const row = await current();
390 if (hookEvent === "SessionEnd") {
391 await this.detach();
392 return "";
393 }
394 const deliveries = row ? await drainDeliveries(db, row) : [];
395 const context = deliveries.length ? describeDeliveries(deliveries) : "";
396 if (hookEvent) return hookOutput(hookEvent, context);
397 return context || (live(row) ? "No new updates." : "You are offline.");
398 },
399 };
400}
401
402/** The SHA-256 of a tool call's input, binding an approval to the exact call it was asked for. */
403export async function inputHash(input: unknown): Promise<string> {
404 const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(input ?? {})));
405 return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
406}
407
408function verdict(behavior: Verdict, sameInput: boolean, input: unknown): string {
409 if (behavior === "allow" && sameInput) return JSON.stringify({ behavior: "allow", updatedInput: input ?? {} });
410 if (behavior === "allow") return JSON.stringify({ behavior: "deny", message: "Your human approved a different input for this request on refs." });
411 if (behavior === "deny") return JSON.stringify({ behavior: "deny", message: "Your human denied this on refs." });
412 if (behavior === "withdrawn") return JSON.stringify({ behavior: "withdrawn" });
413 return JSON.stringify({ behavior: "deny", message: "No one answered this approval on refs in time.", expired: true });
414}
415
416function json(status: number, body: unknown): Response {
417 return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
418}
419
420/**
421 * The daemon reports that a run ended. A sub-agent's session ends with it, and its parent hears about it
422 * at its next turn, through `agent.run_finished`. A session woken in place (OpenCode) only records it.
423 */
424export async function recordRunFinished(env: Env, userId: string, input: Record<string, unknown>): Promise<boolean> {
425 const db = env.DB;
426 const child = typeof input.session === "string" ? await db.prepare(`${SELECT_SESSION} WHERE s.id = ? AND s.user_id = ?`).bind(input.session, userId).first<SessionRow>() : null;
427 if (!child) return false;
428 const summary = typeof input.summary === "string" ? input.summary.slice(0, MAX_PREVIEW) : "";
429 const at = now();
430 await db.batch([
431 ...(child.parent_session ? [db.prepare("UPDATE agent_sessions SET status = 'finished', ended_at = ? WHERE id = ? AND ended_at IS NULL").bind(at, child.id)] : []),
432 recordEvent(db, agentActor(child), repoStream(child.repo_id), "agent.run_finished", {
433 session: child.parent_session ?? child.id,
434 run: child.id,
435 mention: typeof input.mention === "string" ? input.mention : null,
436 ok: input.ok === true,
437 summary,
438 }, at),
439 ]);
440 return true;
441}
442
443/** Serves `/api/`: humans instruct or stop agent sessions with a personal access token. Returns null for any other URL. */
444export async function serveApi(env: Env, ctx: ExecutionContext, request: Request): Promise<Response | null> {
445 const url = new URL(request.url);
446 if (!url.pathname.startsWith("/api/")) return null;
447 const action = url.pathname.match(/^\/api\/sessions\/([0-9a-f-]{36})\/(instructions|stop)$/);
448 if (!action || request.method !== "POST") return json(404, { error: "Not found." });
449
450 const db = env.DB;
451 const { actor } = await resolveActor(db, ctx, request);
452 if (actor.kind !== "human" || actor.via !== "token") return json(401, { error: "Instruct and stop sessions with a personal access token." });
453 const target = await db
454 .prepare("SELECT s.id, s.repo_id, s.ended_at, (SELECT slug FROM namespaces WHERE id = r.namespace_id) || '/' || r.name AS repo_name FROM agent_sessions s JOIN repos r ON r.id = s.repo_id WHERE s.id = ?")
455 .bind(action[1])
456 .first<{ id: string; repo_id: string; ended_at: number | null; repo_name: string }>();
457 const repo = target && (await findRepoRecordById(db, target.repo_id));
458 if (!target || !repo || !(await namespacePolicy(db, new Policy(actor, null), repo.namespace_id)).canWriteRepo(repoFacts(repo))) return json(404, { error: "No such session." });
459 if (target.ended_at !== null) return json(409, { error: "This session has already ended." });
460
461 const input = (await request.json().catch(() => ({}))) as { body?: unknown; reason?: unknown };
462 const at = now();
463 const stream = repoStream(target.repo_id);
464 if (action[2] === "instructions") {
465 if (typeof input.body !== "string" || !input.body.trim() || input.body.length > MAX_INSTRUCTION_LENGTH) return json(400, { error: `Send {"body": string} of 1–${MAX_INSTRUCTION_LENGTH} characters.` });
466 await recordEvent(db, actor, stream, "session.instructed", { session: target.id, body: input.body.trim() }, at).run();
467 } else {
468 const reason = typeof input.reason === "string" && input.reason.trim() ? input.reason.trim().slice(0, 500) : "Stopped by a human.";
469 await db.batch([
470 db.prepare("UPDATE agent_sessions SET status = 'finished', ended_at = ? WHERE id = ? AND ended_at IS NULL").bind(at, target.id),
471 recordEvent(db, actor, stream, "session.ended", { session: target.id, outcome: "finished", reason }, at),
472 ]);
473 }
474 return json(202, { ok: true });
475}