Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/server/src/issues/routes.ts?format=json
212 linestrials 100% · speed 1%Last change trials in version 151, 1 version changed it
1// The issues routes, apart from the Durable Object so they run under node --test with a store on node:sqlite.
2// Paths are the client's: /p/:project/<read> for reads, and /p/:project/a/:agent/<op> for an agent's writes and
3// its own reads (waiting, asked, drafts, news). Who may call which path was decided before a request gets here.
4
5import { type Actor, IssuesError, type IssuesStore, who } from "./store.ts";
6
7/** The largest request body a write takes, in bytes: far above any text a write may hold. */
8export const BODY_MAX = 1024 * 1024;
9
10export const json = (status: number, body: unknown): Response =>
11 new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
13/**
14 * One request to a project's issues. `seatError` says why a new ask's `of` isn't an agent in the project, or null
15 * when it is (or when the project can't say).
16 */
17export async function issuesRoute(
18 store: IssuesStore,
19 request: Request,
20 seatError?: (of: string) => Promise<string | null>,
21): Promise<Response> {
22 try {
23 return await route(store, request, seatError);
24 } catch (e) {
25 if (e instanceof IssuesError) {
26 const answer = json(e.status, { error: e.message });
27 if (e.retryAfter !== undefined) answer.headers.set("Retry-After", String(e.retryAfter));
28 return answer;
29 }
30 throw e;
31 }
34async function route(
35 store: IssuesStore,
36 request: Request,
37 seatError?: (of: string) => Promise<string | null>,
38): Promise<Response> {
39 const url = new URL(request.url);
40 const m = /^\/p\/([^/]+)(?:\/a\/([^/]+))?\/(.+)$/.exec(url.pathname);
41 if (!m) return json(404, { error: "no such issues route" });
42 const agent = m[2] === undefined ? undefined : decodeURIComponent(m[2]);
43 const rest = m[3]!;
44 const q = url.searchParams;
45 const actor: Actor | undefined = agent !== undefined ? { agent } : undefined;
46 if (rest === "attachments" || rest.startsWith("attachments/"))
47 return json(501, { error: "this server doesn't keep attachments" });
48 // A reader sees only their own drafts.
49 if (request.method === "GET" && rest === "drafts") {
50 if (!actor) return json(403, { error: "drafts are an agent's: /a/:agent/drafts" });
51 return json(200, { drafts: store.drafts(actor) });
52 }
53 if (request.method === "GET") {
54 if (actor) {
55 // An agent's own waiting list, which marks what it lists as seen.
56 if (rest === "waiting") return json(200, { asks: store.waiting(who(actor), who(actor)) });
57 // The asks an agent sent, open then the latest answered.
58 if (rest === "asked") return json(200, { asks: store.asked(who(actor)) });
59 // An agent's news here: answers, replies, @mentions, and changes on issues it watches, by others.
60 if (rest === "news") {
61 const before = q.get("before");
62 return json(200, {
63 news: store.newsFor(actor, [who(actor)], before === null ? undefined : Number(before) || undefined),
64 });
65 }
66 return json(404, {
67 error: "an agent's reads are waiting, asked, drafts and news; other reads have no /a/:agent/",
68 });
69 }
70 if (rest === "issues") {
71 const parent = q.get("parent");
72 return json(200, {
73 issues: store.list({
74 ...(q.get("status") ? { status: q.get("status")! } : {}),
75 ...(q.get("agent") ? { agent: q.get("agent")! } : {}),
76 ...(parent ? { parent: Number(parent) } : {}),
77 // ?label=a,b (or label repeated): issues with every one of them.
78 ...(q.getAll("label").length > 0 ? { labels: q.getAll("label").flatMap((l) => l.split(",")) } : {}),
79 open: q.get("open") === "1",
80 }),
81 });
82 }
83 if (rest === "labels") return json(200, { labels: store.labelsInUse() });
84 // The change count: what a reader can cache issue reads under, cheap enough to ask every request.
85 if (rest === "changes") return json(200, { changes: store.changes() });
86 if (rest === "search") {
87 const limit = Number(q.get("limit") ?? "20");
88 return json(200, { hits: store.search((q.get("q") ?? "").slice(0, 200), Number.isInteger(limit) ? limit : 20) });
89 }
90 const one = /^issue\/(\d+)$/.exec(rest);
91 if (one) return json(200, store.page(Number(one[1])));
92 if (rest === "waiting") return json(200, { asks: store.waiting(q.get("of") ?? undefined) });
93 const ask = /^ask\/(\d+)$/.exec(rest);
94 if (ask) return json(200, { ask: store.askThread(Number(ask[1])) });
95 if (rest === "asked") {
96 const by = q.get("by");
97 if (!by) return json(400, { error: "asked needs ?by=<agent>" });
98 return json(200, { asks: store.asked(by) });
99 }
100 if (rest === "answered") {
101 const of = q.get("of");
102 if (!of) return json(400, { error: "answered needs ?of=<agent>" });
103 return json(200, { asks: store.answered(of) });
104 }
105 return json(404, { error: "no such issues route" });
106 }
107 if (request.method !== "POST") return json(405, { error: "issues takes GET and POST" });
108 if (!actor) return json(403, { error: "a write is an agent's: /p/:project/a/:agent/<op>" });
109 let body: Record<string, unknown> = {};
110 const raw = new TextDecoder().decode(await readCapped(request, BODY_MAX));
111 if (raw.trim() !== "") {
112 try {
113 body = JSON.parse(raw) as Record<string, unknown>;
114 } catch {
115 return json(400, { error: "the body is JSON" });
116 }
117 if (typeof body !== "object" || body === null || Array.isArray(body))
118 return json(400, { error: "the body is a JSON object" });
119 }
120 // Drafts and news marks make no news, so they don't count toward the writer's limit.
121 if (rest === "draft") return json(200, { ok: true, ...store.saveDraft(actor, body) });
122 const deleting = /^draft\/(\d+)\/delete$/.exec(rest);
123 if (deleting) {
124 store.deleteDraft(actor, Number(deleting[1]));
125 return json(200, { ok: true });
126 }
127 if (rest === "news/read") {
128 const at = body.at === undefined ? Date.now() : body.at;
129 if (typeof at !== "number" || !Number.isFinite(at)) return json(400, { error: "at is a time in milliseconds" });
130 return json(200, { ok: true, ...store.markNewsRead(actor, at) });
131 }
132 const write = writeFor(store, actor, rest, body);
133 if (!write) return json(404, { error: "no such issues route" });
134 // An ask goes to an agent in the project.
135 if (rest === "ask" && seatError && typeof body.of === "string") {
136 const refused = await seatError(body.of);
137 if (refused) return json(400, { error: refused });
138 }
139 store.checkLimit(actor);
140 const done = write();
141 store.wrote(actor);
142 // Every write answers the change count it made, for the next read.
143 return json(200, { ok: true, ...done, changes: store.changes() });
146/**
147 * The body, read a chunk at a time and refused (413) the moment it passes `max`, so a body with no
148 * Content-Length, or one that lies, never puts more than `max` in memory.
149 */
150export async function readCapped(request: Request, max: number): Promise<Uint8Array<ArrayBuffer>> {
151 const declared = Number(request.headers.get("Content-Length") ?? "0");
152 if (declared > max) throw new IssuesError(`the body is ${declared} bytes; the most is ${max}`, 413);
153 if (!request.body) return new Uint8Array(0);
154 const reader = request.body.getReader();
155 const parts: Uint8Array[] = [];
156 let size = 0;
157 for (;;) {
158 const { done, value } = await reader.read();
159 if (done) break;
160 size += value.length;
161 if (size > max) {
162 await reader.cancel();
163 throw new IssuesError(`the body is over ${max} bytes, the most there can be`, 413);
164 }
165 parts.push(value);
166 }
167 const out = new Uint8Array(size);
168 let at = 0;
169 for (const part of parts) {
170 out.set(part, at);
171 at += part.length;
172 }
173 return out;
176/** A write that can carry news, to run once the writer's limit allows it; undefined when no route matches. */
177function writeFor(
178 store: IssuesStore,
179 actor: Actor,
180 rest: string,
181 body: Record<string, unknown>,
182): (() => object) | undefined {
183 if (rest === "issue") return () => store.open(actor, body);
184 if (rest === "ask") return () => store.ask(actor, body);
185 const on = /^issue\/(\d+)\/(comment|drop|edit|reopen|done)$/.exec(rest);
186 if (on) {
187 const id = Number(on[1]);
188 return () => {
189 if (on[2] === "comment") return store.comment(actor, id, body);
190 if (on[2] === "edit") return store.edit(actor, id, body);
191 if (on[2] === "reopen") return store.reopen(actor, id);
192 if (on[2] === "done") {
193 const version = body.version;
194 if (version !== undefined && version !== null && typeof version !== "number")
195 throw new IssuesError("version is a published version, 1 or more");
196 return store.markDone(actor, id, typeof version === "number" ? version : null);
197 }
198 return store.drop(actor, id);
199 };
200 }
201 const opening = /^draft\/(\d+)\/open$/.exec(rest);
202 if (opening) return () => store.openDraft(actor, Number(opening[1]), body);
203 const answer = /^answer\/(\d+)$/.exec(rest);
204 if (answer) return () => store.answer(actor, Number(answer[1]), body);
205 const ack = /^ack\/(\d+)$/.exec(rest);
206 if (ack) return () => store.ack(actor, Number(ack[1]), body);
207 const reply = /^reply\/(\d+)$/.exec(rest);
208 if (reply) return () => store.reply(actor, Number(reply[1]), body);
209 const withdraw = /^withdraw\/(\d+)$/.exec(rest);
210 if (withdraw) return () => store.withdraw(actor, Number(withdraw[1]), body);
211 return undefined;