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=160&format=json
698 linesspeed 71% · codex-capacity-chair 29%Last change codex-capacity-chair in version 158, 2 versions changed it

You're reading version 160. The newest is 318, and 6 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 { DiskFirstRuntime } from "./disk-first-runtime.ts";
11import { EngineProject, SqliteLog } from "./engine-project.ts";
12import { artifactsOf, type Env } from "./env.ts";
13import { pushedSince, remoteHead } from "./ingest.ts";
14import {
15 checkKey,
16 emptyKeyState,
17 expiresAt,
18 hmac,
19 issueKey,
20 type KeyRole,
21 type KeyState,
22 keyAllows,
23 listKeys,
24 revokeKey,
25} from "./keys.ts";
26import { type PushResult, pushShared, repoName } from "./push.ts";
27import { SqliteWriterState } from "./writer-host.ts";
29const READ_OPS = new Set([
30 "status",
31 "blame",
32 "why",
33 "tree",
34 "path",
35 "follow",
36 "collisions",
37 "draft-state",
38 "refusals",
39 "labels",
40 "log",
41 "show",
42 "file",
43 "files",
44 "compare",
45 "where",
46 "feed",
47 "drafts",
48 "diff",
49 "ribbon",
50 "position",
51 "changes",
52 "notes",
53]);
55/** At most one push out a minute: each one clones the repo, so publishes in a burst share one. */
56export const PUSH_EVERY_MS = 60_000;
57/** While agents are working, how often a call looks for plain-git pushes to the repo. */
58const GIT_CHECK_MS = 15_000;
60/**
61 * The load guard (platform issue 46): an estimate of a loaded project's memory from its log entries, lines and claim
62 * keys, all read from SQLite without loading. A Durable Object has 128 MB. Past the hard cap a project refuses to
63 * load (export still reads it); past the soft cap, new work is held so the hard cap is never reached.
64 */
65const LOAD_BYTES_PER_ENTRY = 1_200;
66const LOAD_BYTES_PER_LINE = 20;
67const LOAD_BYTES_PER_KEY = 20;
68const LOAD_BASE_BYTES = 10_000_000;
69const LOAD_MAX_BYTES = 114_000_000;
70const LOAD_SOFT_BYTES = 94_800_000;
71/** Before its lines are counted, a log over this many characters refuses to load. */
72const LOG_LOAD_MAX_CHARS = 12_000_000;
73/** The ops the soft cap holds: the ones that bring new work into the history. */
74const SOFT_HELD_OPS: ReadonlySet<string> = new Set(["record", "edit", "publish", "land", "amend", "pluck", "drop"]);
76export function loadEstimate(entries: number, lines: number, keys: number): number {
77 return entries * LOAD_BYTES_PER_ENTRY + lines * LOAD_BYTES_PER_LINE + keys * LOAD_BYTES_PER_KEY + LOAD_BASE_BYTES;
80/** A presented agent key, checked inside the call so the check and the call are one trip. */
81export interface KeyForCall {
82 presented: string;
83 address: string;
84 write: boolean;
85 route: string | undefined;
88/** A news item from the issues code: delivered as an announcement from its writer. */
89export interface IssueNews {
90 from: string;
91 issue: number | null;
92 text: string;
93 to?: string[];
96/** What the issues Durable Object hears when a start note naming an issue begins and ends. Each is optional. */
97interface IssueHooks {
98 claim?(agent: string, issue: number, change: number): Promise<unknown>;
99 unclaim?(agent: string, issue: number): Promise<unknown>;
100 done?(agent: string, issue: number, version: number): Promise<unknown>;
103export class ProjectObject extends DurableObject<Env> {
104 private blobs: BlobStore;
105 private loaded: ProjectCalls | undefined;
106 /** Why the log didn't load, if it didn't. */
107 private loadError: unknown;
108 private tried = false;
109 private authorityRevision = 0;
110 /** Feed long-polls waiting for the log to grow; woken after every call that wrote. */
111 private waiting: (() => void)[] = [];
112 /** When this object last asked the repo for pushes made with plain git. */
113 private gitCheckedAt = 0;
114 private gitSyncing: Promise<{ head: string; commits: number; answer: unknown } | null> | undefined;
116 constructor(ctx: DurableObjectState, env: Env) {
117 super(ctx, env);
118 this.blobs = new BlobStore(ctx.storage);
119 }
121 /** Where files kept whole go: the project's blob store. */
122 private wholeFiles() {
123 return { keep: (text: string) => this.blobs.putText(text), read: (sha: string) => this.blobs.textOf(sha) };
124 }
126 private diskRuntime(): DiskFirstRuntime | undefined {
127 return this.env.ABSO_DISK_FIRST === "on"
128 ? new DiskFirstRuntime(this.ctx.storage, this.ctx.id.toString(), "server-disk-v1", {
129 hasBlob: (sha) => this.blobs.has(sha),
130 whole: this.wholeFiles(),
131 })
132 : undefined;
133 }
134 private async prepareDisk(validate: () => void = () => {}) {
135 const runtime = this.diskRuntime();
136 if (!runtime) return undefined;
137 const progress = runtime.preparePage(validate);
138 if (!progress.ready && progress.phase !== "empty") await this.soon(Date.now() + 100);
139 return progress;
140 }
141 /** Once indexing starts, legacy writes would invalidate the persistent root. */
142 private legacyWritesHeld(): boolean {
143 if (this.env.ABSO_DISK_FIRST === "on") return false;
144 const tables = this.ctx.storage.sql
145 .exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'writer_state'")
146 .toArray();
147 return (
148 tables.length > 0 &&
149 new SqliteWriterState(this.ctx.storage, "server-disk-v1").read("runtime", "format") !== undefined
150 );
151 }
152 private useProject<T>(operation: (calls: EngineProject) => T, write = false): T {
153 const runtime = this.diskRuntime();
154 if (runtime) return write ? runtime.write(operation, () => {}) : runtime.read(operation, () => {});
155 if (write && this.legacyWritesHeld())
156 throw Error("disk-first indexes exist; enable ABSO_DISK_FIRST before writing");
157 return operation(this.project as EngineProject);
158 }
159 private async diskCall(
160 name: string,
161 op: string,
162 agent: string | undefined,
163 body: unknown,
164 how: string | undefined,
165 revision: number,
166 ): Promise<Answer> {
167 const runtime = this.diskRuntime()!;
168 const validate = () => {
169 if (revision !== this.authorityRevision)
170 throw Object.assign(Error("project authorization changed during call setup"), { code: "authority-changed" });
171 };
172 const progress = await this.prepareDisk(validate);
173 const known = new Set((await this.ctx.storage.get<string[]>("readers")) ?? []);
174 validate();
175 let readersChanged = false;
176 const readers: Readers = {
177 has: (a) => known.has(a),
178 list: () => [...known].sort(),
179 set: (a, on) => {
180 if (on === known.has(a)) return;
181 if (on) known.add(a);
182 else known.delete(a);
183 readersChanged = true;
184 },
185 };
186 if (progress?.phase === "empty" && op !== "init")
187 return { status: 404, body: { error: "no such project; run init first" } };
188 if (!progress?.ready && !(progress?.phase === "empty" && op === "init"))
189 return { status: 503, body: { error: "project indexes are being prepared", retryAfter: 1, progress } };
190 const before = new SqliteLog(this.ctx.storage).seq();
191 const action = (calls: EngineProject) => {
192 const result = answer(calls, op, agent, body, readers, how);
193 if (result.status >= 500) throw Error(`project operation failed: ${JSON.stringify(result.body)}`);
194 return result;
195 };
197 const result =
198 progress.phase === "empty"
199 ? runtime.initialize(action, validate)
200 : READ_OPS.has(op) || op.startsWith("change/")
201 ? runtime.read(action, validate)
202 : runtime.write(action, validate);
203 if (readersChanged) {
204 this.authorityRevision++;
205 await this.ctx.storage.put("readers", readers.list());
206 }
207 const log = new SqliteLog(this.ctx.storage);
208 if (log.seq() !== before) {
209 this.wake();
210 await this.ctx.storage.put("name", name);
211 await this.soon(Date.now() + 100);
212 }
213 if (
214 result.status === 200 &&
215 artifactsOf(this.env) &&
216 Date.now() - this.gitCheckedAt > GIT_CHECK_MS &&
217 (await this.ctx.storage.get("name")) !== undefined &&
218 (await this.ctx.storage.getAlarm()) === null
219 )
220 await this.ctx.storage.setAlarm(Date.now());
221 if (result.status === 200 && op === "starting") result.body = await this.startingHooks(name, result.body);
222 if (result.status === 200) result.body = this.withBlobSizes(op, result.body);
223 return result;
224 }
226 /** The project, loaded from its log on first use. A log too big for memory is refused, not loaded. */
227 private ensure(): ProjectCalls | undefined {
228 if (this.diskRuntime()) throw Error("legacy project load forbidden in disk-first mode");
229 if (this.loaded || this.tried) return this.loaded;
230 this.tried = true;
231 try {
232 const why = this.tooBigToLoad();
233 if (why) throw new Error(`${why}, too big to load in a Durable Object's memory; GET export still reads it`);
234 this.loaded = EngineProject.open(this.ctx.storage, (sha) => this.blobs.has(sha), this.wholeFiles());
235 } catch (e) {
236 this.loadError = e;
237 }
238 return this.loaded;
239 }
241 private get project(): ProjectCalls {
242 const p = this.ensure();
243 if (!p) throw this.loadError;
244 return p;
245 }
247 private logChars(): { chars: number; entries: number } {
248 const tables = this.ctx.storage.sql
249 .exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'log'")
250 .toArray();
251 return tables.length === 0 ? { chars: 0, entries: 0 } : new SqliteLog(this.ctx.storage).logSize();
252 }
254 private sizes(): { lines: number; keys: number } | undefined {
255 if (this.logChars().entries === 0) return undefined;
256 try {
257 return new SqliteLog(this.ctx.storage).countSizes();
258 } catch {
259 return undefined;
260 }
261 }
263 /** Why recording new work is held: the estimate is past the soft cap; else null. */
264 private softHeld(): string | null {
265 const counted = this.sizes();
266 if (counted === undefined) return null;
267 const bytes = loadEstimate(this.logChars().entries, counted.lines, counted.keys);
268 return bytes > LOAD_SOFT_BYTES
269 ? `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`
270 : null;
271 }
273 /** Why this project mustn't load: its estimated memory, or before its lines are counted, its log's size; else null. */
274 private tooBigToLoad(): string | null {
275 const counted = this.sizes();
276 if (counted !== undefined) {
277 const bytes = loadEstimate(this.logChars().entries, counted.lines, counted.keys);
278 return bytes > LOAD_MAX_BYTES
279 ? `this project holds ${counted.lines} lines and ${this.logChars().entries} entries, an estimated ${(bytes / 1e6).toFixed(0)} MB once loaded`
280 : null;
281 }
282 const { chars } = this.logChars();
283 return chars > LOG_LOAD_MAX_CHARS ? `this project's log is ${(chars / 1e6).toFixed(1)} MB` : null;
284 }
286 // Blobs: binary files' bytes, named by their SHA-256.
288 async putBlob(sha: string, body: ReadableStream<Uint8Array>): Promise<Answer> {
289 const a = await this.blobs.put(sha, body);
290 // A push out waiting on missing blobs goes again now.
291 if (a.status === 200 && (await this.ctx.storage.get("pushError"))) await this.ctx.storage.setAlarm(Date.now());
292 return a;
293 }
295 async getBlob(sha: string): Promise<ReadableStream<Uint8Array> | null> {
296 return this.blobs.stream(sha);
297 }
299 /** Shared's newest version, from storage alone, never loading the project. Null when there's no project. */
300 async head(): Promise<{ version: number; at: string } | null> {
301 if (this.logChars().entries === 0) return null;
302 return { version: new SqliteLog(this.ctx.storage).sharedVersion(), at: new Date().toISOString() };
303 }
305 /** Backups: one page of the log as JSON lines. It works even when the log won't load. */
306 async exportLog(from: number, limit: number): Promise<{ lines: string; next: number | null } | null> {
307 if (this.logChars().entries === 0) return null;
308 const { texts, next } = new SqliteLog(this.ctx.storage).page(from, limit);
309 return { lines: texts.map((t) => `${t}\n`).join(""), next };
310 }
312 private wake(): void {
313 const all = this.waiting;
314 this.waiting = [];
315 for (const w of all) w();
316 }
318 /**
319 * GET feed?from=&wait=<seconds, up to 25>: when nothing is new, hold the call until an entry is written or the wait
320 * ends, then answer as usual.
321 */
322 private async feed(name: string, body: unknown): Promise<Answer> {
323 const q = (body ?? {}) as Record<string, string | undefined>;
324 const wait = Math.min(25, Math.max(0, Number(q.wait) || 0));
325 const first = await this.call(name, "feed", undefined, body, true);
326 const from = Number(q.from) || 0;
327 const empty = first.status === 200 && (first.body as { next: number }).next <= from;
328 if (!empty || wait === 0) return first;
329 await new Promise<void>((resolve) => {
330 const timer = setTimeout(resolve, wait * 1000);
331 this.waiting.push(() => {
332 clearTimeout(timer);
333 resolve();
334 });
335 });
336 return this.call(name, "feed", undefined, body, true);
337 }
339 /** One project call: the agent key (if any), the size caps, then answer() from worker/project/http.ts. */
340 async call(
341 name: string,
342 op: string,
343 agent: string | undefined,
344 body: unknown,
345 inFeed = false,
346 how?: string,
347 key?: KeyForCall,
348 ): Promise<Answer> {
349 const revision = this.authorityRevision;
350 if (key) {
351 const decided = await this.checkAgentKey(key.presented, agent, key.address);
352 if (!decided.ok) return { status: decided.status, body: { error: decided.error } };
353 const allowed = keyAllows(decided.role, { write: key.write, agent, route: key.route });
354 if (!allowed.ok) return { status: allowed.status, body: { error: allowed.error } };
355 how = decided.as;
356 }
357 if (op === "feed" && !inFeed) return this.feed(name, body);
358 if (this.diskRuntime()) {
359 try {
360 return await this.diskCall(name, op, agent, body, how, revision);
361 } catch (error) {
362 if ((error as { code?: string })?.code === "authority-changed")
363 return { status: 409, body: { error: "project authorization changed; retry the request", retryable: true } };
364 throw error;
365 }
366 }
367 if (this.legacyWritesHeld() && !READ_OPS.has(op) && !op.startsWith("change/"))
368 return { status: 409, body: { error: "disk-first indexes exist; enable ABSO_DISK_FIRST before writing" } };
369 if (SOFT_HELD_OPS.has(op)) {
370 const held = this.softHeld();
371 if (held) return { status: 507, body: { error: held } };
372 }
373 const loaded = this.ensure();
374 if (!loaded) {
375 const why = this.loadError instanceof Error ? this.loadError.message : String(this.loadError);
376 return { status: 507, body: { error: `the project's log did not load: ${why}` } };
377 }
378 // Readers live in storage, not the log: a refused call writes nothing, so replay never needs them.
379 const list = new Set((await this.ctx.storage.get<string[]>("readers")) ?? []);
380 let changed = false;
381 const readers: Readers = {
382 has: (a) => list.has(a),
383 set: (a, on) => {
384 if (on === list.has(a)) return;
385 if (on) list.add(a);
386 else list.delete(a);
387 changed = true;
388 },
389 list: () => [...list].sort(),
390 };
391 const before = loaded.exists() ? loaded.shared().version : -1;
392 const logLength = () => (this.loaded as { logLength?: () => number } | undefined)?.logLength?.() ?? 0;
393 const entriesBefore = logLength();
394 const a = answer(loaded, op, agent, body, readers, how);
395 if (changed) await this.ctx.storage.put("readers", readers.list());
396 if (logLength() !== entriesBefore) this.wake();
397 if (a.status === 200 && op === "starting") a.body = await this.startingHooks(name, a.body);
398 if (a.status === 200) a.body = this.withBlobSizes(op, a.body);
399 const after = loaded.exists() ? loaded.shared().version : -1;
400 if (a.status === 200 && after >= 0 && (op === "init" || after > before)) {
401 // A new version of shared: push it out to Artifacts in the background. The alarm retries; the call never waits.
402 await this.ctx.storage.put("name", name);
403 if (artifactsOf(this.env)) await this.ctx.storage.setAlarm(Date.now());
404 } else if (
405 a.status === 200 &&
406 artifactsOf(this.env) &&
407 Date.now() - this.gitCheckedAt > GIT_CHECK_MS &&
408 (await this.ctx.storage.get("name")) !== undefined &&
409 (await this.ctx.storage.getAlarm()) === null
410 ) {
411 // While agents are working, the alarm also looks for plain-git pushes.
412 await this.ctx.storage.setAlarm(Date.now());
413 }
414 return a;
415 }
417 /**
418 * The engine's starting answer carries hooks for the issues code (a start note naming an issue began or ended). They
419 * go to the project's IssueProject, and never to the client. A failed hook is logged and never fails the call.
420 */
421 private async startingHooks(name: string, body: unknown): Promise<unknown> {
422 const { hooks, ...rest } = body as {
423 hooks?: {
424 claim?: { issue: number; agent: string; change: number };
425 unclaim?: { issue: number; agent: string; change: number; done?: boolean; version?: number };
426 };
427 };
428 if (!hooks) return body;
429 const issues = this.env.ISSUES_DO.get(this.env.ISSUES_DO.idFromName(name)) as unknown as IssueHooks;
430 const tell = async (what: string, call: () => Promise<unknown> | undefined) => {
431 try {
432 await call();
433 } catch (e) {
434 console.log(JSON.stringify({ event: "issues-hook", what, project: name, error: String(e).slice(0, 200) }));
435 }
436 };
437 const end = hooks.unclaim;
438 if (end?.done && end.version !== undefined) {
439 const version = end.version;
440 await tell("done", () => issues.done?.(end.agent, end.issue, version));
441 } else if (end) await tell("unclaim", () => issues.unclaim?.(end.agent, end.issue));
442 const claim = hooks.claim;
443 if (claim) await tell("claim", () => issues.claim?.(claim.agent, claim.issue, claim.change));
444 return rest;
445 }
447 /** A folder's binary files count by their bytes, and a binary file says its size: the blob store knows both. */
448 private withBlobSizes(op: string, body: unknown): unknown {
449 if (op === "tree" && Array.isArray((body as { entries?: unknown }).entries)) {
450 const b = body as { entries: { bytes?: number; blobs?: string[] }[] };
451 return {
452 ...b,
453 entries: b.entries.map(({ blobs, ...e }) =>
454 blobs ? { ...e, bytes: (e.bytes ?? 0) + blobs.reduce((n, sha) => n + this.blobs.size(sha), 0) } : e,
455 ),
456 };
457 }
458 if (op === "file" && typeof (body as { blob?: unknown }).blob === "string")
459 return { ...(body as object), size: this.blobs.size((body as { blob: string }).blob) };
460 return body;
461 }
463 // The push out to Artifacts, and plain-git pushes back in.
465 /**
466 * Takes in commits pushed to the project's repo with plain git: the ones above the server's last commit that
467 * haven't been taken in yet. One run at a time; a call while a run is going gets that run's answer.
468 */
469 gitSync(): Promise<{ head: string; commits: number; answer: unknown } | null> {
470 this.gitSyncing ??= this.gitSyncOnce().finally(() => {
471 this.gitSyncing = undefined;
472 });
473 return this.gitSyncing;
474 }
476 private async gitSyncOnce(): Promise<{ head: string; commits: number; answer: unknown } | null> {
477 if (this.legacyWritesHeld()) return null;
478 const artifacts = artifactsOf(this.env);
479 if (!artifacts) return null;
480 this.gitCheckedAt = Date.now();
481 const name = await this.ctx.storage.get<string>("name");
482 if (!name) return null;
483 const progress = await this.prepareDisk();
484 if (progress && !progress.ready) return null;
485 if (!this.useProject((p) => p.exists())) return null;
486 const seen = await this.ctx.storage.get<string>("git:head");
487 const pushed = await this.ctx.storage.get<PushResult>("pushed");
488 const head = await remoteHead(artifacts, name);
489 if (!head || head === seen || head === pushed?.commit) return null;
490 const sharedBlobs = this.useProject((p) => p.shared().blobs ?? {});
491 const found = await pushedSince(
492 artifacts,
493 name,
494 seen,
495 async (bytes) => (bytes.byteLength > BLOB_MAX ? null : this.blobs.putBytes(bytes)),
496 (path) => sharedBlobs[path],
497 );
498 if (!found || found.commits.length === 0) {
499 if (found) await this.ctx.storage.put("git:head", found.head);
500 return null;
501 }
502 let result: unknown;
503 try {
504 result = this.useProject(
505 (p) => p.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now()),
506 true,
507 );
508 } catch (e) {
509 result = { error: e instanceof Error ? e.message : String(e) };
510 }
511 const taken = {
512 at: new Date().toISOString(),
513 head: found.head,
514 commits: found.commits.length,
515 answer: result,
516 ...(found.tooBig.length ? { tooBig: found.tooBig } : {}),
517 };
518 await this.ctx.storage.put({ "git:head": found.head, "git:last": taken });
519 this.wake();
520 if ((result as { landed?: boolean }).landed) await this.ctx.storage.setAlarm(Date.now());
521 return taken;
522 }
524 /** Sets the alarm for `at` unless one is due sooner. */
525 private async soon(at: number): Promise<void> {
526 const now = await this.ctx.storage.getAlarm();
527 if (now === null || now > at) await this.ctx.storage.setAlarm(at);
528 }
530 /**
531 * Plain-git pushes in first, so the push out builds on them; then shared out to the project's Artifacts repo, at
532 * most once a minute, backing off on failure. Without an ARTIFACTS binding (local dev) it does nothing.
533 */
534 async alarm(): Promise<void> {
535 if (!this.diskRuntime() && !artifactsOf(this.env)) return;
536 if (!this.diskRuntime() && !this.ensure()) return;
537 const progress = await this.prepareDisk();
538 if (progress && !progress.ready) return;
539 const artifacts = artifactsOf(this.env);
540 if (!artifacts) return;
541 const name = await this.ctx.storage.get<string>("name");
542 if (!name || !this.useProject((p) => p.exists())) return;
543 await this.gitSync().then(
544 () => this.ctx.storage.delete("git:error"),
545 (e) =>
546 this.ctx.storage.put("git:error", {
547 at: new Date().toISOString(),
548 error: e instanceof Error ? e.message : String(e),
549 }),
550 );
551 const shared = this.useProject((p) => p.shared());
552 const done = await this.ctx.storage.get<PushResult>("pushed");
553 if (done && done.version >= shared.version) return;
554 const pushedAt = (await this.ctx.storage.get<number>("pushedAt")) ?? 0;
555 if (Date.now() - pushedAt < PUSH_EVERY_MS) {
556 await this.soon(pushedAt + PUSH_EVERY_MS);
557 return;
558 }
559 let result: PushResult;
560 try {
561 result = await pushShared(artifacts, name, shared, (sha) => this.blobs.read(sha));
562 } catch (e) {
563 // Kept for /out, and tried again with a backoff of our own (a thrown alarm is retried only six times).
564 const was = await this.ctx.storage.get<{ attempts?: number }>("pushError");
565 const attempts = (was?.attempts ?? 0) + 1;
566 await this.ctx.storage.put("pushError", {
567 version: shared.version,
568 at: new Date().toISOString(),
569 attempts,
570 error: e instanceof Error ? e.message : String(e),
571 });
572 await this.soon(Date.now() + Math.min(10 * 60_000, 15_000 * 2 ** Math.min(attempts - 1, 6)));
573 return;
574 }
575 await this.ctx.storage.put({ pushed: result, "git:head": result.commit, pushedAt: Date.now() });
576 await this.ctx.storage.delete("pushError");
577 // Another publish may have landed while this push ran.
578 if (this.useProject((p) => p.shared().version) > result.version) await this.soon(Date.now() + PUSH_EVERY_MS);
579 }
581 /** The push out: the repo, the last version pushed, and plain-git intake. */
582 async out() {
583 const name = await this.ctx.storage.get<string>("name");
584 return {
585 repo: name ? repoName(name) : null,
586 artifacts: artifactsOf(this.env) ? "bound" : "unbound",
587 version: this.logChars().entries ? new SqliteLog(this.ctx.storage).sharedVersion() : null,
588 pushed: (await this.ctx.storage.get<PushResult>("pushed")) ?? null,
589 error: (await this.ctx.storage.get("pushError")) ?? null,
590 git: {
591 head: (await this.ctx.storage.get<string>("git:head")) ?? null,
592 last: (await this.ctx.storage.get("git:last")) ?? null,
593 error: (await this.ctx.storage.get("git:error")) ?? null,
594 },
595 };
596 }
598 // Per-agent keys: the HMACs live here, one project's keys per object.
600 private async keyState(): Promise<KeyState> {
601 return (await this.ctx.storage.get<KeyState>("agent-keys")) ?? emptyKeyState();
602 }
604 async checkAgentKey(presented: string, agent: string | undefined, address: string) {
605 const state = await this.keyState();
606 const decided = await checkKey(state, this.env.KEY_HMAC_SECRET, presented, agent, Date.now(), address);
607 if (decided.dirty) await this.ctx.storage.put("agent-keys", state);
608 if (!decided.ok) return decided;
609 const row = state.rows.find((r) => r.id === decided.id);
610 return { ...decided, agent: row?.agent ?? "" };
611 }
613 /** Issues a key. The returned key is the only copy. */
614 async issueAgentKey(
615 agent: string,
616 address: string,
617 expiresRaw: string | null,
618 role: KeyRole,
619 ): Promise<{ id: string; key: string; agent: string } | { error: string }> {
620 const secret = this.env.KEY_HMAC_SECRET;
621 if (!secret) return { error: "the key secret (KEY_HMAC_SECRET) is not set" };
622 const when = expiresAt(Date.now(), expiresRaw);
623 if (typeof when !== "number") return { error: when.error };
624 const state = await this.keyState();
625 const issued = await issueKey(state, secret, agent, "admin", Date.now(), address, when, role);
626 this.authorityRevision++;
627 await this.ctx.storage.put("agent-keys", state);
628 return issued;
629 }
631 async revokeAgentKey(id: string, address: string): Promise<{ revoked: boolean }> {
632 const secret = this.env.KEY_HMAC_SECRET;
633 if (!secret) return { revoked: false };
634 const state = await this.keyState();
635 const revoked = revokeKey(state, id, Date.now(), await hmac(secret, address));
636 this.authorityRevision++;
637 await this.ctx.storage.put("agent-keys", state);
638 return { revoked };
639 }
641 async listAgentKeys(agent?: string) {
642 return listKeys(await this.keyState(), agent);
643 }
645 // For the issues code (server/src/issues/).
647 /** The project's agent names, for the ask seat check. None when there's no project. */
648 async agents(_project: string): Promise<string[]> {
649 if (!this.diskRuntime() && !this.ensure()) return [];
650 const progress = await this.prepareDisk();
651 if (progress?.phase === "empty") return [];
652 if (progress && !progress.ready) throw Error("project indexes are being prepared");
653 return this.useProject((p) => (p.exists() ? p.status().agents.map((a) => a.agent) : []));
654 }
656 /**
657 * Issues news, delivered through the engine's announce path: each item goes to the agents whose start note names
658 * its issue and to the known agents in `to`, never back to its writer.
659 */
660 async news(_project: string, items: IssueNews[]): Promise<{ to: string[] }[]> {
661 if (!this.diskRuntime() && !this.ensure()) return items.map(() => ({ to: [] }));
662 const progress = await this.prepareDisk();
663 if (progress?.phase === "empty") return items.map(() => ({ to: [] }));
664 if (progress && !progress.ready) throw Error("project indexes are being prepared");
665 return this.useProject((p) => {
666 if (!p.exists()) return items.map(() => ({ to: [] }));
667 const engine = p as ProjectCalls & ProjectHistory;
668 const out: { to: string[] }[] = [];
669 for (const item of items) {
670 const status = p.status() as { agents: { agent: string; starting?: { issue?: number } }[] };
671 const known = new Set(status.agents.map((a) => a.agent));
672 const to = new Set([
673 ...(item.issue !== null
674 ? status.agents.filter((a) => a.starting?.issue === item.issue).map((a) => a.agent)
675 : []),
676 ...(item.to ?? []).filter((t) => known.has(t)),
677 ]);
678 to.delete(item.from);
679 if (to.size === 0) {
680 out.push({ to: [] });
681 continue;
682 }
683 try {
684 engine.announce(item.from, item.text, [...to]);
685 out.push({ to: [...to] });
686 } catch (e) {
687 // Persistent writer state may already have changed. Let the outer
688 // transaction undo the whole batch before reporting a failure.
689 if (this.env.ABSO_DISK_FIRST === "on") throw e;
690 console.log(JSON.stringify({ event: "issues-news", error: String(e).slice(0, 200) }));
691 out.push({ to: [] });
692 }
693 }
694 this.wake();
695 return out;
696 }, true);
697 }