feat: add hooks system for CLI event interception (#11029)

* 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>
This commit is contained in:
Nate Sesti 2026-03-04 15:37:09 -08:00 • committed by GitHub
parent ec7030d20b
commit abb1fc0439
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 2289 additions and 5 deletions

View file

@ -50,6 +50,20 @@ This is a CLI tool for Continue Dev that provides an interactive AI-assisted dev
6. **MCP Integration** (`src/mcp.ts`): Model Context Protocol service for extended tool capabilities
7. **Hooks System** (`src/hooks/`): Event interception system for extending CLI behavior
- `HookService.ts`: Service container integration, loads config and fires events
- `hookConfig.ts`: Loads hooks from settings files, merges configs from multiple sources
- `hookRunner.ts`: Executes hook handlers (command, HTTP) with exit code semantics
- `fireHook.ts`: Convenience functions for firing events from integration points
- `types.ts`: Claude Code-compatible type definitions for hook inputs/outputs
- **Config locations** (lowest to highest precedence):
- `~/.claude/settings.json`, `~/.continue/settings.json` (user-global)
- `.claude/settings.json`, `.continue/settings.json` (project)
- `.claude/settings.local.json`, `.continue/settings.local.json` (project-local)
- **Exit code semantics**: 0 = proceed, 2 = block (stderr becomes feedback), other = non-blocking error
- **JSON output**: Optional structured output with `hookSpecificOutput` for fine-grained control
- **Hook types**: `command` (shell), `http` (POST request), `prompt`/`agent` (not yet implemented)
### Key Features
- **Streaming Responses**: Real-time AI response streaming (`streamChatResponse.ts`)

View file

@ -0,0 +1,128 @@
/**
* HookService — service container integration for the hooks system.
*
* Loads hook configuration from settings files and provides a `fireEvent`
* method that integration points call to trigger hooks.
*/
import { BaseService } from "../services/BaseService.js";
import { logger } from "../util/logger.js";
import { loadHooksConfig } from "./hookConfig.js";
import { runHooks } from "./hookRunner.js";
import type { HookEventResult, HookInput, HooksConfig } from "./types.js";
// ---------------------------------------------------------------------------
// Service state
// ---------------------------------------------------------------------------
export interface HookServiceState {
/** The merged hooks config from all settings files */
config: HooksConfig;
/** Whether all hooks are disabled (disableAllHooks: true) */
disabled: boolean;
/** Hooks that have already run their "once" execution */
onceKeys: Set<string>;
}
// ---------------------------------------------------------------------------
// Service
// ---------------------------------------------------------------------------
export class HookService extends BaseService<HookServiceState> {
private cwd: string;
constructor() {
super("hooks", {
config: {},
disabled: false,
onceKeys: new Set(),
});
this.cwd = process.cwd();
}
async doInitialize(cwd?: string): Promise<HookServiceState> {
if (cwd) {
this.cwd = cwd;
}
const loaded = loadHooksConfig(this.cwd);
const eventCount = Object.keys(loaded.hooks).length;
const handlerCount = Object.values(loaded.hooks).reduce(
(sum, groups) =>
sum + (groups?.reduce((s, g) => s + g.hooks.length, 0) ?? 0),
0,
);
if (handlerCount > 0) {
logger.debug(
`Hooks loaded: ${handlerCount} handler(s) across ${eventCount} event type(s)`,
);
}
return {
config: loaded.hooks,
disabled: loaded.disabled,
onceKeys: new Set(),
};
}
/**
* Fire a hook event and return the aggregated result.
*
* This is the main entry point used by all integration points.
* Returns a no-op result if hooks are disabled.
*/
async fireEvent(input: HookInput): Promise<HookEventResult> {
if (this.currentState.disabled) {
return { blocked: false, results: [] };
}
if (Object.keys(this.currentState.config).length === 0) {
return { blocked: false, results: [] };
}
try {
const result = await runHooks(this.currentState.config, input, this.cwd);
return result;
} catch (error) {
logger.warn(`Hook event ${input.hook_event_name} failed:`, error);
// Hook errors should not break the main flow
return { blocked: false, results: [] };
}
}
/**
* Reload hooks config from disk (e.g., after config file changes).
*/
async reloadConfig(): Promise<void> {
const loaded = loadHooksConfig(this.cwd);
this.setState({
config: loaded.hooks,
disabled: loaded.disabled,
});
}
/**
* Get the session-level common fields that go into every hook input.
* Integration points should call this and spread it into their event-specific input.
*/
getCommonFields(
sessionId: string,
transcriptPath: string,
permissionMode?: string,
): {
session_id: string;
transcript_path: string;
cwd: string;
permission_mode?: string;
} {
return {
session_id: sessionId,
transcript_path: transcriptPath,
cwd: this.cwd,
permission_mode: permissionMode,
};
}
}

View file

@ -0,0 +1,231 @@
/**
* Convenience functions for firing hook events from integration points.
*
* These functions build the hook input with common fields and delegate
* to the HookService. They are safe to call even if the HookService
* is not yet initialized (they return no-op results).
*/
import { services } from "../services/index.js";
import { getCurrentSession } from "../session.js";
import type {
HookEventResult,
NotificationInput,
PostToolUseFailureInput,
PostToolUseInput,
PreCompactInput,
PreToolUseInput,
SessionEndInput,
SessionEndReason,
SessionStartInput,
SessionStartSource,
StopInput,
UserPromptSubmitInput,
} from "./types.js";
const NOOP_RESULT: HookEventResult = { blocked: false, results: [] };
function getCommonFields(): {
session_id: string;
transcript_path: string;
cwd: string;
permission_mode?: string;
} {
try {
const session = getCurrentSession();
const permissionMode = services.toolPermissions?.isReady()
? services.toolPermissions.getState().currentMode
: undefined;
return {
session_id: session.sessionId,
transcript_path: "", // We don't have a transcript file like Claude Code
cwd: process.cwd(),
permission_mode: permissionMode,
};
} catch {
return {
session_id: "",
transcript_path: "",
cwd: process.cwd(),
};
}
}
function isHookServiceReady(): boolean {
try {
return services.hooks?.isReady() ?? false;
} catch {
return false;
}
}
// ---------------------------------------------------------------------------
// Tool events
// ---------------------------------------------------------------------------
export async function firePreToolUse(
toolName: string,
toolInput: unknown,
toolUseId: string,
): Promise<HookEventResult> {
if (!isHookServiceReady()) return NOOP_RESULT;
const input: PreToolUseInput = {
...getCommonFields(),
hook_event_name: "PreToolUse",
tool_name: toolName,
tool_input: toolInput,
tool_use_id: toolUseId,
};
return services.hooks.fireEvent(input);
}
export async function firePostToolUse(
toolName: string,
toolInput: unknown,
toolResponse: unknown,
toolUseId: string,
): Promise<HookEventResult> {
if (!isHookServiceReady()) return NOOP_RESULT;
const input: PostToolUseInput = {
...getCommonFields(),
hook_event_name: "PostToolUse",
tool_name: toolName,
tool_input: toolInput,
tool_response: toolResponse,
tool_use_id: toolUseId,
};
return services.hooks.fireEvent(input);
}
export async function firePostToolUseFailure(
toolName: string,
toolInput: unknown,
toolUseId: string,
error: string,
isInterrupt?: boolean,
): Promise<HookEventResult> {
if (!isHookServiceReady()) return NOOP_RESULT;
const input: PostToolUseFailureInput = {
...getCommonFields(),
hook_event_name: "PostToolUseFailure",
tool_name: toolName,
tool_input: toolInput,
tool_use_id: toolUseId,
error,
is_interrupt: isInterrupt,
};
return services.hooks.fireEvent(input);
}
// ---------------------------------------------------------------------------
// Lifecycle events
// ---------------------------------------------------------------------------
export async function fireUserPromptSubmit(
prompt: string,
): Promise<HookEventResult> {
if (!isHookServiceReady()) return NOOP_RESULT;
const input: UserPromptSubmitInput = {
...getCommonFields(),
hook_event_name: "UserPromptSubmit",
prompt,
};
return services.hooks.fireEvent(input);
}
export async function fireSessionStart(
source: SessionStartSource,
model?: string,
): Promise<HookEventResult> {
if (!isHookServiceReady()) return NOOP_RESULT;
const input: SessionStartInput = {
...getCommonFields(),
hook_event_name: "SessionStart",
source,
model,
};
return services.hooks.fireEvent(input);
}
export async function fireSessionEnd(
reason: SessionEndReason,
): Promise<HookEventResult> {
if (!isHookServiceReady()) return NOOP_RESULT;
const input: SessionEndInput = {
...getCommonFields(),
hook_event_name: "SessionEnd",
reason,
};
return services.hooks.fireEvent(input);
}
export async function fireStop(
lastAssistantMessage?: string,
): Promise<HookEventResult> {
if (!isHookServiceReady()) return NOOP_RESULT;
const input: StopInput = {
...getCommonFields(),
hook_event_name: "Stop",
stop_hook_active: true,
last_assistant_message: lastAssistantMessage,
};
return services.hooks.fireEvent(input);
}
// ---------------------------------------------------------------------------
// Notification event
// ---------------------------------------------------------------------------
export async function fireNotification(
message: string,
notificationType: string,
title?: string,
): Promise<HookEventResult> {
if (!isHookServiceReady()) return NOOP_RESULT;
const input: NotificationInput = {
...getCommonFields(),
hook_event_name: "Notification",
message,
title,
notification_type: notificationType,
};
return services.hooks.fireEvent(input);
}
// ---------------------------------------------------------------------------
// Compaction event
// ---------------------------------------------------------------------------
export async function firePreCompact(
trigger: "manual" | "auto",
customInstructions: string | null = null,
): Promise<HookEventResult> {
if (!isHookServiceReady()) return NOOP_RESULT;
const input: PreCompactInput = {
...getCommonFields(),
hook_event_name: "PreCompact",
trigger,
custom_instructions: customInstructions,
};
return services.hooks.fireEvent(input);
}

View file

@ -0,0 +1,164 @@
/**
* 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;
}
});
}

View file

@ -0,0 +1,416 @@
import { execFile } from "child_process";
import { logger } from "../util/logger.js";
import { getMatchingHookGroups } from "./hookConfig.js";
import { MATCHER_FIELD_MAP, NO_MATCHER_EVENTS } from "./types.js";
import type {
CommandHookHandler,
HookEventName,
HookEventResult,
HookExecutionResult,
HookHandler,
HookInput,
HookOutput,
HttpHookHandler,
} from "./types.js";
import type { HooksConfig } from "./types.js";
const DEFAULT_COMMAND_TIMEOUT_SECONDS = 600;
const DEFAULT_HTTP_TIMEOUT_SECONDS = 30;
function tryParseJson(str: string): HookOutput | null {
const trimmed = str.trim();
if (!trimmed || !trimmed.startsWith("{")) return null;
try {
return JSON.parse(trimmed) as HookOutput;
} catch {
return null;
}
}
function executeCommandHook(
handler: CommandHookHandler,
input: HookInput,
cwd: string,
): Promise<HookExecutionResult> {
const timeoutMs = (handler.timeout ?? DEFAULT_COMMAND_TIMEOUT_SECONDS) * 1000;
return new Promise((resolve) => {
const env = {
...process.env,
CLAUDE_PROJECT_DIR: cwd,
CONTINUE_PROJECT_DIR: cwd,
};
// Use shell to execute the command (matches Claude Code behavior)
const shell = process.platform === "win32" ? "cmd.exe" : "/bin/sh";
const shellArgs =
process.platform === "win32"
? ["/c", handler.command]
: ["-c", handler.command];
const child = execFile(shell, shellArgs, {
cwd,
env,
timeout: timeoutMs,
maxBuffer: 10 * 1024 * 1024, // 10MB
});
let stdout = "";
let stderr = "";
child.stdout?.setEncoding("utf8");
child.stdout?.on("data", (data: string) => {
stdout += data;
});
child.stderr?.setEncoding("utf8");
child.stderr?.on("data", (data: string) => {
stderr += data;
});
// Send JSON input on stdin
if (child.stdin) {
child.stdin.on("error", (error: NodeJS.ErrnoException) => {
if (error.code !== "EPIPE") {
logger.warn(
`Failed writing hook input to stdin: ${handler.command}`,
error,
);
}
});
child.stdin.write(JSON.stringify(input));
child.stdin.end();
}
child.on("close", (code) => {
const exitCode = code ?? 0;
const output = tryParseJson(stdout);
// Determine if the hook blocked the action
let blocked = false;
let blockReason: string | undefined;
if (exitCode === 2) {
blocked = true;
blockReason = stderr.trim() || "Blocked by hook";
} else if (output?.decision === "block") {
blocked = true;
blockReason = output.reason || stderr.trim() || "Blocked by hook";
}
resolve({
output,
stdout: stdout.trim(),
stderr: stderr.trim(),
exitCode,
blocked,
blockReason,
});
});
child.on("error", (error) => {
logger.warn(`Hook command failed: ${handler.command}`, error);
resolve({
output: null,
stdout: "",
stderr: error.message,
exitCode: 1,
blocked: false,
});
});
});
}
function interpolateEnvVars(value: string, allowedVars: string[]): string {
return value.replace(/\$\{(\w+)\}|\$(\w+)/g, (_, braced, bare) => {
const varName = braced ?? bare;
if (allowedVars.includes(varName)) {
return process.env[varName] ?? "";
}
return "";
});
}
async function executeHttpHook(
handler: HttpHookHandler,
input: HookInput,
): Promise<HookExecutionResult> {
const timeoutMs = (handler.timeout ?? DEFAULT_HTTP_TIMEOUT_SECONDS) * 1000;
try {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (handler.headers) {
const allowedVars = handler.allowedEnvVars ?? [];
for (const [key, value] of Object.entries(handler.headers)) {
headers[key] = interpolateEnvVars(value, allowedVars);
}
}
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
const response = await fetch(handler.url, {
method: "POST",
headers,
body: JSON.stringify(input),
signal: controller.signal,
});
clearTimeout(timeout);
if (!response.ok) {
// Non-2xx = non-blocking error (matches Claude Code behavior)
logger.warn(`HTTP hook returned ${response.status}: ${handler.url}`);
return {
output: null,
stdout: "",
stderr: `HTTP ${response.status}`,
exitCode: 1,
blocked: false,
};
}
const bodyText = await response.text();
const output = tryParseJson(bodyText);
let blocked = false;
let blockReason: string | undefined;
if (output?.decision === "block") {
blocked = true;
blockReason = output.reason || "Blocked by hook";
}
return {
output,
stdout: bodyText.trim(),
stderr: "",
exitCode: 0,
blocked,
blockReason,
};
} catch (error) {
// Connection failures and timeouts = non-blocking errors
logger.warn(`HTTP hook failed: ${handler.url}`, error);
return {
output: null,
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
exitCode: 1,
blocked: false,
};
}
}
async function executeHandler(
handler: HookHandler,
input: HookInput,
cwd: string,
): Promise<HookExecutionResult> {
switch (handler.type) {
case "command":
return executeCommandHook(handler, input, cwd);
case "http":
return executeHttpHook(handler, input);
case "prompt":
case "agent":
// Prompt and agent hooks are not yet implemented
logger.debug(
`Hook type "${handler.type}" is not yet supported, skipping`,
);
return {
output: null,
stdout: "",
stderr: "",
exitCode: 0,
blocked: false,
};
default:
logger.warn(`Unknown hook handler type: ${(handler as any).type}`);
return {
output: null,
stdout: "",
stderr: "",
exitCode: 0,
blocked: false,
};
}
}
function getHandlerDedupeKey(handler: HookHandler): string {
switch (handler.type) {
case "command":
return `command:${handler.command}`;
case "http":
return `http:${handler.url}`;
case "prompt":
return `prompt:${handler.prompt}`;
case "agent":
return `agent:${handler.prompt}`;
default:
return `unknown:${JSON.stringify(handler)}`;
}
}
function getMatcherValue(input: HookInput): string | undefined {
const eventName = input.hook_event_name as HookEventName;
if (NO_MATCHER_EVENTS.includes(eventName)) {
return undefined;
}
const field = MATCHER_FIELD_MAP[eventName];
if (!field) return undefined;
return (input as any)[field] as string | undefined;
}
export async function runHooks(
config: HooksConfig,
input: HookInput,
cwd: string = process.cwd(),
): Promise<HookEventResult> {
const eventName = input.hook_event_name;
const matcherValue = getMatcherValue(input);
const matchingGroups = getMatchingHookGroups(config, eventName, matcherValue);
if (matchingGroups.length === 0) {
return { blocked: false, results: [] };
}
// Collect all handlers, deduplicating by key
const seen = new Set<string>();
const handlers: HookHandler[] = [];
for (const group of matchingGroups) {
for (const handler of group.hooks) {
const key = getHandlerDedupeKey(handler);
if (!seen.has(key)) {
seen.add(key);
handlers.push(handler);
}
}
}
if (handlers.length === 0) {
return { blocked: false, results: [] };
}
// Separate async (fire-and-forget) from sync handlers
const syncHandlers: HookHandler[] = [];
const asyncHandlers: HookHandler[] = [];
for (const handler of handlers) {
if (handler.type === "command" && handler.async) {
asyncHandlers.push(handler);
} else {
syncHandlers.push(handler);
}
}
// Fire async hooks (don't await)
for (const handler of asyncHandlers) {
executeHandler(handler, input, cwd).catch((err) => {
logger.warn("Async hook failed:", err);
});
}
// Execute sync hooks in parallel
const results = await Promise.all(
syncHandlers.map((handler) => executeHandler(handler, input, cwd)),
);
// Aggregate results
return aggregateResults(results, eventName);
}
function aggregateResults(
results: HookExecutionResult[],
eventName: string,
): HookEventResult {
const eventResult: HookEventResult = {
blocked: false,
results,
};
const additionalContextParts: string[] = [];
for (const result of results) {
// Check for blocking
if (result.blocked) {
eventResult.blocked = true;
if (!eventResult.blockReason) {
eventResult.blockReason = result.blockReason;
}
}
const output = result.output;
if (!output?.hookSpecificOutput) {
// For exit 0 with no JSON output, stdout can be context
// (for UserPromptSubmit and SessionStart)
if (
result.exitCode === 0 &&
result.stdout &&
(eventName === "UserPromptSubmit" || eventName === "SessionStart")
) {
additionalContextParts.push(result.stdout);
}
continue;
}
const specific = output.hookSpecificOutput;
// Extract additionalContext from any hook that supports it
if ("additionalContext" in specific && specific.additionalContext) {
additionalContextParts.push(specific.additionalContext);
}
// Event-specific aggregation
switch (specific.hookEventName) {
case "PreToolUse":
if (specific.permissionDecision) {
eventResult.permissionDecision = specific.permissionDecision;
eventResult.permissionDecisionReason =
specific.permissionDecisionReason;
if (specific.permissionDecision === "deny") {
eventResult.blocked = true;
eventResult.blockReason =
specific.permissionDecisionReason ||
output.reason ||
"Blocked by hook";
}
}
if (specific.updatedInput) {
eventResult.updatedInput = specific.updatedInput;
}
break;
case "PermissionRequest":
eventResult.permissionRequestDecision = specific.decision;
if (specific.decision.behavior === "deny") {
eventResult.blocked = true;
eventResult.blockReason =
"message" in specific.decision
? specific.decision.message || "Denied by hook"
: "Denied by hook";
}
break;
// Other events: additionalContext already handled above
default:
break;
}
}
if (additionalContextParts.length > 0) {
eventResult.additionalContext = additionalContextParts.join("\n");
}
return eventResult;
}

View file

@ -0,0 +1,895 @@
/**
* Tests for the hooks system: config loading, matcher matching,
* hook execution (command and HTTP), exit code semantics,
* JSON output parsing, result aggregation, and deduplication.
*/
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { getMatchingHookGroups, loadHooksConfig } from "./hookConfig.js";
import { runHooks } from "./hookRunner.js";
import type {
HookMatcherGroup,
HooksConfig,
PreToolUseInput,
SessionStartInput,
StopInput,
UserPromptSubmitInput,
} from "./types.js";
// ---------------------------------------------------------------------------
// hookConfig tests
// ---------------------------------------------------------------------------
describe("hookConfig", () => {
describe("getMatchingHookGroups", () => {
const baseGroup: HookMatcherGroup = {
hooks: [{ type: "command", command: "echo hello" }],
};
it("matches when no matcher is set", () => {
const config: HooksConfig = {
PreToolUse: [baseGroup],
};
const result = getMatchingHookGroups(config, "PreToolUse", "Bash");
expect(result).toHaveLength(1);
});
it("matches when matcher is empty string", () => {
const config: HooksConfig = {
PreToolUse: [{ matcher: "", hooks: baseGroup.hooks }],
};
const result = getMatchingHookGroups(config, "PreToolUse", "Bash");
expect(result).toHaveLength(1);
});
it("matches when matcher is '*'", () => {
const config: HooksConfig = {
PreToolUse: [{ matcher: "*", hooks: baseGroup.hooks }],
};
const result = getMatchingHookGroups(config, "PreToolUse", "Bash");
expect(result).toHaveLength(1);
});
it("matches with regex matcher", () => {
const config: HooksConfig = {
PreToolUse: [{ matcher: "^Bash$", hooks: baseGroup.hooks }],
};
expect(getMatchingHookGroups(config, "PreToolUse", "Bash")).toHaveLength(
1,
);
expect(getMatchingHookGroups(config, "PreToolUse", "Read")).toHaveLength(
0,
);
});
it("matches partial regex", () => {
const config: HooksConfig = {
PreToolUse: [{ matcher: "File", hooks: baseGroup.hooks }],
};
expect(
getMatchingHookGroups(config, "PreToolUse", "ReadFile"),
).toHaveLength(1);
expect(getMatchingHookGroups(config, "PreToolUse", "Bash")).toHaveLength(
0,
);
});
it("returns empty for missing event", () => {
const config: HooksConfig = {};
expect(getMatchingHookGroups(config, "PreToolUse", "Bash")).toHaveLength(
0,
);
});
it("matches all groups for an event when matcher value is undefined (no-matcher events)", () => {
const config: HooksConfig = {
UserPromptSubmit: [
{ matcher: "something", hooks: baseGroup.hooks },
baseGroup,
],
};
// UserPromptSubmit is a no-matcher event, matcherValue is undefined
const result = getMatchingHookGroups(
config,
"UserPromptSubmit",
undefined,
);
expect(result).toHaveLength(2);
});
it("handles invalid regex gracefully", () => {
const config: HooksConfig = {
PreToolUse: [{ matcher: "[invalid", hooks: baseGroup.hooks }],
};
// Invalid regex should not match
expect(getMatchingHookGroups(config, "PreToolUse", "Bash")).toHaveLength(
0,
);
});
it("filters multiple groups correctly", () => {
const config: HooksConfig = {
PreToolUse: [
{
matcher: "^Bash$",
hooks: [{ type: "command", command: "echo a" }],
},
{
matcher: "^Read$",
hooks: [{ type: "command", command: "echo b" }],
},
{ hooks: [{ type: "command", command: "echo c" }] }, // matches all
],
};
const result = getMatchingHookGroups(config, "PreToolUse", "Bash");
expect(result).toHaveLength(2); // ^Bash$ and wildcard
});
});
describe("loadHooksConfig", () => {
let tmpDir: string;
let fakeHome: string;
let projectDir: string;
let originalContinueGlobalDir: string | undefined;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "hooks-test-"));
// Use separate dirs for home and project to avoid path collision
fakeHome = path.join(tmpDir, "home");
projectDir = path.join(tmpDir, "project");
fs.mkdirSync(fakeHome, { recursive: true });
fs.mkdirSync(projectDir, { recursive: true });
// Override CONTINUE_GLOBAL_DIR so that user-global settings
// from the real ~/.continue/settings.json don't leak into tests
originalContinueGlobalDir = process.env.CONTINUE_GLOBAL_DIR;
process.env.CONTINUE_GLOBAL_DIR = path.join(fakeHome, ".continue");
});
afterEach(() => {
if (originalContinueGlobalDir === undefined) {
delete process.env.CONTINUE_GLOBAL_DIR;
} else {
process.env.CONTINUE_GLOBAL_DIR = originalContinueGlobalDir;
}
fs.rmSync(tmpDir, { recursive: true, force: true });
});
// Helper: call loadHooksConfig with isolated homeDir and project cwd
function loadIsolated(cwd?: string) {
return loadHooksConfig(cwd ?? projectDir, fakeHome);
}
it("returns empty config when no settings files exist", () => {
const result = loadIsolated();
expect(result.hooks).toEqual({});
expect(result.disabled).toBe(false);
});
it("loads hooks from .continue/settings.json", () => {
const settingsDir = path.join(projectDir, ".continue");
fs.mkdirSync(settingsDir, { recursive: true });
fs.writeFileSync(
path.join(settingsDir, "settings.json"),
JSON.stringify({
hooks: {
PreToolUse: [
{
matcher: "Bash",
hooks: [{ type: "command", command: "echo test" }],
},
],
},
}),
);
const result = loadIsolated();
expect(result.hooks.PreToolUse).toHaveLength(1);
expect(result.hooks.PreToolUse![0].matcher).toBe("Bash");
});
it("loads hooks from .claude/settings.json for cross-compatibility", () => {
const settingsDir = path.join(projectDir, ".claude");
fs.mkdirSync(settingsDir, { recursive: true });
fs.writeFileSync(
path.join(settingsDir, "settings.json"),
JSON.stringify({
hooks: {
PostToolUse: [
{
hooks: [{ type: "command", command: "echo claude" }],
},
],
},
}),
);
const result = loadIsolated();
expect(result.hooks.PostToolUse).toHaveLength(1);
});
it("merges hooks from multiple settings files", () => {
// .claude/settings.json (project-level)
const claudeDir = path.join(projectDir, ".claude");
fs.mkdirSync(claudeDir, { recursive: true });
fs.writeFileSync(
path.join(claudeDir, "settings.json"),
JSON.stringify({
hooks: {
PreToolUse: [
{ hooks: [{ type: "command", command: "echo claude" }] },
],
},
}),
);
// .continue/settings.json (project-level)
const continueDir = path.join(projectDir, ".continue");
fs.mkdirSync(continueDir, { recursive: true });
fs.writeFileSync(
path.join(continueDir, "settings.json"),
JSON.stringify({
hooks: {
PreToolUse: [
{ hooks: [{ type: "command", command: "echo continue" }] },
],
},
}),
);
const result = loadIsolated();
// Both hooks should be merged (appended)
expect(result.hooks.PreToolUse).toHaveLength(2);
});
it("respects disableAllHooks", () => {
const settingsDir = path.join(projectDir, ".continue");
fs.mkdirSync(settingsDir, { recursive: true });
fs.writeFileSync(
path.join(settingsDir, "settings.json"),
JSON.stringify({
disableAllHooks: true,
hooks: {
PreToolUse: [
{ hooks: [{ type: "command", command: "echo test" }] },
],
},
}),
);
const result = loadIsolated();
expect(result.disabled).toBe(true);
// Hooks are still loaded but won't be executed
expect(result.hooks.PreToolUse).toHaveLength(1);
});
it("handles malformed settings files gracefully", () => {
const settingsDir = path.join(projectDir, ".continue");
fs.mkdirSync(settingsDir, { recursive: true });
fs.writeFileSync(
path.join(settingsDir, "settings.json"),
"not valid json",
);
const result = loadIsolated();
expect(result.hooks).toEqual({});
});
});
});
// ---------------------------------------------------------------------------
// hookRunner tests
// ---------------------------------------------------------------------------
// hookRunner tests spawn /bin/sh subprocesses — skip on Windows where cmd.exe
// has incompatible shell syntax (redirections, single-quote echo, sleep, etc.)
const describeUnix = process.platform === "win32" ? describe.skip : describe;
describeUnix("hookRunner", () => {
describe("runHooks - command execution", () => {
it("executes a simple command hook and returns stdout", async () => {
const config: HooksConfig = {
PreToolUse: [
{
hooks: [{ type: "command", command: 'echo "hello from hook"' }],
},
],
};
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PreToolUse",
tool_name: "Bash",
tool_input: { command: "ls" },
tool_use_id: "test-id",
};
const result = await runHooks(config, input);
expect(result.blocked).toBe(false);
expect(result.results).toHaveLength(1);
expect(result.results[0].stdout).toContain("hello from hook");
expect(result.results[0].exitCode).toBe(0);
});
it("blocks when command exits with code 2", async () => {
const config: HooksConfig = {
PreToolUse: [
{
hooks: [
{
type: "command",
command: 'echo "blocked reason" >&2; exit 2',
},
],
},
],
};
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PreToolUse",
tool_name: "Bash",
tool_input: { command: "rm -rf /" },
tool_use_id: "test-id",
};
const result = await runHooks(config, input);
expect(result.blocked).toBe(true);
expect(result.blockReason).toContain("blocked reason");
});
it("does not block on non-zero exit codes other than 2", async () => {
const config: HooksConfig = {
PreToolUse: [
{
hooks: [
{
type: "command",
command: "exit 1",
},
],
},
],
};
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PreToolUse",
tool_name: "Bash",
tool_input: {},
tool_use_id: "test-id",
};
const result = await runHooks(config, input);
expect(result.blocked).toBe(false);
expect(result.results[0].exitCode).toBe(1);
});
it("passes JSON input on stdin", async () => {
const config: HooksConfig = {
PreToolUse: [
{
hooks: [
{
type: "command",
// Read stdin and echo tool_name field
command:
"cat | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d['tool_name'])\"",
},
],
},
],
};
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PreToolUse",
tool_name: "MyTool",
tool_input: {},
tool_use_id: "test-id",
};
const result = await runHooks(config, input);
expect(result.results[0].stdout).toContain("MyTool");
});
it("parses JSON output from hook stdout", async () => {
const jsonOutput = JSON.stringify({
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: "dangerous operation",
},
});
const config: HooksConfig = {
PreToolUse: [
{
hooks: [
{
type: "command",
command: `echo '${jsonOutput}'`,
},
],
},
],
};
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PreToolUse",
tool_name: "Bash",
tool_input: {},
tool_use_id: "test-id",
};
const result = await runHooks(config, input);
expect(result.blocked).toBe(true);
expect(result.permissionDecision).toBe("deny");
expect(result.permissionDecisionReason).toBe("dangerous operation");
});
it("allows via PreToolUse hookSpecificOutput", async () => {
const jsonOutput = JSON.stringify({
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "allow",
},
});
const config: HooksConfig = {
PreToolUse: [
{
hooks: [
{
type: "command",
command: `echo '${jsonOutput}'`,
},
],
},
],
};
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PreToolUse",
tool_name: "Bash",
tool_input: {},
tool_use_id: "test-id",
};
const result = await runHooks(config, input);
expect(result.blocked).toBe(false);
expect(result.permissionDecision).toBe("allow");
});
it("blocks when JSON output has decision: 'block'", async () => {
const jsonOutput = JSON.stringify({
decision: "block",
reason: "Blocked by policy",
});
const config: HooksConfig = {
UserPromptSubmit: [
{
hooks: [
{
type: "command",
command: `echo '${jsonOutput}'`,
},
],
},
],
};
const input: UserPromptSubmitInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "UserPromptSubmit",
prompt: "delete everything",
};
const result = await runHooks(config, input);
expect(result.blocked).toBe(true);
expect(result.blockReason).toBe("Blocked by policy");
});
});
describe("runHooks - matcher filtering", () => {
it("only runs hooks that match the tool name", async () => {
const config: HooksConfig = {
PreToolUse: [
{
matcher: "^Bash$",
hooks: [{ type: "command", command: "echo matched" }],
},
{
matcher: "^Read$",
hooks: [{ type: "command", command: "echo not-matched" }],
},
],
};
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PreToolUse",
tool_name: "Bash",
tool_input: {},
tool_use_id: "test-id",
};
const result = await runHooks(config, input);
expect(result.results).toHaveLength(1);
expect(result.results[0].stdout).toContain("matched");
});
it("runs all hooks for events without matchers (e.g., Stop)", async () => {
const config: HooksConfig = {
Stop: [
{
matcher: "ignored_for_stop",
hooks: [{ type: "command", command: "echo stop1" }],
},
{
hooks: [{ type: "command", command: "echo stop2" }],
},
],
};
const input: StopInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "Stop",
stop_hook_active: true,
};
const result = await runHooks(config, input);
// Both groups should match because Stop is a no-matcher event
expect(result.results).toHaveLength(2);
});
});
describe("runHooks - deduplication", () => {
it("deduplicates identical command hooks", async () => {
const config: HooksConfig = {
PreToolUse: [
{
hooks: [{ type: "command", command: "echo dedup" }],
},
{
hooks: [{ type: "command", command: "echo dedup" }],
},
],
};
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PreToolUse",
tool_name: "Bash",
tool_input: {},
tool_use_id: "test-id",
};
const result = await runHooks(config, input);
// Should only run once despite appearing twice
expect(result.results).toHaveLength(1);
});
it("does not deduplicate different commands", async () => {
const config: HooksConfig = {
PreToolUse: [
{
hooks: [
{ type: "command", command: "echo first" },
{ type: "command", command: "echo second" },
],
},
],
};
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PreToolUse",
tool_name: "Bash",
tool_input: {},
tool_use_id: "test-id",
};
const result = await runHooks(config, input);
expect(result.results).toHaveLength(2);
});
});
describe("runHooks - additionalContext", () => {
it("collects stdout as additionalContext for UserPromptSubmit on exit 0", async () => {
const config: HooksConfig = {
UserPromptSubmit: [
{
hooks: [{ type: "command", command: "echo 'extra context'" }],
},
],
};
const input: UserPromptSubmitInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "UserPromptSubmit",
prompt: "hello",
};
const result = await runHooks(config, input);
expect(result.blocked).toBe(false);
expect(result.additionalContext).toContain("extra context");
});
it("collects stdout as additionalContext for SessionStart on exit 0", async () => {
const config: HooksConfig = {
SessionStart: [
{
hooks: [{ type: "command", command: "echo 'session info'" }],
},
],
};
const input: SessionStartInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "SessionStart",
source: "startup",
};
const result = await runHooks(config, input);
expect(result.additionalContext).toContain("session info");
});
it("collects additionalContext from hookSpecificOutput", async () => {
const jsonOutput = JSON.stringify({
hookSpecificOutput: {
hookEventName: "PostToolUse",
additionalContext: "Tool completed successfully with changes",
},
});
const config: HooksConfig = {
PostToolUse: [
{
hooks: [
{
type: "command",
command: `echo '${jsonOutput}'`,
},
],
},
],
};
const input = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PostToolUse" as const,
tool_name: "Bash",
tool_input: {},
tool_response: "ok",
tool_use_id: "test-id",
};
const result = await runHooks(config, input);
expect(result.additionalContext).toContain(
"Tool completed successfully with changes",
);
});
});
describe("runHooks - async hooks", () => {
it("fires async hooks without blocking", async () => {
const config: HooksConfig = {
PreToolUse: [
{
hooks: [
{
type: "command",
command: "sleep 10", // Long-running async hook
async: true,
},
{
type: "command",
command: "echo sync-hook",
// sync (default)
},
],
},
],
};
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PreToolUse",
tool_name: "Bash",
tool_input: {},
tool_use_id: "test-id",
};
const start = Date.now();
const result = await runHooks(config, input);
const elapsed = Date.now() - start;
// Should complete quickly (not wait for the 10s sleep)
expect(elapsed).toBeLessThan(5000);
// Only sync hook result should be in results
expect(result.results).toHaveLength(1);
expect(result.results[0].stdout).toContain("sync-hook");
});
});
describe("runHooks - prompt/agent types", () => {
it("returns no-op for prompt hook type", async () => {
const config: HooksConfig = {
PreToolUse: [
{
hooks: [
{
type: "prompt",
prompt: "Is this safe?",
},
],
},
],
};
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PreToolUse",
tool_name: "Bash",
tool_input: {},
tool_use_id: "test-id",
};
const result = await runHooks(config, input);
expect(result.blocked).toBe(false);
expect(result.results).toHaveLength(1);
expect(result.results[0].exitCode).toBe(0);
});
});
describe("runHooks - no matching hooks", () => {
it("returns empty result when no hooks configured for event", async () => {
const config: HooksConfig = {};
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PreToolUse",
tool_name: "Bash",
tool_input: {},
tool_use_id: "test-id",
};
const result = await runHooks(config, input);
expect(result.blocked).toBe(false);
expect(result.results).toHaveLength(0);
});
it("returns empty result when matcher does not match", async () => {
const config: HooksConfig = {
PreToolUse: [
{
matcher: "^NonExistentTool$",
hooks: [{ type: "command", command: "echo should-not-run" }],
},
],
};
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PreToolUse",
tool_name: "Bash",
tool_input: {},
tool_use_id: "test-id",
};
const result = await runHooks(config, input);
expect(result.blocked).toBe(false);
expect(result.results).toHaveLength(0);
});
});
describe("runHooks - environment variables", () => {
it("sets CONTINUE_PROJECT_DIR and CLAUDE_PROJECT_DIR env vars", async () => {
const config: HooksConfig = {
PreToolUse: [
{
hooks: [
{
type: "command",
command: 'echo "$CONTINUE_PROJECT_DIR|$CLAUDE_PROJECT_DIR"',
},
],
},
],
};
const testCwd = process.cwd();
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: testCwd,
hook_event_name: "PreToolUse",
tool_name: "Bash",
tool_input: {},
tool_use_id: "test-id",
};
const result = await runHooks(config, input, testCwd);
expect(result.results[0].stdout).toContain(testCwd);
// Both vars should be set to the same cwd
expect(result.results[0].stdout).toBe(`${testCwd}|${testCwd}`);
});
});
describe("runHooks - error handling", () => {
it("handles command not found gracefully", async () => {
const config: HooksConfig = {
PreToolUse: [
{
hooks: [
{
type: "command",
command: "this_command_does_not_exist_12345",
},
],
},
],
};
const input: PreToolUseInput = {
session_id: "test-session",
transcript_path: "",
cwd: process.cwd(),
hook_event_name: "PreToolUse",
tool_name: "Bash",
tool_input: {},
tool_use_id: "test-id",
};
// Should not throw
const result = await runHooks(config, input);
expect(result.blocked).toBe(false);
// Exit code should be non-zero (127 for command not found)
expect(result.results[0].exitCode).not.toBe(0);
});
});
});

