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