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