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