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=30&format=json
198 linesFirst import 97% · review 3%Last change review in version 27, 3 versions changed it

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