Skip to content
refs
508 lines · 32.9 KBRaw
1import { branchProblem, describeDeliveries, hookOutput, type Delivery } from "@refs/protocol";
2import { createAgentSession, now, randomToken, rotateAgentToken, type AgentSessionRow } from "./auth.ts";
3import type { Actor, Person } from "./contract/actor.ts";
4import type { Verdict } from "./permissions.ts";
5import { DELIVERABLE_KINDS, framesFor, type DeliverableRow } from "./deliveries.ts";
6import { recordEvent, repoStream } from "./events.ts";
7import { agentActor, resolveActor } from "./identity.ts";
8import { Policy } from "./policy.ts";
9import { findRepoRecord, findRepoRecordById, namespacePolicy, repoFacts, type RepoRecord } from "./repos.ts";
10import { deliverMentions, onPull } from "./mentions.ts";
11import { commentOnPull, findPull, findThread, mentionText, setThreadStatus, threadMentionText } from "./pulls.ts";
12import { bodyError } from "./text.ts";
13import { agentRepo } from "./handles/refs.ts";
14
15const MAX_INSTRUCTION_LENGTH = 10_000;
16const REQUEST_ID = /^[A-Za-z0-9_-]{1,64}$/;
17const MAX_PREVIEW = 4000;
18const DELIVERY_BATCH = 200;
19
20/** A failure the agent can act on. Its message becomes the tool result. */
21export class AgentError extends Error {}
22
23function fail(message: string): never {
24 throw new AgentError(message);
25}
26
27interface SessionRow extends AgentSessionRow {
28 parent_session: string | null;
29 mcp_session: string | null;
30 ended_at: number | null;
31 delivered_through: number | null;
32 started: number | null;
33 default_branch: string;
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, r.default_branch, (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}`, baseRef: `refs/heads/${row.default_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
218 const remote = `${origin}/${repo.full_name}.git`;
219 const git =
220 credentials === "helper"
221 ? ["Leave this clone's git configuration alone: refs_take gives you push access when you take a branch."]
222 : [
223 "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.",
224 "If you have no clone yet, clone it with this session's token:",
225 ` git clone -c "http.${remote}.extraHeader=Authorization: Bearer ${session.token}" ${remote}`,
226 "Never print, log or commit a token.",
227 ];
228 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");
229 return { text, refs: { remote, token: session.token }, session: session.id };
230 },
231
232 async take(target: unknown, credentials?: unknown): Promise<Answer> {
233 const row = await active();
234 const repo = (await findRepoRecordById(db, row.repo_id))!;
235 const work = await workTarget(db, repo, target);
236 await db.batch([
237 db.prepare("UPDATE agent_sessions SET branch = ? WHERE id = ? AND ended_at IS NULL").bind(work.branch, row.id),
238 recordEvent(db, agentActor(row), repoStream(row.repo_id), "session.tasked", { session: row.id, branch: work.branch }, now()),
239 ]);
240 const { branch } = work;
241 const token = await rotateAgentToken(db, row.id);
242 const remote = `${origin}/${row.repo_name}.git`;
243 const git =
244 credentials === "helper"
245 ? ["git in this clone already authenticates as this session, through the refs credential helper. Do not configure git credentials yourself."]
246 : [
247 "Point git at this session, in your clone of the repository:",
248 ` git config --replace-all http.${remote}.extraHeader "Authorization: Bearer ${token}"`,
249 "This replaces any token refs gave you before. Never print, log or commit it.",
250 ];
251 const text = [
252 `You took ${work.what}. You may push only ${branch}.`,
253 ...git,
254 `Check out the branch: \`git fetch origin\`, then \`git checkout -B ${branch} origin/${branch}\` if it exists, otherwise \`git checkout -b ${branch}\`.`,
255 `Push with \`git push origin HEAD:${branch}\`. Call refs_release when the work is done.`,
256 ].join("\n");
257 return { text, refs: { remote, token } };
258 },
259
260 async release(): Promise<string> {
261 const row = await active();
262 if (row.branch === null) return "You have no branch.";
263 await db.batch([
264 db.prepare("UPDATE agent_sessions SET branch = NULL WHERE id = ?").bind(row.id),
265 recordEvent(db, agentActor(row), repoStream(row.repo_id), "session.tasked", { session: row.id, branch: null }, now()),
266 ]);
267 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.`;
268 },
269
270 /**
271 * Posts where the mention was made: the pull request, or the review thread. With `addressedIn`, a
272 * reply in a review thread also marks the thread addressed by that commit; only a human can resolve it.
273 */
274 async reply(mention: unknown, body: unknown, addressedIn?: unknown): Promise<string> {
275 const row = await active();
276 const text = typeof body === "string" ? body.trim() : "";
277 if (!text) fail("body must be the comment to post.");
278 const tooLong = bodyError(text, "The reply");
279 if (tooLong) fail(tooLong);
280 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).");
281 if (mention === undefined || mention === null) fail("mention must be the id of the mention you answer.");
282 const event = await db
283 .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'")
284 .bind(Number(mention), repoStream(row.repo_id))
285 .first<{ session: string; pull: number | null; thread: number | null }>();
286 if (!event || (event.session !== row.id && event.session !== row.parent_session)) fail(`Mention ${mention} was not addressed to you.`);
287 if (event.pull === null) fail(`Mention ${mention} was made on a task. Agents answer only on pull requests now.`);
288 const repo = (await findRepoRecordById(db, row.repo_id))!;
289 const actor = agentActor(row);
290 const pull = await findPull(db, repo.id, event.pull);
291 if (!pull) fail(`Pull request #${event.pull} no longer exists in ${repo.full_name}.`);
292 const thread = event.thread !== null ? await findThread(db, pull.id, event.thread) : null;
293 if (addressedIn && !thread) fail("addressed_in only applies when answering a mention in a review thread.");
294 if (thread) {
295 if (addressedIn) {
296 if (thread.status === "resolved") fail(`Review thread ${thread.id} is already resolved.`);
297 const storage = await env.ARTIFACTS.get(repo.artifacts_name);
298 const commit = await Promise.resolve()
299 .then(() => storage.readCommit(addressedIn as string))
300 .catch(() => null);
301 if (!commit) fail(`Commit ${addressedIn} is not in ${repo.full_name}. Push it first.`);
302 }
303 const comment = await commentOnPull(db, actor, pull, text, undefined, thread.id);
304 if (addressedIn) await setThreadStatus(db, actor, pull, thread, "addressed", addressedIn as string);
305 await deliverMentions(env, ctx, actor, onPull(pull), threadMentionText(pull, origin, thread, text), comment, { thread: thread.id });
306 const link = `${origin}/${repo.full_name}/pulls/${pull.number}`;
307 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}`;
308 }
309 const comment = await commentOnPull(db, actor, pull, text);
310 await deliverMentions(env, ctx, actor, onPull(pull), mentionText(pull, origin, text), comment);
311 return `Posted your comment on pull request #${pull.number}: ${origin}/${repo.full_name}/pulls/${pull.number}`;
312 },
313
314 /** Opens a pull request from the branch the session holds, under the same checks as the compare page. */
315 async openPull(title: unknown, body: unknown, base: unknown): Promise<string> {
316 const row = await active();
317 if (typeof title !== "string" || !title.trim()) fail("title must be the pull request's title.");
318 if (row.branch === null) fail("Take a branch with refs_take, push it, then open its pull request.");
319 const record = (await findRepoRecordById(db, row.repo_id))!;
320 const repo = await agentRepo(env, ctx, origin, agentActor(row), row.repo_name);
321 const outcome = await repo.openPull({
322 title,
323 body: typeof body === "string" ? body : "",
324 base: typeof base === "string" && base ? base : record.default_branch,
325 head: row.branch,
326 });
327 if (!outcome.ok) fail(outcome.problem.message);
328 return `Opened pull request #${outcome.value.number}: ${origin}/${row.repo_name}/pulls/${outcome.value.number}`;
329 },
330
331 /** 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. */
332 async viewPull(): Promise<string> {
333 const row = await active();
334 if (row.branch === null) fail("Take a branch with refs_take first. You see only the pull request of your branch.");
335 const repo = await agentRepo(env, ctx, origin, agentActor(row), row.repo_name);
336 const open = (await repo.pulls({ status: "open" })).items.find((item) => item.head === row.branch);
337 if (!open) fail(`No open pull request from ${row.branch}. Push your work, then open one with refs_open_pull.`);
338 const pull = await repo.pull(open.number);
339 const ci = repo.ci();
340 const [mergeability, threads, timeline, runs] = await Promise.all([pull.mergeability(), pull.threads(), pull.timeline(), ci.runs({ pull: open.number, limit: 1 })]);
341
342 const lines = [`Pull request #${open.number} "${open.title}": ${row.branch} into ${open.base}. ${origin}/${row.repo_name}/pulls/${open.number}`];
343 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}).`);
344
345 const waiting = threads.filter((thread) => thread.status !== "resolved");
346 lines.push("", waiting.length ? `Review threads not resolved (${waiting.length}):` : "Review threads: none open.");
347 for (const thread of waiting) {
348 const place = thread.decision ? `decision "${thread.decision}"` : `${thread.path}${thread.range ? ` lines ${thread.range.start}-${thread.range.end}` : ""}`;
349 const last = timeline.filter((item) => item.kind === "pull.commented" && item.data.thread === thread.id).at(-1);
350 const said = last?.kind === "pull.commented" ? ` Last comment, by ${last.by.actor.name}: "${last.data.body.slice(0, 500)}"` : "";
351 lines.push(`- Thread ${thread.id} on ${place}, ${thread.status}${thread.outdated ? ", outdated" : ""}.${said}`);
352 }
353
354 const latest = runs[0];
355 if (!latest) return [...lines, "", "CI: no runs."].join("\n");
356 const run = await ci.run(latest.id);
357 lines.push("", `CI: run ${run.id} on ${run.sha.slice(0, 7)} is ${run.state}.`);
358 for (const job of run.jobs.filter((candidate) => candidate.state === "failed" || candidate.state === "timed_out")) {
359 const { steps } = await ci.logs(run.id, job.name);
360 const failed = steps.find((step) => step.step === job.failedStep) ?? steps.at(-1);
361 lines.push(`- Job ${job.name} ${job.state}${job.failedStep === null ? "" : ` at step ${job.failedStep}`}. End of its log:`, "```", (failed?.text ?? "").slice(-MAX_PREVIEW), "```");
362 }
363 return lines.join("\n");
364 },
365
366 /**
367 * Claude Code's `--permission-prompt-tool`: records the approval the agent needs, waits for its
368 * human to answer on the portal, and returns the verdict in the shape Claude Code expects.
369 */
370 async approve(toolName: unknown, input: unknown, givenId?: unknown, withdraw = false): Promise<string> {
371 const row = await active();
372 const requestId = typeof givenId === "string" && REQUEST_ID.test(givenId) ? givenId : randomToken(4);
373 if (withdraw) {
374 const at = now();
375 const [{ meta }] = await db.batch([
376 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),
377 recordEvent(db, agentActor(row), repoStream(row.repo_id), "agent.permission_decided", { session: row.id, request_id: requestId, behavior: "withdrawn" }, at),
378 ]);
379 if (meta.changes) await env.REPO_HUB.get(env.REPO_HUB.idFromName(row.repo_id)).decide(row.id, requestId, "withdrawn");
380 return "Withdrawn.";
381 }
382 const hash = await inputHash(input);
383 const stored = await db
384 .prepare("SELECT behavior, input_hash FROM permission_requests WHERE session_id = ? AND request_id = ?")
385 .bind(row.id, requestId)
386 .first<{ behavior: Verdict | null; input_hash: string | null }>();
387 if (!stored) {
388 const request = {
389 session: row.id,
390 request_id: requestId,
391 tool: String(toolName ?? "a tool").slice(0, 200),
392 description: "",
393 preview: JSON.stringify(input ?? {}, null, 2).slice(0, MAX_PREVIEW),
394 };
395 const at = now();
396 await db.batch([
397 db
398 .prepare("INSERT OR IGNORE INTO permission_requests (session_id, request_id, repo_id, tool, description, preview, created_at, input_hash) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
399 .bind(row.id, requestId, row.repo_id, request.tool, request.description, request.preview, at, hash),
400 recordEvent(db, agentActor(row), repoStream(row.repo_id), "agent.permission_requested", request, at),
401 ]);
402 }
403 const behavior = stored?.behavior ?? (await env.REPO_HUB.get(env.REPO_HUB.idFromName(row.repo_id)).awaitDecision(row.repo_id, row.id, requestId));
404 return verdict(behavior, (stored ? stored.input_hash : hash) === hash, input);
405 },
406
407 async end(outcome: "finished" | "failed", reason: string): Promise<string | Answer> {
408 const row = await current();
409 if (!live(row)) return "You are already offline.";
410 await endRow(row, agentActor(row), outcome, reason);
411 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` } };
412 },
413
414 async status(): Promise<string> {
415 const row = await current();
416 if (!live(row)) return "Offline. In a clone of a refs repository, call refs_connect with the repository's full name (<namespace>/<repo>).";
417 return `Online on ${row.repo_name} as session ${row.id}, ${working(row) === "idle" ? "idle" : `on ${working(row)}`}.`;
418 },
419
420 /** 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. */
421 async events(hookEvent?: string): Promise<string> {
422 const row = await current();
423 if (hookEvent === "SessionEnd") {
424 await this.detach();
425 return "";
426 }
427 const deliveries = row ? await drainDeliveries(db, row) : [];
428 const context = deliveries.length ? describeDeliveries(deliveries) : "";
429 if (hookEvent) return hookOutput(hookEvent, context);
430 return context || (live(row) ? "No new updates." : "You are offline.");
431 },
432 };
433}
434
435/** The SHA-256 of a tool call's input, binding an approval to the exact call it was asked for. */
436export async function inputHash(input: unknown): Promise<string> {
437 const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(input ?? {})));
438 return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
439}
440
441function verdict(behavior: Verdict, sameInput: boolean, input: unknown): string {
442 if (behavior === "allow" && sameInput) return JSON.stringify({ behavior: "allow", updatedInput: input ?? {} });
443 if (behavior === "allow") return JSON.stringify({ behavior: "deny", message: "Your human approved a different input for this request on refs." });
444 if (behavior === "deny") return JSON.stringify({ behavior: "deny", message: "Your human denied this on refs." });
445 if (behavior === "withdrawn") return JSON.stringify({ behavior: "withdrawn" });
446 return JSON.stringify({ behavior: "deny", message: "No one answered this approval on refs in time.", expired: true });
447}
448
449function json(status: number, body: unknown): Response {
450 return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
451}
452
453/**
454 * The daemon reports that a run ended. A sub-agent's session ends with it, and its parent hears about it
455 * at its next turn, through `agent.run_finished`. A session woken in place (OpenCode) only records it.
456 */
457export async function recordRunFinished(env: Env, userId: string, input: Record<string, unknown>): Promise<boolean> {
458 const db = env.DB;
459 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;
460 if (!child) return false;
461 const summary = typeof input.summary === "string" ? input.summary.slice(0, MAX_PREVIEW) : "";
462 const at = now();
463 await db.batch([
464 ...(child.parent_session ? [db.prepare("UPDATE agent_sessions SET status = 'finished', ended_at = ? WHERE id = ? AND ended_at IS NULL").bind(at, child.id)] : []),
465 recordEvent(db, agentActor(child), repoStream(child.repo_id), "agent.run_finished", {
466 session: child.parent_session ?? child.id,
467 run: child.id,
468 mention: typeof input.mention === "string" ? input.mention : null,
469 ok: input.ok === true,
470 summary,
471 }, at),
472 ]);
473 return true;
474}
475
476/** Serves `/api/`: humans instruct or stop agent sessions with a personal access token. Returns null for any other URL. */
477export async function serveApi(env: Env, ctx: ExecutionContext, request: Request): Promise<Response | null> {
478 const url = new URL(request.url);
479 if (!url.pathname.startsWith("/api/")) return null;
480 const action = url.pathname.match(/^\/api\/sessions\/([0-9a-f-]{36})\/(instructions|stop)$/);
481 if (!action || request.method !== "POST") return json(404, { error: "Not found." });
482
483 const db = env.DB;
484 const { actor } = await resolveActor(db, ctx, request);
485 if (actor.kind !== "human" || actor.via !== "token") return json(401, { error: "Instruct and stop sessions with a personal access token." });
486 const target = await db
487 .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 = ?")
488 .bind(action[1])
489 .first<{ id: string; repo_id: string; ended_at: number | null; repo_name: string }>();
490 const repo = target && (await findRepoRecordById(db, target.repo_id));
491 if (!target || !repo || !(await namespacePolicy(db, new Policy(actor, null), repo.namespace_id)).canWriteRepo(repoFacts(repo))) return json(404, { error: "No such session." });
492 if (target.ended_at !== null) return json(409, { error: "This session has already ended." });
493
494 const input = (await request.json().catch(() => ({}))) as { body?: unknown; reason?: unknown };
495 const at = now();
496 const stream = repoStream(target.repo_id);
497 if (action[2] === "instructions") {
498 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.` });
499 await recordEvent(db, actor, stream, "session.instructed", { session: target.id, body: input.body.trim() }, at).run();
500 } else {
501 const reason = typeof input.reason === "string" && input.reason.trim() ? input.reason.trim().slice(0, 500) : "Stopped by a human.";
502 await db.batch([
503 db.prepare("UPDATE agent_sessions SET status = 'finished', ended_at = ? WHERE id = ? AND ended_at IS NULL").bind(at, target.id),
504 recordEvent(db, actor, stream, "session.ended", { session: target.id, outcome: "finished", reason }, at),
505 ]);
506 }
507 return json(202, { ok: true });
508}