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 318

Compare

+887 −47 in 48 places
Lines 107–114 at 318 (were 107–112 at 286)
107107 try {
108108 const ended = await follow({
109109 mint: () => api.newsTicket(),
110+ // A frame is a wake: read the news, which marks it heard, and print that (news-stream.ts).
111+ take: async () => newsLines((await api.news()).news),
110112 connect: (url, protocols) => new WebSocket(url, [...protocols]) as unknown as Socket,
111113 write: (line) => {
112114 logNews(root, [line]);
Lines 20–26 at 318 (were 20–25 at 286)
2020 SyncAnswer,
2121} from "./api-answers.ts";
2222import { ApiError, errorSentence, neverSent } from "./api-error.ts";
23+import { UsageError } from "./args.ts";
2324import type { AutosettleAnswer, AutosettleMode } from "./autosettle-commands.ts";
2425import {
2526 boxQuery,
Lines 69–75 at 318 (were 68–73 at 286)
6869 IssueRow,
6970 IssueSearchHit,
7071} from "./issues-wire.ts";
72+import { isLocal, LOCAL_BASE, localFetch, NO_STORE } from "./local-store.ts";
7173import type { Modes } from "./modes.ts";
7274
7375export * from "./api-answers.ts";
Lines 193–205 at 318 (were 191–199 at 286)
191193 caller: string | undefined;
192194
193195 url(path: string, server = this.config.server): string {
194− return `${server.replace(/\/+$/, "")}/p/${encodeURIComponent(this.config.project)}${path}`;
196+ const base = isLocal(server) ? LOCAL_BASE : server;
197+ return `${base.replace(/\/+$/, "")}/p/${encodeURIComponent(this.config.project)}${path}`;
195198 }
196199
200+ /** A local project's calls: answered in this process (local-store.ts). */
201+ private local: ((input: string, init?: RequestInit) => Promise<Response>) | undefined;
197203 agentPath(action: string): string {
198204 return `/a/${encodeURIComponent(this.config.agent)}/${action}`;
199205 }
Lines 220–231 at 318 (were 214–219 at 286)
214220 * and follows no redirect, so nothing it sends goes anywhere it didn't name (headers() adds no sign-in).
215221 */
216222 send(url: string, init: RequestInit = {}): Promise<Response> {
223+ if (isLocal(this.config.server)) {
224+ const dir = this.config.localStore;
225+ if (dir === undefined) return Promise.reject(new UsageError(NO_STORE));
226+ this.local ??= localFetch(dir);
227+ return this.local(url, init);
228+ }
217229 if (!this.config.visitor) return fetch(url, init);
218230 if ((init.method ?? "GET") !== "GET")
219231 return Promise.reject(new ApiError("a folder that reads signed out sends only reads"));
Lines 260–267 at 318 (were 248–253 at 286)
248260 signal: AbortSignal.timeout(timeoutMs),
249261 });
250262 } catch (err) {
263+ // A local project's refusal (no store, a Node without SQLite) says itself.
264+ if (err instanceof UsageError) throw err;
251265 const e = err as Error;
252266 const why =
253267 e.name === "TimeoutError"
Lines 80–122 at 318 (were 80–85 at 286)
8080 return lines;
8181}
8282
83+/** A stored pipeline run as runRuns lists it: what the CI lines need of it. */
84+interface StoredRun {
85+ readonly id: number;
86+ readonly version: number;
87+ readonly state: string;
88+ readonly file: string;
89+}
91+/** The stored pipeline runs, newest first, from the server's `pipelines` read; empty for anything else. */
92+export function storedRuns(raw: unknown): StoredRun[] {
93+ const runs = (raw as { runs?: unknown } | null)?.runs;
94+ if (!Array.isArray(runs)) return [];
95+ return runs.filter(
96+ (r): r is StoredRun =>
97+ typeof r === "object" &&
98+ r !== null &&
99+ Number.isInteger((r as StoredRun).id) &&
100+ Number.isInteger((r as StoredRun).version) &&
101+ typeof (r as StoredRun).state === "string" &&
102+ typeof (r as StoredRun).file === "string",
103+ );
104+}
106+/** One stored run in a line, with where its jobs are. */
107+export function runLine(run: StoredRun): string {
108+ const how = run.state === "planned" ? "was planned, not run," : run.state === "running" ? "is running" : run.state;
109+ return `Pipeline run ${run.id} (${run.file}) ${how} on version ${run.version}. abso pipeline runs ${run.id} shows its jobs.`;
110+}
112+/**
113+ * Whether the built-in check (abso.json's setup, build and check) had nothing of its own to run. With stored runs, that is
114+ * about the built-in check, not the project's CI, so it isn't said as the project's (abso 719).
115+ */
116+export function builtInHasNothing(ci: CiStatus): boolean {
117+ return ci.red === null && ci.skipped?.reason.startsWith("nothing to run") === true;
118+}
83120/** A shared version's mark in abso log; "not checked" says nothing, since most versions in a busy hour are covered by a newer one's job. */
84121export function ciMarkText(mark: CiMark | undefined): string {
85122 switch (mark) {
Lines 180–199 at 318 (were 143–153 at 286)
143180 }
144181 if (typed !== undefined) {
145182 if (!/^\d+$/.test(typed)) throw new UsageError(`a version is a number (got ${JSON.stringify(typed)})`);
146− const job = await api.ci(Number(typed));
147− return { text: jobText(job).join("\n"), json: { ...job } };
183+ const [job, raw] = await Promise.all([api.ci(Number(typed)), api.pipelineRuns().catch(() => null)]);
184+ const run = storedRuns(raw).find((r) => r.version === job.version);
185+ // A version the built-in check never ran, with a pipeline run of its own: the run is its CI (abso 719).
186+ const text = run !== undefined && job.result === "none" ? [runLine(run)] : jobText(job);
187+ return { text: text.join("\n"), json: { ...job } };
148188 }
149− const [ci, status] = await Promise.all([api.ci(), api.status()]);
150− const lines = ciText(ci, status.version);
189+ const [ci, status, raw] = await Promise.all([api.ci(), api.status(), api.pipelineRuns().catch(() => null)]);
190+ const newest = storedRuns(raw)[0];
191+ const lines =
192+ newest === undefined
193+ ? ciText(ci, status.version)
194+ : builtInHasNothing(ci)
195+ ? [runLine(newest)]
196+ : [...ciText(ci, status.version), runLine(newest)];
151197 return {
152198 text: [
153199 `shared is at version ${status.version}.`,
Lines 2–7 at 318 (were 2–8 at 286)
22
33import { createHash } from "node:crypto";
44import { hostname } from "node:os";
5−import { basename } from "node:path";
65import { callerHeader } from "../../src/caller.ts";
76import { Api, type News, newsLines, type RunKind, takeSeatNotices } from "./api.ts";
87import { UsageError } from "./args.ts";
Lines 59–71 at 318 (were 60–66 at 286)
6059 */
6160export function callerFor(session: string | undefined, machine: string, root: string): string | undefined {
6261 const hashed = session ? createHash("sha256").update(session).digest("hex").slice(0, 16) : undefined;
63− return callerHeader({ session: hashed, machine, folder: basename(root) });
62+ // The last part on either separator, so a Windows path names its folder on any machine.
63+ const folder =
64+ root
65+ .split(/[\\/]+/)
66+ .filter((p) => p !== "")
67+ .at(-1) ?? "";
68+ return callerHeader({ session: hashed, machine, folder });
6469}
6570
6671/**
Lines 11–17 at 318 (were 11–16 at 286)
1111import { UsageError } from "./args.ts";
1212import { type MachineServers, machineServers, TOKEN_SERVERS, tokenGoesTo, trustedList } from "./core.ts";
1313import { fromEnv } from "./env-names.ts";
14+import { isLocal, storeDir } from "./local-store.ts";
1415import { homeFile, stateDir } from "./state-dir.ts";
1516
1617/** What .avcs/config.json holds. */
Lines 28–41 at 318 (were 27–36 at 286)
2728 * routes anyone can read and sends no credential. It has no agent; its config holds server, project and this.
2829 */
2930 readonly visitor?: boolean;
31+ /** A local project's store (abso init --local --store), when it isn't the machine's own: ABSO_STORE or the OS data folder. */
32+ readonly store?: string;
3033}
3134
3235export interface Config extends Settings {
3336 readonly token?: string;
37+ /** For a local project (server "local"): the store folder its history is in, or undefined when there's none to use. */
38+ readonly localStore?: string;
3439}
3540
3641export function configPath(root: string): string {
Lines 69–83 at 318 (were 64–74 at 286)
6469 for (const key of ["server", "project", "agent"] as const) {
6570 if (typeof raw[key] !== "string" || raw[key] === "") throw new Error(`${configPath(root)} has no "${key}"`);
6671 }
67− const token = tokenFor(raw.server!, env, root, tokenFileOk);
72+ // A local project's calls never leave this process, so no credential goes with them.
73+ const local = isLocal(raw.server);
74+ const token = local ? undefined : tokenFor(raw.server!, env, root, tokenFileOk);
6875 return {
6976 server: raw.server!,
7077 project: raw.project!,
7178 agent: raw.agent!,
79+ ...(typeof raw.store === "string" && raw.store !== "" ? { store: raw.store } : {}),
80+ ...(local ? { localStore: storeDir(env, raw.store, root) } : {}),
7281 ...(typeof raw.follow === "string" && raw.follow !== "" ? { follow: raw.follow } : {}),
7382 ...(raw.reader === true ? { reader: true } : {}),
7483 ...(token ? { token } : {}),
Lines 284–300 at 318 (were 275–284 at 286)
275284
276285export function writeConfig(root: string, settings: Settings): void {
277286 mkdirSync(stateDir(root), { recursive: true });
278− const { server, project, agent, follow, reader, visitor } = settings;
287+ const { server, project, agent, follow, reader, visitor, store } = settings;
279288 const written = visitor
280289 ? { server, project, visitor: true }
281− : { server, project, agent, ...(follow ? { follow } : {}), ...(reader ? { reader: true } : {}) };
290+ : {
291+ server,
292+ project,
293+ agent,
294+ ...(follow ? { follow } : {}),
295+ ...(reader ? { reader: true } : {}),
296+ ...(store ? { store } : {}),
297+ };
282298 writeFileSync(configPath(root), `${JSON.stringify(written, null, 2)}\n`);
283299 excludeFromGit(root);
284300}
new file, 13 lines
1+// What `import { DurableObject } from "cloudflare:workers"` gives the open server's code when it runs inside the client
2+// for a local project (local-store.ts): a base class that keeps the object's state and settings, which is all the
3+// project object takes from it. The build points that import here (scripts/build-client.mjs); run as .ts files, a
4+// module hook does (local-store.ts).
5+
6+export class DurableObject<Env = unknown> {
7+ ctx: unknown;
8+ env: Env;
9+ constructor(ctx: unknown, env: Env) {
10+ this.ctx = ctx;
11+ this.env = env;
12+ }
13+}
Lines 94–101 at 318 (were 94–99 at 286)
9494 /** For tests: the rename that moves each file into place. */
9595 readonly rename?: (from: string, to: string) => void;
9696 readonly now?: Date;
97+ /** For tests: the command stamped as HOOK_COMMAND, instead of this client's own `abso hook`. */
98+ readonly hookCommand?: readonly string[];
9799}
98100
99101const RECORD = ".avcs-install.json";
Lines 134–148 at 318 (were 132–137 at 286)
132134 existsSync(at(skillsFolder(AVCS_MOD.name, env), MANIFEST)) ||
133135 existsSync(at(skillsFolder(OLD_MOD_NAMES[AVCS_MOD.name]!, env), MANIFEST));
134136
137+/** Whether the installed abso mod hands a local project's edits to abso hook: it was installed with a HOOK_COMMAND. */
138+export function modHandsLocal(env: Readonly<Record<string, string | undefined>> = process.env): boolean {
139+ try {
140+ return /HOOK_COMMAND[^=\n]*=\s*\[/.test(readFileSync(at(skillsFolder(AVCS_MOD.name, env), STAMP_FILE), "utf8"));
141+ } catch {
142+ return false;
143+ }
144+}
135146/**
136147 * After the new mod is in, the folder it replaces (skills/avcs, skills/avcs-view) would load beside it, so it
137148 * is moved, not deleted, to ~/.abso/retired-mods/<name>-<stamp>. Returns where it went, or undefined when there was none.
Lines 237–247 at 318 (were 226–233 at 286)
226237 return commit;
227238}
228239
229−/** The files to install, stamped with `version`, in install order. */
230−function filesFor(spec: ModSpec, version: string): Map<string, Buffer> {
240+/** The command that runs this checkout's `abso hook`: what the mod hands a local project's edits to. */
241+export const hookCommand = (): readonly string[] => [process.execPath, join(CLIENT_DIR, "abso.ts"), "hook"];
243+/** The files to install, stamped with `version` (and HOOK_COMMAND, where a stamp.ts has it), in install order. */
244+function filesFor(spec: ModSpec, version: string, hook: readonly string[] = hookCommand()): Map<string, Buffer> {
231245 if (!/^[\w.+-]+$/.test(version)) throw new Error(`can't stamp the version ${JSON.stringify(version)}`);
232246 const out = new Map<string, Buffer>();
233247 for (const rel of spec.files) {
Lines 253–261 at 318 (were 239–245 at 286)
239253 const text = data.toString("utf8");
240254 const stamped = text.replace(/(STAMP[^=\n]*=\s*)undefined/, `$1'${version}'`);
241255 if (stamped === text) throw new Error(`${rel} has no "STAMP ... = undefined" line to stamp`);
242− data = Buffer.from(stamped);
256+ data = Buffer.from(
257+ stamped.replace(/(HOOK_COMMAND[^=\n]*=\s*)undefined/, (_, head: string) => head + JSON.stringify(hook)),
258+ );
243259 }
244260 out.set(rel, data);
245261 }
Lines 402–408 at 318 (were 386–392 at 286)
386402export function installMod(spec: ModSpec, options: InstallOptions): Installed {
387403 const target = resolve(options.target);
388404 const version = versionFor(spec, options.commit);
389− const next = filesFor(spec, version);
405+ const next = filesFor(spec, version, options.hookCommand);
390406 const existed = existsSync(target);
391407 mkdirSync(target, { recursive: true });
392408 try {
Lines 28–34 at 318 (were 28–33 at 286)
2828import { ignoredHere } from "./fetch.ts";
2929import { loadIgnore, relativeTo } from "./folder.ts";
3030import type { AskReply } from "./issues-wire.ts";
31+import { isLocal, LOCAL_BASE } from "./local-store.ts";
3132import { queuedLines, standing } from "./queue.ts";
3233import { seenText, shortWhen } from "./times.ts";
3334
Lines 37–47 at 318 (were 36–41 at 286)
3637/** The folder, with its Api pointed at the Issues Worker: the token goes only where tokenGoesTo allows, as for the avcs server. */
3738export function openIssues(env: Env): { root: string; config: Config; api: Api } {
3839 const { root, config, api } = open(env);
40+ // A local project's issues are in its store, where the open server keeps them: at /issues.
41+ if (isLocal(config.server)) {
42+ api.issuesServer = `${LOCAL_BASE}/issues`;
43+ return { root, config, api };
44+ }
3945 // An explicit --server goes to that server's own Issues Worker: ABSO_ISSUES_SERVER doesn't redirect it.
4046 const server =
4147 (env.server === undefined ? fromEnv(env.env, "ISSUES_SERVER") : undefined) ||
Lines 2–8 at 318 (were 2–8 at 286)
22
33import { randomUUID } from "node:crypto";
44import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
5−import { join, relative, resolve } from "node:path";
5+import { isAbsolute, join, relative, resolve, sep } from "node:path";
66import { Api, ApiError, type SyncAnswer } from "./api.ts";
77import { bool, type Parsed, str, UsageError } from "./args.ts";
88import { writeKnownBlobs } from "./blobs.ts";
Lines 32–39 at 318 (were 32–38 at 286)
3232import { elsewhereText } from "./doctor.ts";
3333import { fromEnv } from "./env-names.ts";
3434import { clearKnown, loadIgnore, readFolder, writeKnown } from "./folder.ts";
35−import { installerCommand, modInstalled } from "./install.ts";
35+import { installerCommand, modHandsLocal, modInstalled } from "./install.ts";
36+import { LOCAL, NO_STORE, storeDir } from "./local-store.ts";
3637import { type FullMode, foldModes, writeKnownModes } from "./modes.ts";
3738import { initInOrg, siteOf } from "./orgs.ts";
3839import { projectFileName, readProjectFile, startingProjectFileText, writeStartingProjectFile } from "./project-file.ts";
Lines 102–149 at 318 (were 101–106 at 286)
101102 return undefined;
102103}
103104
105+/**
106+ * --local (abso init, abso join): the project's history is in a store on this machine, not on a server. The store is
107+ * --store, else ABSO_STORE, else the OS's data folder; one given with --store is kept in the folder's config.
108+ */
109+function localFrom(args: Parsed, env: Env, command: string): { dir: string; settings: { store?: string } } | undefined {
110+ const store = str(args, "store");
111+ if (!bool(args, "local")) {
112+ if (store !== undefined)
113+ throw new UsageError("--store goes with --local: it says where a local project's history is");
114+ return undefined;
115+ }
116+ if (str(args, "server") !== undefined)
117+ throw new UsageError("--local or --server, not both: a local project has no server");
118+ if (str(args, "org") !== undefined || bool(args, "public") || bool(args, "private") || bool(args, "reader"))
119+ throw new UsageError(
120+ `abso ${command} --local takes --project, --agent, --store and --as-is; a local project has no server to share it`,
121+ );
122+ const dir = storeDir(env.env, store, env.cwd);
123+ if (dir === undefined) throw new UsageError(NO_STORE);
124+ return { dir, settings: store === undefined ? {} : { store: dir } };
125+}
127+/** A store inside the project folder is left out of its files: a line in .absoignore. Its relative path, if so. */
128+function ignoreStoreInside(root: string, dir: string): string | undefined {
129+ const rel = relative(root, dir);
130+ if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) return undefined;
131+ const line = `/${rel.split(sep).join("/")}/`;
132+ const file = join(root, ".absoignore");
133+ const had = existsSync(file) ? readFileSync(file, "utf8") : "";
134+ const lines = had.split(/\r?\n/);
135+ if (!lines.includes(line)) {
136+ const gap = had === "" || had.endsWith("\n") ? "" : "\n";
137+ writeFileSync(file, `${had}${gap}${line}\n`);
138+ }
139+ return rel;
140+}
142+/** What init and join say about a local project's store. */
143+function localText(dir: string, project: string, ignored?: string): string {
144+ return `It's a local project: its history is in ${join(dir, project)}, on this machine, and no server is needed.${ignored === undefined ? "" : ` .absoignore leaves the store, ${ignored}, out of the project's files.`}`;
145+}
104147/** Why a token file is no fallback: said when one is here and nothing else signs in. */
105148const TOKEN_FILE_ASKED = "~/.abso/token is used only with --token-file.";
106149
Lines 154–200 at 318 (were 111–146 at 286)
111154 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);
112155 const project = str(args, "project");
113156 if (!project) throw new UsageError("give the project a name with --project <name>");
157+ // Checked before any call: a name like ".." would otherwise go out as part of the request's path.
158+ if (!NAME.test(project))
159+ throw new UsageError(
160+ `project names are letters, digits, dot, dash and underscore (got ${JSON.stringify(project)})`,
161+ );
114162 if (bool(args, "public") && bool(args, "private")) throw new UsageError("--public or --private, not both");
163+ const local = localFrom(args, env, "init");
115164 // A box signed in here, and no other credential asked for: the project is made as the person who approved the box,
116165 // the way the website makes one (abso 663). The token file only with --token-file, never by itself.
117− const server = serverFrom(args, env);
118− const box = readBox(server);
119− const credential = tokenCredential(args, env.env, server, root);
166+ const server = local ? LOCAL : serverFrom(args, env);
167+ const box = local ? undefined : readBox(server);
168+ const credential = local ? undefined : tokenCredential(args, env.env, server, root);
120169 const say = env.writeErr ?? env.write;
121170 if (box && credential === undefined) {
122171 say(`Signing in with this box's sign-in, ${box.id}.
123172`);
124173 return initFromBox(args, env, root, project, server, box);
125174 }
126− if (credential === undefined && tokenFile() !== undefined)
175+ if (!local && credential === undefined && tokenFile() !== undefined)
127176 throw new UsageError(
128177 `abso init signs in with this box's sign-in, and this box isn't signed in to ${server}: abso login signs it in. ${TOKEN_FILE_ASKED}`,
129178 );
130179 const org = str(args, "org");
131180 if (org !== undefined) return initInOrg(org, server);
132− const config = makeSettings(args, env, project);
181+ const config: Settings = local
182+ ? { server: LOCAL, project, agent: agentFrom(args, str(args, "agent") ?? defaultAgentName()), ...local.settings }
183+ : makeSettings(args, env, project);
133184 const asIs = bool(args, "as-is");
134185 const absoignore = join(root, ".absoignore");
135186 const wroteIgnore = !asIs && !existsSync(absoignore) && !existsSync(join(root, ".avcsignore"));
136187 if (wroteIgnore) writeFileSync(absoignore, STARTING_ABSOIGNORE);
188+ // A store kept inside the project folder, like a virtual environment, isn't the project's files.
189+ const ignoredStore = local ? ignoreStoreInside(root, local.dir) : undefined;
137190 // What the server runs on each new version (#39), guessed from package.json; recorded with the rest.
138191 const wroteProject = asIs ? "exists" : writeStartingProjectFile(root);
139192 const { files, blobs, modes, leftOut } = readFolder(root, loadIgnore(root));
140193 const token = credential?.token;
141− say(`Signing in with ${credential?.words ?? `no credential: nothing here signs in to ${server}`}.
194+ if (!local)
195+ say(`Signing in with ${credential?.words ?? `no credential: nothing here signs in to ${server}`}.
142196`);
143− const api = new Api({ ...config, ...(token ? { token } : {}) });
197+ const api = new Api({ ...config, ...(token ? { token } : {}), ...(local ? { localStore: local.dir } : {}) });
144198 let answer: Awaited<ReturnType<Api["init"]>>;
145199 try {
146200 await uploadBlobs(api, blobs);
Lines 224–237 at 318 (were 170–181 at 286)
170224 ...(wroteIgnore
171225 ? ["Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore."]
172226 : []),
173− ...startingProjectFileText(wroteProject),
227+ // A local project has no CI to run abso.json, so no word about one that isn't there.
228+ ...(local && wroteProject === "nothing" ? [] : startingProjectFileText(wroteProject)),
174229 ...(answer.skipped && answer.skipped.length > 0 ? [`The server skipped: ${answer.skipped.join(", ")}.`] : []),
230+ ...(local ? [localText(local.dir, project, ignoredStore)] : []),
175231 `This folder is agent ${config.agent}. Settings are in .abso/config.json.`,
176232 ...refusedText(synced.refused),
177233 ...(synced.kept.length > 0 ? [`Kept your copy of ${synced.kept.join(", ")}.`] : []),
178− hookHint(env.env),
234+ hookHint(env.env, local !== undefined),
179235 ].join("\n"),
180236 json: {
181237 project,
Lines 242–248 at 318 (were 186–191 at 286)
186242 wroteAbsoignore: wroteIgnore,
187243 wroteProjectFile: typeof wroteProject === "string" ? null : wroteProject,
188244 leftOut,
245+ ...(local ? { store: local.dir } : {}),
189246 },
190247 };
191248}
Lines 437–453 at 318 (were 380–393 at 286)
380437 mkdirSync(root, { recursive: true });
381438 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);
382439 const reader = bool(args, "reader");
383− const server = serverFrom(args, env);
384− const box = readBox(server);
385− const hasKey = existsSync(join(stateDir(root), "key"));
386− const credential = tokenCredential(args, env.env, server, root);
440+ // A local project: no box, key or credential, and the agent is --agent or this computer's name.
441+ const local = localFrom(args, env, "join");
442+ const server = local ? LOCAL : serverFrom(args, env);
443+ const box = local ? undefined : readBox(server);
444+ const hasKey = !local && existsSync(join(stateDir(root), "key"));
445+ const credential = local ? undefined : tokenCredential(args, env.env, server, root);
387446 const tokenFileAsked = bool(args, "token-file");
388447 let agent: string;
389448 let minted: { key: string; id: string } | undefined;
390− if (str(args, "agent") !== undefined) {
449+ if (local) agent = agentFrom(args, str(args, "agent") ?? defaultAgentName());
450+ else if (str(args, "agent") !== undefined) {
391451 agent = agentFrom(args);
392452 minted =
393453 box && !hasKey && !fromEnv(env.env, "KEY_FILE") && !tokenFileAsked
Lines 472–478 at 318 (were 412–418 at 286)
412472 agent = free.agent;
413473 minted = { key: free.key, id: free.id };
414474 }
415− const config = { server, project, agent, ...(reader ? { reader: true } : {}) };
475+ const config = { server, project, agent, ...(reader ? { reader: true } : {}), ...local?.settings };
416476 writeConfig(root, config);
417477 clearKnown(root);
418478 if (minted) installKey(root, JSON.stringify(minted));
Lines 485–495 at 318 (were 425–434 at 286)
425485 throw error;
426486 }
427487 const settings = tokenFileAsked ? { ...read, token: credential?.token } : read;
428− (env.writeErr ?? env.write)(
429− `Signing in with ${minted && box ? `a new key from this box's sign-in, ${box.id}` : hasKey ? "this folder's key" : (credential?.words ?? `no credential: nothing here signs in to ${server}`)}.
488+ if (!local)
489+ (env.writeErr ?? env.write)(
490+ `Signing in with ${minted && box ? `a new key from this box's sign-in, ${box.id}` : hasKey ? "this folder's key" : (credential?.words ?? `no credential: nothing here signs in to ${server}`)}.
430491`,
431− );
492+ );
432493 const api = new Api(settings);
433494 let answer: SyncAnswer;
434495 try {
Lines 515–524 at 318 (were 454–462 at 286)
454515 `These files were already here and differ from shared, so they were left alone: ${synced.kept.join(", ")}. abso record sends them as your changes.`,
455516 ]
456517 : []),
518+ ...(local ? [localText(local.dir, project)] : []),
457519 ...emptyHint(synced.version, synced.written.length, synced.kept.length, reader),
458520 ...setupHint(root),
459− hookHint(env.env),
521+ hookHint(env.env, local !== undefined),
460522 ...(root === resolve(env.cwd) ? [] : [`cd ${relative(env.cwd, root) || root}`]),
461523 ].join("\n"),
462524 json: {
Lines 542–556 at 318 (were 480–486 at 286)
480542 : [`Nothing is installed yet. Before building or testing here, run ${projectFileName(root)}'s setup: ${setup}`];
481543}
482544
483−function hookHint(env: Readonly<Record<string, string | undefined>>): string {
545+function hookHint(env: Readonly<Record<string, string | undefined>>, local = false): string {
546+ // A local project has no server: the mod hands its edits to abso hook, when it was installed with one to hand them to.
547+ if (local) {
548+ if (modHandsLocal(env))
549+ return "Edits made by Claude Code here are recorded by the abso mod on this machine, through abso hook. Anything else: abso record.";
550+ if (modInstalled(env) && !builtCopy())
551+ return `abso record sends the edits made here: the abso mod on this machine is older than local projects. ${installerCommand("install-mod.ts")} updates it, and new chats load it.`;
552+ return "abso record sends the edits made here, whoever made them.";
553+ }
484554 if (modInstalled(env))
485555 return "Edits made by Claude Code here are recorded by the abso mod on this machine, signed in as this folder. Anything else: abso record.";
486556 // A built copy (the npm package) has no installer to point at (abso-core 18).
new file, 5 lines
1+// The types of local-server.mjs: as much of the open server as the client calls.
2+export declare function handle(request: Request, env: unknown, ctx: unknown, issues: unknown): Promise<Response>;
3+export declare const ProjectObject: new (ctx: unknown, env: unknown) => object;
4+export declare const IssueProject: new (ctx: unknown, env: unknown) => object;
5+export declare function issuesFetch(request: Request, env: unknown, ctx: unknown, route: unknown): Promise<Response>;
new file, 7 lines
1+// The open server's router, project object and issues, for local projects (local-store.ts). Plain JS, with its types
2+// in local-server.d.mts, so the client's typecheck stops here: server/src is typechecked with the Workers' types
3+// (server/tsconfig.json). The build and Node follow these imports as usual.
4+
5+export { IssueProject, issuesFetch } from "../../server/src/issues-entry.ts";
6+export { ProjectObject } from "../../server/src/project-object.ts";
7+export { handle } from "../../server/src/router.ts";
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+}
Lines 59–65 at 318 (were 59–64 at 286)
5959 runWaiting,
6060} from "./issues.ts";
6161import { adminToken, adminTokenWords, issuedPublic, keyList, keyListText, keyNew, keyRevoke } from "./key-admin.ts";
62+import { closeLocalStores } from "./local-store.ts";
6263import { browserSkip, openInBrowser } from "./open-browser.ts";
6364import { runOrg, runOrgs } from "./orgs.ts";
6465import { runUnqueue } from "./queue.ts";
Lines 79–85 at 318 (were 78–83 at 286)
7879import { runAmend, runDrop, runFollow, runLabel, runLabels, runPluck } from "./versions.ts";
7980import { runVisibility } from "./visibility-commands.ts";
8081import { checkVisitor } from "./visitor.ts";
82+import { handoffText, patFromFile, webLogin } from "./web-session.ts";
8183
8284interface CommandDef {
8385 readonly flags: FlagSpec;
Lines 123–135 at 318 (were 121–131 at 286)
121123 public: "boolean",
122124 private: "boolean",
123125 "token-file": "boolean",
126+ local: "boolean",
127+ store: "string",
124128 },
125129 usage:
126− "abso init [folder] --project <name> [--agent <name>] [--as-is] [--org <org>] [--public|--private] [--token-file]",
130+ "abso init [folder] --project <name> [--agent <name>] [--as-is] [--org <org>] [--public|--private] [--token-file] | abso init [folder] --local --project <name> [--agent <name>] [--store <folder>] [--as-is]",
127131 about:
128− "Create a project on the server from a folder's text files. The folder becomes that agent's folder. It writes a starting .absoignore, and, when the folder has no abso.json and package.json gives a check or a build to guess, an abso.json (setup, check, build and out): what the server's CI runs on each new version of shared. Without one, CI runs what it can guess itself, or nothing. --as-is writes neither: the folder goes up exactly as it is (an import). On a server this box is signed in to (abso login, approving all your projects), the project is made as you, the way the website's New project makes it: you own it, it's private unless you say --public, and the folder joins it at once with its own key (--agent names it; else the box's name). --org <org> makes it that organization's project. Elsewhere it needs --agent and a token: ABSO_TOKEN, or with --token-file this machine's ~/.abso/token, which is never used unasked. Before it makes anything, it says what it signs in with.",
132+ "Create a project on the server from a folder's text files. The folder becomes that agent's folder. It writes a starting .absoignore, and, when the folder has no abso.json and package.json gives a check or a build to guess, an abso.json (setup, check, build and out): what the server's CI runs on each new version of shared. Without one, CI runs what it can guess itself, or nothing. --as-is writes neither: the folder goes up exactly as it is (an import). On a server this box is signed in to (abso login, approving all your projects), the project is made as you, the way the website's New project makes it: you own it, it's private unless you say --public, and the folder joins it at once with its own key (--agent names it; else the box's name). --org <org> makes it that organization's project. Elsewhere it needs --agent and a token: ABSO_TOKEN, or with --token-file this machine's ~/.abso/token, which is never used unasked. Before it makes anything, it says what it signs in with. --local makes a local project instead: its history is kept on this machine, in a store folder, and no server, sign-in or network is needed (Node 22.13 or later). The store is --store <folder> (kept in the folder's settings; inside the folder, .absoignore leaves it out), else ABSO_STORE, else this user's data folder (%LOCALAPPDATA%\\abso\\store, ~/Library/Application Support/abso/store, or $XDG_DATA_HOME/abso/store). The agent is --agent, else this computer's name.",
129133 run: (args, env) => runInit(args, env),
130134 },
131135 key: {
Lines 213–244 at 318 (were 209–221 at 286)
209213 projects: "string",
210214 role: "string",
211215 days: "string",
216+ web: "boolean",
217+ site: "string",
218+ "pat-file": "string",
212219 },
213220 usage:
214− "abso login [--no-browser] [--no-ask] [--projects <name,name>] [--role <reader|writer|owner>] [--days <1-90>]",
221+ "abso login [--no-browser] [--no-ask] [--projects <name,name>] [--role <reader|writer|owner>] [--days <1-90>] | abso login --web [--pat-file <file> [--site http://localhost:<port>]]",
215222 about:
216− "Sign this box in once: it opens the approve page in your browser with the code filled in, prints the link and the code too, and waits while a person approves the code on the website, choosing the projects, the highest role and how long. Then abso join in any of those projects gives each agent its own key, with no approval. The box's sign-in is kept in your user folder, never in a project folder, and is never printed. No browser opens with --no-browser or ABSO_NO_BROWSER, over SSH, under CI, or on Linux without a display. In an agent's folder on the same server, it also asks a person in that project to approve it (the person who approved the agent's box, else the project's owners), as an abso ask, so nobody has to relay the code; the box can then be granted that project at no more than the agent's own role. --no-ask shows the code only.",
223+ "Sign this box in once: it opens the approve page in your browser with the code filled in, prints the link and the code too, and waits while a person approves the code on the website, choosing the projects, the highest role and how long. Then abso join in any of those projects gives each agent its own key, with no approval. The box's sign-in is kept in your user folder, never in a project folder, and is never printed. No browser opens with --no-browser or ABSO_NO_BROWSER, over SSH, under CI, or on Linux without a display. In an agent's folder on the same server, it also asks a person in that project to approve it (the person who approved the agent's box, else the project's owners), as an abso ask, so nobody has to relay the code; the box can then be granted that project at no more than the agent's own role. --no-ask shows the code only. --web, on staging only, signs a browser in to the website instead: it prints a link that works once, within a minute, and signs whichever browser opens it in as the person who approved this box, but only to the projects the box was granted and at most as a writer, until the box is revoked or ends (or, with --pat-file, as the test account whose PAT that file holds, at most as a writer). It writes issues, replies, answers, groups and announcements, and changes no members, roles, visibility, keys, boxes or settings. The box's sign-in, the PAT and the session never appear. It goes only to the staging website beside this folder's staging server; any other server, prod included, is refused and nothing is sent. --site, with --pat-file only, points it at a website on this machine (http://localhost or 127.0.0.1).",
217224 run: async (args, env) => {
218225 const server = boxServer(args, env);
226+ if (bool(args, "web")) {
227+ const patFile = str(args, "pat-file");
228+ const { handoff, site } = await webLogin({
229+ server,
230+ site: str(args, "site"),
231+ kind: patFile === undefined ? "box" : "pat",
232+ credential: () => {
233+ if (patFile !== undefined) return patFromFile(patFile);
234+ const record = readBox(server);
235+ if (record === undefined || record.expiresAt <= Date.now())
236+ throw new UsageError(`this box isn't signed in to ${server}: abso login first, or --pat-file <file>`);
237+ return record.credential;
238+ },
239+ });
240+ return { text: handoffText(handoff, site, patFile === undefined), json: { ...handoff } };
241+ }
219242 const open =
220243 bool(args, "no-browser") || browserSkip(env.env, process.platform) !== null
221244 ? undefined
Lines 350–368 at 318 (were 327–336 at 286)
327350 },
328351 },
329352 join: {
330− flags: { server: "string", agent: "string", dir: "string", reader: "boolean", "token-file": "boolean" },
331− usage: "abso join <project> [--agent <name>] [--dir <folder>] [--reader] [--token-file]",
353+ flags: {
354+ server: "string",
355+ agent: "string",
356+ dir: "string",
357+ reader: "boolean",
358+ "token-file": "boolean",
359+ local: "boolean",
360+ store: "string",
361+ },
362+ usage:
363+ "abso join <project> [--agent <name>] [--dir <folder>] [--reader] [--token-file] | abso join <project> --local [--agent <name>] [--store <folder>] [--dir <folder>]",
332364 about:
333− "Join a project as a new agent and write its shared files into a folder: --dir, else here when this folder is empty, else ./<project> (which has to be new or empty). Without --agent the agent is named after this box (the name abso login gave it, lower-cased), or the next free <name>-2, <name>-3; that needs the box signed in with abso login. --reader joins as a reader: it reads everything and records nothing, and the server refuses its edits, records and pushes. With --reader and no sign-in, a public project is joined to read signed out: the folder holds only its settings, sends no sign-in, and runs status, log, show, files, blame, why, where, issues, issue and search; every other command is refused. It says what it signs in with: a new key from this box's sign-in, the folder's key, or ABSO_TOKEN; this machine's ~/.abso/token only with --token-file, never unasked.",
365+ "Join a project as a new agent and write its shared files into a folder: --dir, else here when this folder is empty, else ./<project> (which has to be new or empty). Without --agent the agent is named after this box (the name abso login gave it, lower-cased), or the next free <name>-2, <name>-3; that needs the box signed in with abso login. --reader joins as a reader: it reads everything and records nothing, and the server refuses its edits, records and pushes. With --reader and no sign-in, a public project is joined to read signed out: the folder holds only its settings, sends no sign-in, and runs status, log, show, files, blame, why, where, issues, issue and search; every other command is refused. It says what it signs in with: a new key from this box's sign-in, the folder's key, or ABSO_TOKEN; this machine's ~/.abso/token only with --token-file, never unasked. --local joins a local project (abso init --local) from the same store: --store, else ABSO_STORE, else this user's data folder; the agent is --agent, else this computer's name.",
334366 run: runJoin,
335367 },
336368 record: {
Lines 1021–1035 at 318 (were 989–994 at 286)
9891021}
9901022
9911023export async function main(argv: readonly string[], env: Env): Promise<MainResult> {
1024+ try {
1025+ return await runMain(argv, env);
1026+ } finally {
1027+ // A local project's store stays open only while its command runs.
1028+ closeLocalStores();
1029+ }
1032+async function runMain(argv: readonly string[], env: Env): Promise<MainResult> {
9921033 const command = argv[0];
9931034 const json = argv.includes("--json") && command !== "run" && command !== "logs";
9941035 const asked = argv.includes("--token-file");
Lines 94–101 at 318 (were 94–99 at 286)
9494 sleep(ms: number): Promise<void>;
9595 now(): number;
9696 every(ms: number, fn: () => void): () => void;
97+ /** Reads the seat's news, marking it heard (POST news); a frame calls it. Without it, frames are printed as they come. */
98+ take?(): Promise<readonly string[]>;
9799 /** Called when a socket opens and at each ping: the stream is held until the next ping is due, and a little more. */
98100 held?(until: number): void;
99101 /** Set when --follow should stop (Ctrl-C, or a test). */
Lines 109–163 at 318 (were 107–116 at 286)
107109}
108110
109111/**
112+ * A frame is a wake (abso 690): on one, read the seat's news (which marks it heard) and print what that answers, one
113+ * read at a time, with frames that arrive meanwhile folded into one more read. When the read answers nothing (a server
114+ * that counts a frame as heard already, or another chat on the seat took it first), the frames themselves are printed.
115+ */
116+function frameReads(deps: FollowDeps): { frame(text: string): void; idle(): Promise<void> } {
117+ let frames: string[] = [];
118+ /** The lines printed lately, so a frame a read already printed isn't printed again. */
119+ const shown: string[] = [];
120+ const show = (line: string) => {
121+ deps.write(line);
122+ shown.push(line);
123+ if (shown.length > 200) shown.shift();
124+ };
125+ let running: Promise<void> | undefined;
126+ let again = false;
127+ const pass = async () => {
128+ do {
129+ again = false;
130+ const these = frames;
131+ frames = [];
132+ let items: readonly string[] = [];
133+ try {
134+ items = await deps.take!();
135+ } catch (err) {
136+ deps.note(`(abso news --follow: couldn't read the news: ${(err as Error).message}; showing the frames)`);
137+ }
138+ for (const line of items) show(line);
139+ // A frame the read didn't cover still shows: on a server that counts a frame as heard, its item never comes back
140+ // from the read. A catch-up frame names several items, so a frame holding a shown item counts as covered.
141+ for (const frame of these) if (!shown.some((line) => frame.includes(line) || line.includes(frame))) show(frame);
142+ } while (again);
143+ running = undefined;
144+ };
145+ return {
146+ frame(text) {
147+ frames.push(text);
148+ if (running !== undefined) again = true;
149+ else running = pass();
150+ },
151+ idle: () => running ?? Promise.resolve(),
152+ };
153+}
155+/**
110156 * Holds the seat's stream, printing one line per item, until the key is refused or `stopped()`.
111157 * Returns why it ended.
112158 */
113159export async function follow(deps: FollowDeps): Promise<{ ended: "refused" | "stopped"; reason: string }> {
160+ const reads = frameReads(deps);
114161 let wait = 1_000;
115162 while (!deps.stopped()) {
116163 let ticket: NewsTicket;
Lines 186–198 at 318 (were 139–150 at 286)
139186 };
140187 socket.onmessage = (e) => {
141188 if (typeof e.data !== "string" || e.data === PONG) return;
142− deps.write(e.data);
189+ if (deps.take === undefined) deps.write(e.data);
190+ else reads.frame(e.data);
143191 };
144192 socket.onerror = () => {};
145193 socket.onclose = (e) => {
146194 stopPing();
147− done({ code: e.code, reason: e.reason });
195+ void reads.idle().then(() => done({ code: e.code, reason: e.reason }));
148196 };
149197 });
150198 if (isRefusal(closed.code)) return { ended: "refused", reason: closed.reason || `closed ${closed.code}` };
Lines 40–46 at 318 (were 40–45 at 286)
4040} from "./folder.ts";
4141import { fileArg } from "./history.ts";
4242import { modsBehindText } from "./install.ts";
43+import { isLocal } from "./local-store.ts";
4344import { withFolderLock } from "./lock.ts";
4445import { readKnownModes, writeKnownModes } from "./modes.ts";
4546import { queueText } from "./queue.ts";
Lines 326–336 at 318 (were 325–333 at 286)
325326 const space = (draft: string | null | undefined): string => (draft ? `draft ${draft}` : "shared");
326327 const parked = (me?.parked ?? []).filter((p) => p.draftChanges > 0);
327328 const credential = credentialLabel(root, config.server, env.env);
328− const behind = await newerClientNote(config.server);
329+ // A local project reaches for nothing on the network, npm included.
330+ const localProject = isLocal(config.server);
331+ const behind = localProject ? undefined : await newerClientNote(config.server);
329332 const lines = [
330− `Project ${config.project}: shared is at version ${status.version}. This folder is ${config.agent}${config.reader || me?.reader ? ", a reader (it records and pushes nothing)" : ""}, working in ${space(me?.draft)}.${config.follow ? ` It follows label ${config.follow}: pulls take it to the newest version with that label.` : ""} Signed in with ${credential.kind}${credential.id ? ` ${credential.id}` : ""}.`,
333+ `Project ${config.project}: shared is at version ${status.version}. This folder is ${config.agent}${config.reader || me?.reader ? ", a reader (it records and pushes nothing)" : ""}, working in ${space(me?.draft)}.${config.follow ? ` It follows label ${config.follow}: pulls take it to the newest version with that label.` : ""}${localProject ? ` It's a local project, in ${join(config.localStore ?? "", config.project)}.` : ` Signed in with ${credential.kind}${credential.id ? ` ${credential.id}` : ""}.`}`,
331334 ...(behind ? [behind] : []),
332335 // Is shared green (#39)? Right under the first line, since it decides what to do next.
333336 ...ciText(status.ci, status.version),
new file, 141 lines
1+// abso login --web: a staging website session for the person a box is signed in as, opened in an agent's own browser, with
2+// no secret in the agent's hands. The website's /login/handoff takes this box's sign-in (or a test account's PAT, from a file)
3+// and answers a one-use link that works for a minute; opening it signs that browser in. Only the link is printed: never the
4+// box's sign-in, the PAT or the session cookie, which the website sets in the browser itself.
5+
6+import { readFileSync } from "node:fs";
7+import { UsageError } from "./args.ts";
8+
9+/** The website beside each staging server. Prod has none here: agents never sign in to the website on prod. */
10+const STAGING_SITES: Readonly<Record<string, string>> = {
11+ "https://abso-staging.chrisazy.workers.dev": "https://abso-website-staging.chrisazy.workers.dev",
12+ "https://avcs-staging.chrisazy.workers.dev": "https://abso-website-staging.chrisazy.workers.dev",
13+};
15+/** What the website answers: the link, when it stops working, and who and until when it signs in. */
16+export interface Handoff {
17+ readonly url: string;
18+ readonly expiresAt: string;
19+ readonly account: string;
20+ readonly name: string;
21+ readonly sessionEnds: string;
22+}
24+/**
25+ * The website a handoff's credential goes to (Security condition 6, Code Review): the staging website beside the folder's own
26+ * staging server, from the fixed list above, and never an origin from a flag. A server that isn't on the list is refused,
27+ * prod included. --site is only for a test account's PAT on this machine (http://localhost or 127.0.0.1); a box's sign-in
28+ * takes no --site at all.
29+ */
30+export function siteFor(server: string, site: string | undefined, kind: "box" | "pat"): string {
31+ const origin = new URL(server).origin;
32+ const known = STAGING_SITES[origin];
33+ if (known === undefined)
34+ throw new UsageError(
35+ `abso login --web is for staging: ${origin} has no staging website beside it that abso knows, and agents never sign in to the website on prod. Nothing was sent.`,
36+ );
37+ if (site === undefined) return known;
38+ if (kind === "box")
39+ throw new UsageError(`--site isn't taken with a box's sign-in, which goes only to ${known}. Nothing was sent.`);
40+ let url: URL | null = null;
41+ try {
42+ url = new URL(site);
43+ } catch {
44+ // Not an address: refused below.
45+ }
46+ if (url === null || url.protocol !== "http:" || (url.hostname !== "localhost" && url.hostname !== "127.0.0.1"))
47+ throw new UsageError(
48+ "--site, with --pat-file, names this machine only (http://localhost:<port> or http://127.0.0.1:<port>). Nothing was sent.",
49+ );
50+ return url.origin;
51+}
53+/**
54+ * abso login --web: where the credential would go is settled before it is read, so a refusal reads and sends nothing
55+ * (Security). `credential` reads the box's sign-in or the PAT only once the website is one it may go to.
56+ */
57+export async function webLogin(options: {
58+ readonly server: string;
59+ readonly site: string | undefined;
60+ /** A box's sign-in, or a test account's PAT (--pat-file). */
61+ readonly kind: "box" | "pat";
62+ readonly credential: () => string;
63+ readonly fetcher?: typeof fetch;
64+}): Promise<{ handoff: Handoff; site: string }> {
65+ const site = siteFor(options.server, options.site, options.kind);
66+ return { handoff: await webHandoff(site, options.credential(), options.fetcher), site };
67+}
69+/** A PAT from the file --pat-file names: read here, never printed. */
70+export function patFromFile(path: string): string {
71+ let text: string;
72+ try {
73+ text = readFileSync(path, "utf8").trim();
74+ } catch {
75+ throw new UsageError(`--pat-file names ${path}, which abso can't read`);
76+ }
77+ if (!/^abso_pat_[A-Za-z0-9_-]{16,200}$/.test(text))
78+ throw new UsageError(`--pat-file names ${path}, which doesn't hold a PAT`);
79+ return text;
80+}
82+/** Words from the website, with any secret this call sent taken out. */
83+function scrubbed(text: string, secret: string): string {
84+ return text.split(secret).join("[the credential]").slice(0, 300);
85+}
87+/** Asks the website for a handoff link with `credential` (a box sign-in or a PAT) in Authorization. */
88+export async function webHandoff(site: string, credential: string, fetcher: typeof fetch = fetch): Promise<Handoff> {
89+ let res: Response;
90+ try {
91+ res = await fetcher(`${site}/login/handoff`, {
92+ method: "POST",
93+ headers: { authorization: `Bearer ${credential}`, accept: "application/json" },
94+ redirect: "error",
95+ signal: AbortSignal.timeout(30_000),
96+ });
97+ } catch (err) {
98+ throw new UsageError(`couldn't reach ${site}: ${scrubbed((err as Error).message, credential)}`);
99+ }
100+ const text = await res.text().catch(() => "");
101+ let body: Partial<Handoff> & { error?: unknown } = {};
102+ try {
103+ body = JSON.parse(text) as typeof body;
104+ } catch {
105+ // Not JSON: the status says enough.
106+ }
107+ if (!res.ok) {
108+ const why = typeof body.error === "string" ? body.error : `it answered ${res.status}`;
109+ throw new UsageError(
110+ res.status === 404
111+ ? `${site} doesn't hand out sign-in links (its key sign-in is off, or it isn't staging)`
112+ : `${site} refused: ${scrubbed(why, credential)}`,
113+ );
114+ }
115+ if (
116+ typeof body.url !== "string" ||
117+ !body.url.startsWith(`${site}/login/handoff#`) ||
118+ typeof body.expiresAt !== "string" ||
119+ typeof body.account !== "string"
120+ )
121+ throw new UsageError(`${site} answered something that isn't a sign-in link`);
122+ return {
123+ url: body.url,
124+ expiresAt: body.expiresAt,
125+ account: body.account,
126+ name: typeof body.name === "string" ? body.name : body.account,
127+ sessionEnds: typeof body.sessionEnds === "string" ? body.sessionEnds : body.expiresAt,
128+ };
129+}
131+/** What abso login --web says: the one link, how long it works, who it signs in as, and what it reaches (Security). */
132+export function handoffText(h: Handoff, site: string, boxed = true, now = Date.now()): string {
133+ const seconds = Math.max(0, Math.round((Date.parse(h.expiresAt) - now) / 1000));
134+ const reach = boxed
135+ ? "only to the projects this box was granted, at most as a writer, until the box is revoked or ends"
136+ : "at most as a writer";
137+ return [
138+ `Open this link in your browser within ${seconds} seconds. It signs that browser in to ${site} as ${h.name}, until ${h.sessionEnds}, and works once. It reaches ${reach}:`,
139+ h.url,
140+ ].join("\n");
141+}
MCP
compare on this site's /mcp
CLI
abso diff 286 318 client/src --json
JSON
/christopher/abso-core/compare/286..318?file=client%2Fsrc&format=json