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/src/hook.ts?version=14&format=json
196 linesFirst import 100%Last change First import in version 0, 1 version changed it

You're reading version 14. The newest is 318, and 5 versions since then changed this file. Go to the newestCompare with 318

1// `abso hook`: the Claude Code PostToolUse hook on Edit, MultiEdit, Write and
2// NotebookEdit. It reads the hook's JSON on stdin, sends the edit into the
3// agent's draft, and hands any news back to the agent as extra context.
4//
5// It never blocks the agent and never fails: on any error it logs to
6// .avcs/hook.log, forgets the file's known copy (so the next `abso record`
7// sends it whole), and exits 0.
8//
9// Before sending an Edit, it replays the edit on the known copy. Only when the
10// replay gives exactly the file on disk (both with `\n` line endings, as the
11// server holds text) does it send the edit itself; otherwise (a file changed
12// by a shell command, an edit the tool adjusted) it sends the whole file with
13// `record`.
15import { appendFileSync, existsSync, realpathSync } from "node:fs";
16import { homedir } from "node:os";
17import { dirname, isAbsolute, join, resolve } from "node:path";
18import { Api, type News, newsLines } from "./api.ts";
19import { AVCS_DIR, findRoot, isReader, readConfig } from "./config.ts";
20import { editBody, newsContext, normalize, spellingText, uncomposedText } from "./core.ts";
21import { forgetKnown, isPaused, loadIgnore, logNews, readKnown, readText, relativeTo, writeKnown } from "./folder.ts";
22import { tryFolderLock } from "./lock.ts";
23import { readKnownModes } from "./modes.ts";
25/** The fields of Claude Code's PostToolUse input that the hook reads. */
26interface HookInput {
27 readonly session_id?: string;
28 readonly cwd?: string;
29 readonly tool_name?: string;
30 readonly tool_input?: Record<string, unknown>;
31 readonly agent_id?: string;
34export interface HookResult {
35 /** What to print on stdout: Claude Code's JSON, or nothing. */
36 readonly stdout: string;
37 /** What happened, for the log and for tests. */
38 readonly outcome: string;
41const DEFAULT_TIMEOUT_MS = 4000;
43/** Where install-mod.ts puts the mod: Claude Code's skills folder, which every session loads. */
44export function modDir(env: Readonly<Record<string, string | undefined>> = process.env): string {
45 return join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "skills", "avcs");
48export async function runHook(
49 stdin: string,
50 env: Readonly<Record<string, string | undefined>> = process.env,
51): Promise<HookResult> {
52 const started = performance.now();
53 let input: HookInput;
54 try {
55 input = JSON.parse(stdin) as HookInput;
56 } catch {
57 return { stdout: "", outcome: "skipped: stdin was not JSON" };
58 }
59 // With the abso mod installed, every Claude Code session on this machine sends
60 // its edits in-process, so this hook stands down rather than send them twice.
61 if (env.AVCS_HOOK_FORCE !== "1" && existsSync(join(modDir(env), ".claude-plugin", "plugin.json"))) {
62 return { stdout: "", outcome: "skipped: the abso mod sends edits" };
63 }
64 const tool = input.tool_name ?? "";
65 const toolInput = input.tool_input ?? {};
66 const rawPath = toolInput.file_path ?? toolInput.notebook_path;
67 if (typeof rawPath !== "string" || rawPath === "")
68 return { stdout: "", outcome: `skipped: ${tool} has no file path` };
69 // An edit through a link changes the link's target: judge the file it reached.
70 const path = realOrSame(isAbsolute(rawPath) ? rawPath : resolve(input.cwd ?? process.cwd(), rawPath));
71 const root = findRoot(dirname(path));
72 if (root === undefined) return { stdout: "", outcome: "skipped: not in an abso folder" };
74 let rel: string | undefined;
75 let outcome: string;
76 let news: string[] = [];
77 try {
78 rel = relativeTo(root, path);
79 if (isPaused(root)) {
80 outcome = "skipped: recording is paused (abso resume)";
81 } else if (isReader(root)) {
82 outcome = "skipped: this folder is a reader";
83 } else if (rel === undefined || loadIgnore(root)(rel, false)) {
84 outcome = "skipped: ignored path";
85 } else if (readKnownModes(root).get(rel)?.link != null) {
86 outcome = "skipped: a link (a file standing in for one); abso record sends links";
87 } else {
88 const config = readConfig(root, env);
89 const timeout = Number(env.AVCS_HOOK_TIMEOUT_MS) || DEFAULT_TIMEOUT_MS;
90 const api = new Api(config, timeout);
91 const who = {
92 ...(input.session_id ? { session: input.session_id } : {}),
93 ...(input.agent_id ? { subagent: input.agent_id } : {}),
94 };
95 // Never waits: while another abso command changes the folder's records, the edit is left for the next record (#51).
96 const unlock = tryFolderLock(root, "hook");
97 if (unlock === undefined) {
98 outcome = "skipped: another abso command is changing this folder; abso record sends it";
99 } else {
100 try {
101 const sent = await send(api, root, rel, tool, toolInput, who);
102 outcome = sent.outcome;
103 news = newsLines(sent.news);
104 logNews(root, news);
105 } finally {
106 unlock();
107 }
108 }
109 }
110 } catch (err) {
111 outcome = `error: ${(err as Error).message}`;
112 if (rel !== undefined) {
113 try {
114 forgetKnown(root, rel);
115 } catch {
116 // Nothing more to do; the log line below still says what failed.
117 }
118 }
119 }
120 log(
121 root,
122 `${new Date().toISOString()}\t${tool}\t${rel ?? path}\t${outcome}\t${Math.round(performance.now())}ms total, ${Math.round(performance.now() - started)}ms in hook`,
123 );
124 if (news.length === 0) return { stdout: "", outcome };
125 const context = newsContext(news);
126 if (context === undefined) return { stdout: "", outcome };
127 return {
128 stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context } })}\n`,
129 outcome,
130 };
133async function send(
134 api: Api,
135 root: string,
136 rel: string,
137 tool: string,
138 toolInput: Record<string, unknown>,
139 who: { session?: string; subagent?: string },
140): Promise<{ outcome: string; news?: News }> {
141 const raw = readText(join(root, ...rel.split("/")));
142 if (raw === undefined) {
143 // Deleted, or not text. `record` with null says it's gone; a binary file is left out entirely.
144 return { outcome: "skipped: file is missing or not text; abso record catches up" };
145 }
146 const disk = normalize(raw);
147 const known = readKnown(root, rel);
148 const body = editBody(tool, toolInput, rel, known, disk, who);
149 if (body !== undefined) {
150 const answer = await api.edit(body);
151 if (answer.ok) {
152 remember(root, rel, disk);
153 return {
154 outcome: body.content !== undefined ? "sent write" : "sent edit",
155 news: [
156 ...newsLines(answer.news),
157 ...(answer.spelling ?? []).map(spellingText),
158 ...(answer.uncomposed ?? []).map(uncomposedText),
159 ],
160 };
161 }
162 if (answer.reason !== "out of step") throw new Error(`edit refused: ${answer.reason}`);
163 }
164 const answer = await api.record({ [rel]: disk }, who);
165 if (!answer.ok) throw new Error(`record refused: ${answer.reason ?? "no reason given"}`);
166 remember(root, rel, disk);
167 return {
168 outcome: body === undefined ? "sent whole file" : "out of step; sent whole file",
169 news: [
170 ...newsLines(answer.news),
171 ...(answer.spelling ?? []).map(spellingText),
172 ...(answer.uncomposed ?? []).map(uncomposedText),
173 ],
174 };
177/** Keep the known copy in step. */
178function remember(root: string, rel: string, text: string): void {
179 writeKnown(root, rel, text);
182function realOrSame(path: string): string {
183 try {
184 return realpathSync.native(path);
185 } catch {
186 return path;
187 }
190function log(root: string, line: string): void {
191 try {
192 appendFileSync(join(root, AVCS_DIR, "hook.log"), `${line}\n`);
193 } catch {
194 // Logging is best effort.
195 }