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
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/client/hooks/register.ts?draft=login-timeout&format=json
406 linesFirst import 94% · review 6% · pinch 1%0 versions changed it
1// The abso hook as a Claude Code function hook: after each Edit, MultiEdit,
2// Write or NotebookEdit in an abso folder, it sends the change into the
3// agent's draft, and hands any news back to the model.
4//
5// The agent never waits for it. The hook takes a snapshot of the file and
6// returns; a queue in this module then sends the edits in the order they were
7// made, each judged against its own snapshot (src/core.ts makes the same
8// decisions as `abso hook`). News reaches the model as a row the engine
9// appends, read at the model's next request.
10//
11// Outside an abso folder it costs one cached lookup. It never throws into a
12// chat: on any error it logs to .avcs/hook.log and forgets the file's known
13// copy, so the next `abso record` (publish and sync run one) sends it whole.
15import type { Register } from "claude-code";
16import {
17 type EditBody,
18 editBody,
19 type GitIgnoreSetup,
20 gitIgnoreSetup,
21 ignoreFilesFor,
22 LOCK_FILE,
23 lockHeld,
24 looksBinary,
25 machineServers,
26 makeIgnore,
27 newsContext,
28 normalize,
29 readAll,
30 spellingText,
31 tokenGoesTo,
32 trustedList,
33 uncomposedText,
34 type Who,
35} from "../src/core.ts";
36import { STAMP } from "./stamp.ts";
38const TOOLS = ["Edit", "MultiEdit", "Write", "NotebookEdit"];
39/** A known copy holding a NUL byte reads as no known copy (the client treats it as binary). */
40const FORGOTTEN = "\u0000";
41const LOG_LIMIT = 256 * 1024;
42/** How long a folder's "is this in an abso folder" answer is kept. */
43const ROOT_CACHE_MS = 30_000;
44/** Sent with each call, so the server can tell which mod, from which commit, made it (#29). */
45const CLIENT = `avcs-mod/${STAMP ?? "checkout"}`;
47type Engine = Parameters<Parameters<Register>[0]>[2] extends never ? never : any;
49interface Answer {
50 readonly ok: boolean;
51 readonly reason?: string;
52 readonly news?: readonly string[];
53 /** Another spelling of an existing file, recorded as it (#49). */
54 readonly spelling?: readonly { path: string; existing: string }[];
55 /** New names not in composed Unicode form (#49). */
56 readonly uncomposed?: readonly string[];
59/** The answer's news, with the spelling warnings (#49) the agent should hear too. */
60function heardFrom(answer: Answer): readonly string[] {
61 return [
62 ...(answer.news ?? []),
63 ...(answer.spelling ?? []).map(spellingText),
64 ...(answer.uncomposed ?? []).map(uncomposedText),
65 ];
68interface Job {
69 readonly root: string;
70 readonly rel: string;
71 readonly tool: string;
72 readonly input: Readonly<Record<string, unknown>>;
73 /** The file right after this edit, in the server's form (undefined: missing or not text). */
74 readonly snapshot: string | undefined;
75 /** Where a NUL byte is, when the edit left one (the file then reads as binary). */
76 readonly nul?: { readonly line: number; readonly at: number };
77 readonly agentId: string | undefined;
78 readonly queuedAt: number;
81const slash = (p: string) => p.replace(/\\/g, "/");
83// Module state: the jobs waiting to be sent, in order, and the folder lookup cache.
84// Sending outlives the edit's own hook, so a timer started in session.start
85// sends the waiting jobs; while there are none, each tick only checks a list.
86const jobs: Job[] = [];
87/** News that couldn't be appended, by agent ('' for the main chat), for the next edit's result. */
88const pendingNews = new Map<string, string[]>();
89let draining = false;
90const TICK_MS = 150;
91const roots = new Map<string, { root: string | undefined; at: number }>();
92/** How often to ask for news without an edit (announcements reach an agent that isn't editing). */
93const NEWS_POLL_MS = 30_000;
94/** The abso folder this chat works in: the session's folder, or the first edited file's. */
95let newsRoot: string | undefined;
96let polling = false;
97/** Each folder's rules from git's own files, kept as long as the folder lookup. */
98const gitSetups = new Map<string, { git: GitIgnoreSetup; at: number }>();
100export const register: Register = (on) => {
101 on("session.start", async ($, e, next) => {
102 $.clock.every(TICK_MS, () => {
103 if (draining || jobs.length === 0) return;
104 draining = true;
105 void drain($).finally(() => {
106 draining = false;
107 });
108 });
109 // Outside an abso folder each tick only reads a variable.
110 newsRoot = await findRoot($, `${slash(await $.session.cwd())}/.`).catch(() => undefined);
111 $.clock.every(NEWS_POLL_MS, () => {
112 if (polling || newsRoot === undefined) return;
113 polling = true;
114 void pollNews($, newsRoot).finally(() => {
115 polling = false;
116 });
117 });
118 return next(e);
119 });
121 on("tool.call", { tool: TOOLS }, async ($, e, next) => {
122 const ran = await next(e);
123 try {
124 if (ran.deny !== undefined || ran.isError) return ran;
125 const input = e as unknown as Record<string, unknown>;
126 const raw = input.file_path ?? input.notebook_path;
127 if (typeof raw !== "string" || raw === "") return ran;
128 // The model may pass a path relative to the session's folder; the host resolves it.
129 const path = slash(
130 /^([A-Za-z]:)?[\\/]/.test(raw) ? raw : ((await $.fs.stat(raw, { resolve: true })).realPath ?? raw),
131 );
132 const root = await findRoot($, path);
133 if (root === undefined) return ran;
134 newsRoot ??= root;
135 const rel = path.slice(root.length + 1);
136 const text = await readOr($, path);
137 const job: Job = {
138 root,
139 rel,
140 tool: String(input.tool),
141 input: Object.fromEntries(
142 Object.entries(input).filter(
143 ([k]) => k !== "tool" && k !== "tool_use_id" && k !== "agentId" && k !== "consent",
144 ),
145 ),
146 snapshot: text === undefined || looksBinary(text) ? undefined : normalize(text),
147 ...(text !== undefined && text.includes("\u0000")
148 ? { nul: { at: text.indexOf("\u0000"), line: text.slice(0, text.indexOf("\u0000")).split("\n").length } }
149 : {}),
150 agentId: typeof input.agentId === "string" ? input.agentId : undefined,
151 queuedAt: await $.clock.now(),
152 };
153 jobs.push(job);
154 const waitingNews = pendingNews.get(job.agentId ?? "");
155 if (waitingNews !== undefined) {
156 pendingNews.delete(job.agentId ?? "");
157 return { ...ran, context: [...(ran.context ?? []), ...waitingNews] };
158 }
159 } catch {
160 // Never into the chat. The next `abso record` catches up.
161 }
162 return ran;
163 });
164};
166/** Send the waiting jobs one at a time, oldest first. */
167async function drain($: Engine): Promise<void> {
168 for (let job = jobs.shift(); job !== undefined; job = jobs.shift()) await run($, job);
171async function run($: Engine, job: Job): Promise<void> {
172 const started = await $.clock.now().catch(() => job.queuedAt);
173 let outcome: string;
174 let news: readonly string[] = [];
175 try {
176 if ((await readOr($, `${await stateOf($, job.root)}/paused`)) !== undefined) {
177 outcome = "skipped: recording is paused (abso resume)";
178 } else if (/"reader"\s*:\s*true/.test((await readOr($, `${await stateOf($, job.root)}/config.json`)) ?? "")) {
179 outcome = "skipped: this folder is a reader";
180 } else if (await ignored($, job.root, job.rel)) {
181 outcome = "skipped: ignored path";
182 } else if (await isLink($, job.root, job.rel)) {
183 outcome = "skipped: a link (or a file standing in for one); abso record sends links";
184 } else {
185 const who: Who = { session: await $.session.id(), ...(job.agentId ? { subagent: job.agentId } : {}) };
186 const sent = await send($, job, who);
187 outcome = sent.outcome;
188 news = sent.news;
189 }
190 } catch (err) {
191 outcome = `error: ${(err as Error).message}`;
192 await $.fs.write(`${await stateOf($, job.root)}/known/${job.rel}`, FORGOTTEN).catch(() => {});
193 }
194 const done = await $.clock.now().catch(() => started);
195 await log(
196 $,
197 job.root,
198 `${new Date(job.queuedAt).toISOString()}\t${job.tool}\t${job.rel}\t${outcome}\t${done - started}ms sending, ${started - job.queuedAt}ms queued (in process, async)\t${CLIENT}`,
199 );
200 const context = newsContext(news);
201 if (context === undefined) return;
202 // For anything that shows news later (the avcs-view mod reads it).
203 const at = new Date(done).toISOString();
204 await log($, job.root, news.map((n) => `${at}\t${n}`).join("\n"), "news.log");
205 try {
206 await $.session.append({
207 message: { type: "user", content: [{ type: "text", text: context }] },
208 ...(job.agentId ? { agentId: job.agentId } : {}),
209 });
210 } catch {
211 // Older Claude Code has no append; the agent's next edit carries it instead.
212 const key = job.agentId ?? "";
213 pendingNews.set(key, [...(pendingNews.get(key) ?? []), context]);
214 }
217/** Ask for the news waiting for this agent (announcements, collisions) and hand it to the model. */
218async function pollNews($: Engine, root: string): Promise<void> {
219 try {
220 const config = JSON.parse(await $.fs.read(`${await stateOf($, root)}/config.json`)) as {
221 server: string;
222 project: string;
223 agent: string;
224 };
225 const bearer = await token($, config.server);
226 const r = await $.http.fetch(
227 `${config.server.replace(/\/+$/, "")}/p/${encodeURIComponent(config.project)}/a/${encodeURIComponent(config.agent)}/news`,
228 {
229 method: "POST",
230 headers: {
231 "content-type": "application/json",
232 "x-abso-client": CLIENT,
233 ...(bearer ? { authorization: `Bearer ${bearer}` } : {}),
234 },
235 body: "{}",
236 },
237 );
238 if (!r.ok) return;
239 const news = ((JSON.parse(r.text) as { news?: readonly string[] }).news ?? []).filter(
240 (n) => typeof n === "string" && n.trim() !== "",
241 );
242 const context = newsContext(news);
243 if (context === undefined) return;
244 const at = new Date(await $.clock.now()).toISOString();
245 await log($, root, news.map((n) => `${at}\t${n}`).join("\n"), "news.log");
246 try {
247 await $.session.append({ message: { type: "user", content: [{ type: "text", text: context }] } });
248 } catch (err) {
249 // It rides on the next edit's result instead; say why in the log.
250 await log($, root, `${at}\tnews\t-\tcould not append (${(err as Error).message}); the next edit carries it`);
251 pendingNews.set("", [...(pendingNews.get("") ?? []), context]);
252 }
253 } catch {
254 // The next poll, edit or abso command picks it up; nothing is lost on the server.
255 }
258async function readOr($: Engine, path: string): Promise<string | undefined> {
259 try {
260 return await $.fs.read(path);
261 } catch {
262 return undefined;
263 }
266/** A folder's state folder: .abso, or .avcs in a folder from before the rename. (A mod can't import the client's state-dir.ts.) */
267async function stateOf($: Engine, root: string): Promise<string> {
268 return (await $.fs.exists(`${root}/.abso/config.json`)) ? `${root}/.abso` : `${root}/.avcs`;
271/** A file under the user's home: ~/.abso/<name>, else the older ~/.avcs/<name>. */
272async function readHome($: Engine, home: string, name: string): Promise<string | undefined> {
273 return (await readOr($, `${slash(home)}/.abso/${name}`)) ?? (await readOr($, `${slash(home)}/.avcs/${name}`));
276/** Whether the server has this path as a symbolic link (.avcs/modes.json, written by the client). */
277async function isLink($: Engine, root: string, rel: string): Promise<boolean> {
278 const raw = await readOr($, `${await stateOf($, root)}/modes.json`);
279 if (raw === undefined) return false;
280 try {
281 const modes = JSON.parse(raw) as Record<string, { link?: unknown }>;
282 return typeof modes[rel]?.link === "string";
283 } catch {
284 return false;
285 }
288/** The client's ignore rules (src/core.ts), reading only the ignore files above the path. */
289async function ignored($: Engine, root: string, rel: string): Promise<boolean> {
290 const now = await $.clock.now();
291 let setup = gitSetups.get(root);
292 if (!setup || now - setup.at >= ROOT_CACHE_MS) {
293 const home = (await $.env.get("HOME")) ?? (await $.env.get("USERPROFILE"));
294 const xdgConfigHome = await $.env.get("XDG_CONFIG_HOME");
295 const git = await readAll(gitIgnoreSetup(root, { home, ...(xdgConfigHome ? { xdgConfigHome } : {}) }), (p) =>
296 readOr($, p),
297 );
298 setup = { git, at: now };
299 gitSetups.set(root, setup);
300 }
301 const files = new Map<string, string | undefined>();
302 for (const f of ignoreFilesFor(rel)) files.set(f, await readOr($, `${root}/${f}`));
303 return makeIgnore((f) => files.get(f), setup.git)(rel, false);
306/** The nearest folder above the file that has .abso/config.json (or .avcs/config.json from before the rename), cached per folder. */
307async function findRoot($: Engine, path: string): Promise<string | undefined> {
308 const start = path.slice(0, path.lastIndexOf("/"));
309 const now = await $.clock.now();
310 const hit = roots.get(start);
311 if (hit && now - hit.at < ROOT_CACHE_MS) return hit.root;
312 let found: string | undefined;
313 let dir = start;
314 while (dir.includes("/")) {
315 if ((await $.fs.exists(`${dir}/.abso/config.json`)) || (await $.fs.exists(`${dir}/.avcs/config.json`))) {
316 found = dir;
317 break;
318 }
319 const up = dir.slice(0, dir.lastIndexOf("/"));
320 if (up === dir || up === "" || /^[A-Za-z]:$/.test(up)) break;
321 dir = up;
322 }
323 roots.set(start, { root: found, at: now });
324 return found;
327/** AVCS_TOKEN if set, else ~/.abso/token, else ~/.avcs/token; none for a server the token may not go to (core.ts tokenGoesTo, with this machine's servers.json). */
328async function token($: Engine, server: string): Promise<string | undefined> {
329 const home = (await $.env.get("USERPROFILE")) ?? (await $.env.get("HOME"));
330 const machine = machineServers(home ? await readHome($, home, "servers.json") : undefined);
331 if (!tokenGoesTo(server, trustedList(await $.env.get("AVCS_TRUSTED_SERVERS"), machine))) return undefined;
332 const env = await $.env.get("AVCS_TOKEN");
333 if (env) return env.trim();
334 return home ? (await readHome($, home, "token"))?.trim() || undefined : undefined;
337async function send($: Engine, job: Job, who: Who): Promise<{ outcome: string; news: readonly string[] }> {
338 const { root, rel } = job;
339 // While an abso command changes the folder's records, leave the known copy alone: the next record sends the file (#51).
340 if (lockHeld(await readOr($, `${await stateOf($, root)}/${LOCK_FILE}`), Date.now()))
341 return { outcome: "skipped: another abso command is changing this folder; abso record sends it", news: [] };
342 const disk = job.snapshot;
343 const knownPath = `${await stateOf($, root)}/known/${rel}`;
344 const knownRaw = await readOr($, knownPath);
345 if (disk === undefined) {
346 if (job.nul !== undefined && knownRaw !== undefined && !looksBinary(knownRaw)) {
347 // A text file an edit left with a NUL byte: tell the agent now, not forty minutes later (#25).
348 const warning = `${rel} now has a NUL byte at line ${job.nul.line} (character ${job.nul.at}), so it reads as binary. abso will not send or publish it, and the other agents keep its last text, until the NUL is gone.`;
349 return { outcome: `not sent: a NUL byte at line ${job.nul.line}`, news: [warning] };
350 }
351 return { outcome: "skipped: file is missing or not text; abso record catches up", news: [] };
352 }
353 const known = knownRaw === undefined || looksBinary(knownRaw) ? undefined : knownRaw;
355 const config = JSON.parse(await $.fs.read(`${await stateOf($, root)}/config.json`)) as {
356 server: string;
357 project: string;
358 agent: string;
359 };
360 const bearer = await token($, config.server);
361 const post = async (action: string, payload: unknown): Promise<Answer> => {
362 const url = `${config.server.replace(/\/+$/, "")}/p/${encodeURIComponent(config.project)}/a/${encodeURIComponent(config.agent)}/${action}`;
363 const r = await $.http.fetch(url, {
364 method: "POST",
365 headers: {
366 "content-type": "application/json",
367 "x-abso-client": CLIENT,
368 ...(bearer ? { authorization: `Bearer ${bearer}` } : {}),
369 },
370 body: JSON.stringify(payload),
371 });
372 if (!r.ok) throw new Error(`${action} answered ${r.status}: ${r.text.slice(0, 300)}`);
373 return JSON.parse(r.text) as Answer;
374 };
376 const body: EditBody | undefined = editBody(job.tool, job.input, rel, known, disk, who);
377 if (body !== undefined) {
378 const answer = await post("edit", body);
379 if (answer.ok) {
380 await remember($, knownPath, disk);
381 return { outcome: body.content !== undefined ? "sent write" : "sent edit", news: heardFrom(answer) };
382 }
383 if (answer.reason !== "out of step") throw new Error(`edit refused: ${answer.reason}`);
384 }
385 const answer = await post("record", { files: { [rel]: disk }, ...who });
386 if (!answer.ok) throw new Error(`record refused: ${answer.reason ?? "no reason given"}`);
387 await remember($, knownPath, disk);
388 return { outcome: body === undefined ? "sent whole file" : "out of step; sent whole file", news: heardFrom(answer) };
391/** Keep the known copy in step. */
392async function remember($: Engine, knownPath: string, text: string): Promise<void> {
393 await $.fs.write(knownPath, text);
396/** One line per edit in .avcs/hook.log (or another log there), as the command hook writes, kept under LOG_LIMIT. */
397async function log($: Engine, root: string, line: string, file = "hook.log"): Promise<void> {
398 try {
399 const path = `${await stateOf($, root)}/${file}`;
400 let text = `${(await readOr($, path)) ?? ""}${line}\n`;
401 if (text.length > LOG_LIMIT) text = text.slice(text.indexOf("\n", text.length - LOG_LIMIT / 2) + 1);
402 await $.fs.write(path, text);
403 } catch {
404 // Logging is best effort.
405 }