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