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?format=json
209 linesFirst import 92% · review 4% · pinch 4%Last change pinch in version 86, 6 versions changed it
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 { findRoot, isReader, isVisitor, readConfig } from "./config.ts";
20import { editBody, newsContext, normalize, spellingText, uncomposedText } from "./core.ts";
21import { fromEnv } from "./env-names.ts";
22import { forgetKnown, isPaused, loadIgnore, logNews, readKnown, readText, relativeTo, writeKnown } from "./folder.ts";
23import { tryFolderLock } from "./lock.ts";
24import { readKnownModes } from "./modes.ts";
25import { stateDir } from "./state-dir.ts";
27/** The fields of Claude Code's PostToolUse input that the hook reads. */
28interface HookInput {
29 readonly session_id?: string;
30 readonly cwd?: string;
31 readonly tool_name?: string;
32 readonly tool_input?: Record<string, unknown>;
33 readonly agent_id?: string;
36export interface HookResult {
37 /** What to print on stdout: Claude Code's JSON, or nothing. */
38 readonly stdout: string;
39 /** What happened, for the log and for tests. */
40 readonly outcome: string;
43const DEFAULT_TIMEOUT_MS = 4000;
45/** Where install-mod.ts puts the mod: Claude Code's skills folder, which every session loads. */
46export function modDir(env: Readonly<Record<string, string | undefined>> = process.env): string {
47 return join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "skills", "abso-hooks");
50/** Where the same mod lived before the rename. */
51export function oldModDir(env: Readonly<Record<string, string | undefined>> = process.env): string {
52 return join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "skills", "avcs");
55export async function runHook(
56 stdin: string,
57 env: Readonly<Record<string, string | undefined>> = process.env,
58): Promise<HookResult> {
59 const started = performance.now();
60 let input: HookInput;
61 try {
62 input = JSON.parse(stdin) as HookInput;
63 } catch {
64 return { stdout: "", outcome: "skipped: stdin was not JSON" };
65 }
66 // With the abso mod installed, every Claude Code session on this machine sends
67 // its edits in-process, so this hook stands down rather than send them twice.
68 if (
69 fromEnv(env, "HOOK_FORCE") !== "1" &&
70 (existsSync(join(modDir(env), ".claude-plugin", "plugin.json")) ||
71 existsSync(join(oldModDir(env), ".claude-plugin", "plugin.json")))
72 ) {
73 return { stdout: "", outcome: "skipped: the abso mod sends edits" };
74 }
75 const tool = input.tool_name ?? "";
76 const toolInput = input.tool_input ?? {};
77 const rawPath = toolInput.file_path ?? toolInput.notebook_path;
78 if (typeof rawPath !== "string" || rawPath === "")
79 return { stdout: "", outcome: `skipped: ${tool} has no file path` };
80 // An edit through a link changes the link's target: judge the file it reached.
81 const path = realOrSame(isAbsolute(rawPath) ? rawPath : resolve(input.cwd ?? process.cwd(), rawPath));
82 const root = findRoot(dirname(path));
83 if (root === undefined) return { stdout: "", outcome: "skipped: not in an abso folder" };
85 let rel: string | undefined;
86 let outcome: string;
87 let news: string[] = [];
88 try {
89 rel = relativeTo(root, path);
90 if (isPaused(root)) {
91 outcome = "skipped: recording is paused (abso resume)";
92 } else if (isReader(root)) {
93 outcome = "skipped: this folder is a reader";
94 } else if (isVisitor(root)) {
95 outcome = "skipped: this folder reads signed out";
96 } else if (rel === undefined || loadIgnore(root)(rel, false)) {
97 outcome = "skipped: ignored path";
98 } else if (readKnownModes(root).get(rel)?.link != null) {
99 outcome = "skipped: a link (a file standing in for one); abso record sends links";
100 } else {
101 const config = readConfig(root, env);
102 const timeout = Number(fromEnv(env, "HOOK_TIMEOUT_MS")) || DEFAULT_TIMEOUT_MS;
103 const api = new Api(config, timeout);
104 const who = {
105 ...(input.session_id ? { session: input.session_id } : {}),
106 ...(input.agent_id ? { subagent: input.agent_id } : {}),
107 };
108 // Never waits: while another abso command changes the folder's records, the edit is left for the next record (#51).
109 const unlock = tryFolderLock(root, "hook");
110 if (unlock === undefined) {
111 outcome = "skipped: another abso command is changing this folder; abso record sends it";
112 } else {
113 try {
114 const sent = await send(api, root, rel, tool, toolInput, who);
115 outcome = sent.outcome;
116 news = newsLines(sent.news);
117 logNews(root, news);
118 } finally {
119 unlock();
120 }
121 }
122 }
123 } catch (err) {
124 outcome = `error: ${(err as Error).message}`;
125 if (rel !== undefined) {
126 try {
127 forgetKnown(root, rel);
128 } catch {
129 // Nothing more to do; the log line below still says what failed.
130 }
131 }
132 }
133 log(
134 root,
135 `${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`,
136 );
137 if (news.length === 0) return { stdout: "", outcome };
138 const context = newsContext(news);
139 if (context === undefined) return { stdout: "", outcome };
140 return {
141 stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context } })}\n`,
142 outcome,
143 };
146async function send(
147 api: Api,
148 root: string,
149 rel: string,
150 tool: string,
151 toolInput: Record<string, unknown>,
152 who: { session?: string; subagent?: string },
153): Promise<{ outcome: string; news?: News }> {
154 const raw = readText(join(root, ...rel.split("/")));
155 if (raw === undefined) {
156 // Deleted, or not text. `record` with null says it's gone; a binary file is left out entirely.
157 return { outcome: "skipped: file is missing or not text; abso record catches up" };
158 }
159 const disk = normalize(raw);
160 const known = readKnown(root, rel);
161 const body = editBody(tool, toolInput, rel, known, disk, who);
162 if (body !== undefined) {
163 const answer = await api.edit(body);
164 if (answer.ok) {
165 remember(root, rel, disk);
166 return {
167 outcome: body.content !== undefined ? "sent write" : "sent edit",
168 news: [
169 ...newsLines(answer.news),
170 ...(answer.spelling ?? []).map(spellingText),
171 ...(answer.uncomposed ?? []).map(uncomposedText),
172 ],
173 };
174 }
175 if (answer.reason !== "out of step") throw new Error(`edit refused: ${answer.reason}`);
176 }
177 const answer = await api.record({ [rel]: disk }, who);
178 if (!answer.ok) throw new Error(`record refused: ${answer.reason ?? "no reason given"}`);
179 remember(root, rel, disk);
180 return {
181 outcome: body === undefined ? "sent whole file" : "out of step; sent whole file",
182 news: [
183 ...newsLines(answer.news),
184 ...(answer.spelling ?? []).map(spellingText),
185 ...(answer.uncomposed ?? []).map(uncomposedText),
186 ],
187 };
190/** Keep the known copy in step. */
191function remember(root: string, rel: string, text: string): void {
192 writeKnown(root, rel, text);
195function realOrSame(path: string): string {
196 try {
197 return realpathSync.native(path);
198 } catch {
199 return path;
200 }
203function log(root: string, line: string): void {
204 try {
205 appendFileSync(join(stateDir(root), "hook.log"), `${line}\n`);
206 } catch {
207 // Logging is best effort.
208 }