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/worker/project/http.ts?version=249&format=json
635 linesFirst import 93% · engine 3% · candidates 2% · capacity 1% · pinch 1% · rename 1% · Last change capacity in version 248, 9 versions changed it

You're reading version 249. The newest is 318, and 1 version since then changed this file. Go to the newestCompare with 318

1// The JSON routes of the contract (docs/v2-slice1.md), as a pure function of
2// the project calls, so they can be tested in Node without a Worker.
3
4import type { EditBody, ProjectCalls, ProjectHistory } from "./project-api.ts";
5import { unseenError } from "./unseen.ts";
6
7export interface Answer {
8 status: number;
9 body: unknown;
12const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
14export function validName(name: string | undefined): name is string {
15 return name !== undefined && NAME.test(name);
18/**
19 * The call's answer, or undefined when `ms` passes or the call fails.
20 * The call keeps running either way: this only bounds how long the caller waits.
21 */
22export function within<T>(work: Promise<T>, ms: number): Promise<T | undefined> {
23 return new Promise((resolve) => {
24 const timer = setTimeout(() => resolve(undefined), ms);
25 work.then(
26 (value) => {
27 clearTimeout(timer);
28 resolve(value);
29 },
30 () => {
31 clearTimeout(timer);
32 resolve(undefined);
33 },
34 );
35 });
38const fail = (status: number, error: string): Answer => ({ status, body: { error } });
40/**
41 * Agents that read everything and record nothing (#37, Reporter). Kept by the
42 * caller outside the log: a refused call writes nothing, so replay never
43 * needs it, and an older Worker can still load the log.
44 */
45export interface Readers {
46 has(agent: string): boolean;
47 set(agent: string, reader: boolean): void;
48 list(): string[];
51/**
52 * What a reader may not do. Edits and records (which old edit mods send on
53 * their own) and publishes answer 200 {ok: false, reason}, so a mod only logs
54 * it; the rest are refused outright.
55 */
56const NOT_FOR_READERS: Record<string, "answer" | "refuse"> = {
57 edit: "answer",
58 record: "answer",
59 publish: "answer",
60 land: "answer",
61 pluck: "answer",
62 "draft-sync": "refuse",
63 drop: "refuse",
64 amend: "refuse",
65 label: "refuse",
66 starting: "refuse",
67 move: "refuse",
68 // A reader sends nothing either (abso 682): news to other agents, and notes on lines, made or closed.
69 announce: "refuse",
70 note: "refuse",
71 "note-close": "refuse",
72};
74/** A path the project won't hold: .avcs/ is each folder's own settings. */
75/** A path under a folder's state folder (.abso/, or .avcs/ from before the rename), which never leaves it. */
76function localPath(paths: string[]): string | undefined {
77 return paths.find((p) => [".abso", ".avcs"].some((d) => p === d || p.startsWith(`${d}/`) || p.startsWith(`./${d}/`)));
79const LOCAL = (p: string) =>
80 fail(400, `${p} is under ${p.replace(/^\.\//, "").split("/")[0]}/, which stays in the agent's folder`);
82/**
83 * The reader rules (#37, Reporter), for one agent call: the answer to
84 * `reader {reader}`, or the refusal of something a reader may not do, or
85 * undefined when the call goes ahead. An agent holding unpublished work
86 * can't become a reader.
87 */
88export function readerAnswer(
89 project: { status(): unknown },
90 op: string,
91 agent: string,
92 body: unknown,
93 readers: Readers,
94): Answer | undefined {
95 if (op === "reader") {
96 const on = (body as { reader?: unknown } | undefined)?.reader;
97 if (typeof on !== "boolean") return fail(400, "reader needs {reader: true} or {reader: false}");
98 if (on) {
99 const me = (
100 project.status() as { agents?: { agent: string; draftChanges: number; parked?: unknown[] }[] }
101 ).agents?.find((a) => a.agent === agent);
102 if (me && (me.draftChanges > 0 || (me.parked?.length ?? 0) > 0)) {
103 return fail(
104 409,
105 `${agent} has unpushed changes; push or restore them (abso restore --all) before it becomes a reader`,
106 );
107 }
108 }
109 readers.set(agent, on);
110 return { status: 200, body: { agent, reader: on } };
111 }
112 const barred = readers.has(agent) ? NOT_FOR_READERS[op] : undefined;
113 if (!barred) return undefined;
114 const reason = `agent ${agent} is a reader: it records nothing (abso join --reader)`;
115 if (barred === "refuse") return fail(403, reason);
116 return { status: 200, body: { ok: false, reason, ...(op === "edit" || op === "record" ? {} : { collisions: [] }) } };
119/** The status answer with readers marked on their agent entries and listed (#37). */
120export function statusWithReaders(status: unknown, readers: Readers | undefined): unknown {
121 const s = status as { agents?: { agent: string }[] };
122 if (!readers || readers.list().length === 0) return s;
123 return {
124 ...s,
125 agents: (s.agents ?? []).map((a) => (readers.has(a.agent) ? { ...a, reader: true } : a)),
126 readers: readers.list(),
127 };
130/** op is "init", "status", or an agent op ("edit", "record", "publish", "sync"). */
131export function answer(
132 project: ProjectCalls,
133 op: string,
134 agent: string | undefined,
135 body: unknown,
136 readers?: Readers,
137 how?: string,
138): Answer {
139 try {
140 if (op === "init") {
141 const files = (body as { files?: Record<string, string> })?.files;
142 if (!files || typeof files !== "object") return fail(400, "init needs {files: {path: text}}");
143 if (project.exists()) return fail(409, "the project already exists");
144 const bad = localPath(Object.keys(files));
145 if (bad) return LOCAL(bad);
146 const modes = (body as { modes?: unknown })?.modes;
147 if (modes !== undefined && (typeof modes !== "object" || modes === null))
148 return fail(400, "modes must be {path: {exec, link}}");
149 const blobs = (body as { blobs?: unknown })?.blobs;
150 if (blobs !== undefined && (typeof blobs !== "object" || blobs === null))
151 return fail(400, "blobs must be {path: sha256}");
152 if (blobs && localPath(Object.keys(blobs))) return LOCAL(localPath(Object.keys(blobs))!);
153 return {
154 status: 200,
155 body: project.init(
156 files,
157 modes as Record<string, { exec?: boolean; link?: string | null }> | undefined,
158 blobs as Record<string, string> | undefined,
159 ),
160 };
161 }
162 if (!project.exists()) return fail(404, "no such project; run init first");
163 // Readers (#37): marked on their agent entries, and listed even before their first sync.
164 // Reads for the website (#41): ?at=<log position> replays status and where as they stood then.
165 const atOf = (): number | undefined => {
166 const at = (body as { at?: string } | undefined)?.at;
167 return at !== undefined && at !== "" && Number.isInteger(Number(at)) && Number(at) >= 0 ? Number(at) : undefined;
168 };
169 if (op === "status" && agent === undefined) {
170 const at = atOf();
171 const history = project as ProjectCalls & Partial<ProjectHistory>;
172 if (at !== undefined)
173 return history.statusAt
174 ? { status: 200, body: history.statusAt(at) }
175 : fail(501, "status at a log position needs the engine");
176 return { status: 200, body: statusWithReaders(project.status(), readers) };
177 }
178 if (op === "where") {
179 const history = project as ProjectCalls & Partial<ProjectHistory>;
180 if (!history.where) return fail(501, "where needs the engine");
181 const at = atOf();
182 if (at !== undefined)
183 return history.whereAt
184 ? { status: 200, body: history.whereAt(at) }
185 : fail(501, "where at a log position needs the engine");
186 return { status: 200, body: history.where() };
187 }
188 if (op === "changes" || op.startsWith("change/")) {
189 const history = project as ProjectCalls & Partial<ProjectHistory>;
190 if (!history.change || !history.changes) return fail(501, `${op} needs the engine`);
191 const q = (body ?? {}) as Record<string, string | undefined>;
192 if (op !== "changes") return { status: 200, body: history.change(Number(op.slice("change/".length))) };
193 const since = q.since === undefined || q.since === "" ? 0 : Number(q.since);
194 const limit = q.limit === undefined || q.limit === "" ? 50 : Number(q.limit);
195 if (!Number.isInteger(since) || since < 0) return fail(400, "changes needs ?since=<log position>");
196 if (!Number.isInteger(limit) || limit < 1 || limit > 200) return fail(400, "limit is 1-200");
197 const before = q.before === undefined || q.before === "" ? undefined : Number(q.before);
198 if (before !== undefined && (!Number.isInteger(before) || before < 0))
199 return fail(400, "before must be a log position");
200 // ?issue= (#54): the changes whose start note named that issue.
201 if (q.issue !== undefined && q.issue !== "" && !/^[1-9]\d{0,9}$/.test(q.issue))
202 return fail(400, "issue must be an issue number");
203 return { status: 200, body: history.changes(since, limit, before, q.issue ? Number(q.issue) : undefined) };
204 }
205 if (op === "notes") {
206 const history = project as ProjectCalls & Partial<ProjectHistory>;
207 if (!history.notes) return fail(501, "notes needs the engine");
208 const q = (body ?? {}) as Record<string, string | undefined>;
209 if (q.change !== undefined && !/^\d+$/.test(q.change)) return fail(400, "change must be a change id");
210 return {
211 status: 200,
212 body: history.notes({
213 ...(q.file ? { file: q.file } : {}),
214 ...(q.change ? { change: Number(q.change) } : {}),
215 ...(q.open === "1" || q.open === "true" ? { open: true } : {}),
216 }),
217 };
218 }
219 if (op === "position") {
220 const history = project as ProjectCalls & Partial<ProjectHistory>;
221 if (!history.position) return fail(501, "position needs the engine");
222 const q = (body ?? {}) as Record<string, string | undefined>;
223 if (q.version !== undefined && q.version !== "") {
224 if (!/^\d+$/.test(q.version)) return fail(400, "version must be a version number");
225 return { status: 200, body: history.position({ version: Number(q.version) }) };
226 }
227 if (q.time === undefined || q.time === "")
228 return fail(400, "position needs ?time=<ISO time or ms since 1970> or ?version=<n>");
229 const time = /^\d+$/.test(q.time) ? Number(q.time) : Date.parse(q.time);
230 if (!Number.isFinite(time)) return fail(400, "time is an ISO time or ms since 1970");
231 return { status: 200, body: history.position({ time }) };
232 }
233 if (op === "ribbon") {
234 const history = project as ProjectCalls & Partial<ProjectHistory>;
235 if (!history.ribbon) return fail(501, "ribbon needs the engine");
236 return { status: 200, body: history.ribbon() };
237 }
238 if (op === "feed" || op === "drafts" || (op === "diff" && agent === undefined)) {
239 const q = (body ?? {}) as Record<string, string | undefined>;
240 const history = project as ProjectCalls & Partial<ProjectHistory>;
241 if (!history.feed || !history.drafts || !history.diffOf) return fail(501, `${op} needs the engine`);
242 if (op === "drafts") return { status: 200, body: history.drafts() };
243 if (op === "diff") {
244 if (!q.agent) return fail(400, "diff needs ?agent=<name>");
245 return { status: 200, body: history.diffOf(q.agent) };
246 }
247 const from = q.from === undefined || q.from === "" ? 0 : Number(q.from);
248 const limit = q.limit === undefined || q.limit === "" ? 500 : Number(q.limit);
249 if (!Number.isInteger(from) || from < 0) return fail(400, "feed needs ?from=<log position>");
250 if (!Number.isInteger(limit) || limit < 1 || limit > 2000) return fail(400, "limit is 1-2000");
251 return { status: 200, body: history.feed(from, limit) };
252 }
253 if (op === "draft-state") {
254 // A named draft's state in one read (#41, the Drafts page): base, behind, versions, first edit, collisions.
255 const history = project as ProjectCalls & Partial<ProjectHistory>;
256 if (!history.draftState) return fail(501, "draft-state needs the engine");
257 const q = (body ?? {}) as Record<string, string | undefined>;
258 if (!q.name) return fail(400, "draft-state needs ?name=<draft>");
259 return { status: 200, body: history.draftState(q.name) };
260 }
261 if (
262 op === "tree" ||
263 op === "path" ||
264 op === "follow" ||
265 op === "collisions" ||
266 (op === "blame" && (body as { folder?: unknown } | undefined)?.folder !== undefined)
267 ) {
268 // Reads for the Files pages (#41): GETs, the body is the query string.
269 const q = (body ?? {}) as Record<string, string | undefined>;
270 const history = project as ProjectCalls & Partial<ProjectHistory>;
271 if (!history.tree || !history.pathLife || !history.follow || !history.collisions || !history.folderBlame)
272 return fail(501, `${op} needs the engine`);
273 const int = (s: string | undefined): number | undefined | null =>
274 s === undefined || s === "" ? undefined : /^\d+$/.test(s) ? Number(s) : null;
275 const version = int(q.version);
276 if (version === null) return fail(400, "version must be a version number");
277 const draft = q.draft || null;
278 if (op === "blame")
279 return {
280 status: 200,
281 body: history.folderBlame(q.folder ?? "", version, q.draft || undefined, q.agent || undefined),
282 };
283 // agent= (#41, F25): the folder as that agent has it; authors=1 (F33): each entry's authors in the same read.
284 if (op === "tree") {
285 if (q.authors !== undefined && q.authors !== "" && q.authors !== "1")
286 return fail(400, "authors is 1 or left out");
287 return {
288 status: 200,
289 body: history.tree(q.folder ?? "", version, draft, q.agent || undefined, q.authors === "1"),
290 };
291 }
292 if (op === "collisions")
293 return { status: 200, body: history.collisions(q.file || undefined, q.folder || undefined) };
294 if (!q.path) return fail(400, `${op} needs ?path=<path>`);
295 if (op === "path") return { status: 200, body: history.pathLife(q.path, version, draft) };
296 const from = int(q.from);
297 const to = int(q.to) ?? from;
298 const at = int(q.at);
299 if (
300 version === undefined ||
301 from === undefined ||
302 from === null ||
303 to === null ||
304 to === undefined ||
305 at === null
306 )
307 return fail(400, "follow needs ?path=&version=&from=, and ?to= and ?at= if wanted");
308 return { status: 200, body: history.follow(q.path, version, from, to, at, draft) };
309 }
310 if (op === "blame" || op === "why") {
311 // GETs: the body is the query string as {file, from, to, line}.
312 const q = (body ?? {}) as Record<string, string | undefined>;
313 const history = project as ProjectCalls & Partial<ProjectHistory>;
314 if (!q.file) return fail(400, `${op} needs ?file=<path>, or blame ?folder=<path> ("" for the whole project)`);
315 if (!history.blame || !history.why) return fail(501, `${op} needs the engine`);
316 const num = (s: string | undefined) => (s === undefined || s === "" ? undefined : Number(s));
317 const draft = q.draft || undefined;
318 const who = q.agent || undefined;
319 if (op === "blame")
320 return { status: 200, body: history.blame(q.file, num(q.from), num(q.to), num(q.version), draft, who) };
321 const line = num(q.line);
322 if (!line || !Number.isInteger(line)) return fail(400, "why needs ?line=<number>");
323 return { status: 200, body: history.why(q.file, line, draft, who, num(q.version)) };
324 }
325 if (op === "announce" && agent === undefined) {
326 // The sender comes from the route, like every other agent op, not from
327 // a body field anyone can fill in (#31).
328 return fail(400, "announce from your own agent: POST /p/:project/a/<you>/announce {text, to?}");
329 }
330 if (op === "files" && agent === undefined) {
331 // GET ?version=&draft=: the paths in shared (or a named draft) at a version.
332 const q = (body ?? {}) as Record<string, string | undefined>;
333 const history = project as ProjectCalls & Partial<ProjectHistory>;
334 // ?agent=: the files as an agent has them (#41, F25), read only, so an unknown agent is 404.
335 if (q.agent !== undefined) {
336 if (!history.pathsOf) return fail(501, "files?agent= needs the engine");
337 return { status: 200, body: history.pathsOf(q.agent) };
338 }
339 if (!history.pathsAt) return fail(501, "files needs the engine");
340 const version = q.version !== undefined && q.version !== "" ? Number(q.version) : undefined;
341 if (version !== undefined && !Number.isInteger(version)) return fail(400, "version must be a number");
342 return { status: 200, body: history.pathsAt(version, q.draft || null) };
343 }
344 if (op === "labels") {
345 const history = project as ProjectCalls & Partial<ProjectHistory>;
346 if (!history.labels) return fail(501, "labels needs the engine");
347 return { status: 200, body: history.labels() };
348 }
349 if (op === "refusals") {
350 // GET ?agent=<name>&limit=<n>: refused publishes and lands, newest first, and counts.
351 const q = (body ?? {}) as Record<string, string | undefined>;
352 const history = project as ProjectCalls & Partial<ProjectHistory>;
353 if (!history.refusals) return fail(501, "refusals needs the engine");
354 const limit = q.limit !== undefined && Number.isInteger(Number(q.limit)) ? Number(q.limit) : undefined;
355 return { status: 200, body: history.refusals(q.agent || undefined, limit) };
356 }
357 if (op === "without") {
358 // GET ?version=<n>&versions=<n,n>: version n of shared with those versions left out (without.ts).
359 const q = (body ?? {}) as Record<string, string | undefined>;
360 const history = project as ProjectCalls & Partial<ProjectHistory>;
361 if (!history.without) return fail(501, "without needs the engine");
362 const version = q.version !== undefined && /^\d+$/.test(q.version) ? Number(q.version) : undefined;
363 const versions = (q.versions ?? "").split(",").filter((s) => s.trim() !== "");
364 if (version === undefined || versions.length === 0 || versions.some((s) => !/^\s*\d+\s*$/.test(s)))
365 return fail(400, "without needs ?version=<number>&versions=<number,number>");
366 return { status: 200, body: history.without(version, versions.map(Number)) };
367 }
368 if (op === "log" || op === "show" || op === "file" || op === "compare") {
369 // GETs: ?draft=<name> (shared when absent); log ?limit, ?path; show ?version; file ?path, ?version; compare ?from, ?to.
370 const q = (body ?? {}) as Record<string, string | undefined>;
371 const history = project as ProjectCalls & Partial<ProjectHistory>;
372 if (!history.log || !history.show || !history.fileAt || !history.compare)
373 return fail(501, `${op} needs the engine`);
374 const draft = q.draft ? q.draft : null;
375 const int = (s: string | undefined): number | undefined =>
376 s !== undefined && s !== "" && Number.isInteger(Number(s)) ? Number(s) : undefined;
377 const who = q.agent || undefined;
378 if (op === "log")
379 return {
380 status: 200,
381 body: history.log(
382 draft,
383 int(q.limit),
384 q.path || undefined,
385 who,
386 int(q.before),
387 q.follow === "1" || q.follow === "true",
388 ),
389 };
390 if (op === "file") {
391 const version = int(q.version);
392 if (!q.path || version === undefined) return fail(400, "file needs ?path=<path>&version=<number>");
393 return { status: 200, body: history.fileAt(q.path, version, draft, who) };
394 }
395 if (op === "compare") {
396 const from = int(q.from);
397 const to = int(q.to);
398 if (from === undefined || to === undefined) return fail(400, "compare needs ?from=<number>&to=<number>");
399 // summary=1: each file's size and SHA-256, not its texts (abso issue 680).
400 return { status: 200, body: history.compare(from, to, draft, who, q.summary === "1") };
401 }
402 const version = Number(q.version);
403 if (q.version === undefined || !Number.isInteger(version)) return fail(400, "show needs ?version=<number>");
404 return { status: 200, body: history.show(version, draft, who) };
405 }
406 if (!validName(agent)) return fail(400, "agent names use letters, digits, '.', '_' and '-'");
407 if (op === "reader" && !readers) return fail(501, "reader needs the Worker");
408 const gated = readers ? readerAnswer(project, op, agent, body, readers) : undefined;
409 if (gated) return gated;
410 switch (op) {
411 case "edit": {
412 const b = body as EditBody;
413 if (!b || typeof b.file !== "string")
414 return fail(400, "edit needs {file, old, new}, {file, content} or {file, edits}");
415 if (localPath([b.file])) return LOCAL(b.file);
416 return { status: 200, body: project.edit(agent, b) };
417 }
418 case "record": {
419 const files = (body as { files?: Record<string, string | null> })?.files;
420 if (!files || typeof files !== "object") return fail(400, "record needs {files: {path: text or null}}");
421 const bad = localPath(Object.keys(files));
422 if (bad) return LOCAL(bad);
423 const modes = (body as { modes?: unknown })?.modes;
424 if (modes !== undefined && (typeof modes !== "object" || modes === null))
425 return fail(400, "modes must be {path: {exec, link}}");
426 const blobs = (body as { blobs?: unknown })?.blobs;
427 if (blobs !== undefined && (typeof blobs !== "object" || blobs === null))
428 return fail(400, "blobs must be {path: sha256}");
429 if (blobs && localPath(Object.keys(blobs))) return LOCAL(localPath(Object.keys(blobs))!);
430 const who = body as { session?: unknown; subagent?: unknown; client?: unknown };
431 const meta = {
432 ...(typeof who.session === "string" ? { session: who.session } : {}),
433 ...(typeof who.subagent === "string" ? { subagent: who.subagent } : {}),
434 ...(typeof who.client === "string" ? { client: who.client } : {}),
435 };
436 return {
437 status: 200,
438 body: project.record(
439 agent,
440 files,
441 modes as Record<string, { exec?: boolean; link?: string | null }> | undefined,
442 blobs as Record<string, string> | undefined,
443 meta,
444 ),
445 };
446 }
447 case "publish": {
448 const message = (body as { message?: string })?.message;
449 if (typeof message !== "string" || !message.trim()) return fail(400, "push needs {message} saying why");
450 const unseen = unseenError("the message", message);
451 if (unseen) return fail(400, unseen);
452 // asIs (#37): publish even with collided lines untouched since the sync, both sides kept.
453 return { status: 200, body: project.publish(agent, message, (body as { asIs?: unknown }).asIs === true) };
454 }
455 case "sync": {
456 // {label}: follow a label (#10), syncing to the newest version of shared that carries it.
457 const label = (body as { label?: unknown } | undefined)?.label;
458 if ((body as { full?: unknown } | undefined)?.full === true) {
459 // {full: true}: every file in the agent's view, as a first sync answers (#37).
460 const history = project as ProjectCalls & Partial<ProjectHistory>;
461 if (!history.syncFull) return fail(501, "a full pull needs the engine");
462 if (label !== undefined && typeof label !== "string") return fail(400, "label must be a label name");
463 return { status: 200, body: history.syncFull(agent, label as string | undefined) };
464 }
465 if (label === undefined) return { status: 200, body: project.sync(agent) };
466 if (typeof label !== "string") return fail(400, "label must be a label name");
467 const history = project as ProjectCalls & Partial<ProjectHistory>;
468 if (!history.syncTo) return fail(501, "following a label needs the engine");
469 return { status: 200, body: history.syncTo(agent, label) };
470 }
471 case "label": {
472 const history = project as ProjectCalls & Partial<ProjectHistory>;
473 if (!history.label) return fail(501, "label needs the engine");
474 const b = (body ?? {}) as { name?: unknown; version?: unknown; remove?: unknown };
475 if (typeof b.name !== "string") return fail(400, "label needs {name}, and {version} unless it's the newest");
476 if (b.version !== undefined && !Number.isInteger(b.version)) return fail(400, "version must be a number");
477 return { status: 200, body: history.label(agent, b.name, b.version as number | undefined, b.remove === true) };
478 }
479 // Named drafts (#10).
480 case "draft": {
481 const name = (body as { name?: unknown })?.name;
482 if (name !== null && typeof name !== "string")
483 return fail(400, "draft needs {name}, or {name: null} for shared");
484 return { status: 200, body: project.switchTo(agent, name, (body as { carry?: unknown }).carry === true) };
485 }
486 case "land": {
487 const message = (body as { message?: string })?.message;
488 if (typeof message !== "string" || !message.trim()) return fail(400, "land needs {message} saying why");
489 const unseen = unseenError("the message", message);
490 if (unseen) return fail(400, unseen);
491 return { status: 200, body: project.land(agent, message) };
492 }
493 case "draft-sync":
494 return { status: 200, body: project.syncDraft(agent) };
495 // The paths in the agent's view (#37): what its folder should hold. A GET; changes nothing.
496 case "files": {
497 const history = project as ProjectCalls & Partial<ProjectHistory>;
498 if (!history.agentPaths) return fail(501, "files needs the engine");
499 return { status: 200, body: history.agentPaths(agent) };
500 }
501 // abso status in one trip (abso issue 80): the project's status and the agent's paths.
502 case "status": {
503 const history = project as ProjectCalls & Partial<ProjectHistory>;
504 if (!history.agentPaths) return fail(501, "status needs the engine");
505 return {
506 status: 200,
507 body: { ...(statusWithReaders(project.status(), readers) as object), files: history.agentPaths(agent) },
508 };
509 }
510 // Amend (#27): correct the message of the agent's newest publish.
511 case "amend": {
512 const history = project as ProjectCalls & Partial<ProjectHistory>;
513 if (!history.amend) return fail(501, "amend needs the engine");
514 const message = (body as { message?: unknown } | undefined)?.message;
515 if (typeof message !== "string" || !message.trim()) return fail(400, "amend needs {message}");
516 const unseen = unseenError("the message", message);
517 if (unseen) return fail(400, unseen);
518 return { status: 200, body: history.amend(agent, message) };
519 }
520 // Pluck (#27): take some versions of a named draft into shared.
521 case "pluck": {
522 const history = project as ProjectCalls & Partial<ProjectHistory>;
523 if (!history.pluck) return fail(501, "pluck needs the engine");
524 const b = (body ?? {}) as {
525 draft?: unknown;
526 versions?: unknown;
527 message?: unknown;
528 withDependencies?: unknown;
529 };
530 if (typeof b.draft !== "string") return fail(400, "pluck needs {draft, versions: [number], message}");
531 if (!Array.isArray(b.versions) || b.versions.length === 0 || !b.versions.every((v) => Number.isInteger(v)))
532 return fail(400, "pluck needs {versions: [number]}");
533 if (typeof b.message !== "string" || !b.message.trim()) return fail(400, "pluck needs {message} saying why");
534 const unseen = unseenError("the message", b.message);
535 if (unseen) return fail(400, unseen);
536 return {
537 status: 200,
538 body: history.pluck(agent, b.draft, b.versions as number[], b.message, b.withDependencies === true),
539 };
540 }
541 // Drop (#10): take published versions out of shared.
542 case "drop": {
543 const history = project as ProjectCalls & Partial<ProjectHistory>;
544 if (!history.drop) return fail(501, "drop needs the engine");
545 const b = (body ?? {}) as { versions?: unknown; message?: unknown; withDependents?: unknown };
546 if (!Array.isArray(b.versions) || b.versions.length === 0 || !b.versions.every((v) => Number.isInteger(v)))
547 return fail(400, "drop needs {versions: [number], message}");
548 if (typeof b.message !== "string" || !b.message.trim()) return fail(400, "drop needs {message} saying why");
549 const unseen = unseenError("the message", b.message);
550 if (unseen) return fail(400, unseen);
551 return { status: 200, body: history.drop(agent, b.versions as number[], b.message, b.withDependents === true) };
552 }
553 // Announcements, and news without an edit.
554 case "move": {
555 const history = project as ProjectCalls & Partial<ProjectHistory>;
556 if (!history.move) return fail(501, "move needs the engine");
557 const b = (body ?? {}) as { from?: unknown; to?: unknown };
558 if (typeof b.from !== "string" || typeof b.to !== "string") return fail(400, "move needs {from, to}");
559 if (localPath([b.from, b.to])) return LOCAL(localPath([b.from, b.to])!);
560 return { status: 200, body: history.move(agent, b.from, b.to) };
561 }
562 case "note":
563 case "note-close": {
564 const history = project as ProjectCalls & Partial<ProjectHistory>;
565 if (!history.note || !history.closeNote) return fail(501, `${op} needs the engine`);
566 const b = (body ?? {}) as Record<string, unknown>;
567 if (op === "note-close") return { status: 200, body: history.closeNote(agent, b.id as number, b.how) };
568 const unseen = unseenError("the note", b.text);
569 if (unseen) return fail(400, unseen);
570 return { status: 200, body: history.note(agent, b) };
571 }
572 case "announce":
573 case "news": {
574 const history = project as ProjectCalls & Partial<ProjectHistory>;
575 if (!history.announce || !history.news) return fail(501, `${op} needs the engine`);
576 if (op === "news") return { status: 200, body: history.news(agent) };
577 const b = (body ?? {}) as { text?: unknown; to?: unknown };
578 if (typeof b.text !== "string" || !b.text.trim()) return fail(400, "announce needs {text}");
579 const unseen = unseenError("the text", b.text);
580 if (unseen) return fail(400, unseen);
581 if (b.to !== undefined && (!Array.isArray(b.to) || !b.to.every((a) => typeof a === "string")))
582 return fail(400, "to must be a list of agent names");
583 return { status: 200, body: history.announce(agent, b.text, b.to as string[] | undefined, how) };
584 }
585 // What the agent is starting on (#37, #13): {text, files?}, or {text: null} to take it back.
586 case "starting": {
587 const history = project as ProjectCalls & Partial<ProjectHistory>;
588 if (!history.starting) return fail(501, "starting needs the engine");
589 const b = (body ?? {}) as { text?: unknown; files?: unknown; issue?: unknown; done?: unknown };
590 if (b.text !== null && (typeof b.text !== "string" || !b.text.trim()))
591 return fail(400, "starting needs {text}, or {text: null} to take it back");
592 const unseen = unseenError("the note", b.text);
593 if (unseen) return fail(400, unseen);
594 if (b.files !== undefined && (!Array.isArray(b.files) || !b.files.every((f) => typeof f === "string")))
595 return fail(400, "files must be a list of paths");
596 // issue (#54): the issue the note works on; done: a take-back because the work is finished, closing it.
597 return {
598 status: 200,
599 body: history.starting(agent, b.text as string | null, b.files as string[] | undefined, {
600 ...(b.issue !== undefined ? { issue: b.issue } : {}),
601 ...(b.done !== undefined ? { done: b.done } : {}),
602 }),
603 };
604 }
605 // Everyday commands (#27).
606 case "diff":
607 case "restore": {
608 const history = project as ProjectCalls & Partial<ProjectHistory>;
609 if (!history.diff || !history.restore) return fail(501, `${op} needs the engine`);
610 if (op === "diff") return { status: 200, body: history.diff(agent) };
611 const b = (body ?? {}) as { files?: unknown; all?: unknown };
612 if (b.all === true) return { status: 200, body: history.restore(agent, null) };
613 if (!Array.isArray(b.files) || !b.files.every((f) => typeof f === "string")) {
614 return fail(400, "restore needs {files: [path]} or {all: true}");
615 }
616 return { status: 200, body: history.restore(agent, b.files as string[]) };
617 }
618 }
619 return fail(404, `no such operation: ${op}`);
620 } catch (e) {
621 // The engine throws ProjectError with a code; anything else is ours.
622 const code = (e as { code?: string }).code;
623 const status =
624 code === "not-implemented"
625 ? 501
626 : code === "not-initialized" || code === "not-found"
627 ? 404
628 : code === "already-initialized" || code === "conflict"
629 ? 409
630 : code === "bad-request" || code === "bad-agent"
631 ? 400
632 : 500;
633 return fail(status, e instanceof Error ? e.message : String(e));
634 }