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

Versions 116 to 318

Compare

+407 −0 in 1 place
new file, 407 lines
1+// Local projects (abso init --local): the open server's own router and project object (server/src) run in this
2+// process, over Node's SQLite, so a project needs no server, account or network. Each project is one SQLite file in a
3+// store folder. Every call runs in one SQLite write transaction, which is the store's lock: another process's call
4+// waits for it, and a process that dies mid-call leaves nothing half-written.
5+
6+import { existsSync, mkdirSync } from "node:fs";
7+import { homedir } from "node:os";
8+import { join, resolve } from "node:path";
9+import { deserialize, serialize } from "node:v8";
10+import { UsageError } from "./args.ts";
11+import { fromEnv } from "./env-names.ts";
13+/** The server a local folder's config names. */
14+export const LOCAL = "local";
15+/** The address the client's calls use for a local project; they never leave this process. */
16+export const LOCAL_BASE = "http://local.abso.invalid";
17+/** The shared token the in-process server is given, and that its calls carry. Not a secret: nothing listens. */
18+const LOCAL_TOKEN = "local-store";
20+export const isLocal = (server: string | undefined): boolean => server === LOCAL;
22+type EnvMap = Readonly<Record<string, string | undefined>>;
24+/**
25+ * Where local projects live: the folder's own store (--store, kept in its config), else ABSO_STORE, else the OS's
26+ * per-user data folder. Undefined when there is none to use (no data folder and nothing named), so nothing assumes a
27+ * writable home folder.
28+ */
29+export function storeDir(env: EnvMap, configured?: string, cwd = process.cwd()): string | undefined {
30+ if (configured) return resolve(cwd, configured);
31+ const named = fromEnv(env, "STORE");
32+ if (named) return resolve(cwd, named);
33+ const data =
34+ process.platform === "win32"
35+ ? env.LOCALAPPDATA
36+ : process.platform === "darwin"
37+ ? env.HOME && join(env.HOME, "Library", "Application Support")
38+ : env.XDG_DATA_HOME || (env.HOME ? join(env.HOME, ".local", "share") : undefined);
39+ if (data) return join(data, "abso", "store");
40+ try {
41+ const home = homedir();
42+ return home ? join(home, ".local", "share", "abso", "store") : undefined;
43+ } catch {
44+ return undefined;
45+ }
46+}
48+export const NO_STORE =
49+ "there's no folder for local projects here: set ABSO_STORE to one, or give abso init --local a --store <folder>";
51+// --- The Workers runtime's parts the server uses, over node:sqlite -----------------------------------------------
53+interface Db {
54+ exec(sql: string): void;
55+ prepare(sql: string): {
56+ all(...args: unknown[]): unknown[];
57+ run(...args: unknown[]): unknown;
58+ get(...args: unknown[]): unknown;
59+ columns(): unknown[];
60+ };
61+ close(): void;
62+}
64+/** A Durable Object's storage: SQL, synchronous transactions, the key-value calls and the alarm, on one database. */
65+function storageOver(db: Db) {
66+ db.exec(
67+ "CREATE TABLE IF NOT EXISTS _local_kv (key TEXT PRIMARY KEY, value BLOB NOT NULL); CREATE TABLE IF NOT EXISTS _local_alarm (id INTEGER PRIMARY KEY CHECK (id = 0), at INTEGER)",
68+ );
69+ const statements = new Map<string, ReturnType<Db["prepare"]>>();
70+ const prepared = (query: string) => {
71+ let s = statements.get(query);
72+ if (!s) {
73+ s = db.prepare(query);
74+ statements.set(query, s);
75+ }
76+ return s;
77+ };
78+ // Workers takes and gives BLOB columns as ArrayBuffers; node:sqlite as Uint8Arrays.
79+ const bind = (v: unknown) => (v instanceof ArrayBuffer ? new Uint8Array(v) : v);
80+ const out = (v: unknown) => (v instanceof Uint8Array ? v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength) : v);
81+ let depth = 0;
82+ const kvGet = (key: string) => {
83+ const row = prepared("SELECT value FROM _local_kv WHERE key = ?").get(key) as { value: Uint8Array } | undefined;
84+ return row ? deserialize(row.value) : undefined;
85+ };
86+ const kvPut = (key: string, value: unknown) =>
87+ prepared(
88+ "INSERT INTO _local_kv (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value",
89+ ).run(key, serialize(value));
90+ const kvDelete = (key: string) =>
91+ (prepared("DELETE FROM _local_kv WHERE key = ?").run(key) as { changes: number | bigint }).changes > 0;
92+ const storage = {
93+ sql: {
94+ exec(query: string, ...bindings: unknown[]) {
95+ const statement = prepared(query);
96+ const args = bindings.map(bind);
97+ const rows = statement.columns().length > 0 ? statement.all(...args) : (statement.run(...args), []);
98+ return {
99+ toArray: () =>
100+ (rows as Record<string, unknown>[]).map((r) =>
101+ Object.fromEntries(Object.entries(r).map(([k, v]) => [k, out(v)])),
102+ ),
103+ };
104+ },
105+ },
106+ transactionSync<T>(fn: () => T): T {
107+ const name = `local_t${depth++}`;
108+ db.exec(`SAVEPOINT ${name}`);
109+ try {
110+ const value = fn();
111+ db.exec(`RELEASE ${name}`);
112+ return value;
113+ } catch (e) {
114+ db.exec(`ROLLBACK TO ${name}; RELEASE ${name}`);
115+ throw e;
116+ } finally {
117+ depth--;
118+ }
119+ },
120+ async transaction<T>(fn: (txn: unknown) => Promise<T>): Promise<T> {
121+ return fn(storage);
122+ },
123+ async get(key: string | string[]) {
124+ if (typeof key === "string") return kvGet(key);
125+ return new Map(key.flatMap((k) => (kvGet(k) === undefined ? [] : [[k, kvGet(k)] as const])));
126+ },
127+ async put(key: string | Record<string, unknown>, value?: unknown) {
128+ if (typeof key === "string") kvPut(key, value);
129+ else for (const [k, v] of Object.entries(key)) kvPut(k, v);
130+ },
131+ async delete(key: string | string[]) {
132+ if (typeof key === "string") return kvDelete(key);
133+ return key.filter(kvDelete).length;
134+ },
135+ async list(options: { prefix?: string } = {}) {
136+ const rows = prepared("SELECT key, value FROM _local_kv WHERE key >= ? ORDER BY key").all(
137+ options.prefix ?? "",
138+ ) as { key: string; value: Uint8Array }[];
139+ return new Map(
140+ rows.filter((r) => r.key.startsWith(options.prefix ?? "")).map((r) => [r.key, deserialize(r.value)]),
141+ );
142+ },
143+ // The alarm is kept, but nothing in a local project needs it: it pushes out to Artifacts, which is off here.
144+ async getAlarm() {
145+ const row = prepared("SELECT at FROM _local_alarm WHERE id = 0").get() as { at: number | null } | undefined;
146+ return row?.at ?? null;
147+ },
148+ async setAlarm(at: number | Date) {
149+ prepared("INSERT INTO _local_alarm (id, at) VALUES (0, ?) ON CONFLICT (id) DO UPDATE SET at = excluded.at").run(
150+ Number(at),
151+ );
152+ },
153+ async deleteAlarm() {
154+ prepared("DELETE FROM _local_alarm WHERE id = 0").run();
155+ },
156+ };
157+ return storage;
158+}
160+/** Workers' crypto.DigestStream, which the blob store hashes uploads with. */
161+async function installDigestStream(): Promise<void> {
162+ // Through a cast: abso's worker compiles this file too (tool.lock.json), and its types have no globalThis.crypto.
163+ const c = (globalThis as unknown as { crypto: { DigestStream?: unknown } }).crypto;
164+ if (c.DigestStream) return;
165+ const { createHash } = await import("node:crypto");
166+ class DigestStream extends WritableStream<Uint8Array> {
167+ readonly digest: Promise<ArrayBuffer>;
168+ constructor(algorithm: string) {
169+ const hash = createHash(algorithm.replace("-", "").toLowerCase());
170+ let done!: (b: ArrayBuffer) => void;
171+ const digest = new Promise<ArrayBuffer>((ok) => {
172+ done = ok;
173+ });
174+ super({
175+ write: (chunk) => void hash.update(chunk),
176+ close: () => {
177+ const b = hash.digest();
178+ done(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer);
179+ },
180+ });
181+ this.digest = digest;
182+ }
183+ }
184+ c.DigestStream = DigestStream;
185+}
187+// --- Loading the server's code ------------------------------------------------------------------------------------
189+type Server = {
190+ DatabaseSync: new (path: string) => Db;
191+ handle: (request: Request, env: unknown, ctx: unknown, issues: unknown) => Promise<Response>;
192+ ProjectObject: new (ctx: unknown, env: unknown) => object;
193+ IssueProject: new (ctx: unknown, env: unknown) => object;
194+ issuesFetch: (request: Request, env: unknown, ctx: unknown, route: unknown) => Promise<Response>;
195+};
196+let server: Promise<Server> | undefined;
198+/** Node's SQLite says it's experimental on every start; that line would land in every local command's output. */
199+function quietSqliteWarning(): void {
200+ const emit = process.emitWarning;
201+ if ((emit as { quiet?: boolean }).quiet) return;
202+ const quiet = ((warning: string | Error, ...rest: unknown[]) => {
203+ const text = typeof warning === "string" ? warning : warning.message;
204+ if (text.startsWith("SQLite is an experimental feature")) return;
205+ return (emit as (...a: unknown[]) => void).call(process, warning, ...rest);
206+ }) as typeof process.emitWarning;
207+ (quiet as unknown as { quiet: boolean }).quiet = true;
208+ process.emitWarning = quiet;
209+}
211+export const NODE_TOO_OLD = `local projects need Node 22.13 or later, for its built-in SQLite; this is Node ${process.versions.node}`;
213+function loadServer(): Promise<Server> {
214+ server ??= (async () => {
215+ quietSqliteWarning();
216+ let sqlite: { DatabaseSync: Server["DatabaseSync"] };
217+ try {
218+ sqlite = (await import("node:sqlite")) as unknown as typeof sqlite;
219+ } catch {
220+ throw new LocalError(NODE_TOO_OLD);
221+ }
222+ await installDigestStream();
223+ // Run as .ts files, the server's `import { DurableObject } from "cloudflare:workers"` needs a stand-in. A built
224+ // copy has it already: the build points the import at the same file (scripts/build-client.mjs).
225+ const standIn = new URL("./durable-object-stand-in.ts", import.meta.url).href;
226+ const mod = (await import("node:module")) as unknown as {
227+ registerHooks?: (hooks: unknown) => unknown;
228+ };
229+ // The hook stays for the rest of the process: deregistering it crashes Node 24 at exit when the compile cache
230+ // is on (client/avcs.ts turns it on). It answers only cloudflare:workers.
231+ mod.registerHooks?.({
232+ resolve(specifier: string, context: unknown, next: (s: string, c: unknown) => unknown) {
233+ if (specifier === "cloudflare:workers") return { url: standIn, shortCircuit: true };
234+ return next(specifier, context);
235+ },
236+ });
237+ let loaded: typeof import("./local-server.mjs");
238+ try {
239+ loaded = await import("./local-server.mjs");
240+ } catch (e) {
241+ // Nothing is reached for here: a part of the client is missing (its packages not installed, say).
242+ throw new LocalError(
243+ `local projects couldn't load the server's code: ${e instanceof Error ? e.message : String(e)}`,
244+ );
245+ }
246+ return {
247+ DatabaseSync: sqlite.DatabaseSync,
248+ handle: loaded.handle,
249+ ProjectObject: loaded.ProjectObject,
250+ IssueProject: loaded.IssueProject,
251+ issuesFetch: loaded.issuesFetch,
252+ };
253+ })();
254+ return server;
255+}
257+/** What stops a local project from opening at all: said plainly, like a usage error. */
258+export class LocalError extends UsageError {}
260+// --- One store, as a fetch -----------------------------------------------------------------------------------------
262+interface Open {
263+ db: Db;
264+ storage: ReturnType<typeof storageOver>;
265+ object: object | undefined;
266+ /** PRAGMA data_version when this process last used the project: it changes when another process writes. */
267+ seen: number | undefined;
268+ /** The project's issues, asks and news: issues.sqlite beside it, opened when a call first reaches them. */
269+ issues?: { db: Db; storage: ReturnType<typeof storageOver> };
270+ /** The issues object for the call under way: made again for each call, as another process may have written. */
271+ issueObject?: object;
272+}
274+/** Every store file this process has open: closed when its command ends (closeLocalStores). */
275+const opened = new Set<Db>();
277+/** Closes every local project this process opened. Its next call opens them again. */
278+export function closeLocalStores(): void {
279+ for (const db of opened) {
280+ try {
281+ db.close();
282+ } catch {}
283+ }
284+ opened.clear();
285+}
287+/** A project's calls, and its issues, asks and news, which the open server keeps at /issues/p/<project>/. */
288+const PROJECT_PATH = /^(?:\/issues)?\/p\/([^/]+)\//;
289+/** A project's name is also its folder in the store, so it never starts with a dot ("." and ".." would leave it). */
290+const NAME = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,99}$/;
291+const json = (status: number, body: unknown) => Response.json(body, { status });
293+/**
294+ * The fetch a local folder's calls go through: each call is answered by the open server's router, in this process,
295+ * against the project's SQLite file in `dir`. Only init makes a project's file.
296+ */
297+export function localFetch(dir: string): (input: string, init?: RequestInit) => Promise<Response> {
298+ const open = new Map<string, Open>();
299+ let opening: Server | undefined;
300+ const openProject = (name: string, create: boolean): Open | undefined => {
301+ const existing = open.get(name);
302+ if (existing && opened.has(existing.db)) return existing;
303+ const folder = join(dir, name);
304+ const file = join(folder, "project.sqlite");
305+ if (create) mkdirSync(folder, { recursive: true });
306+ else if (!existsSync(file)) return undefined;
307+ const db = new opening!.DatabaseSync(file);
308+ opened.add(db);
309+ db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 120000; PRAGMA synchronous = NORMAL");
310+ const project = { db, storage: storageOver(db), object: undefined, seen: undefined };
311+ open.set(name, project);
312+ return project;
313+ };
314+ const env = (name: string) => ({
315+ ABSO_TOKEN: LOCAL_TOKEN,
316+ ABSO_ARTIFACTS: "off",
317+ ABSO_DISK_FIRST: "off",
318+ PROJECT: {
319+ idFromName: (n: string) => n,
320+ get: (n: string) => {
321+ const p = open.get(n);
322+ if (!p || n !== name) throw new LocalError(`no local project ${n}`);
323+ p.object ??= new opening!.ProjectObject(
324+ { id: { toString: () => n, name: n }, storage: p.storage, waitUntil: () => {} },
325+ env(name),
326+ );
327+ return p.object;
328+ },
329+ },
330+ ISSUES_DO: {
331+ idFromName: (n: string) => n,
332+ get: (n: string) => {
333+ const p = open.get(n);
334+ if (!p || n !== name) throw new LocalError(`no local project ${n}`);
335+ if (p.issues === undefined || !opened.has(p.issues.db)) {
336+ const db = new opening!.DatabaseSync(join(dir, name, "issues.sqlite"));
337+ opened.add(db);
338+ db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 120000; PRAGMA synchronous = NORMAL");
339+ p.issues = { db, storage: storageOver(db) };
340+ }
341+ // Its writes need no lock of their own: every call holds the project file's (see below).
342+ p.issueObject ??= new opening!.IssueProject(
343+ { id: { toString: () => n, name: n }, storage: p.issues.storage },
344+ env(name),
345+ );
346+ return p.issueObject;
347+ },
348+ },
349+ });
350+ // One call at a time, as a Durable Object takes them: a call holds its project's write transaction across awaits,
351+ // and the connection can't start a second (two calls at once come from Promise.all in ci and waiting --mine).
352+ let last: Promise<unknown> = Promise.resolve();
353+ return (input, init) => {
354+ const next = last.then(
355+ () => call(input, init),
356+ () => call(input, init),
357+ );
358+ last = next.catch(() => {});
359+ return next;
360+ };
362+ async function call(input: string, init: RequestInit = {}): Promise<Response> {
363+ const s = await loadServer();
364+ opening = s;
365+ const url = new URL(input);
366+ const match = PROJECT_PATH.exec(url.pathname);
367+ if (!match) return json(404, { error: "a local store answers only project calls" });
368+ const name = decodeURIComponent(match[1]!);
369+ if (!NAME.test(name)) return json(400, { error: "project names use letters, digits, '.', '_' and '-'" });
370+ const p = openProject(name, url.pathname === `/p/${match[1]}/init`);
371+ if (!p) return json(404, { error: `no local project ${name} in ${dir}` });
372+ const headers = new Headers(init.headers);
373+ headers.set("authorization", `Bearer ${LOCAL_TOKEN}`);
374+ const request = new Request(url, { ...init, headers });
375+ const waits: Promise<unknown>[] = [];
376+ // Every call, issues ones too, holds the project file's lock, so local writers of the project and of its
377+ // issues take one lock in one order.
378+ p.db.exec("BEGIN IMMEDIATE");
379+ p.issueObject = undefined;
380+ try {
381+ const version = (p.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version;
382+ if (p.seen !== undefined && version !== p.seen) p.object = undefined;
383+ const response = await s.handle(
384+ request,
385+ env(name),
386+ { waitUntil: (w: Promise<unknown>) => waits.push(w) },
387+ s.issuesFetch,
388+ );
389+ await Promise.allSettled(waits);
390+ // The answer is read whole before the write is kept, so a body that fails to arrive keeps nothing either.
391+ const body = await response.arrayBuffer();
392+ p.db.exec("COMMIT");
393+ p.seen = (p.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version;
394+ return new Response(body, { status: response.status, headers: response.headers });
395+ } catch (e) {
396+ try {
397+ p.db.exec("ROLLBACK");
398+ } catch {}
399+ // What the object held in memory may be from the rolled-back call.
400+ p.object = undefined;
401+ p.seen = undefined;
402+ if (e instanceof LocalError) throw e;
403+ // Where the Workers runtime answers a throw with a 500, so does this.
404+ return json(500, { error: e instanceof Error ? e.message : String(e) });
405+ }
406+ }
407+}
MCP
compare on this site's /mcp
CLI
abso diff 116 318 client/src/local-store.ts --json
JSON
/christopher/abso-core/compare/116..318?file=client%2Fsrc%2Flocal-store.ts&format=json