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