- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/hook.ts?draft=login-timeout&format=json
207 linesFirst import 93% · review 5% · pinch 2%0 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, 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;
34}
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;
41}
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");
48}
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");
53}
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 (rel === undefined || loadIgnore(root)(rel, false)) {
95 outcome = "skipped: ignored path";
96 } else if (readKnownModes(root).get(rel)?.link != null) {
97 outcome = "skipped: a link (a file standing in for one); abso record sends links";
98 } else {
99 const config = readConfig(root, env);
100 const timeout = Number(fromEnv(env, "HOOK_TIMEOUT_MS")) || DEFAULT_TIMEOUT_MS;
101 const api = new Api(config, timeout);
102 const who = {
103 ...(input.session_id ? { session: input.session_id } : {}),
104 ...(input.agent_id ? { subagent: input.agent_id } : {}),
105 };
106 // Never waits: while another abso command changes the folder's records, the edit is left for the next record (#51).
107 const unlock = tryFolderLock(root, "hook");
108 if (unlock === undefined) {
109 outcome = "skipped: another abso command is changing this folder; abso record sends it";
110 } else {
111 try {
112 const sent = await send(api, root, rel, tool, toolInput, who);
113 outcome = sent.outcome;
114 news = newsLines(sent.news);
115 logNews(root, news);
116 } finally {
117 unlock();
118 }
119 }
120 }
121 } catch (err) {
122 outcome = `error: ${(err as Error).message}`;
123 if (rel !== undefined) {
124 try {
125 forgetKnown(root, rel);
126 } catch {
127 // Nothing more to do; the log line below still says what failed.
128 }
129 }
130 }
131 log(
132 root,
133 `${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`,
134 );
135 if (news.length === 0) return { stdout: "", outcome };
136 const context = newsContext(news);
137 if (context === undefined) return { stdout: "", outcome };
138 return {
139 stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context } })}\n`,
140 outcome,
141 };
142}
144async function send(
145 api: Api,
146 root: string,
147 rel: string,
148 tool: string,
149 toolInput: Record<string, unknown>,
150 who: { session?: string; subagent?: string },
151): Promise<{ outcome: string; news?: News }> {
152 const raw = readText(join(root, ...rel.split("/")));
153 if (raw === undefined) {
154 // Deleted, or not text. `record` with null says it's gone; a binary file is left out entirely.
155 return { outcome: "skipped: file is missing or not text; abso record catches up" };
156 }
157 const disk = normalize(raw);
158 const known = readKnown(root, rel);
159 const body = editBody(tool, toolInput, rel, known, disk, who);
160 if (body !== undefined) {
161 const answer = await api.edit(body);
162 if (answer.ok) {
163 remember(root, rel, disk);
164 return {
165 outcome: body.content !== undefined ? "sent write" : "sent edit",
166 news: [
167 ...newsLines(answer.news),
168 ...(answer.spelling ?? []).map(spellingText),
169 ...(answer.uncomposed ?? []).map(uncomposedText),
170 ],
171 };
172 }
173 if (answer.reason !== "out of step") throw new Error(`edit refused: ${answer.reason}`);
174 }
175 const answer = await api.record({ [rel]: disk }, who);
176 if (!answer.ok) throw new Error(`record refused: ${answer.reason ?? "no reason given"}`);
177 remember(root, rel, disk);
178 return {
179 outcome: body === undefined ? "sent whole file" : "out of step; sent whole file",
180 news: [
181 ...newsLines(answer.news),
182 ...(answer.spelling ?? []).map(spellingText),
183 ...(answer.uncomposed ?? []).map(uncomposedText),
184 ],
185 };
186}
188/** Keep the known copy in step. */
189function remember(root: string, rel: string, text: string): void {
190 writeKnown(root, rel, text);
191}
193function realOrSame(path: string): string {
194 try {
195 return realpathSync.native(path);
196 } catch {
197 return path;
198 }
199}
201function log(root: string, line: string): void {
202 try {
203 appendFileSync(join(stateDir(root), "hook.log"), `${line}\n`);
204 } catch {
205 // Logging is best effort.
206 }
207}