View file

@ -0,0 +1,424 @@
/**
* Claude Code-compatible hooks system for Continue CLI.
*
* These types match the exact schemas from Claude Code so that any hook
* written for `claude` works with `cn` out of the box.
*/
// ---------------------------------------------------------------------------
// Hook event names
// ---------------------------------------------------------------------------
export const HOOK_EVENT_NAMES = [
"PreToolUse",
"PostToolUse",
"PostToolUseFailure",
"PermissionRequest",
"UserPromptSubmit",
"SessionStart",
"SessionEnd",
"Stop",
"Notification",
"SubagentStart",
"SubagentStop",
"PreCompact",
"ConfigChange",
"TeammateIdle",
"TaskCompleted",
"WorktreeCreate",
"WorktreeRemove",
] as const;
export type HookEventName = (typeof HOOK_EVENT_NAMES)[number];
// ---------------------------------------------------------------------------
// Hook handler configuration (what users write in settings.json)
// ---------------------------------------------------------------------------
/** Common fields shared by all hook handler types */
interface HookHandlerBase {
/** Seconds before canceling. Defaults: 600 for command, 30 for http/prompt, 60 for agent */
timeout?: number;
/** Custom spinner message displayed while the hook runs */
statusMessage?: string;
/** If true, runs only once per session then is removed (skills only) */
once?: boolean;
}
/** Command hook handler — runs a shell command */
export interface CommandHookHandler extends HookHandlerBase {
type: "command";
/** Shell command to execute */
command: string;
/** If true, runs in the background without blocking */
async?: boolean;
}
/** HTTP hook handler — sends a POST request */
export interface HttpHookHandler extends HookHandlerBase {
type: "http";
/** URL to send the POST request to */
url: string;
/** Additional HTTP headers (values support env var interpolation) */
headers?: Record<string, string>;
/** Environment variable names allowed in header interpolation */
allowedEnvVars?: string[];
}
/** Prompt hook handler — single-turn LLM evaluation */
export interface PromptHookHandler extends HookHandlerBase {
type: "prompt";
/** Prompt text. Use $ARGUMENTS as a placeholder for hook input JSON */
prompt: string;
/** Model to use. Defaults to a fast model */
model?: string;
}
/** Agent hook handler — multi-turn subagent with tool access */
export interface AgentHookHandler extends HookHandlerBase {
type: "agent";
/** Prompt text. Use $ARGUMENTS as a placeholder for hook input JSON */
prompt: string;
/** Model to use. Defaults to a fast model */
model?: string;
}
export type HookHandler =
| CommandHookHandler
| HttpHookHandler
| PromptHookHandler
| AgentHookHandler;
/** A matcher group: a regex filter + one or more handlers */
export interface HookMatcherGroup {
/** Regex string to filter when hooks fire. "*", "", or omitted = match all */
matcher?: string;
/** The hook handlers to run when the matcher matches */
hooks: HookHandler[];
}
/** Top-level hooks configuration object (the `hooks` key in settings.json) */
export type HooksConfig = Partial<Record<HookEventName, HookMatcherGroup[]>>;
/** Full settings file shape (only the hooks portion) */
export interface HookSettingsFile {
hooks?: HooksConfig;
/** Plugin-level description */
description?: string;
/** If true, all hooks are disabled */
disableAllHooks?: boolean;
}
// ---------------------------------------------------------------------------
// Hook input — JSON sent to hooks on stdin / as POST body
// ---------------------------------------------------------------------------
/** Common fields included in every hook event input */
export interface HookInputBase {
session_id: string;
transcript_path: string;
cwd: string;
permission_mode?: string;
}
export interface PreToolUseInput extends HookInputBase {
hook_event_name: "PreToolUse";
tool_name: string;
tool_input: unknown;
tool_use_id: string;
}
export interface PostToolUseInput extends HookInputBase {
hook_event_name: "PostToolUse";
tool_name: string;
tool_input: unknown;
tool_response: unknown;
tool_use_id: string;
}
export interface PostToolUseFailureInput extends HookInputBase {
hook_event_name: "PostToolUseFailure";
tool_name: string;
tool_input: unknown;
tool_use_id: string;
error: string;
is_interrupt?: boolean;
}
export interface PermissionRequestInput extends HookInputBase {
hook_event_name: "PermissionRequest";
tool_name: string;
tool_input: unknown;
}
export interface UserPromptSubmitInput extends HookInputBase {
hook_event_name: "UserPromptSubmit";
prompt: string;
}
export type SessionStartSource = "startup" | "resume" | "clear" | "compact";
export interface SessionStartInput extends HookInputBase {
hook_event_name: "SessionStart";
source: SessionStartSource;
agent_type?: string;
model?: string;
}
export type SessionEndReason =
| "clear"
| "logout"
| "prompt_input_exit"
| "other"
| "bypass_permissions_disabled";
export interface SessionEndInput extends HookInputBase {
hook_event_name: "SessionEnd";
reason: SessionEndReason;
}
export interface StopInput extends HookInputBase {
hook_event_name: "Stop";
stop_hook_active: boolean;
last_assistant_message?: string;
}
export interface NotificationInput extends HookInputBase {
hook_event_name: "Notification";
message: string;
title?: string;
notification_type: string;
}
export interface SubagentStartInput extends HookInputBase {
hook_event_name: "SubagentStart";
agent_id: string;
agent_type: string;
}
export interface SubagentStopInput extends HookInputBase {
hook_event_name: "SubagentStop";
stop_hook_active: boolean;
agent_id: string;
agent_transcript_path: string;
agent_type: string;
last_assistant_message?: string;
}
export interface PreCompactInput extends HookInputBase {
hook_event_name: "PreCompact";
trigger: "manual" | "auto";
custom_instructions: string | null;
}
export interface ConfigChangeInput extends HookInputBase {
hook_event_name: "ConfigChange";
source: string;
file_path?: string;
}
export interface TeammateIdleInput extends HookInputBase {
hook_event_name: "TeammateIdle";
teammate_name: string;
team_name: string;
}
export interface TaskCompletedInput extends HookInputBase {
hook_event_name: "TaskCompleted";
task_id: string;
task_subject: string;
task_description?: string;
teammate_name?: string;
team_name?: string;
}
export interface WorktreeCreateInput extends HookInputBase {
hook_event_name: "WorktreeCreate";
name: string;
}
export interface WorktreeRemoveInput extends HookInputBase {
hook_event_name: "WorktreeRemove";
worktree_path: string;
}
export type HookInput =
| PreToolUseInput
| PostToolUseInput
| PostToolUseFailureInput
| PermissionRequestInput
| UserPromptSubmitInput
| SessionStartInput
| SessionEndInput
| StopInput
| NotificationInput
| SubagentStartInput
| SubagentStopInput
| PreCompactInput
| ConfigChangeInput
| TeammateIdleInput
| TaskCompletedInput
| WorktreeCreateInput
| WorktreeRemoveInput;
// ---------------------------------------------------------------------------
// Hook output — JSON returned by hooks on stdout / response body
// ---------------------------------------------------------------------------
/** PreToolUse-specific output */
export interface PreToolUseHookOutput {
hookEventName: "PreToolUse";
permissionDecision?: "allow" | "deny" | "ask";
permissionDecisionReason?: string;
updatedInput?: Record<string, unknown>;
additionalContext?: string;
}
/** UserPromptSubmit-specific output */
export interface UserPromptSubmitHookOutput {
hookEventName: "UserPromptSubmit";
additionalContext?: string;
}
/** SessionStart-specific output */
export interface SessionStartHookOutput {
hookEventName: "SessionStart";
additionalContext?: string;
}
/** PostToolUse-specific output */
export interface PostToolUseHookOutput {
hookEventName: "PostToolUse";
additionalContext?: string;
updatedMCPToolOutput?: unknown;
}
/** PostToolUseFailure-specific output */
export interface PostToolUseFailureHookOutput {
hookEventName: "PostToolUseFailure";
additionalContext?: string;
}
/** Notification-specific output */
export interface NotificationHookOutput {
hookEventName: "Notification";
additionalContext?: string;
}
/** SubagentStart-specific output */
export interface SubagentStartHookOutput {
hookEventName: "SubagentStart";
additionalContext?: string;
}
/** PermissionRequest-specific output */
export interface PermissionRequestHookOutput {
hookEventName: "PermissionRequest";
decision:
| {
behavior: "allow";
updatedInput?: Record<string, unknown>;
}
| {
behavior: "deny";
message?: string;
interrupt?: boolean;
};
}
export type HookSpecificOutput =
| PreToolUseHookOutput
| UserPromptSubmitHookOutput
| SessionStartHookOutput
| PostToolUseHookOutput
| PostToolUseFailureHookOutput
| NotificationHookOutput
| SubagentStartHookOutput
| PermissionRequestHookOutput;
/** The full JSON output schema returned by hooks */
export interface HookOutput {
continue?: boolean;
suppressOutput?: boolean;
stopReason?: string;
decision?: "approve" | "block";
systemMessage?: string;
reason?: string;
hookSpecificOutput?: HookSpecificOutput;
}
// ---------------------------------------------------------------------------
// Hook execution result (internal)
// ---------------------------------------------------------------------------
export interface HookExecutionResult {
/** The parsed output from the hook, if any */
output: HookOutput | null;
/** Raw stdout from the hook */
stdout: string;
/** Raw stderr from the hook */
stderr: string;
/** Exit code (command hooks only) */
exitCode: number;
/** Whether the hook blocked the action (exit code 2 or decision:"block") */
blocked: boolean;
/** The blocking error message (from stderr or output.reason) */
blockReason?: string;
}
/**
* Aggregated result from running all matching hooks for an event.
* Used by integration points to decide what to do.
*/
export interface HookEventResult {
/** Whether any hook blocked the action */
blocked: boolean;
/** The reason the action was blocked (first blocking hook's reason) */
blockReason?: string;
/** Additional context to inject (concatenated from all hooks) */
additionalContext?: string;
/** For PreToolUse: permission decision from hooks */
permissionDecision?: "allow" | "deny" | "ask";
/** For PreToolUse: reason for permission decision */
permissionDecisionReason?: string;
/** For PreToolUse: updated tool input */
updatedInput?: Record<string, unknown>;
/** For PermissionRequest: the decision */
permissionRequestDecision?: PermissionRequestHookOutput["decision"];
/** All individual hook results */
results: HookExecutionResult[];
}
// ---------------------------------------------------------------------------
// Matcher field mapping
// ---------------------------------------------------------------------------
/**
* Which field from the hook input the matcher regex runs against,
* per event type. Events not listed here don't support matchers.
*/
export const MATCHER_FIELD_MAP: Partial<Record<HookEventName, string>> = {
PreToolUse: "tool_name",
PostToolUse: "tool_name",
PostToolUseFailure: "tool_name",
PermissionRequest: "tool_name",
SessionStart: "source",
SessionEnd: "reason",
Notification: "notification_type",
SubagentStart: "agent_type",
SubagentStop: "agent_type",
PreCompact: "trigger",
ConfigChange: "source",
};
/**
* Events that don't support matchers — they always fire on every occurrence.
*/
export const NO_MATCHER_EVENTS: HookEventName[] = [
"UserPromptSubmit",
"Stop",
"TeammateIdle",
"TaskCompleted",
"WorktreeCreate",
"WorktreeRemove",
];

