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?format=json
473 linesFirst import 78% · pinch 11% · review 5% · box-grants 5% · rename 1%Last change pinch in version 293, 9 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` (push and pull 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 { HOOK_COMMAND, 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/**
93 * How often to ask for news without an edit (announcements reach an agent that isn't editing). Every 5 minutes, and
94 * not at all in a chat that has made no tool call for IDLE_MS: prod abso's object reset under the load of every chat
95 * asking every 30 seconds (2026-10-15). abso news --stream (abso 690) wakes a chat without asking.
96 */
97const NEWS_POLL_MS = 5 * 60_000;
98const IDLE_MS = 10 * 60_000;
99/** When this chat last made a tool call (or started). */
100let activeAt = 0;
101/** The abso folder this chat works in: the session's folder, or the first edited file's. */
102let newsRoot: string | undefined;
103let polling = false;
104/** Each folder's rules from git's own files, kept as long as the folder lookup. */
105const gitSetups = new Map<string, { git: GitIgnoreSetup; at: number }>();
107export const register: Register = (on) => {
108 on("session.start", async ($, e, next) => {
109 $.clock.every(TICK_MS, () => {
110 if (draining || jobs.length === 0) return;
111 draining = true;
112 void drain($).finally(() => {
113 draining = false;
114 });
115 });
116 // Outside an abso folder each tick only reads a variable.
117 newsRoot = await findRoot($, `${slash(await $.session.cwd())}/.`).catch(() => undefined);
118 activeAt = await $.clock.now();
119 $.clock.every(NEWS_POLL_MS, async () => {
120 if (polling || newsRoot === undefined) return;
121 if ((await $.clock.now()) - activeAt >= IDLE_MS) return;
122 polling = true;
123 void pollNews($, newsRoot).finally(() => {
124 polling = false;
125 });
126 });
127 return next(e);
128 });
130 on("tool.call", async ($, e, next) => {
131 activeAt = await $.clock.now();
132 return next(e);
133 });
135 on("tool.call", { tool: TOOLS }, async ($, e, next) => {
136 const ran = await next(e);
137 try {
138 if (ran.deny !== undefined || ran.isError) return ran;
139 const input = e as unknown as Record<string, unknown>;
140 const raw = input.file_path ?? input.notebook_path;
141 if (typeof raw !== "string" || raw === "") return ran;
142 // The model may pass a path relative to the session's folder; the host resolves it.
143 const path = slash(
144 /^([A-Za-z]:)?[\\/]/.test(raw) ? raw : ((await $.fs.stat(raw, { resolve: true })).realPath ?? raw),
145 );
146 const root = await findRoot($, path);
147 if (root === undefined) return ran;
148 newsRoot ??= root;
149 const rel = path.slice(root.length + 1);
150 const text = await readOr($, path);
151 const job: Job = {
152 root,
153 rel,
154 tool: String(input.tool),
155 input: Object.fromEntries(
156 Object.entries(input).filter(
157 ([k]) => k !== "tool" && k !== "tool_use_id" && k !== "agentId" && k !== "consent",
158 ),
159 ),
160 snapshot: text === undefined || looksBinary(text) ? undefined : normalize(text),
161 ...(text?.includes("\u0000")
162 ? { nul: { at: text.indexOf("\u0000"), line: text.slice(0, text.indexOf("\u0000")).split("\n").length } }
163 : {}),
164 agentId: typeof input.agentId === "string" ? input.agentId : undefined,
165 queuedAt: await $.clock.now(),
166 };
167 jobs.push(job);
168 const waitingNews = pendingNews.get(job.agentId ?? "");
169 if (waitingNews !== undefined) {
170 pendingNews.delete(job.agentId ?? "");
171 return { ...ran, context: [...(ran.context ?? []), ...waitingNews] };
172 }
173 } catch {
174 // Never into the chat. The next `abso record` catches up.
175 }
176 return ran;
177 });
178};
180/** Send the waiting jobs one at a time, oldest first. */
181async function drain($: Engine): Promise<void> {
182 for (let job = jobs.shift(); job !== undefined; job = jobs.shift()) await run($, job);
185/** A local project's folder (abso init --local): its config names no server. */
186const LOCAL_FOLDER = /"server"\s*:\s*"local"/;
187/** How long abso hook may take on a local project's edit: it waits up to two minutes for the store's lock. */
188const LOCAL_HOOK_MS = 150_000;
190async function run($: Engine, job: Job): Promise<void> {
191 const started = await $.clock.now().catch(() => job.queuedAt);
192 let outcome: string;
193 let news: readonly string[] = [];
194 /** What abso hook handed back for the agent, on a local project's edit (it keeps the news log itself). */
195 let handed: string | undefined;
196 try {
197 if ((await readOr($, `${await stateOf($, job.root)}/paused`)) !== undefined) {
198 outcome = "skipped: recording is paused (abso resume)";
199 } else if (/"reader"\s*:\s*true/.test((await readOr($, `${await stateOf($, job.root)}/config.json`)) ?? "")) {
200 outcome = "skipped: this folder is a reader";
201 } else if (LOCAL_FOLDER.test((await readOr($, `${await stateOf($, job.root)}/config.json`)) ?? "")) {
202 ({ outcome, context: handed } = await handToClient($, job));
203 } else if (await ignored($, job.root, job.rel)) {
204 outcome = "skipped: ignored path";
205 } else if (await isLink($, job.root, job.rel)) {
206 outcome = "skipped: a link (or a file standing in for one); abso record sends links";
207 } else {
208 const who: Who = { session: await $.session.id(), ...(job.agentId ? { subagent: job.agentId } : {}) };
209 const sent = await send($, job, who);
210 outcome = sent.outcome;
211 news = sent.news;
212 }
213 } catch (err) {
214 outcome = `error: ${(err as Error).message}`;
215 await $.fs.write(`${await stateOf($, job.root)}/known/${job.rel}`, FORGOTTEN).catch(() => {});
216 }
217 const done = await $.clock.now().catch(() => started);
218 await log(
219 $,
220 job.root,
221 `${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}`,
222 );
223 const context = handed ?? newsContext(news);
224 if (context === undefined) return;
225 // For anything that shows news later (the avcs-view mod reads it).
226 const at = new Date(done).toISOString();
227 if (news.length > 0) await log($, job.root, news.map((n) => `${at}\t${n}`).join("\n"), "news.log");
228 try {
229 await $.session.append({
230 message: { type: "user", content: [{ type: "text", text: context }] },
231 ...(job.agentId ? { agentId: job.agentId } : {}),
232 });
233 } catch {
234 // Older Claude Code has no append; the agent's next edit carries it instead.
235 const key = job.agentId ?? "";
236 pendingNews.set(key, [...(pendingNews.get(key) ?? []), context]);
237 }
240/**
241 * A local project's history is in a store on this machine that only the abso command opens, so its edits go to
242 * `abso hook` from the checkout this mod was installed from, as Claude Code's command hook would run it.
243 */
244async function handToClient($: Engine, job: Job): Promise<{ outcome: string; context?: string }> {
245 if (HOOK_COMMAND === undefined || HOOK_COMMAND.length === 0)
246 return {
247 outcome:
248 "skipped: a local project, and this mod has no abso to hand it to (install-mod.ts adds one); abso record sends it",
249 };
250 const hookInput = {
251 session_id: await $.session.id(),
252 cwd: slash(await $.session.cwd()),
253 tool_name: job.tool,
254 tool_input: job.input,
255 ...(job.agentId ? { agent_id: job.agentId } : {}),
256 };
257 const ran = await $.process.run(HOOK_COMMAND, {
258 cwd: job.root,
259 env: { ABSO_HOOK_FORCE: "1" },
260 stdin: JSON.stringify(hookInput),
261 timeoutMs: LOCAL_HOOK_MS,
262 });
263 if (ran.exitCode !== 0) throw new Error(`abso hook exited ${ran.exitCode}: ${ran.stderr.trim().split("\n").at(-1)}`);
264 // It prints Claude Code's JSON when it has news for the agent, and nothing otherwise.
265 const out = ran.stdout.trim();
266 const context =
267 out === ""
268 ? undefined
269 : (JSON.parse(out) as { hookSpecificOutput?: { additionalContext?: unknown } }).hookSpecificOutput
270 ?.additionalContext;
271 return {
272 outcome: "handed to abso hook (a local project; its own line is just above)",
273 ...(typeof context === "string" ? { context } : {}),
274 };
277/** Ask for the news waiting for this agent (announcements, collisions) and hand it to the model. */
278async function pollNews($: Engine, root: string): Promise<void> {
279 try {
280 // While this seat holds its news stream (abso news --stream or --follow, abso 690), the stream wakes the chat.
281 const mark = await readOr($, `${await stateOf($, root)}/news-stream.json`);
282 if (mark !== undefined) {
283 const until = Number((JSON.parse(mark) as { until?: unknown }).until);
284 if (Number.isFinite(until) && until > (await $.clock.now())) return;
285 }
286 const config = JSON.parse(await $.fs.read(`${await stateOf($, root)}/config.json`)) as {
287 server: string;
288 project: string;
289 agent: string;
290 };
291 if (config.server === "local") return;
292 const bearer = await token($, config.server);
293 const r = await $.http.fetch(
294 `${config.server.replace(/\/+$/, "")}/p/${encodeURIComponent(config.project)}/a/${encodeURIComponent(config.agent)}/news`,
295 {
296 method: "POST",
297 headers: {
298 "content-type": "application/json",
299 "x-abso-client": CLIENT,
300 ...(bearer ? { authorization: `Bearer ${bearer}` } : {}),
301 },
302 body: "{}",
303 },
304 );
305 if (!r.ok) return;
306 const news = ((JSON.parse(r.text) as { news?: readonly string[] }).news ?? []).filter(
307 (n) => typeof n === "string" && n.trim() !== "",
308 );
309 const context = newsContext(news);
310 if (context === undefined) return;
311 const at = new Date(await $.clock.now()).toISOString();
312 await log($, root, news.map((n) => `${at}\t${n}`).join("\n"), "news.log");
313 try {
314 await $.session.append({ message: { type: "user", content: [{ type: "text", text: context }] } });
315 } catch (err) {
316 // It rides on the next edit's result instead; say why in the log.
317 await log($, root, `${at}\tnews\t-\tcould not append (${(err as Error).message}); the next edit carries it`);
318 pendingNews.set("", [...(pendingNews.get("") ?? []), context]);
319 }
320 } catch {
321 // The next poll, edit or abso command picks it up; nothing is lost on the server.
322 }
325async function readOr($: Engine, path: string): Promise<string | undefined> {
326 try {
327 return await $.fs.read(path);
328 } catch {
329 return undefined;
330 }
333/** 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.) */
334async function stateOf($: Engine, root: string): Promise<string> {
335 return (await $.fs.exists(`${root}/.abso/config.json`)) ? `${root}/.abso` : `${root}/.avcs`;
338/** A file under the user's home: ~/.abso/<name>, else the older ~/.avcs/<name>. */
339async function readHome($: Engine, home: string, name: string): Promise<string | undefined> {
340 return (await readOr($, `${slash(home)}/.abso/${name}`)) ?? (await readOr($, `${slash(home)}/.avcs/${name}`));
343/** Whether the server has this path as a symbolic link (.avcs/modes.json, written by the client). */
344async function isLink($: Engine, root: string, rel: string): Promise<boolean> {
345 const raw = await readOr($, `${await stateOf($, root)}/modes.json`);
346 if (raw === undefined) return false;
347 try {
348 const modes = JSON.parse(raw) as Record<string, { link?: unknown }>;
349 return typeof modes[rel]?.link === "string";
350 } catch {
351 return false;
352 }
355/** The client's ignore rules (src/core.ts), reading only the ignore files above the path. */
356async function ignored($: Engine, root: string, rel: string): Promise<boolean> {
357 const now = await $.clock.now();
358 let setup = gitSetups.get(root);
359 if (!setup || now - setup.at >= ROOT_CACHE_MS) {
360 const home = (await $.env.get("HOME")) ?? (await $.env.get("USERPROFILE"));
361 const xdgConfigHome = await $.env.get("XDG_CONFIG_HOME");
362 const git = await readAll(gitIgnoreSetup(root, { home, ...(xdgConfigHome ? { xdgConfigHome } : {}) }), (p) =>
363 readOr($, p),
364 );
365 setup = { git, at: now };
366 gitSetups.set(root, setup);
367 }
368 const files = new Map<string, string | undefined>();
369 for (const f of ignoreFilesFor(rel)) files.set(f, await readOr($, `${root}/${f}`));
370 return makeIgnore((f) => files.get(f), setup.git)(rel, false);
373/** The nearest folder above the file that has .abso/config.json (or .avcs/config.json from before the rename), cached per folder. */
374async function findRoot($: Engine, path: string): Promise<string | undefined> {
375 const start = path.slice(0, path.lastIndexOf("/"));
376 const now = await $.clock.now();
377 const hit = roots.get(start);
378 if (hit && now - hit.at < ROOT_CACHE_MS) return hit.root;
379 let found: string | undefined;
380 let dir = start;
381 while (dir.includes("/")) {
382 if ((await $.fs.exists(`${dir}/.abso/config.json`)) || (await $.fs.exists(`${dir}/.avcs/config.json`))) {
383 found = dir;
384 break;
385 }
386 const up = dir.slice(0, dir.lastIndexOf("/"));
387 if (up === dir || up === "" || /^[A-Za-z]:$/.test(up)) break;
388 dir = up;
389 }
390 roots.set(start, { root: found, at: now });
391 return found;
394/** 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). */
395async function token($: Engine, server: string): Promise<string | undefined> {
396 const home = (await $.env.get("USERPROFILE")) ?? (await $.env.get("HOME"));
397 const machine = machineServers(home ? await readHome($, home, "servers.json") : undefined);
398 if (!tokenGoesTo(server, trustedList(await $.env.get("AVCS_TRUSTED_SERVERS"), machine))) return undefined;
399 const env = await $.env.get("AVCS_TOKEN");
400 if (env) return env.trim();
401 return home ? (await readHome($, home, "token"))?.trim() || undefined : undefined;
404async function send($: Engine, job: Job, who: Who): Promise<{ outcome: string; news: readonly string[] }> {
405 const { root, rel } = job;
406 // While an abso command changes the folder's records, leave the known copy alone: the next record sends the file (#51).
407 if (lockHeld(await readOr($, `${await stateOf($, root)}/${LOCK_FILE}`), Date.now()))
408 return { outcome: "skipped: another abso command is changing this folder; abso record sends it", news: [] };
409 const disk = job.snapshot;
410 const knownPath = `${await stateOf($, root)}/known/${rel}`;
411 const knownRaw = await readOr($, knownPath);
412 if (disk === undefined) {
413 if (job.nul !== undefined && knownRaw !== undefined && !looksBinary(knownRaw)) {
414 // A text file an edit left with a NUL byte: tell the agent now, not forty minutes later (#25).
415 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 push it, and the other agents keep its last text, until the NUL is gone.`;
416 return { outcome: `not sent: a NUL byte at line ${job.nul.line}`, news: [warning] };
417 }
418 return { outcome: "skipped: file is missing or not text; abso record catches up", news: [] };
419 }
420 const known = knownRaw === undefined || looksBinary(knownRaw) ? undefined : knownRaw;
422 const config = JSON.parse(await $.fs.read(`${await stateOf($, root)}/config.json`)) as {
423 server: string;
424 project: string;
425 agent: string;
426 };
427 const bearer = await token($, config.server);
428 const post = async (action: string, payload: unknown): Promise<Answer> => {
429 const url = `${config.server.replace(/\/+$/, "")}/p/${encodeURIComponent(config.project)}/a/${encodeURIComponent(config.agent)}/${action}`;
430 const r = await $.http.fetch(url, {
431 method: "POST",
432 headers: {
433 "content-type": "application/json",
434 "x-abso-client": CLIENT,
435 ...(bearer ? { authorization: `Bearer ${bearer}` } : {}),
436 },
437 body: JSON.stringify(payload),
438 });
439 if (!r.ok) throw new Error(`${action} answered ${r.status}: ${r.text.slice(0, 300)}`);
440 return JSON.parse(r.text) as Answer;
441 };
443 const body: EditBody | undefined = editBody(job.tool, job.input, rel, known, disk, who);
444 if (body !== undefined) {
445 const answer = await post("edit", body);
446 if (answer.ok) {
447 await remember($, knownPath, disk);
448 return { outcome: body.content !== undefined ? "sent write" : "sent edit", news: heardFrom(answer) };
449 }
450 if (answer.reason !== "out of step") throw new Error(`edit refused: ${answer.reason}`);
451 }
452 const answer = await post("record", { files: { [rel]: disk }, ...who });
453 if (!answer.ok) throw new Error(`record refused: ${answer.reason ?? "no reason given"}`);
454 await remember($, knownPath, disk);
455 return { outcome: body === undefined ? "sent whole file" : "out of step; sent whole file", news: heardFrom(answer) };
458/** Keep the known copy in step. */
459async function remember($: Engine, knownPath: string, text: string): Promise<void> {
460 await $.fs.write(knownPath, text);
463/** One line per edit in .avcs/hook.log (or another log there), as the command hook writes, kept under LOG_LIMIT. */
464async function log($: Engine, root: string, line: string, file = "hook.log"): Promise<void> {
465 try {
466 const path = `${await stateOf($, root)}/${file}`;
467 let text = `${(await readOr($, path)) ?? ""}${line}\n`;
468 if (text.length > LOG_LIMIT) text = text.slice(text.indexOf("\n", text.length - LOG_LIMIT / 2) + 1);
469 await $.fs.write(path, text);
470 } catch {
471 // Logging is best effort.
472 }