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