View file

@ -74,9 +74,9 @@ export function useService<T>(serviceName: string): ServiceResult<T> & {
};
}, [serviceName, container]);
const reload = async (): Promise<void> => {
const reload = useCallback(async (): Promise<void> => {
await container.reload(serviceName);
};
}, [container, serviceName]);
return {
...result,
@ -97,6 +97,9 @@ export function useServices<T extends Record<string, any>>(
} {
const container = useServiceContainer();
// Memoize serviceNames to avoid unnecessary recalculations
const serviceNamesKey = serviceNames.join(",");
const getServiceStates = useCallback(() => {
const services: Partial<T> = {};
let hasLoading = false;
@ -114,7 +117,6 @@ export function useServices<T extends Record<string, any>>(
container.load(serviceName as string).catch(() => {});
} else if (result.state === "ready" && result.value !== null) {
services[serviceName] = result.value as T[keyof T];
} else {
}
}
@ -123,7 +125,7 @@ export function useServices<T extends Record<string, any>>(
hasError,
services,
};
}, [serviceNames, container]);
}, [serviceNamesKey, container]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
@ -162,7 +164,7 @@ export function useServices<T extends Record<string, any>>(
return () => {
listeners.forEach((cleanup) => cleanup());
};
}, [serviceNames.join(","), container, getServiceStates]);
}, [serviceNamesKey, container, getServiceStates]);
const allReady = serviceNames.every((name) =>
container.isReady(name as string),

View file

@ -1,4 +1,5 @@
import { loadAuthConfig } from "../auth/workos.js";
import { HookService } from "../hooks/HookService.js";
import { initializeWithOnboarding } from "../onboarding.js";
import {
setBetaSubagentToolEnabled,
@ -53,6 +54,7 @@ const toolPermissionService = new ToolPermissionService();
const systemMessageService = new SystemMessageService();
const artifactUploadService = new ArtifactUploadService();
const gitAiIntegrationService = new GitAiIntegrationService();
const hookService = new HookService();
/**
* Initialize all services and register them with the service container
@ -332,6 +334,12 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
[], // No dependencies
);
serviceContainer.register(
SERVICE_NAMES.HOOKS,
() => hookService.initialize(),
[], // No dependencies
);
// Eagerly initialize all services to ensure they're ready when needed
// This avoids race conditions and "service not ready" errors
await serviceContainer.initializeAll();
@ -397,6 +405,7 @@ export const services = {
gitAiIntegration: gitAiIntegrationService,
backgroundJobs: backgroundJobService,
quiz: quizService,
hooks: hookService,
} as const;
export type ServicesType = typeof services;

View file

@ -159,6 +159,7 @@ export const SERVICE_NAMES = {
GIT_AI_INTEGRATION: "gitAiIntegration",
BACKGROUND_JOBS: "backgroundJobs",
QUIZ: "quiz",
HOOKS: "hooks",
} as const;
/**