Skip to content
refs
History
53 lines · 2.7 KBRaw
1import type { Delivery } from "@refs/protocol";
2import type { RefUpdate } from "./git.ts";
3
4export interface DeliverableRow {
5 id: number;
6 kind: string;
7 data: string;
8 session_id: string | null;
9 actor: string | null;
10}
11
12export interface Recipient {
13 session: string;
14 /** The session's current branch, or null while it idles. */
15 branchRef: string | null;
16}
17
18export const DELIVERABLE_KINDS = ["repo.pushed", "session.problem", "session.instructed", "agent.mentioned", "agent.run_finished", "session.ended"] as const;
19
20/**
21 * The frames one session receives for one event on its repository's stream: pushes to its current
22 * branch by anyone else, problems with its own commits, and the instructions, mentions and stop addressed to it.
23 */
24export function framesFor(row: DeliverableRow, to: Recipient): Delivery[] {
25 const id = String(row.id);
26 if (row.kind === "repo.pushed") {
27 if (to.branchRef === null || row.session_id === to.session) return [];
28 const { updates } = JSON.parse(row.data) as { updates: RefUpdate[] };
29 const by = { session: row.session_id, actor: row.actor ?? "unknown" };
30 return updates.filter((update) => update.ref === to.branchRef).map((update) => ({ type: "event", id, event: "repo.pushed", ref: update.ref, from: update.from, to: update.to, by }));
31 }
32 if (row.kind === "session.problem") {
33 const { commit, message } = JSON.parse(row.data) as { commit: string; message: string };
34 return row.session_id === to.session ? [{ type: "problem", id, commit, message }] : [];
35 }
36 if (row.kind === "session.instructed") {
37 const { session, body } = JSON.parse(row.data) as { session: string; body: string };
38 return session === to.session ? [{ type: "instruction", id, body, by: { person: row.actor ?? "unknown" } }] : [];
39 }
40 if (row.kind === "agent.mentioned") {
41 const { session, pull, title, body, assigned, run } = JSON.parse(row.data) as { session: string; pull?: number; title: string; body: string; assigned: boolean; run?: boolean };
42 return session === to.session && pull !== undefined ? [{ type: "mention", id, pull, title, body, assigned, run: run === true, by: { person: row.actor ?? "unknown" } }] : [];
43 }
44 if (row.kind === "agent.run_finished") {
45 const { session, run, mention, ok, summary } = JSON.parse(row.data) as { session: string; run: string; mention: string | null; ok: boolean; summary: string };
46 return session === to.session && run !== session ? [{ type: "run", id, mention, ok, summary }] : [];
47 }
48 if (row.kind === "session.ended") {
49 const { session, reason } = JSON.parse(row.data) as { session: string; reason: string };
50 return session === to.session ? [{ type: "stop", id, reason }] : [];
51 }
52 return [];
53}