import { branchProblem, describeDeliveries, hookOutput, type Delivery } from "@refs/protocol"; import { captureWorkEvent } from "./analytics.ts"; import { createAgentSession, now, randomToken, rotateAgentToken, type AgentSessionRow } from "./auth.ts"; import type { Actor, Person } from "./contract/actor.ts"; import type { Verdict } from "./permissions.ts"; import { DELIVERABLE_KINDS, framesFor, type DeliverableRow } from "./deliveries.ts"; import { recordEvent, repoStream } from "./events.ts"; import { agentActor, resolveActor } from "./identity.ts"; import { Policy } from "./policy.ts"; import { findRepoRecord, findRepoRecordById, namespacePolicy, repoFacts, type RepoRecord } from "./repos.ts"; import { deliverMentions, onPull } from "./mentions.ts"; import { commentOnPull, findPull, findThread, mentionText, setThreadStatus, threadMentionText } from "./pulls.ts"; import { bodyError } from "./text.ts"; import { agentRepo } from "./handles/refs.ts"; const MAX_INSTRUCTION_LENGTH = 10_000; const REQUEST_ID = /^[A-Za-z0-9_-]{1,64}$/; const MAX_PREVIEW = 4000; const DELIVERY_BATCH = 200; /** A failure the agent can act on. Its message becomes the tool result. */ export class AgentError extends Error {} function fail(message: string): never { throw new AgentError(message); } interface SessionRow extends AgentSessionRow { parent_session: string | null; mcp_session: string | null; ended_at: number | null; delivered_through: number | null; started: number | null; } const 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, u.id AS user_id, u.email, u.name, s.started_event AS started FROM agent_sessions s JOIN users u ON u.id = s.user_id JOIN repos r ON r.id = s.repo_id`; /** * Hands over the session's updates since its cursor, and moves the cursor past them. The cursor moves only from the * value this call read, so when two calls race, one of them gets the updates and the other gets none. */ async function drainDeliveries(db: D1Database, row: SessionRow): Promise { const cursor = row.delivered_through ?? row.started ?? 0; const { results } = await db .prepare( `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 WHERE e.id > ? AND e.stream = ? AND e.kind IN (${DELIVERABLE_KINDS.map(() => "?").join(", ")}) ORDER BY e.id LIMIT ${DELIVERY_BATCH}`, ) .bind(cursor, repoStream(row.repo_id), ...DELIVERABLE_KINDS) .all(); if (!results.length) return []; const { meta } = await db .prepare("UPDATE agent_sessions SET delivered_through = ?1 WHERE id = ?2 AND coalesce(delivered_through, started_event, 0) = ?3") .bind(results[results.length - 1].id, row.id, cursor) .run(); if (!meta.changes) return []; const recipient = { session: row.id, branchRef: row.branch === null ? null : `refs/heads/${row.branch}` }; return results.flatMap((event) => framesFor(event, recipient)); } function machineName(value: unknown): string | null { return typeof value === "string" && /^[A-Za-z0-9._-]{1,64}$/.test(value) ? value : null; } /** What `refs_take` hands the session: a branch by name, or a pull request's head branch. */ async function workTarget(db: D1Database, repo: RepoRecord, target: unknown): Promise<{ branch: string; what: string }> { const { branch, pull } = (target ?? {}) as { branch?: unknown; pull?: unknown }; if ([branch, pull].filter((value) => value !== undefined && value !== null).length !== 1) fail("Give exactly one of branch or pull."); if (branch !== undefined && branch !== null) { if (typeof branch !== "string") fail("branch must be a branch name."); const problem = branchProblem(branch, repo.default_branch); if (problem) fail(problem); return { branch, what: `branch ${branch}` }; } if (!Number.isInteger(pull) || (pull as number) < 1) fail("pull must be a pull request number."); const record = await findPull(db, repo.id, pull as number); if (!record) fail(`No pull request #${pull} in ${repo.full_name}.`); if (record.status !== "open") fail(`Pull request #${record.number} is ${record.status}.`); const problem = branchProblem(record.head_ref, repo.default_branch); if (problem) fail(problem); return { branch: record.head_ref, what: `pull request #${record.number}: ${record.title}, on branch ${record.head_ref}` }; } /** What the session works on, for the texts that report it. */ function working(row: AgentSessionRow): string { return row.branch === null ? "idle" : `branch ${row.branch}`; } const RULES = `Rules for working here: - 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:\`. - Never force-push. If a push is rejected, run \`git pull --rebase\` and push again. - 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. - 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. - 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 #). \`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: /llms.txt. - 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. - 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. - Humans and other agents reach you with mentions. Answer them, and report on assigned work, with refs_reply. - Call refs_release when the work is done; you stay online, idle. Call refs_end only to go offline. - 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.`; /** * A tool's answer. `refs` carries the session's git credential outside the text, so the refs CLI can hand it to * git through its credential helper; with `credentials: "helper"` the text then leaves the token out. */ /** What `refs_connect` receives, unchecked: it arrives from an MCP client as JSON. */ export interface ConnectInput { readonly repo: unknown; readonly resume?: unknown; readonly machine?: unknown; readonly parent?: unknown; readonly credentials?: unknown; } export interface Answer { text: string; refs?: { remote: string; token?: string }; /** The session the answer is about, for clients that act on it without reading the text. */ session?: string; } /** * One MCP connection's view of its agent session. A session acts for the human who authorized the * client over OAuth, on one repository, and outlives the connection: it belongs to the client's * conversation (`clientSession`, sent by Claude Code's hooks), so a reconnect picks it back up. */ export function agentSessions(env: Env, ctx: Pick, userId: string, mcpSession: string, runtime: string, origin: string, clientSession: string | null = null, grantId: string | null = null) { const db = env.DB; function live(row: SessionRow | null): row is SessionRow { return row !== null && row.ended_at === null && row.expires_at > now(); } async function liveWhere(condition: string, value: string): Promise { return db .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`) .bind(userId, value, now()) .first(); } async function reattach(row: SessionRow): Promise { await db .prepare("UPDATE agent_sessions SET mcp_session = ?, client_session = coalesce(?, client_session), last_seen_at = ?, status = 'running' WHERE id = ? AND user_id = ?") .bind(mcpSession, clientSession, now(), row.id, userId) .run(); return row; } async function current(): Promise { const carried = clientSession ? await liveWhere("s.client_session = ?", clientSession) : null; if (carried) return carried.mcp_session === mcpSession ? carried : reattach(carried); 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(); } async function active(): Promise { const row = await current(); if (!live(row)) fail(`You are offline${row ? ": your session ended or expired" : ""}. Call refs_connect with this repository's full name (/).`); return row; } async function endRow(row: SessionRow, actor: Actor, outcome: "finished" | "failed", reason: string): Promise { const at = now(); await db.batch([ db.prepare("UPDATE agent_sessions SET status = ?, ended_at = ? WHERE id = ? AND ended_at IS NULL").bind(outcome, at, row.id), recordEvent(db, actor, repoStream(row.repo_id), "session.ended", { session: row.id, outcome, reason }, at), ]); } return { /** Marks the session as seen, which is what keeps it listed as online. Writes at most once a minute. */ async touch(): Promise { await db .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')") .bind(now(), userId, mcpSession) .run(); }, /** Takes the connection offline without ending its session, so the client can pick it back up. */ async detach(): Promise { 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(); }, async connect({ repo: repoName, resume, machine, parent, credentials }: ConnectInput): Promise { if (typeof repoName !== "string" || !repoName) fail("repo must be the repository's full name, as in //.git."); const user = await db.prepare("SELECT id, email, name FROM users WHERE id = ?").bind(userId).first(); if (!user) fail("The human who authorized this client no longer exists. Sign in again."); const repo = await findRepoRecord(db, repoName); const policy = repo && (await namespacePolicy(db, new Policy({ kind: "human", person: user, via: "token" }, null), repo.namespace_id)); if (!repo || !policy || !policy.canSeeRepo(repoFacts(repo))) fail(`No repository named "${repoName}".`); if (!policy.canWriteRepo(repoFacts(repo))) fail(`${user.name} cannot push to ${repo.full_name}.`); const bound = await current(); const previous = !live(bound) && typeof resume === "string" && resume ? ((await liveWhere("s.id = ?", resume)) ?? bound) : bound; if (live(previous) && previous.repo_id === repo.id) { await reattach(previous); if (machineName(machine)) await db.prepare("UPDATE agent_sessions SET machine = ? WHERE id = ?").bind(machineName(machine), previous.id).run(); const text = [ `You are back online on ${repo.full_name} as session ${previous.id}, ${working(previous)}. Humans can mention you as @agent/${previous.id}.`, "Your git setup is unchanged, and mentions sent to you while you were away are waiting in refs_events.", "", RULES.replace("", origin), ].join("\n"); return { text, session: previous.id }; } if (live(previous)) await endRow(previous, agentActor(previous), "finished", "Moved to another repository."); const parentRow = typeof parent === "string" && parent ? await liveWhere("s.id = ?", parent) : null; if (parent && parentRow?.repo_id !== repo.id) fail("parent must be one of your live sessions on this repository."); const session = await createAgentSession(db, { userId: user.id, repoId: repo.id, runtime, mcpSession, clientSession, machine: machineName(machine), parent: parentRow?.id ?? null, grantId }); 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 }); await db.batch([ session.insert, recordEvent(db, actor, repoStream(repo.id), "session.started", { runtime }, now()), 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), ]); captureWorkEvent(env, ctx, actor, { name: "agent.connected", repoId: repo.id, namespaceId: repo.namespace_id }); const remote = `${origin}/${repo.full_name}.git`; const git = credentials === "helper" ? ["Leave this clone's git configuration alone: refs_take gives you push access when you take a branch."] : [ "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.", "If you have no clone yet, clone it with this session's token:", ` git clone -c "http.${remote}.extraHeader=Authorization: Bearer ${session.token}" ${remote}`, "Never print, log or commit a token.", ]; 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)].join("\n"); return { text, refs: { remote, token: session.token }, session: session.id }; }, async take(target: unknown, credentials?: unknown): Promise { const row = await active(); const repo = (await findRepoRecordById(db, row.repo_id))!; const work = await workTarget(db, repo, target); await db.batch([ db.prepare("UPDATE agent_sessions SET branch = ? WHERE id = ? AND ended_at IS NULL").bind(work.branch, row.id), recordEvent(db, agentActor(row), repoStream(row.repo_id), "session.tasked", { session: row.id, branch: work.branch }, now()), ]); captureWorkEvent(env, ctx, agentActor(row), { name: "task.taken", repoId: row.repo_id, namespaceId: repo.namespace_id, branch: work.branch }); const { branch } = work; const token = await rotateAgentToken(db, row.id); const remote = `${origin}/${row.repo_name}.git`; const git = credentials === "helper" ? ["git in this clone already authenticates as this session, through the refs credential helper. Do not configure git credentials yourself."] : [ "Point git at this session, in your clone of the repository:", ` git config --replace-all http.${remote}.extraHeader "Authorization: Bearer ${token}"`, "This replaces any token refs gave you before. Never print, log or commit it.", ]; const text = [ `You took ${work.what}. You may push only ${branch}.`, ...git, `Check out the branch: \`git fetch origin\`, then \`git checkout -B ${branch} origin/${branch}\` if it exists, otherwise \`git checkout -b ${branch}\`.`, `Push with \`git push origin HEAD:${branch}\`. Call refs_release when the work is done.`, ].join("\n"); return { text, refs: { remote, token } }; }, async release(): Promise { const row = await active(); if (row.branch === null) return "You have no branch."; await db.batch([ db.prepare("UPDATE agent_sessions SET branch = NULL WHERE id = ?").bind(row.id), recordEvent(db, agentActor(row), repoStream(row.repo_id), "session.tasked", { session: row.id, branch: null }, now()), ]); 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.`; }, /** * Posts where the mention was made: the pull request, or the review thread. With `addressedIn`, a * reply in a review thread also marks the thread addressed by that commit; only a human can resolve it. */ async reply(mention: unknown, body: unknown, addressedIn?: unknown): Promise { const row = await active(); const text = typeof body === "string" ? body.trim() : ""; if (!text) fail("body must be the comment to post."); const tooLong = bodyError(text, "The reply"); if (tooLong) fail(tooLong); 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)."); if (mention === undefined || mention === null) fail("mention must be the id of the mention you answer."); const event = await db .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'") .bind(Number(mention), repoStream(row.repo_id)) .first<{ session: string; pull: number | null; thread: number | null }>(); if (!event || (event.session !== row.id && event.session !== row.parent_session)) fail(`Mention ${mention} was not addressed to you.`); if (event.pull === null) fail(`Mention ${mention} was made on a task. Agents answer only on pull requests now.`); const repo = (await findRepoRecordById(db, row.repo_id))!; const actor = agentActor(row); const pull = await findPull(db, repo.id, event.pull); if (!pull) fail(`Pull request #${event.pull} no longer exists in ${repo.full_name}.`); const thread = event.thread !== null ? await findThread(db, pull.id, event.thread) : null; if (addressedIn && !thread) fail("addressed_in only applies when answering a mention in a review thread."); if (thread) { if (addressedIn) { if (thread.status === "resolved") fail(`Review thread ${thread.id} is already resolved.`); const storage = await env.ARTIFACTS.get(repo.artifacts_name); const commit = await Promise.resolve() .then(() => storage.readCommit(addressedIn as string)) .catch(() => null); if (!commit) fail(`Commit ${addressedIn} is not in ${repo.full_name}. Push it first.`); } const comment = await commentOnPull(db, actor, pull, text, undefined, thread.id); if (addressedIn) await setThreadStatus(db, actor, pull, thread, "addressed", addressedIn as string); await deliverMentions(env, ctx, actor, onPull(pull), threadMentionText(pull, origin, thread, text), comment, { thread: thread.id }); const link = `${origin}/${repo.full_name}/pulls/${pull.number}`; 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}`; } const comment = await commentOnPull(db, actor, pull, text); await deliverMentions(env, ctx, actor, onPull(pull), mentionText(pull, origin, text), comment); return `Posted your comment on pull request #${pull.number}: ${origin}/${repo.full_name}/pulls/${pull.number}`; }, /** Opens a pull request from the branch the session holds, under the same checks as the compare page. */ async openPull(title: unknown, body: unknown, base: unknown): Promise { const row = await active(); if (typeof title !== "string" || !title.trim()) fail("title must be the pull request's title."); if (row.branch === null) fail("Take a branch with refs_take, push it, then open its pull request."); const record = (await findRepoRecordById(db, row.repo_id))!; const repo = await agentRepo(env, ctx, origin, agentActor(row), row.repo_name); const outcome = await repo.openPull({ title, body: typeof body === "string" ? body : "", base: typeof base === "string" && base ? base : record.default_branch, head: row.branch, }); if (!outcome.ok) fail(outcome.problem.message); return `Opened pull request #${outcome.value.number}: ${origin}/${row.repo_name}/pulls/${outcome.value.number}`; }, /** 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. */ async viewPull(): Promise { const row = await active(); if (row.branch === null) fail("Take a branch with refs_take first. You see only the pull request of your branch."); const repo = await agentRepo(env, ctx, origin, agentActor(row), row.repo_name); const open = (await repo.pulls({ status: "open" })).items.find((item) => item.head === row.branch); if (!open) fail(`No open pull request from ${row.branch}. Push your work, then open one with refs_open_pull.`); const pull = await repo.pull(open.number); const ci = repo.ci(); const [mergeability, threads, timeline, runs] = await Promise.all([pull.mergeability(), pull.threads(), pull.timeline(), ci.runs({ pull: open.number, limit: 1 })]); const lines = [`Pull request #${open.number} "${open.title}": ${row.branch} into ${open.base}. ${origin}/${row.repo_name}/pulls/${open.number}`]; 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}).`); const waiting = threads.filter((thread) => thread.status !== "resolved"); lines.push("", waiting.length ? `Review threads not resolved (${waiting.length}):` : "Review threads: none open."); for (const thread of waiting) { const place = thread.decision ? `decision "${thread.decision}"` : `${thread.path}${thread.range ? ` lines ${thread.range.start}-${thread.range.end}` : ""}`; const last = timeline.filter((item) => item.kind === "pull.commented" && item.data.thread === thread.id).at(-1); const said = last?.kind === "pull.commented" ? ` Last comment, by ${last.by.actor.name}: "${last.data.body.slice(0, 500)}"` : ""; lines.push(`- Thread ${thread.id} on ${place}, ${thread.status}${thread.outdated ? ", outdated" : ""}.${said}`); } const latest = runs[0]; if (!latest) return [...lines, "", "CI: no runs."].join("\n"); const run = await ci.run(latest.id); lines.push("", `CI: run ${run.id} on ${run.sha.slice(0, 7)} is ${run.state}.`); for (const job of run.jobs.filter((candidate) => candidate.state === "failed" || candidate.state === "timed_out")) { const { steps } = await ci.logs(run.id, job.name); const failed = steps.find((step) => step.step === job.failedStep) ?? steps.at(-1); lines.push(`- Job ${job.name} ${job.state}${job.failedStep === null ? "" : ` at step ${job.failedStep}`}. End of its log:`, "```", (failed?.text ?? "").slice(-MAX_PREVIEW), "```"); } return lines.join("\n"); }, /** * Claude Code's `--permission-prompt-tool`: records the approval the agent needs, waits for its * human to answer on the portal, and returns the verdict in the shape Claude Code expects. */ async approve(toolName: unknown, input: unknown, givenId?: unknown, withdraw = false): Promise { const row = await active(); const requestId = typeof givenId === "string" && REQUEST_ID.test(givenId) ? givenId : randomToken(4); if (withdraw) { const at = now(); const [{ meta }] = await db.batch([ 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), recordEvent(db, agentActor(row), repoStream(row.repo_id), "agent.permission_decided", { session: row.id, request_id: requestId, behavior: "withdrawn" }, at), ]); if (meta.changes) await env.REPO_HUB.get(env.REPO_HUB.idFromName(row.repo_id)).decide(row.id, requestId, "withdrawn"); return "Withdrawn."; } const hash = await inputHash(input); const stored = await db .prepare("SELECT behavior, input_hash FROM permission_requests WHERE session_id = ? AND request_id = ?") .bind(row.id, requestId) .first<{ behavior: Verdict | null; input_hash: string | null }>(); if (!stored) { const request = { session: row.id, request_id: requestId, tool: String(toolName ?? "a tool").slice(0, 200), description: "", preview: JSON.stringify(input ?? {}, null, 2).slice(0, MAX_PREVIEW), }; const at = now(); await db.batch([ db .prepare("INSERT OR IGNORE INTO permission_requests (session_id, request_id, repo_id, tool, description, preview, created_at, input_hash) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") .bind(row.id, requestId, row.repo_id, request.tool, request.description, request.preview, at, hash), recordEvent(db, agentActor(row), repoStream(row.repo_id), "agent.permission_requested", request, at), ]); } const behavior = stored?.behavior ?? (await env.REPO_HUB.get(env.REPO_HUB.idFromName(row.repo_id)).awaitDecision(row.repo_id, row.id, requestId)); return verdict(behavior, (stored ? stored.input_hash : hash) === hash, input); }, async end(outcome: "finished" | "failed", reason: string): Promise { const row = await current(); if (!live(row)) return "You are already offline."; await endRow(row, agentActor(row), outcome, reason); 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` } }; }, async status(): Promise { const row = await current(); if (!live(row)) return "Offline. In a clone of a refs repository, call refs_connect with the repository's full name (/)."; return `Online on ${row.repo_name} as session ${row.id}, ${working(row) === "idle" ? "idle" : `on ${working(row)}`}.`; }, /** 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. */ async events(hookEvent?: string): Promise { const row = await current(); if (hookEvent === "SessionEnd") { await this.detach(); return ""; } const deliveries = row ? await drainDeliveries(db, row) : []; const context = deliveries.length ? describeDeliveries(deliveries) : ""; if (hookEvent) return hookOutput(hookEvent, context); return context || (live(row) ? "No new updates." : "You are offline."); }, }; } /** The SHA-256 of a tool call's input, binding an approval to the exact call it was asked for. */ export async function inputHash(input: unknown): Promise { const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(input ?? {}))); return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); } function verdict(behavior: Verdict, sameInput: boolean, input: unknown): string { if (behavior === "allow" && sameInput) return JSON.stringify({ behavior: "allow", updatedInput: input ?? {} }); if (behavior === "allow") return JSON.stringify({ behavior: "deny", message: "Your human approved a different input for this request on refs." }); if (behavior === "deny") return JSON.stringify({ behavior: "deny", message: "Your human denied this on refs." }); if (behavior === "withdrawn") return JSON.stringify({ behavior: "withdrawn" }); return JSON.stringify({ behavior: "deny", message: "No one answered this approval on refs in time.", expired: true }); } function json(status: number, body: unknown): Response { return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); } /** * The daemon reports that a run ended. A sub-agent's session ends with it, and its parent hears about it * at its next turn, through `agent.run_finished`. A session woken in place (OpenCode) only records it. */ export async function recordRunFinished(env: Env, userId: string, input: Record): Promise { const db = env.DB; const child = typeof input.session === "string" ? await db.prepare(`${SELECT_SESSION} WHERE s.id = ? AND s.user_id = ?`).bind(input.session, userId).first() : null; if (!child) return false; const summary = typeof input.summary === "string" ? input.summary.slice(0, MAX_PREVIEW) : ""; const at = now(); await db.batch([ ...(child.parent_session ? [db.prepare("UPDATE agent_sessions SET status = 'finished', ended_at = ? WHERE id = ? AND ended_at IS NULL").bind(at, child.id)] : []), recordEvent(db, agentActor(child), repoStream(child.repo_id), "agent.run_finished", { session: child.parent_session ?? child.id, run: child.id, mention: typeof input.mention === "string" ? input.mention : null, ok: input.ok === true, summary, }, at), ]); return true; } /** Serves `/api/`: humans instruct or stop agent sessions with a personal access token. Returns null for any other URL. */ export async function serveApi(env: Env, ctx: ExecutionContext, request: Request): Promise { const url = new URL(request.url); if (!url.pathname.startsWith("/api/")) return null; const action = url.pathname.match(/^\/api\/sessions\/([0-9a-f-]{36})\/(instructions|stop)$/); if (!action || request.method !== "POST") return json(404, { error: "Not found." }); const db = env.DB; const { actor } = await resolveActor(db, ctx, request); if (actor.kind !== "human" || actor.via !== "token") return json(401, { error: "Instruct and stop sessions with a personal access token." }); const target = await db .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 = ?") .bind(action[1]) .first<{ id: string; repo_id: string; ended_at: number | null; repo_name: string }>(); const repo = target && (await findRepoRecordById(db, target.repo_id)); if (!target || !repo || !(await namespacePolicy(db, new Policy(actor, null), repo.namespace_id)).canWriteRepo(repoFacts(repo))) return json(404, { error: "No such session." }); if (target.ended_at !== null) return json(409, { error: "This session has already ended." }); const input = (await request.json().catch(() => ({}))) as { body?: unknown; reason?: unknown }; const at = now(); const stream = repoStream(target.repo_id); if (action[2] === "instructions") { 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.` }); await recordEvent(db, actor, stream, "session.instructed", { session: target.id, body: input.body.trim() }, at).run(); } else { const reason = typeof input.reason === "string" && input.reason.trim() ? input.reason.trim().slice(0, 500) : "Stopped by a human."; await db.batch([ db.prepare("UPDATE agent_sessions SET status = 'finished', ended_at = ? WHERE id = ? AND ended_at IS NULL").bind(at, target.id), recordEvent(db, actor, stream, "session.ended", { session: target.id, outcome: "finished", reason }, at), ]); } return json(202, { ok: true }); }