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=40&format=json
205 linesFirst import 94% · review 6%Last change review in version 40, 4 versions changed it

You're reading version 40. The newest is 318, and 2 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 { findRoot, isReader, 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 (fromEnv(env, "HOOK_FORCE") !== "1" && (existsSync(join(modDir(env), ".claude-plugin", "plugin.json")) ||
69 existsSync(join(oldModDir(env), ".claude-plugin", "plugin.json"))))
70 {
71 return { stdout: "", outcome: "skipped: the abso mod sends edits" };
72 }
73 const tool = input.tool_name ?? "";
74 const toolInput = input.tool_input ?? {};
75 const rawPath = toolInput.file_path ?? toolInput.notebook_path;
76 if (typeof rawPath !== "string" || rawPath === "")
77 return { stdout: "", outcome: `skipped: ${tool} has no file path` };
78 // An edit through a link changes the link's target: judge the file it reached.
79 const path = realOrSame(isAbsolute(rawPath) ? rawPath : resolve(input.cwd ?? process.cwd(), rawPath));
80 const root = findRoot(dirname(path));
81 if (root === undefined) return { stdout: "", outcome: "skipped: not in an abso folder" };
83 let rel: string | undefined;
84 let outcome: string;
85 let news: string[] = [];
86 try {
87 rel = relativeTo(root, path);
88 if (isPaused(root)) {
89 outcome = "skipped: recording is paused (abso resume)";
90 } else if (isReader(root)) {
91 outcome = "skipped: this folder is a reader";
92 } else if (rel === undefined || loadIgnore(root)(rel, false)) {
93 outcome = "skipped: ignored path";
94 } else if (readKnownModes(root).get(rel)?.link != null) {
95 outcome = "skipped: a link (a file standing in for one); abso record sends links";
96 } else {
97 const config = readConfig(root, env);
98 const timeout = Number(fromEnv(env, "HOOK_TIMEOUT_MS")) || DEFAULT_TIMEOUT_MS;
99 const api = new Api(config, timeout);
100 const who = {
101 ...(input.session_id ? { session: input.session_id } : {}),
102 ...(input.agent_id ? { subagent: input.agent_id } : {}),
103 };
104 // Never waits: while another abso command changes the folder's records, the edit is left for the next record (#51).
105 const unlock = tryFolderLock(root, "hook");
106 if (unlock === undefined) {
107 outcome = "skipped: another abso command is changing this folder; abso record sends it";
108 } else {
109 try {
110 const sent = await send(api, root, rel, tool, toolInput, who);
111 outcome = sent.outcome;
112 news = newsLines(sent.news);
113 logNews(root, news);
114 } finally {
115 unlock();
116 }
117 }
118 }
119 } catch (err) {
120 outcome = `error: ${(err as Error).message}`;
121 if (rel !== undefined) {
122 try {
123 forgetKnown(root, rel);
124 } catch {
125 // Nothing more to do; the log line below still says what failed.
126 }
127 }
128 }
129 log(
130 root,
131 `${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`,
132 );
133 if (news.length === 0) return { stdout: "", outcome };
134 const context = newsContext(news);
135 if (context === undefined) return { stdout: "", outcome };
136 return {
137 stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context } })}\n`,
138 outcome,
139 };
142async function send(
143 api: Api,
144 root: string,
145 rel: string,
146 tool: string,
147 toolInput: Record<string, unknown>,
148 who: { session?: string; subagent?: string },
149): Promise<{ outcome: string; news?: News }> {
150 const raw = readText(join(root, ...rel.split("/")));
151 if (raw === undefined) {
152 // Deleted, or not text. `record` with null says it's gone; a binary file is left out entirely.
153 return { outcome: "skipped: file is missing or not text; abso record catches up" };
154 }
155 const disk = normalize(raw);
156 const known = readKnown(root, rel);
157 const body = editBody(tool, toolInput, rel, known, disk, who);
158 if (body !== undefined) {
159 const answer = await api.edit(body);
160 if (answer.ok) {
161 remember(root, rel, disk);
162 return {
163 outcome: body.content !== undefined ? "sent write" : "sent edit",
164 news: [
165 ...newsLines(answer.news),
166 ...(answer.spelling ?? []).map(spellingText),
167 ...(answer.uncomposed ?? []).map(uncomposedText),
168 ],
169 };
170 }
171 if (answer.reason !== "out of step") throw new Error(`edit refused: ${answer.reason}`);
172 }
173 const answer = await api.record({ [rel]: disk }, who);
174 if (!answer.ok) throw new Error(`record refused: ${answer.reason ?? "no reason given"}`);
175 remember(root, rel, disk);
176 return {
177 outcome: body === undefined ? "sent whole file" : "out of step; sent whole file",
178 news: [
179 ...newsLines(answer.news),
180 ...(answer.spelling ?? []).map(spellingText),
181 ...(answer.uncomposed ?? []).map(uncomposedText),
182 ],
183 };
186/** Keep the known copy in step. */
187function remember(root: string, rel: string, text: string): void {
188 writeKnown(root, rel, text);
191function realOrSame(path: string): string {
192 try {
193 return realpathSync.native(path);
194 } catch {
195 return path;
196 }
199function log(root: string, line: string): void {
200 try {
201 appendFileSync(join(stateDir(root), "hook.log"), `${line}\n`);
202 } catch {
203 // Logging is best effort.
204 }