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=17&format=json
197 linesFirst import 98% · review 2%Last change review in version 17, 2 versions changed it

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