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 286 to 287

Compare

+360 −0 in 1 place
new file, 360 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+ const c = globalThis.crypto as unknown as { DigestStream?: unknown };
163+ if (c.DigestStream) return;
164+ const { createHash } = await import("node:crypto");
165+ class DigestStream extends WritableStream<Uint8Array> {
166+ readonly digest: Promise<ArrayBuffer>;
167+ constructor(algorithm: string) {
168+ const hash = createHash(algorithm.replace("-", "").toLowerCase());
169+ let done!: (b: ArrayBuffer) => void;
170+ const digest = new Promise<ArrayBuffer>((ok) => {
171+ done = ok;
172+ });
173+ super({
174+ write: (chunk) => void hash.update(chunk),
175+ close: () => {
176+ const b = hash.digest();
177+ done(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer);
178+ },
179+ });
180+ this.digest = digest;
181+ }
182+ }
183+ c.DigestStream = DigestStream;
184+}
186+// --- Loading the server's code ------------------------------------------------------------------------------------
188+type Server = {
189+ DatabaseSync: new (path: string) => Db;
190+ handle: (request: Request, env: unknown, ctx: unknown, issues: unknown) => Promise<Response>;
191+ ProjectObject: new (ctx: unknown, env: unknown) => object;
192+};
193+let server: Promise<Server> | undefined;
195+/** Node's SQLite says it's experimental on every start; that line would land in every local command's output. */
196+function quietSqliteWarning(): void {
197+ const emit = process.emitWarning;
198+ if ((emit as { quiet?: boolean }).quiet) return;
199+ const quiet = ((warning: string | Error, ...rest: unknown[]) => {
200+ const text = typeof warning === "string" ? warning : warning.message;
201+ if (text.startsWith("SQLite is an experimental feature")) return;
202+ return (emit as (...a: unknown[]) => void).call(process, warning, ...rest);
203+ }) as typeof process.emitWarning;
204+ (quiet as unknown as { quiet: boolean }).quiet = true;
205+ process.emitWarning = quiet;
206+}
208+export const NODE_TOO_OLD = `local projects need Node 22.13 or later, for its built-in SQLite; this is Node ${process.versions.node}`;
210+function loadServer(): Promise<Server> {
211+ server ??= (async () => {
212+ quietSqliteWarning();
213+ let sqlite: { DatabaseSync: Server["DatabaseSync"] };
214+ try {
215+ sqlite = (await import("node:sqlite")) as unknown as typeof sqlite;
216+ } catch {
217+ throw new LocalError(NODE_TOO_OLD);
218+ }
219+ await installDigestStream();
220+ // Run as .ts files, the server's `import { DurableObject } from "cloudflare:workers"` needs a stand-in. A built
221+ // copy has it already: the build points the import at the same file (scripts/build-client.mjs).
222+ const standIn = new URL("./durable-object-stand-in.ts", import.meta.url).href;
223+ const mod = (await import("node:module")) as unknown as {
224+ registerHooks?: (hooks: unknown) => { deregister(): void };
225+ };
226+ const hooks = mod.registerHooks?.({
227+ resolve(specifier: string, context: unknown, next: (s: string, c: unknown) => unknown) {
228+ if (specifier === "cloudflare:workers") return { url: standIn, shortCircuit: true };
229+ return next(specifier, context);
230+ },
231+ });
232+ try {
233+ const { handle, ProjectObject } = await import("./local-server.mjs");
234+ return {
235+ DatabaseSync: sqlite.DatabaseSync,
236+ handle,
237+ ProjectObject,
238+ };
239+ } finally {
240+ hooks?.deregister();
241+ }
242+ })();
243+ return server;
244+}
246+/** What stops a local project from opening at all: said plainly, like a usage error. */
247+export class LocalError extends UsageError {}
249+// --- One store, as a fetch -----------------------------------------------------------------------------------------
251+interface Open {
252+ db: Db;
253+ storage: ReturnType<typeof storageOver>;
254+ object: object | undefined;
255+ /** PRAGMA data_version when this process last used the project: it changes when another process writes. */
256+ seen: number | undefined;
257+}
259+/** Every store file this process has open: closed when its command ends (closeLocalStores). */
260+const opened = new Set<Db>();
262+/** Closes every local project this process opened. Its next call opens them again. */
263+export function closeLocalStores(): void {
264+ for (const db of opened) {
265+ try {
266+ db.close();
267+ } catch {}
268+ }
269+ opened.clear();
270+}
272+const PROJECT_PATH = /^\/p\/([^/]+)\//;
273+const NAME = /^[A-Za-z0-9._-]{1,100}$/;
274+const json = (status: number, body: unknown) => Response.json(body, { status });
276+/**
277+ * The fetch a local folder's calls go through: each call is answered by the open server's router, in this process,
278+ * against the project's SQLite file in `dir`. Only init makes a project's file.
279+ */
280+export function localFetch(dir: string): (input: string, init?: RequestInit) => Promise<Response> {
281+ const open = new Map<string, Open>();
282+ let opening: Server | undefined;
283+ const openProject = (name: string, create: boolean): Open | undefined => {
284+ const existing = open.get(name);
285+ if (existing && opened.has(existing.db)) return existing;
286+ const folder = join(dir, name);
287+ const file = join(folder, "project.sqlite");
288+ if (create) mkdirSync(folder, { recursive: true });
289+ else if (!existsSync(file)) return undefined;
290+ const db = new opening!.DatabaseSync(file);
291+ opened.add(db);
292+ db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 120000; PRAGMA synchronous = NORMAL");
293+ const project = { db, storage: storageOver(db), object: undefined, seen: undefined };
294+ open.set(name, project);
295+ return project;
296+ };
297+ const env = (name: string) => ({
298+ ABSO_TOKEN: LOCAL_TOKEN,
299+ ABSO_ARTIFACTS: "off",
300+ ABSO_DISK_FIRST: "off",
301+ PROJECT: {
302+ idFromName: (n: string) => n,
303+ get: (n: string) => {
304+ const p = open.get(n);
305+ if (!p || n !== name) throw new LocalError(`no local project ${n}`);
306+ p.object ??= new opening!.ProjectObject(
307+ { id: { toString: () => n, name: n }, storage: p.storage, waitUntil: () => {} },
308+ env(name),
309+ );
310+ return p.object;
311+ },
312+ },
313+ // Issues, asks and news aren't in local projects yet: a start note's issue hooks find nothing to call.
314+ ISSUES_DO: { idFromName: (n: string) => n, get: () => ({}) },
315+ });
316+ return async (input, init = {}) => {
317+ const s = await loadServer();
318+ opening = s;
319+ const url = new URL(input);
320+ const match = PROJECT_PATH.exec(url.pathname);
321+ if (!match) return json(404, { error: "a local store answers only project calls" });
322+ const name = decodeURIComponent(match[1]!);
323+ if (!NAME.test(name)) return json(400, { error: "project names use letters, digits, '.', '_' and '-'" });
324+ const p = openProject(name, url.pathname === `/p/${match[1]}/init`);
325+ if (!p) return json(404, { error: `no local project ${name} in ${dir}` });
326+ const headers = new Headers(init.headers);
327+ headers.set("authorization", `Bearer ${LOCAL_TOKEN}`);
328+ const request = new Request(url, { ...init, headers });
329+ const waits: Promise<unknown>[] = [];
330+ p.db.exec("BEGIN IMMEDIATE");
331+ try {
332+ const version = (p.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version;
333+ if (p.seen !== undefined && version !== p.seen) p.object = undefined;
334+ const response = await s.handle(
335+ request,
336+ env(name),
337+ { waitUntil: (w: Promise<unknown>) => waits.push(w) },
338+ issuesNone,
339+ );
340+ await Promise.allSettled(waits);
341+ // The answer is read whole before the write is kept, so a body that fails to arrive keeps nothing either.
342+ const body = await response.arrayBuffer();
343+ p.db.exec("COMMIT");
344+ p.seen = (p.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version;
345+ return new Response(body, { status: response.status, headers: response.headers });
346+ } catch (e) {
347+ try {
348+ p.db.exec("ROLLBACK");
349+ } catch {}
350+ // What the object held in memory may be from the rolled-back call.
351+ p.object = undefined;
352+ p.seen = undefined;
353+ if (e instanceof LocalError) throw e;
354+ // Where the Workers runtime answers a throw with a 500, so does this.
355+ return json(500, { error: e instanceof Error ? e.message : String(e) });
356+ }
357+ };
358+}
360+const issuesNone = async () => json(404, { error: "issues, asks and news aren't in local projects yet" });
MCP
compare on this site's /mcp
CLI
abso diff 286 287 client/src/local-store.ts --json
JSON
/christopher/abso-core/compare/286..287?file=client%2Fsrc%2Flocal-store.ts&format=json