* feat: add hooks system for CLI event interception
Adds a Claude Code-compatible hooks system that allows external handlers
(shell commands, HTTP endpoints) to intercept and respond to CLI events.
Supports 16 event types with regex-based matching, typed inputs/outputs,
sync/async execution, and multi-source config merging.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: register HookService in service container
The fireHook.ts module references services.hooks, which requires the
HookService to be registered in the service container and exposed in
the services object.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: resolve eslint errors in hooks files and services/index.ts
Fix unused imports, import ordering, and negated condition lint errors.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: handle EPIPE errors on hook stdin writes
When a hook command exits before we finish writing to stdin, an EPIPE
error is emitted. Add an error handler to suppress it gracefully.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: skip hookRunner tests on Windows
The hookRunner tests use /bin/sh syntax (>&2, single-quote echo, sleep)
that is incompatible with Windows cmd.exe.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: address cubic review - utf8 encoding, regex, EPIPE handling
- Use setEncoding("utf8") on stdout/stderr instead of data.toString()
to prevent multi-byte character corruption at buffer boundaries
- Fix env var interpolation regex to use alternation instead of
independent optionals, preventing unbalanced brace matching
- Only suppress EPIPE errors on stdin, log other errors
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Remove AI slop from hookRunner.ts
* Update AGENTS.md to document hooks system
* Fix React hooks best practices in useService.ts
* fix: correct indentation in useService.ts for prettier
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: remove invalid eslint-disable for react-hooks/exhaustive-deps
The react-hooks eslint plugin is not configured in the CLI package,
so the disable comment causes an eslint error.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: continue[bot] <230936708+continue[bot]@users.noreply.github.com>
164 lines
4.4 KiB
TypeScript
164 lines
4.4 KiB
TypeScript
/**
|
|
* Hook configuration loader.
|
|
*
|
|
* Loads hooks from settings files in the same locations as Claude Code:
|
|
* - ~/.continue/settings.json (user-global)
|
|
* - .continue/settings.json (project, committable)
|
|
* - .continue/settings.local.json (project-local, gitignored)
|
|
*
|
|
* Also supports Claude Code's native locations for cross-compatibility:
|
|
* - ~/.claude/settings.json
|
|
* - .claude/settings.json
|
|
* - .claude/settings.local.json
|
|
*
|
|
* Hooks from all sources are merged (project > user, continue > claude).
|
|
*/
|
|
|
|
import * as fs from "fs";
|
|
import * as os from "os";
|
|
import * as path from "path";
|
|
|
|
import { logger } from "../util/logger.js";
|
|
|
|
import type {
|
|
HookMatcherGroup,
|
|
HookSettingsFile,
|
|
HooksConfig,
|
|
} from "./types.js";
|
|
|
|
/**
|
|
* Load and parse a settings JSON file, returning only the hooks portion.
|
|
* Returns null if file doesn't exist or fails to parse.
|
|
*/
|
|
function loadSettingsFile(filePath: string): HookSettingsFile | null {
|
|
try {
|
|
if (!fs.existsSync(filePath)) {
|
|
return null;
|
|
}
|
|
const content = fs.readFileSync(filePath, "utf-8");
|
|
const parsed = JSON.parse(content);
|
|
return parsed as HookSettingsFile;
|
|
} catch (error) {
|
|
logger.warn(`Failed to load hooks settings from ${filePath}:`, error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Merge two hook configs. Later config entries are appended (not replaced).
|
|
* This matches Claude Code's behavior: hooks from multiple sources all run.
|
|
*/
|
|
function mergeHooksConfigs(
|
|
base: HooksConfig,
|
|
overlay: HooksConfig,
|
|
): HooksConfig {
|
|
const merged: HooksConfig = { ...base };
|
|
|
|
for (const [eventName, matcherGroups] of Object.entries(overlay)) {
|
|
const key = eventName as keyof HooksConfig;
|
|
if (merged[key]) {
|
|
merged[key] = [...merged[key]!, ...matcherGroups!];
|
|
} else {
|
|
merged[key] = matcherGroups;
|
|
}
|
|
}
|
|
|
|
return merged;
|
|
}
|
|
|
|
/**
|
|
* Resolve all settings file paths in precedence order (lowest to highest).
|
|
* Later files' hooks are appended but all run.
|
|
*/
|
|
function getSettingsFilePaths(cwd: string, homeDir?: string): string[] {
|
|
const home = homeDir ?? os.homedir();
|
|
const continueHome =
|
|
process.env.CONTINUE_GLOBAL_DIR || path.join(home, ".continue");
|
|
|
|
return [
|
|
// User-global (lowest precedence)
|
|
path.join(home, ".claude", "settings.json"),
|
|
path.join(continueHome, "settings.json"),
|
|
|
|
// Project-level
|
|
path.join(cwd, ".claude", "settings.json"),
|
|
path.join(cwd, ".continue", "settings.json"),
|
|
|
|
// Project-local (highest precedence)
|
|
path.join(cwd, ".claude", "settings.local.json"),
|
|
path.join(cwd, ".continue", "settings.local.json"),
|
|
];
|
|
}
|
|
|
|
export interface LoadedHooksConfig {
|
|
hooks: HooksConfig;
|
|
disabled: boolean;
|
|
}
|
|
|
|
/**
|
|
* Load all hook configurations from settings files and merge them.
|
|
*/
|
|
export function loadHooksConfig(
|
|
cwd: string = process.cwd(),
|
|
homeDir?: string,
|
|
): LoadedHooksConfig {
|
|
const paths = getSettingsFilePaths(cwd, homeDir);
|
|
let mergedHooks: HooksConfig = {};
|
|
let disabled = false;
|
|
|
|
for (const filePath of paths) {
|
|
const settings = loadSettingsFile(filePath);
|
|
if (!settings) continue;
|
|
|
|
if (settings.disableAllHooks) {
|
|
disabled = true;
|
|
}
|
|
|
|
if (settings.hooks) {
|
|
mergedHooks = mergeHooksConfigs(mergedHooks, settings.hooks);
|
|
}
|
|
}
|
|
|
|
return { hooks: mergedHooks, disabled };
|
|
}
|
|
|
|
/**
|
|
* Get matching hook handlers for a given event and matcher value.
|
|
*
|
|
* @param config - The merged hooks config
|
|
* @param eventName - The hook event name
|
|
* @param matcherValue - The value to match against (e.g., tool name). Undefined for events without matchers.
|
|
* @returns Array of matching hook handler groups
|
|
*/
|
|
export function getMatchingHookGroups(
|
|
config: HooksConfig,
|
|
eventName: string,
|
|
matcherValue?: string,
|
|
): HookMatcherGroup[] {
|
|
const groups = config[eventName as keyof HooksConfig];
|
|
if (!groups) return [];
|
|
|
|
return groups.filter((group) => {
|
|
// No matcher, empty matcher, or "*" = match all
|
|
if (!group.matcher || group.matcher === "" || group.matcher === "*") {
|
|
return true;
|
|
}
|
|
|
|
// If no matcher value provided (e.g., events without matcher support), match all
|
|
if (matcherValue === undefined) {
|
|
return true;
|
|
}
|
|
|
|
// Regex match
|
|
try {
|
|
const regex = new RegExp(group.matcher);
|
|
return regex.test(matcherValue);
|
|
} catch (error) {
|
|
logger.warn(
|
|
`Invalid hook matcher regex "${group.matcher}" for event ${eventName}:`,
|
|
error,
|
|
);
|
|
return false;
|
|
}
|
|
});
|
|
}
|