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/server/src/project-object.ts?version=152&format=json
534 linesspeed 100%Last change speed in version 150, 1 version changed it

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

1// One project: its append-only log and blobs in the Durable Object's SQLite, the engine loaded from them, and the push
2// out to the project's Artifacts repo after each new version of shared. Ported from the platform's ProjectObject
3// (worker/src/index.ts), trimmed to the core path: no CI, merge queue checker, boxes, pipelines, members, visibility,
4// R2 copies, edge cache, probes or disk-first writer.
5
6import { DurableObject } from "cloudflare:workers";
7import { type Answer, answer, type Readers } from "../../worker/project/http.ts";
8import type { ProjectCalls, ProjectHistory } from "../../worker/project/project-api.ts";
9import { BLOB_MAX, BlobStore } from "./blobs.ts";
10import { EngineProject, SqliteLog } from "./engine-project.ts";
11import { artifactsOf, type Env } from "./env.ts";
12import { pushedSince, remoteHead } from "./ingest.ts";
13import {
14 checkKey,
15 emptyKeyState,
16 expiresAt,
17 hmac,
18 issueKey,
19 type KeyRole,
20 type KeyState,
21 keyAllows,
22 listKeys,
23 revokeKey,
24} from "./keys.ts";
25import { type PushResult, pushShared, repoName } from "./push.ts";
27/** At most one push out a minute: each one clones the repo, so publishes in a burst share one. */
28export const PUSH_EVERY_MS = 60_000;
29/** While agents are working, how often a call looks for plain-git pushes to the repo. */
30const GIT_CHECK_MS = 15_000;
32/**
33 * The load guard (platform issue 46): an estimate of a loaded project's memory from its log entries, lines and claim
34 * keys, all read from SQLite without loading. A Durable Object has 128 MB. Past the hard cap a project refuses to
35 * load (export still reads it); past the soft cap, new work is held so the hard cap is never reached.
36 */
37const LOAD_BYTES_PER_ENTRY = 1_200;
38const LOAD_BYTES_PER_LINE = 20;
39const LOAD_BYTES_PER_KEY = 20;
40const LOAD_BASE_BYTES = 10_000_000;
41const LOAD_MAX_BYTES = 114_000_000;
42const LOAD_SOFT_BYTES = 94_800_000;
43/** Before its lines are counted, a log over this many characters refuses to load. */
44const LOG_LOAD_MAX_CHARS = 12_000_000;
45/** The ops the soft cap holds: the ones that bring new work into the history. */
46const SOFT_HELD_OPS: ReadonlySet<string> = new Set(["record", "edit", "publish", "land", "amend", "pluck", "drop"]);
48export function loadEstimate(entries: number, lines: number, keys: number): number {
49 return entries * LOAD_BYTES_PER_ENTRY + lines * LOAD_BYTES_PER_LINE + keys * LOAD_BYTES_PER_KEY + LOAD_BASE_BYTES;
52/** A presented agent key, checked inside the call so the check and the call are one trip. */
53export interface KeyForCall {
54 presented: string;
55 address: string;
56 write: boolean;
57 route: string | undefined;
60/** A news item from the issues code: delivered as an announcement from its writer. */
61export interface IssueNews {
62 from: string;
63 issue: number | null;
64 text: string;
65 to?: string[];
68/** What the issues Durable Object hears when a start note naming an issue begins and ends. Each is optional. */
69interface IssueHooks {
70 claim?(agent: string, issue: number, change: number): Promise<unknown>;
71 unclaim?(agent: string, issue: number): Promise<unknown>;
72 done?(agent: string, issue: number, version: number): Promise<unknown>;
75export class ProjectObject extends DurableObject<Env> {
76 private blobs: BlobStore;
77 private loaded: ProjectCalls | undefined;
78 /** Why the log didn't load, if it didn't. */
79 private loadError: unknown;
80 private tried = false;
81 /** Feed long-polls waiting for the log to grow; woken after every call that wrote. */
82 private waiting: (() => void)[] = [];
83 /** When this object last asked the repo for pushes made with plain git. */
84 private gitCheckedAt = 0;
85 private gitSyncing: Promise<{ head: string; commits: number; answer: unknown } | null> | undefined;
87 constructor(ctx: DurableObjectState, env: Env) {
88 super(ctx, env);
89 this.blobs = new BlobStore(ctx.storage);
90 }
92 /** Where files kept whole go: the project's blob store. */
93 private wholeFiles() {
94 return { keep: (text: string) => this.blobs.putText(text), read: (sha: string) => this.blobs.textOf(sha) };
95 }
97 /** The project, loaded from its log on first use. A log too big for memory is refused, not loaded. */
98 private ensure(): ProjectCalls | undefined {
99 if (this.loaded || this.tried) return this.loaded;
100 this.tried = true;
101 try {
102 const why = this.tooBigToLoad();
103 if (why) throw new Error(`${why}, too big to load in a Durable Object's memory; GET export still reads it`);
104 this.loaded = EngineProject.open(this.ctx.storage, (sha) => this.blobs.has(sha), this.wholeFiles());
105 } catch (e) {
106 this.loadError = e;
107 }
108 return this.loaded;
109 }
111 private get project(): ProjectCalls {
112 const p = this.ensure();
113 if (!p) throw this.loadError;
114 return p;
115 }
117 private logChars(): { chars: number; entries: number } {
118 const tables = this.ctx.storage.sql
119 .exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'log'")
120 .toArray();
121 return tables.length === 0 ? { chars: 0, entries: 0 } : new SqliteLog(this.ctx.storage).logSize();
122 }
124 private sizes(): { lines: number; keys: number } | undefined {
125 if (this.logChars().entries === 0) return undefined;
126 try {
127 return new SqliteLog(this.ctx.storage).countSizes();
128 } catch {
129 return undefined;
130 }
131 }
133 /** Why recording new work is held: the estimate is past the soft cap; else null. */
134 private softHeld(): string | null {
135 const counted = this.sizes();
136 if (counted === undefined) return null;
137 const bytes = loadEstimate(this.logChars().entries, counted.lines, counted.keys);
138 return bytes > LOAD_SOFT_BYTES
139 ? `this project is near the most a project can hold (an estimated ${(bytes / 1e6).toFixed(0)} MB of ${LOAD_MAX_BYTES / 1e6} MB), so recording and publishing are held; status and reads keep working`
140 : null;
141 }
143 /** Why this project mustn't load: its estimated memory, or before its lines are counted, its log's size; else null. */
144 private tooBigToLoad(): string | null {
145 const counted = this.sizes();
146 if (counted !== undefined) {
147 const bytes = loadEstimate(this.logChars().entries, counted.lines, counted.keys);
148 return bytes > LOAD_MAX_BYTES
149 ? `this project holds ${counted.lines} lines and ${this.logChars().entries} entries, an estimated ${(bytes / 1e6).toFixed(0)} MB once loaded`
150 : null;
151 }
152 const { chars } = this.logChars();
153 return chars > LOG_LOAD_MAX_CHARS ? `this project's log is ${(chars / 1e6).toFixed(1)} MB` : null;
154 }
156 // Blobs: binary files' bytes, named by their SHA-256.
158 async putBlob(sha: string, body: ReadableStream<Uint8Array>): Promise<Answer> {
159 const a = await this.blobs.put(sha, body);
160 // A push out waiting on missing blobs goes again now.
161 if (a.status === 200 && (await this.ctx.storage.get("pushError"))) await this.ctx.storage.setAlarm(Date.now());
162 return a;
163 }
165 async getBlob(sha: string): Promise<ReadableStream<Uint8Array> | null> {
166 return this.blobs.stream(sha);
167 }
169 /** Shared's newest version, from storage alone, never loading the project. Null when there's no project. */
170 async head(): Promise<{ version: number; at: string } | null> {
171 if (this.logChars().entries === 0) return null;
172 return { version: new SqliteLog(this.ctx.storage).sharedVersion(), at: new Date().toISOString() };
173 }
175 /** Backups: one page of the log as JSON lines. It works even when the log won't load. */
176 async exportLog(from: number, limit: number): Promise<{ lines: string; next: number | null } | null> {
177 if (this.logChars().entries === 0) return null;
178 const { texts, next } = new SqliteLog(this.ctx.storage).page(from, limit);
179 return { lines: texts.map((t) => `${t}\n`).join(""), next };
180 }
182 private wake(): void {
183 const all = this.waiting;
184 this.waiting = [];
185 for (const w of all) w();
186 }
188 /**
189 * GET feed?from=&wait=<seconds, up to 25>: when nothing is new, hold the call until an entry is written or the wait
190 * ends, then answer as usual.
191 */
192 private async feed(name: string, body: unknown): Promise<Answer> {
193 const q = (body ?? {}) as Record<string, string | undefined>;
194 const wait = Math.min(25, Math.max(0, Number(q.wait) || 0));
195 const first = await this.call(name, "feed", undefined, body, true);
196 const from = Number(q.from) || 0;
197 const empty = first.status === 200 && (first.body as { next: number }).next <= from;
198 if (!empty || wait === 0) return first;
199 await new Promise<void>((resolve) => {
200 const timer = setTimeout(resolve, wait * 1000);
201 this.waiting.push(() => {
202 clearTimeout(timer);
203 resolve();
204 });
205 });
206 return this.call(name, "feed", undefined, body, true);
207 }
209 /** One project call: the agent key (if any), the size caps, then answer() from worker/project/http.ts. */
210 async call(
211 name: string,
212 op: string,
213 agent: string | undefined,
214 body: unknown,
215 inFeed = false,
216 how?: string,
217 key?: KeyForCall,
218 ): Promise<Answer> {
219 if (key) {
220 const decided = await this.checkAgentKey(key.presented, agent, key.address);
221 if (!decided.ok) return { status: decided.status, body: { error: decided.error } };
222 const allowed = keyAllows(decided.role, { write: key.write, agent, route: key.route });
223 if (!allowed.ok) return { status: allowed.status, body: { error: allowed.error } };
224 how = decided.as;
225 }
226 if (op === "feed" && !inFeed) return this.feed(name, body);
227 if (SOFT_HELD_OPS.has(op)) {
228 const held = this.softHeld();
229 if (held) return { status: 507, body: { error: held } };
230 }
231 const loaded = this.ensure();
232 if (!loaded) {
233 const why = this.loadError instanceof Error ? this.loadError.message : String(this.loadError);
234 return { status: 507, body: { error: `the project's log did not load: ${why}` } };
235 }
236 // Readers live in storage, not the log: a refused call writes nothing, so replay never needs them.
237 const list = new Set((await this.ctx.storage.get<string[]>("readers")) ?? []);
238 let changed = false;
239 const readers: Readers = {
240 has: (a) => list.has(a),
241 set: (a, on) => {
242 if (on === list.has(a)) return;
243 if (on) list.add(a);
244 else list.delete(a);
245 changed = true;
246 },
247 list: () => [...list].sort(),
248 };
249 const before = loaded.exists() ? loaded.shared().version : -1;
250 const logLength = () => (this.loaded as { logLength?: () => number } | undefined)?.logLength?.() ?? 0;
251 const entriesBefore = logLength();
252 const a = answer(loaded, op, agent, body, readers, how);
253 if (changed) await this.ctx.storage.put("readers", readers.list());
254 if (logLength() !== entriesBefore) this.wake();
255 if (a.status === 200 && op === "starting") a.body = await this.startingHooks(name, a.body);
256 if (a.status === 200) a.body = this.withBlobSizes(op, a.body);
257 const after = loaded.exists() ? loaded.shared().version : -1;
258 if (a.status === 200 && after >= 0 && (op === "init" || after > before)) {
259 // A new version of shared: push it out to Artifacts in the background. The alarm retries; the call never waits.
260 await this.ctx.storage.put("name", name);
261 if (artifactsOf(this.env)) await this.ctx.storage.setAlarm(Date.now());
262 } else if (
263 a.status === 200 &&
264 artifactsOf(this.env) &&
265 Date.now() - this.gitCheckedAt > GIT_CHECK_MS &&
266 (await this.ctx.storage.get("name")) !== undefined &&
267 (await this.ctx.storage.getAlarm()) === null
268 ) {
269 // While agents are working, the alarm also looks for plain-git pushes.
270 await this.ctx.storage.setAlarm(Date.now());
271 }
272 return a;
273 }
275 /**
276 * The engine's starting answer carries hooks for the issues code (a start note naming an issue began or ended). They
277 * go to the project's IssueProject, and never to the client. A failed hook is logged and never fails the call.
278 */
279 private async startingHooks(name: string, body: unknown): Promise<unknown> {
280 const { hooks, ...rest } = body as {
281 hooks?: {
282 claim?: { issue: number; agent: string; change: number };
283 unclaim?: { issue: number; agent: string; change: number; done?: boolean; version?: number };
284 };
285 };
286 if (!hooks) return body;
287 const issues = this.env.ISSUES_DO.get(this.env.ISSUES_DO.idFromName(name)) as unknown as IssueHooks;
288 const tell = async (what: string, call: () => Promise<unknown> | undefined) => {
289 try {
290 await call();
291 } catch (e) {
292 console.log(JSON.stringify({ event: "issues-hook", what, project: name, error: String(e).slice(0, 200) }));
293 }
294 };
295 const end = hooks.unclaim;
296 if (end?.done && end.version !== undefined) {
297 const version = end.version;
298 await tell("done", () => issues.done?.(end.agent, end.issue, version));
299 } else if (end) await tell("unclaim", () => issues.unclaim?.(end.agent, end.issue));
300 const claim = hooks.claim;
301 if (claim) await tell("claim", () => issues.claim?.(claim.agent, claim.issue, claim.change));
302 return rest;
303 }
305 /** A folder's binary files count by their bytes, and a binary file says its size: the blob store knows both. */
306 private withBlobSizes(op: string, body: unknown): unknown {
307 if (op === "tree" && Array.isArray((body as { entries?: unknown }).entries)) {
308 const b = body as { entries: { bytes?: number; blobs?: string[] }[] };
309 return {
310 ...b,
311 entries: b.entries.map(({ blobs, ...e }) =>
312 blobs ? { ...e, bytes: (e.bytes ?? 0) + blobs.reduce((n, sha) => n + this.blobs.size(sha), 0) } : e,
313 ),
314 };
315 }
316 if (op === "file" && typeof (body as { blob?: unknown }).blob === "string")
317 return { ...(body as object), size: this.blobs.size((body as { blob: string }).blob) };
318 return body;
319 }
321 // The push out to Artifacts, and plain-git pushes back in.
323 /**
324 * Takes in commits pushed to the project's repo with plain git: the ones above the server's last commit that
325 * haven't been taken in yet. One run at a time; a call while a run is going gets that run's answer.
326 */
327 gitSync(): Promise<{ head: string; commits: number; answer: unknown } | null> {
328 this.gitSyncing ??= this.gitSyncOnce().finally(() => {
329 this.gitSyncing = undefined;
330 });
331 return this.gitSyncing;
332 }
334 private async gitSyncOnce(): Promise<{ head: string; commits: number; answer: unknown } | null> {
335 const artifacts = artifactsOf(this.env);
336 if (!artifacts) return null;
337 this.gitCheckedAt = Date.now();
338 const name = await this.ctx.storage.get<string>("name");
339 if (!name || !this.project.exists()) return null;
340 const seen = await this.ctx.storage.get<string>("git:head");
341 const pushed = await this.ctx.storage.get<PushResult>("pushed");
342 const head = await remoteHead(artifacts, name);
343 if (!head || head === seen || head === pushed?.commit) return null;
344 const sharedBlobs = this.project.shared().blobs ?? {};
345 const found = await pushedSince(
346 artifacts,
347 name,
348 seen,
349 async (bytes) => (bytes.byteLength > BLOB_MAX ? null : this.blobs.putBytes(bytes)),
350 (path) => sharedBlobs[path],
351 );
352 if (!found || found.commits.length === 0) {
353 if (found) await this.ctx.storage.put("git:head", found.head);
354 return null;
355 }
356 let result: unknown;
357 try {
358 result = this.project.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now());
359 } catch (e) {
360 result = { error: e instanceof Error ? e.message : String(e) };
361 }
362 const taken = {
363 at: new Date().toISOString(),
364 head: found.head,
365 commits: found.commits.length,
366 answer: result,
367 ...(found.tooBig.length ? { tooBig: found.tooBig } : {}),
368 };
369 await this.ctx.storage.put({ "git:head": found.head, "git:last": taken });
370 this.wake();
371 if ((result as { landed?: boolean }).landed) await this.ctx.storage.setAlarm(Date.now());
372 return taken;
373 }
375 /** Sets the alarm for `at` unless one is due sooner. */
376 private async soon(at: number): Promise<void> {
377 const now = await this.ctx.storage.getAlarm();
378 if (now === null || now > at) await this.ctx.storage.setAlarm(at);
379 }
381 /**
382 * Plain-git pushes in first, so the push out builds on them; then shared out to the project's Artifacts repo, at
383 * most once a minute, backing off on failure. Without an ARTIFACTS binding (local dev) it does nothing.
384 */
385 async alarm(): Promise<void> {
386 const artifacts = artifactsOf(this.env);
387 if (!artifacts) return;
388 const name = await this.ctx.storage.get<string>("name");
389 if (!name || !this.ensure()?.exists()) return;
390 await this.gitSync().then(
391 () => this.ctx.storage.delete("git:error"),
392 (e) =>
393 this.ctx.storage.put("git:error", {
394 at: new Date().toISOString(),
395 error: e instanceof Error ? e.message : String(e),
396 }),
397 );
398 const shared = this.project.shared();
399 const done = await this.ctx.storage.get<PushResult>("pushed");
400 if (done && done.version >= shared.version) return;
401 const pushedAt = (await this.ctx.storage.get<number>("pushedAt")) ?? 0;
402 if (Date.now() - pushedAt < PUSH_EVERY_MS) {
403 await this.soon(pushedAt + PUSH_EVERY_MS);
404 return;
405 }
406 let result: PushResult;
407 try {
408 result = await pushShared(artifacts, name, shared, (sha) => this.blobs.read(sha));
409 } catch (e) {
410 // Kept for /out, and tried again with a backoff of our own (a thrown alarm is retried only six times).
411 const was = await this.ctx.storage.get<{ attempts?: number }>("pushError");
412 const attempts = (was?.attempts ?? 0) + 1;
413 await this.ctx.storage.put("pushError", {
414 version: shared.version,
415 at: new Date().toISOString(),
416 attempts,
417 error: e instanceof Error ? e.message : String(e),
418 });
419 await this.soon(Date.now() + Math.min(10 * 60_000, 15_000 * 2 ** Math.min(attempts - 1, 6)));
420 return;
421 }
422 await this.ctx.storage.put({ pushed: result, "git:head": result.commit, pushedAt: Date.now() });
423 await this.ctx.storage.delete("pushError");
424 // Another publish may have landed while this push ran.
425 if (this.project.shared().version > result.version) await this.soon(Date.now() + PUSH_EVERY_MS);
426 }
428 /** The push out: the repo, the last version pushed, and plain-git intake. */
429 async out() {
430 const name = await this.ctx.storage.get<string>("name");
431 const p = this.ensure();
432 return {
433 repo: name ? repoName(name) : null,
434 artifacts: artifactsOf(this.env) ? "bound" : "unbound",
435 version: p?.exists() ? p.shared().version : null,
436 pushed: (await this.ctx.storage.get<PushResult>("pushed")) ?? null,
437 error: (await this.ctx.storage.get("pushError")) ?? null,
438 git: {
439 head: (await this.ctx.storage.get<string>("git:head")) ?? null,
440 last: (await this.ctx.storage.get("git:last")) ?? null,
441 error: (await this.ctx.storage.get("git:error")) ?? null,
442 },
443 };
444 }
446 // Per-agent keys: the HMACs live here, one project's keys per object.
448 private async keyState(): Promise<KeyState> {
449 return (await this.ctx.storage.get<KeyState>("agent-keys")) ?? emptyKeyState();
450 }
452 async checkAgentKey(presented: string, agent: string | undefined, address: string) {
453 const state = await this.keyState();
454 const decided = await checkKey(state, this.env.KEY_HMAC_SECRET, presented, agent, Date.now(), address);
455 if (decided.dirty) await this.ctx.storage.put("agent-keys", state);
456 if (!decided.ok) return decided;
457 const row = state.rows.find((r) => r.id === decided.id);
458 return { ...decided, agent: row?.agent ?? "" };
459 }
461 /** Issues a key. The returned key is the only copy. */
462 async issueAgentKey(
463 agent: string,
464 address: string,
465 expiresRaw: string | null,
466 role: KeyRole,
467 ): Promise<{ id: string; key: string; agent: string } | { error: string }> {
468 const secret = this.env.KEY_HMAC_SECRET;
469 if (!secret) return { error: "the key secret (KEY_HMAC_SECRET) is not set" };
470 const when = expiresAt(Date.now(), expiresRaw);
471 if (typeof when !== "number") return { error: when.error };
472 const state = await this.keyState();
473 const issued = await issueKey(state, secret, agent, "admin", Date.now(), address, when, role);
474 await this.ctx.storage.put("agent-keys", state);
475 return issued;
476 }
478 async revokeAgentKey(id: string, address: string): Promise<{ revoked: boolean }> {
479 const secret = this.env.KEY_HMAC_SECRET;
480 if (!secret) return { revoked: false };
481 const state = await this.keyState();
482 const revoked = revokeKey(state, id, Date.now(), await hmac(secret, address));
483 await this.ctx.storage.put("agent-keys", state);
484 return { revoked };
485 }
487 async listAgentKeys(agent?: string) {
488 return listKeys(await this.keyState(), agent);
489 }
491 // For the issues code (server/src/issues/).
493 /** The project's agent names, for the ask seat check. None when there's no project. */
494 async agents(_project: string): Promise<string[]> {
495 const p = this.ensure();
496 if (!p?.exists()) return [];
497 return p.status().agents.map((a) => a.agent);
498 }
500 /**
501 * Issues news, delivered through the engine's announce path: each item goes to the agents whose start note names
502 * its issue and to the known agents in `to`, never back to its writer.
503 */
504 async news(_project: string, items: IssueNews[]): Promise<{ to: string[] }[]> {
505 const p = this.ensure();
506 if (!p?.exists()) return items.map(() => ({ to: [] }));
507 const engine = p as ProjectCalls & ProjectHistory;
508 const out: { to: string[] }[] = [];
509 for (const item of items) {
510 const status = p.status() as { agents: { agent: string; starting?: { issue?: number } }[] };
511 const known = new Set(status.agents.map((a) => a.agent));
512 const to = new Set([
513 ...(item.issue !== null
514 ? status.agents.filter((a) => a.starting?.issue === item.issue).map((a) => a.agent)
515 : []),
516 ...(item.to ?? []).filter((t) => known.has(t)),
517 ]);
518 to.delete(item.from);
519 if (to.size === 0) {
520 out.push({ to: [] });
521 continue;
522 }
523 try {
524 engine.announce(item.from, item.text, [...to]);
525 out.push({ to: [...to] });
526 } catch (e) {
527 console.log(JSON.stringify({ event: "issues-news", error: String(e).slice(0, 200) }));
528 out.push({ to: [] });
529 }
530 }
531 this.wake();
532 return out;
533 }