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