@goodfoot/agent-hooks 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +137 -0
  2. package/dist/agents/antigravity/events.js +42 -0
  3. package/dist/agents/antigravity/hooks.js +59 -0
  4. package/dist/agents/antigravity/index.js +28 -0
  5. package/dist/agents/antigravity/outputs.js +81 -0
  6. package/dist/agents/antigravity/transport.js +84 -0
  7. package/dist/agents/antigravity/types.js +11 -0
  8. package/dist/agents/claude-code/env.js +27 -0
  9. package/dist/agents/claude-code/events.js +87 -0
  10. package/dist/agents/claude-code/hooks.js +1000 -0
  11. package/dist/agents/claude-code/index.js +57 -0
  12. package/dist/agents/claude-code/outputs.js +579 -0
  13. package/dist/agents/claude-code/tool-helpers.js +840 -0
  14. package/dist/agents/claude-code/transport.js +254 -0
  15. package/dist/agents/claude-code/types.js +11 -0
  16. package/dist/agents/codex/cli-support.js +318 -0
  17. package/dist/agents/codex/constants.js +29 -0
  18. package/dist/agents/codex/events.js +68 -0
  19. package/dist/agents/codex/hooks.js +93 -0
  20. package/dist/agents/codex/index.js +21 -0
  21. package/dist/agents/codex/outputs.js +189 -0
  22. package/dist/agents/codex/scaffold.js +273 -0
  23. package/dist/agents/codex/transport.js +139 -0
  24. package/dist/agents/codex/types.js +1 -0
  25. package/dist/cli.js +1357 -0
  26. package/dist/constants.js +39 -0
  27. package/dist/core/define-hook.js +61 -0
  28. package/dist/core/env.js +186 -0
  29. package/dist/core/logger.js +508 -0
  30. package/dist/core/stdin.js +38 -0
  31. package/dist/core/transport.js +231 -0
  32. package/dist/core/types.js +10 -0
  33. package/dist/index.js +17 -0
  34. package/dist/scaffold.js +512 -0
  35. package/package.json +61 -0
  36. package/types/agents/antigravity/events.d.ts +50 -0
  37. package/types/agents/antigravity/hooks.d.ts +76 -0
  38. package/types/agents/antigravity/index.d.ts +27 -0
  39. package/types/agents/antigravity/outputs.d.ts +107 -0
  40. package/types/agents/antigravity/transport.d.ts +47 -0
  41. package/types/agents/antigravity/types.d.ts +58 -0
  42. package/types/agents/claude-code/env.d.ts +27 -0
  43. package/types/agents/claude-code/events.d.ts +69 -0
  44. package/types/agents/claude-code/hooks.d.ts +1182 -0
  45. package/types/agents/claude-code/index.d.ts +23 -0
  46. package/types/agents/claude-code/outputs.d.ts +1160 -0
  47. package/types/agents/claude-code/tool-helpers.d.ts +807 -0
  48. package/types/agents/claude-code/transport.d.ts +119 -0
  49. package/types/agents/claude-code/types.d.ts +557 -0
  50. package/types/agents/codex/cli-support.d.ts +105 -0
  51. package/types/agents/codex/constants.d.ts +10 -0
  52. package/types/agents/codex/events.d.ts +63 -0
  53. package/types/agents/codex/hooks.d.ts +135 -0
  54. package/types/agents/codex/index.d.ts +19 -0
  55. package/types/agents/codex/outputs.d.ts +190 -0
  56. package/types/agents/codex/scaffold.d.ts +14 -0
  57. package/types/agents/codex/transport.d.ts +74 -0
  58. package/types/agents/codex/types.d.ts +131 -0
  59. package/types/cli.d.ts +315 -0
  60. package/types/constants.d.ts +9 -0
  61. package/types/core/define-hook.d.ts +39 -0
  62. package/types/core/env.d.ts +150 -0
  63. package/types/core/logger.d.ts +476 -0
  64. package/types/core/stdin.d.ts +21 -0
  65. package/types/core/transport.d.ts +131 -0
  66. package/types/core/types.d.ts +137 -0
  67. package/types/index.d.ts +18 -0
  68. package/types/scaffold.d.ts +46 -0
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Wire transport for Claude Code hooks.
3
+ *
4
+ * Rewritten against the core `drive()`/`Transport` interface (plan step 2.1);
5
+ * the wire semantics carried over from the source runtime are:
6
+ *
7
+ * - success → output JSON serialized to stdout, exit 0 (empty object `{}`
8
+ * when the handler returned nothing);
9
+ * - a returned `stderr` payload → that message written to stderr, exit code
10
+ * `EXIT_CODES.BLOCK` (2) and **no stdout write at all** — Claude Code's
11
+ * hook-result parser treats any stdout that parses as JSON as success
12
+ * regardless of exit code, so blocking via stderr only takes effect when
13
+ * stdout carries no JSON;
14
+ * - an unexpected handler error under the default `"error"` policy → its
15
+ * stacktrace on stderr, exit 2, no stdout;
16
+ * - malformed/unreadable stdin → fail-open unconditionally, `{}` + exit 0;
17
+ * - worktree events (`WorktreeCreate`, always; `WorktreeRemove`, when a path
18
+ * is supplied) carry their plain-text payload in `rawStdout`, which is
19
+ * written verbatim — the host reads stdout as the worktree path.
20
+ *
21
+ * Plus the class-finding fix new to this package: a caught
22
+ * {@link HookBlockError} — classified by `drive()` **before** policy is ever
23
+ * consulted — is translated per event via {@link BLOCK_SHAPE_BY_EVENT}
24
+ * (`PreToolUse`/`PermissionRequest` get their narrower native deny shapes,
25
+ * every other event gets `{ continue: false, stopReason }`), so an advisory
26
+ * event's intentional block survives even when the decision computation
27
+ * itself throws mid-way.
28
+ * @module
29
+ * @example
30
+ * ```typescript
31
+ * // In a compiled hook file
32
+ * import { execute } from './transport.js';
33
+ * import myHook from './my-hook.js';
34
+ *
35
+ * execute(myHook);
36
+ * ```
37
+ * @see https://code.claude.com/docs/en/hooks
38
+ */
39
+ import type { Transport } from "../../core/transport.js";
40
+ import type { HookFunction } from "../../core/types.js";
41
+ import type { SpecificHookOutput, SyncHookJSONOutput } from "./outputs.js";
42
+ import type { HookEventName, HookInput } from "./types.js";
43
+ /**
44
+ * Per-event translation table for a caught {@link HookBlockError}.
45
+ *
46
+ * Absent events fall back to the whole-session shape
47
+ * (`{ continue: false, stopReason }`). The two entries present here are the
48
+ * events whose native protocol refuses *that one tool call* rather than
49
+ * halting the session — reusing exactly the shapes `outputs.ts`'s builders
50
+ * produce natively:
51
+ *
52
+ * - `PreToolUse` → `hookSpecificOutput.permissionDecision: "deny"`
53
+ * - `PermissionRequest` → `hookSpecificOutput.decision.behavior: "deny"`
54
+ */
55
+ export declare const BLOCK_SHAPE_BY_EVENT: Readonly<Partial<Record<HookEventName, (reason: string) => SyncHookJSONOutput>>>;
56
+ /**
57
+ * Converts a SpecificHookOutput to HookOutput for wire format.
58
+ *
59
+ * SpecificHookOutput types have: { _type, stdout, stderr?, rawStdout? }
60
+ * HookOutput has: { stdout, stderr?, rawStdout? }
61
+ *
62
+ * Since output builders now produce wire-format directly, this function
63
+ * simply strips the `_type` discriminator field.
64
+ * @param specificOutput - The specific output from a hook handler
65
+ * @returns HookOutput ready for serialization
66
+ * @see https://code.claude.com/docs/en/hooks#hook-output-structure
67
+ */
68
+ export declare function convertToHookOutput(specificOutput: SpecificHookOutput): {
69
+ stdout: SyncHookJSONOutput;
70
+ stderr?: string;
71
+ rawStdout?: string;
72
+ };
73
+ /**
74
+ * Builds the Claude Code wire transport for one event.
75
+ *
76
+ * `policy`/`onUnexpectedError` close over the executing hook's configuration
77
+ * purely to reproduce the source runtime's serialize-failure wiring: under
78
+ * `"continue"` a serialization failure still emits `{}` at exit 0, while the
79
+ * default `"error"` policy surfaces the stacktrace and exits
80
+ * `EXIT_CODES.ERROR`. Every other policy decision (block precedence,
81
+ * swallow-vs-surface of unexpected throws) lives in `drive()`.
82
+ * @param eventName - The bound hook event name (drives the block translation)
83
+ * @param policy - The executing hook's resolved fail-open policy
84
+ * @param onUnexpectedError - Optional diagnostic sink, forwarded for parity
85
+ * with the source runtime's serialize-failure reporting.
86
+ */
87
+ export declare function createClaudeCodeTransport(eventName: string, policy: "error" | "continue", onUnexpectedError?: (error: unknown, phase: "serialize") => void): Transport<SpecificHookOutput>;
88
+ /**
89
+ * Executes a hook handler with full runtime orchestration (delegates to the
90
+ * shared core driver with this agent's transport).
91
+ *
92
+ * This is the main entry point that compiled hooks use. When a compiled hook
93
+ * runs as a CLI:
94
+ *
95
+ * 1. Reads all stdin
96
+ * 2. Parses JSON (wire format with snake_case properties)
97
+ * 3. Sets up logger context (hookType, input)
98
+ * 4. Calls handler with input and context (logger)
99
+ * 5. Handles any errors, logs them
100
+ * 6. Writes JSON to stdout
101
+ * 7. Closes logger
102
+ * 8. Exits with appropriate code
103
+ * @param hookFn - The hook function to execute (from hook factory)
104
+ * @example
105
+ * ```typescript
106
+ * // In compiled hook file
107
+ * import { execute } from '@goodfoot/agent-hooks/claude-code/runtime';
108
+ * import { preToolUseHook, preToolUseOutput } from '@goodfoot/agent-hooks/claude-code';
109
+ *
110
+ * const myHook = preToolUseHook({ matcher: 'Bash' }, async (input, { logger }) => {
111
+ * logger.info('Processing Bash command');
112
+ * return preToolUseOutput({ allow: true });
113
+ * });
114
+ *
115
+ * execute(myHook);
116
+ * ```
117
+ * @see https://code.claude.com/docs/en/hooks
118
+ */
119
+ export declare function execute<TInput extends HookInput, TOutput extends SpecificHookOutput>(hookFn: HookFunction<TInput, TOutput>): Promise<void>;
@@ -0,0 +1,557 @@
1
+ /**
2
+ * Type definitions for Claude Code hooks.
3
+ *
4
+ * This module provides:
5
+ * - Hook input types (wire format with snake_case)
6
+ * - Tool input types for type guards
7
+ * - SDK type re-exports for extension and reference
8
+ * @see https://code.claude.com/docs/en/hooks
9
+ * @module
10
+ */
11
+ /**
12
+ * Re-exports types from @anthropic-ai/claude-agent-sdk with "SDK" prefix.
13
+ * These are used as base types for extension, ensuring synchronization with the SDK.
14
+ */
15
+ export type { BaseHookInput as SDKBaseHookInput, ConfigChangeHookInput as SDKConfigChangeHookInput, CwdChangedHookInput as SDKCwdChangedHookInput, ElicitationHookInput as SDKElicitationHookInput, ElicitationResultHookInput as SDKElicitationResultHookInput, FileChangedHookInput as SDKFileChangedHookInput, HookEvent as SDKHookEvent, HookInput as SDKHookInput, InstructionsLoadedHookInput as SDKInstructionsLoadedHookInput, MessageDisplayHookInput as SDKMessageDisplayHookInput, NotificationHookInput as SDKNotificationHookInput, PermissionDeniedHookInput as SDKPermissionDeniedHookInput, PermissionMode as SDKPermissionMode, PermissionRequestHookInput as SDKPermissionRequestHookInput, PermissionUpdate as SDKPermissionUpdate, PostCompactHookInput as SDKPostCompactHookInput, PostToolBatchHookInput as SDKPostToolBatchHookInput, PostToolUseFailureHookInput as SDKPostToolUseFailureHookInput, PostToolUseHookInput as SDKPostToolUseHookInput, PreCompactHookInput as SDKPreCompactHookInput, PreToolUseHookInput as SDKPreToolUseHookInput, SessionEndHookInput as SDKSessionEndHookInput, SessionStartHookInput as SDKSessionStartHookInput, SetupHookInput as SDKSetupHookInput, StopFailureHookInput as SDKStopFailureHookInput, StopHookInput as SDKStopHookInput, SubagentStartHookInput as SDKSubagentStartHookInput, SubagentStopHookInput as SDKSubagentStopHookInput, TaskCompletedHookInput as SDKTaskCompletedHookInput, TaskCreatedHookInput as SDKTaskCreatedHookInput, TeammateIdleHookInput as SDKTeammateIdleHookInput, UserPromptExpansionHookInput as SDKUserPromptExpansionHookInput, UserPromptSubmitHookInput as SDKUserPromptSubmitHookInput, WorktreeCreateHookInput as SDKWorktreeCreateHookInput, WorktreeRemoveHookInput as SDKWorktreeRemoveHookInput, } from "@anthropic-ai/claude-agent-sdk";
16
+ import type { BaseHookInput as SDKBaseHookInput, ConfigChangeHookInput as SDKConfigChangeHookInput, CwdChangedHookInput as SDKCwdChangedHookInput, ElicitationHookInput as SDKElicitationHookInput, ElicitationResultHookInput as SDKElicitationResultHookInput, FileChangedHookInput as SDKFileChangedHookInput, InstructionsLoadedHookInput as SDKInstructionsLoadedHookInput, MessageDisplayHookInput as SDKMessageDisplayHookInput, NotificationHookInput as SDKNotificationHookInput, PermissionDeniedHookInput as SDKPermissionDeniedHookInput, PermissionMode as SDKPermissionMode, PermissionRequestHookInput as SDKPermissionRequestHookInput, PermissionUpdate as SDKPermissionUpdate, PostCompactHookInput as SDKPostCompactHookInput, PostToolBatchHookInput as SDKPostToolBatchHookInput, PostToolUseFailureHookInput as SDKPostToolUseFailureHookInput, PostToolUseHookInput as SDKPostToolUseHookInput, PreCompactHookInput as SDKPreCompactHookInput, PreToolUseHookInput as SDKPreToolUseHookInput, SessionEndHookInput as SDKSessionEndHookInput, SessionStartHookInput as SDKSessionStartHookInput, SetupHookInput as SDKSetupHookInput, StopFailureHookInput as SDKStopFailureHookInput, StopHookInput as SDKStopHookInput, SubagentStartHookInput as SDKSubagentStartHookInput, SubagentStopHookInput as SDKSubagentStopHookInput, TaskCompletedHookInput as SDKTaskCompletedHookInput, TaskCreatedHookInput as SDKTaskCreatedHookInput, TeammateIdleHookInput as SDKTeammateIdleHookInput, UserPromptExpansionHookInput as SDKUserPromptExpansionHookInput, UserPromptSubmitHookInput as SDKUserPromptSubmitHookInput, WorktreeCreateHookInput as SDKWorktreeCreateHookInput, WorktreeRemoveHookInput as SDKWorktreeRemoveHookInput } from "@anthropic-ai/claude-agent-sdk";
17
+ import type { AgentInput, AskUserQuestionInput, BashInput, CronCreateInput, CronDeleteInput, CronListInput, EnterPlanModeInput, EnterWorktreeInput, ExitPlanModeInput, ExitWorktreeInput, FileEditInput, FileReadInput, FileWriteInput, GlobInput, GrepInput, TaskStopInput as KillShellInput, ListMcpResourcesInput, McpInput, MonitorInput, NotebookEditInput, PushNotificationInput, REPLInput, ReadMcpResourceInput, RemoteTriggerInput, ScheduleWakeupInput, TaskCreateInput, TaskGetInput, TaskListInput, TaskOutputInput, TaskUpdateInput, TodoWriteInput, WebFetchInput, WebSearchInput, WorkflowInput } from "@anthropic-ai/claude-agent-sdk/sdk-tools.js";
18
+ /**
19
+ * Permission mode for controlling how tool executions are handled.
20
+ * @see https://code.claude.com/docs/en/hooks#permission-modes
21
+ */
22
+ export type PermissionMode = SDKPermissionMode;
23
+ /**
24
+ * Reason for session end events.
25
+ *
26
+ * - `'clear'` - Session cleared by user
27
+ * - `'resume'` - Session resumed from a previous session
28
+ * - `'logout'` - User logged out
29
+ * - `'prompt_input_exit'` - User exited at prompt input
30
+ * - `'other'` - Other reasons
31
+ * - `'bypass_permissions_disabled'` - Session ended because bypass permissions was disabled
32
+ *
33
+ * Note: SDK's ExitReason resolves to string. This type provides concrete literals for better DX.
34
+ */
35
+ export type SessionEndReason = "clear" | "resume" | "logout" | "prompt_input_exit" | "other" | "bypass_permissions_disabled";
36
+ /**
37
+ * Common fields present in all hook inputs.
38
+ *
39
+ * Every hook receives these base fields providing session context.
40
+ * Hook-specific inputs extend this base with additional fields.
41
+ * @example
42
+ * ```typescript
43
+ * // All hook inputs include these fields
44
+ * const handleAnyHook = (input: BaseHookInput) => {
45
+ * console.log(`Session: ${input.session_id}`);
46
+ * console.log(`Working directory: ${input.cwd}`);
47
+ * console.log(`Transcript: ${input.transcript_path}`);
48
+ * };
49
+ * ```
50
+ * @see https://code.claude.com/docs/en/hooks#hook-input-structure
51
+ */
52
+ export interface BaseHookInput extends SDKBaseHookInput {
53
+ /**
54
+ * Current permission mode for tool execution.
55
+ * Overrides SDK's string type with stricter literal union.
56
+ * May be undefined if using default mode.
57
+ */
58
+ permission_mode?: PermissionMode;
59
+ }
60
+ /**
61
+ * Input for PreToolUse hooks.
62
+ * @see https://code.claude.com/docs/en/hooks#pretooluse
63
+ */
64
+ export type PreToolUseInput = {
65
+ [K in keyof SDKPreToolUseHookInput]: SDKPreToolUseHookInput[K];
66
+ } & {};
67
+ /**
68
+ * Input for PostToolUse hooks.
69
+ * @see https://code.claude.com/docs/en/hooks#posttooluse
70
+ */
71
+ export type PostToolUseInput = {
72
+ [K in keyof SDKPostToolUseHookInput]: SDKPostToolUseHookInput[K];
73
+ } & {};
74
+ /**
75
+ * Input for PostToolUseFailure hooks.
76
+ * @see https://code.claude.com/docs/en/hooks#posttoolusefailure
77
+ */
78
+ export type PostToolUseFailureInput = {
79
+ [K in keyof SDKPostToolUseFailureHookInput]: SDKPostToolUseFailureHookInput[K];
80
+ } & {};
81
+ /**
82
+ * Input for PostToolBatch hooks.
83
+ *
84
+ * Fired once after every tool call in a batch has resolved, before the next model
85
+ * request. PostToolUse fires per-tool and may run concurrently for parallel tool
86
+ * calls; PostToolBatch fires exactly once with the full batch in `tool_calls`.
87
+ * @see https://code.claude.com/docs/en/hooks#posttoolbatch
88
+ */
89
+ export type PostToolBatchInput = {
90
+ [K in keyof SDKPostToolBatchHookInput]: SDKPostToolBatchHookInput[K];
91
+ } & {};
92
+ /**
93
+ * Input for Notification hooks.
94
+ * @see https://code.claude.com/docs/en/hooks#notification
95
+ */
96
+ export type NotificationInput = {
97
+ [K in keyof SDKNotificationHookInput]: SDKNotificationHookInput[K];
98
+ } & {};
99
+ /**
100
+ * Input for UserPromptExpansion hooks.
101
+ *
102
+ * Fires when a user prompt is expanded from a slash command or MCP prompt,
103
+ * allowing you to:
104
+ * - Add context based on the command being invoked
105
+ * - Log slash command and MCP prompt usage
106
+ * - Observe prompt expansion events
107
+ * @see https://code.claude.com/docs/en/hooks#userpromptexpansion
108
+ */
109
+ export type UserPromptExpansionInput = {
110
+ [K in keyof SDKUserPromptExpansionHookInput]: SDKUserPromptExpansionHookInput[K];
111
+ } & {};
112
+ /**
113
+ * Input for UserPromptSubmit hooks.
114
+ * @see https://code.claude.com/docs/en/hooks#userpromptsubmit
115
+ */
116
+ export type UserPromptSubmitInput = {
117
+ [K in keyof SDKUserPromptSubmitHookInput]: SDKUserPromptSubmitHookInput[K];
118
+ } & {};
119
+ /**
120
+ * Input for SessionStart hooks.
121
+ * @see https://code.claude.com/docs/en/hooks#sessionstart
122
+ */
123
+ export type SessionStartInput = {
124
+ [K in keyof SDKSessionStartHookInput]: SDKSessionStartHookInput[K];
125
+ } & {};
126
+ /**
127
+ * Input for Stop hooks.
128
+ * @see https://code.claude.com/docs/en/hooks#stop
129
+ */
130
+ export type StopInput = {
131
+ [K in keyof SDKStopHookInput]: SDKStopHookInput[K];
132
+ } & {};
133
+ /**
134
+ * Input for StopFailure hooks.
135
+ *
136
+ * Fires when Claude Code encounters an error while stopping (e.g., API errors,
137
+ * rate limits, authentication failures), allowing you to:
138
+ * - Log stop failure events and error details
139
+ * - Alert on unexpected session termination errors
140
+ * @see https://code.claude.com/docs/en/hooks#stopfailure
141
+ */
142
+ export type StopFailureInput = {
143
+ [K in keyof SDKStopFailureHookInput]: SDKStopFailureHookInput[K];
144
+ } & {};
145
+ /**
146
+ * Input for SubagentStart hooks.
147
+ * @see https://code.claude.com/docs/en/hooks#subagentstart
148
+ */
149
+ export type SubagentStartInput = {
150
+ [K in keyof SDKSubagentStartHookInput]: SDKSubagentStartHookInput[K];
151
+ } & {};
152
+ /**
153
+ * Input for SubagentStop hooks.
154
+ * @see https://code.claude.com/docs/en/hooks#subagentstop
155
+ */
156
+ export type SubagentStopInput = {
157
+ [K in keyof SDKSubagentStopHookInput]: SDKSubagentStopHookInput[K];
158
+ } & {};
159
+ /**
160
+ * Input for PreCompact hooks.
161
+ * @see https://code.claude.com/docs/en/hooks#precompact
162
+ */
163
+ export type PreCompactInput = {
164
+ [K in keyof SDKPreCompactHookInput]: SDKPreCompactHookInput[K];
165
+ } & {};
166
+ /**
167
+ * Input for PostCompact hooks.
168
+ *
169
+ * Fires after context compaction completes, allowing you to:
170
+ * - Observe the compaction summary
171
+ * - Log compaction events with context details
172
+ * - React to the new compacted state
173
+ * @see https://code.claude.com/docs/en/hooks#postcompact
174
+ */
175
+ export type PostCompactInput = {
176
+ [K in keyof SDKPostCompactHookInput]: SDKPostCompactHookInput[K];
177
+ } & {};
178
+ /**
179
+ * Input for Setup hooks.
180
+ * @see https://code.claude.com/docs/en/hooks#setup
181
+ */
182
+ export type SetupInput = {
183
+ [K in keyof SDKSetupHookInput]: SDKSetupHookInput[K];
184
+ } & {};
185
+ /**
186
+ * Input for TeammateIdle hooks.
187
+ * @see https://code.claude.com/docs/en/hooks#teammateidle
188
+ */
189
+ export type TeammateIdleInput = {
190
+ [K in keyof SDKTeammateIdleHookInput]: SDKTeammateIdleHookInput[K];
191
+ } & {};
192
+ /**
193
+ * Input for TaskCreated hooks.
194
+ *
195
+ * Fires when a new task is created and assigned to a teammate, allowing you to:
196
+ * - Observe task creation events
197
+ * - Log task assignments for auditing
198
+ * - React to new work being assigned
199
+ * @see https://code.claude.com/docs/en/hooks#taskcreated
200
+ */
201
+ export type TaskCreatedInput = {
202
+ [K in keyof SDKTaskCreatedHookInput]: SDKTaskCreatedHookInput[K];
203
+ } & {};
204
+ /**
205
+ * Input for TaskCompleted hooks.
206
+ * @see https://code.claude.com/docs/en/hooks#taskcompleted
207
+ */
208
+ export type TaskCompletedInput = {
209
+ [K in keyof SDKTaskCompletedHookInput]: SDKTaskCompletedHookInput[K];
210
+ } & {};
211
+ /**
212
+ * Input for Elicitation hooks.
213
+ *
214
+ * Fires when an MCP server requests user input (elicitation), allowing you to:
215
+ * - Intercept and handle MCP server prompts programmatically
216
+ * - Accept, decline, or cancel elicitation requests
217
+ * - Provide structured form input or URL-based auth responses
218
+ * @see https://code.claude.com/docs/en/hooks#elicitation
219
+ */
220
+ export type ElicitationInput = {
221
+ [K in keyof SDKElicitationHookInput]: SDKElicitationHookInput[K];
222
+ } & {};
223
+ /**
224
+ * Input for ElicitationResult hooks.
225
+ *
226
+ * Fires with the result of an elicitation request, allowing you to:
227
+ * - Observe and log elicitation outcomes
228
+ * - Modify the result before it is returned to the MCP server
229
+ * @see https://code.claude.com/docs/en/hooks#elicitationresult
230
+ */
231
+ export type ElicitationResultInput = {
232
+ [K in keyof SDKElicitationResultHookInput]: SDKElicitationResultHookInput[K];
233
+ } & {};
234
+ /**
235
+ * Input for ConfigChange hooks.
236
+ *
237
+ * Fires when Claude Code configuration changes (settings files, skills), allowing you to:
238
+ * - React to configuration changes
239
+ * - Log or audit configuration changes
240
+ * - Apply custom logic when settings are updated
241
+ * @see https://code.claude.com/docs/en/hooks#configchange
242
+ */
243
+ export type ConfigChangeInput = {
244
+ [K in keyof SDKConfigChangeHookInput]: SDKConfigChangeHookInput[K];
245
+ } & {};
246
+ /**
247
+ * Input for InstructionsLoaded hooks.
248
+ *
249
+ * Fires when a CLAUDE.md (or similar instructions file) is loaded, allowing you to:
250
+ * - React to instructions being loaded
251
+ * - Log which instruction files are active for the session
252
+ * @see https://code.claude.com/docs/en/hooks#instructionsloaded
253
+ */
254
+ export type InstructionsLoadedInput = {
255
+ [K in keyof SDKInstructionsLoadedHookInput]: SDKInstructionsLoadedHookInput[K];
256
+ } & {};
257
+ /**
258
+ * Input for WorktreeCreate hooks.
259
+ *
260
+ * Fires when a git worktree is created, allowing you to:
261
+ * - React to new worktree creation
262
+ * - Set up worktree-specific configuration
263
+ * @see https://code.claude.com/docs/en/hooks#worktreecreate
264
+ */
265
+ export type WorktreeCreateInput = {
266
+ [K in keyof SDKWorktreeCreateHookInput]: SDKWorktreeCreateHookInput[K];
267
+ } & {};
268
+ /**
269
+ * Input for WorktreeRemove hooks.
270
+ *
271
+ * Fires when a git worktree is removed, allowing you to:
272
+ * - React to worktree removal
273
+ * - Clean up worktree-specific resources
274
+ * @see https://code.claude.com/docs/en/hooks#worktreeremove
275
+ */
276
+ export type WorktreeRemoveInput = {
277
+ [K in keyof SDKWorktreeRemoveHookInput]: SDKWorktreeRemoveHookInput[K];
278
+ } & {};
279
+ /**
280
+ * Input for CwdChanged hooks.
281
+ *
282
+ * Fires when Claude Code's current working directory changes, allowing you to:
283
+ * - React to directory changes within a session
284
+ * - Update file watchers or environment state
285
+ * - Return `watchPaths` to register paths for FileChanged events
286
+ * @see https://code.claude.com/docs/en/hooks#cwdchanged
287
+ */
288
+ export type CwdChangedInput = {
289
+ [K in keyof SDKCwdChangedHookInput]: SDKCwdChangedHookInput[K];
290
+ } & {};
291
+ /**
292
+ * Input for MessageDisplay hooks.
293
+ *
294
+ * Fires with each batch of newly completed lines while an assistant message streams.
295
+ * Display-only: the stored message and what the model sees are untouched. Allows you to:
296
+ * - Replace the delta shown on screen with custom content (via `displayContent` output)
297
+ * - Observe and log message streaming
298
+ *
299
+ * @see https://code.claude.com/docs/en/hooks#messagedisplay
300
+ */
301
+ export type MessageDisplayInput = {
302
+ [K in keyof SDKMessageDisplayHookInput]: SDKMessageDisplayHookInput[K];
303
+ } & {};
304
+ /**
305
+ * Input for FileChanged hooks.
306
+ *
307
+ * Fires when a watched file changes on disk, allowing you to:
308
+ * - React to file system changes during a session
309
+ * - Invalidate caches or reload configuration
310
+ * - Return `watchPaths` to update the set of watched paths
311
+ *
312
+ * The `event` field indicates the type of change:
313
+ * - `'change'` - File contents changed
314
+ * - `'add'` - File was created
315
+ * - `'unlink'` - File was deleted
316
+ * @see https://code.claude.com/docs/en/hooks#filechanged
317
+ */
318
+ export type FileChangedInput = {
319
+ [K in keyof SDKFileChangedHookInput]: SDKFileChangedHookInput[K];
320
+ } & {};
321
+ /**
322
+ * Input for SessionEnd hooks.
323
+ *
324
+ * Fires when a Claude Code session ends, allowing you to:
325
+ * - Clean up session resources
326
+ * - Log session metrics
327
+ * - Persist session state
328
+ *
329
+ * This hook uses `reason` for matcher matching.
330
+ * @example
331
+ * ```typescript
332
+ * // Log session end
333
+ * sessionEndHook({}, async (input: SessionEndInput) => {
334
+ * console.log(`Session ended: ${input.reason}`);
335
+ * return sessionEndOutput({});
336
+ * });
337
+ * ```
338
+ * @see https://code.claude.com/docs/en/hooks#sessionend
339
+ */
340
+ type _SessionEndInputBase = Omit<SDKSessionEndHookInput, "reason"> & {
341
+ /**
342
+ * The reason the session ended.
343
+ *
344
+ * - `'clear'` - Session cleared by user
345
+ * - `'logout'` - User logged out
346
+ * - `'prompt_input_exit'` - User exited at prompt input
347
+ * - `'other'` - Other reasons
348
+ */
349
+ reason: SessionEndReason;
350
+ };
351
+ export type SessionEndInput = {
352
+ [K in keyof _SessionEndInputBase]: _SessionEndInputBase[K];
353
+ } & {};
354
+ /**
355
+ * Input for PermissionRequest hooks.
356
+ *
357
+ * Fires when a permission prompt would be shown, allowing you to:
358
+ * - Auto-approve or deny tool executions
359
+ * - Implement custom permission logic
360
+ * - Modify tool inputs before approval
361
+ *
362
+ * This hook uses `tool_name` for matcher matching.
363
+ * @example
364
+ * ```typescript
365
+ * // Auto-approve read operations in allowed directories
366
+ * permissionRequestHook({ matcher: 'Read' }, async (input: PermissionRequestInput) => {
367
+ * const filePath = input.tool_input.file_path as string;
368
+ * if (filePath.startsWith('/allowed/')) {
369
+ * return permissionRequestOutput({
370
+ * allow: true
371
+ * });
372
+ * }
373
+ * return permissionRequestOutput({}); // Fall through to normal permission prompt
374
+ * });
375
+ * ```
376
+ * @see https://code.claude.com/docs/en/hooks#permissionrequest
377
+ */
378
+ type _PermissionRequestInputBase = SDKPermissionRequestHookInput & {
379
+ /**
380
+ * Unique identifier for this specific tool invocation.
381
+ */
382
+ tool_use_id: string;
383
+ };
384
+ export type PermissionRequestInput = {
385
+ [K in keyof _PermissionRequestInputBase]: _PermissionRequestInputBase[K];
386
+ } & {};
387
+ /**
388
+ * Input for PermissionDenied hooks.
389
+ *
390
+ * Fires when a permission request is denied (either by the user or by a hook),
391
+ * allowing you to:
392
+ * - Log permission denials for auditing
393
+ * - React to denied tool executions
394
+ * - Optionally request a retry
395
+ *
396
+ * This hook uses `tool_name` for matcher matching.
397
+ * @see https://code.claude.com/docs/en/hooks#permissiondenied
398
+ */
399
+ export type PermissionDeniedInput = {
400
+ [K in keyof SDKPermissionDeniedHookInput]: SDKPermissionDeniedHookInput[K];
401
+ } & {};
402
+ /**
403
+ * Trigger type for Setup hooks.
404
+ */
405
+ export type SetupTrigger = "init" | "maintenance";
406
+ /**
407
+ * Discriminated union of all hook input types.
408
+ *
409
+ * Use this type when handling multiple hook types in a single handler
410
+ * or when the hook type is not known statically.
411
+ * @example
412
+ * ```typescript
413
+ * // Handle any hook type with type narrowing
414
+ * function handleHook(input: HookInput) {
415
+ * switch (input.hook_event_name) {
416
+ * case 'PreToolUse':
417
+ * // TypeScript knows input is PreToolUseInput here
418
+ * console.log(`Tool: ${input.tool_name}`);
419
+ * break;
420
+ * case 'SessionStart':
421
+ * // TypeScript knows input is SessionStartInput here
422
+ * console.log(`Source: ${input.source}`);
423
+ * break;
424
+ * // ... handle other hook types
425
+ * }
426
+ * }
427
+ * ```
428
+ * @see https://code.claude.com/docs/en/hooks
429
+ */
430
+ export type HookInput = PreToolUseInput | PostToolUseInput | PostToolUseFailureInput | PostToolBatchInput | NotificationInput | UserPromptExpansionInput | UserPromptSubmitInput | SessionStartInput | SessionEndInput | StopInput | StopFailureInput | SubagentStartInput | SubagentStopInput | PreCompactInput | PostCompactInput | PermissionRequestInput | PermissionDeniedInput | SetupInput | TeammateIdleInput | TaskCreatedInput | TaskCompletedInput | ElicitationInput | ElicitationResultInput | ConfigChangeInput | InstructionsLoadedInput | WorktreeCreateInput | WorktreeRemoveInput | CwdChangedInput | FileChangedInput | MessageDisplayInput;
431
+ /**
432
+ * Hook event name literal union.
433
+ *
434
+ * All valid hook event names that can appear in the `hook_event_name` field.
435
+ */
436
+ export type HookEventName = HookInput["hook_event_name"];
437
+ export type { SDKPermissionUpdate as PermissionUpdate };
438
+ /**
439
+ * Re-export all tool input types from the official Claude Agent SDK.
440
+ * Uses `export type *` because sdk-tools.d.ts has no JavaScript runtime counterpart.
441
+ * @see {@link https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk | @anthropic-ai/claude-agent-sdk}
442
+ */
443
+ export type * from "@anthropic-ai/claude-agent-sdk/sdk-tools.js";
444
+ /**
445
+ * Input structure for the Config tool.
446
+ *
447
+ * The Config tool reads or updates Claude Code configuration settings. This type was
448
+ * removed from `@anthropic-ai/claude-agent-sdk` in 0.3.x, so it is defined locally to
449
+ * preserve type-safe support for the {@link isConfigTool} guard.
450
+ */
451
+ export interface ConfigInput {
452
+ /** The setting key (e.g., "theme", "model", "permissions.defaultMode"). */
453
+ setting: string;
454
+ /** The new value. Omit to read the current value. */
455
+ value?: string | boolean | number;
456
+ }
457
+ /**
458
+ * A single edit entry within a MultiEdit operation.
459
+ */
460
+ export interface MultiEditEntry {
461
+ /** The text to search for. */
462
+ old_string: string;
463
+ /** The text to replace old_string with. */
464
+ new_string: string;
465
+ }
466
+ /**
467
+ * Input structure for the MultiEdit tool.
468
+ *
469
+ * The MultiEdit tool performs multiple search-and-replace operations on a single file.
470
+ * All edits are applied atomically.
471
+ * @example
472
+ * ```typescript
473
+ * // Example tool input
474
+ * {
475
+ * file_path: '/workspace/src/index.ts',
476
+ * edits: [
477
+ * { old_string: 'const x = 1;', new_string: 'const x = 2;' },
478
+ * { old_string: 'const y = 1;', new_string: 'const y = 2;' }
479
+ * ]
480
+ * }
481
+ * ```
482
+ */
483
+ export interface MultiEditToolInput {
484
+ /** Absolute path to the file to edit. */
485
+ file_path: string;
486
+ /** Array of edit operations to apply. */
487
+ edits: MultiEditEntry[];
488
+ }
489
+ /**
490
+ * Union of all file-modifying tool inputs.
491
+ *
492
+ * Use this type when you need to handle Write, Edit, or MultiEdit generically.
493
+ */
494
+ export type FileModifyingToolInput = FileWriteInput | FileEditInput | MultiEditToolInput;
495
+ /**
496
+ * Tool names for file-modifying tools.
497
+ *
498
+ * Use this type when you need to reference the tool name in type guards.
499
+ */
500
+ export type FileModifyingToolName = "Write" | "Edit" | "MultiEdit";
501
+ /**
502
+ * Union of all known tool inputs.
503
+ *
504
+ * This includes all tool inputs that have well-defined type structures.
505
+ */
506
+ export type KnownToolInput = FileWriteInput | FileEditInput | MultiEditToolInput | FileReadInput | BashInput | GlobInput | GrepInput | AgentInput | TaskOutputInput | ExitPlanModeInput | KillShellInput | NotebookEditInput | TodoWriteInput | WebFetchInput | WebSearchInput | AskUserQuestionInput | ListMcpResourcesInput | McpInput | ReadMcpResourceInput | ConfigInput | TaskCreateInput | TaskGetInput | TaskListInput | TaskUpdateInput | CronCreateInput | CronDeleteInput | CronListInput | ScheduleWakeupInput | MonitorInput | RemoteTriggerInput | PushNotificationInput | EnterPlanModeInput | EnterWorktreeInput | ExitWorktreeInput | REPLInput | WorkflowInput;
507
+ /**
508
+ * Tool names for all known tools with typed inputs.
509
+ */
510
+ export type KnownToolName = "Write" | "Edit" | "MultiEdit" | "Read" | "Bash" | "Glob" | "Grep" | "Agent" | "TaskOutput" | "ExitPlanMode" | "KillShell" | "NotebookEdit" | "TodoWrite" | "WebFetch" | "WebSearch" | "AskUserQuestion" | "ListMcpResources" | "Mcp" | "ReadMcpResource" | "Config" | "TaskCreate" | "TaskGet" | "TaskList" | "TaskUpdate" | "CronCreate" | "CronDelete" | "CronList" | "ScheduleWakeup" | "Monitor" | "RemoteTrigger" | "PushNotification" | "EnterPlanMode" | "EnterWorktree" | "ExitWorktree" | "REPL" | "Workflow";
511
+ /**
512
+ * Type mapping from tool name to tool input type.
513
+ *
514
+ * Used by typed factory overloads to provide automatic typing.
515
+ * @example
516
+ * ```typescript
517
+ * type WriteInput = ToolInputMap['Write']; // FileWriteInput
518
+ * ```
519
+ */
520
+ export interface ToolInputMap {
521
+ Write: FileWriteInput;
522
+ Edit: FileEditInput;
523
+ MultiEdit: MultiEditToolInput;
524
+ Read: FileReadInput;
525
+ Bash: BashInput;
526
+ Glob: GlobInput;
527
+ Grep: GrepInput;
528
+ Agent: AgentInput;
529
+ TaskOutput: TaskOutputInput;
530
+ ExitPlanMode: ExitPlanModeInput;
531
+ KillShell: KillShellInput;
532
+ NotebookEdit: NotebookEditInput;
533
+ TodoWrite: TodoWriteInput;
534
+ WebFetch: WebFetchInput;
535
+ WebSearch: WebSearchInput;
536
+ AskUserQuestion: AskUserQuestionInput;
537
+ ListMcpResources: ListMcpResourcesInput;
538
+ Mcp: McpInput;
539
+ ReadMcpResource: ReadMcpResourceInput;
540
+ Config: ConfigInput;
541
+ TaskCreate: TaskCreateInput;
542
+ TaskGet: TaskGetInput;
543
+ TaskList: TaskListInput;
544
+ TaskUpdate: TaskUpdateInput;
545
+ CronCreate: CronCreateInput;
546
+ CronDelete: CronDeleteInput;
547
+ CronList: CronListInput;
548
+ ScheduleWakeup: ScheduleWakeupInput;
549
+ Monitor: MonitorInput;
550
+ RemoteTrigger: RemoteTriggerInput;
551
+ PushNotification: PushNotificationInput;
552
+ EnterPlanMode: EnterPlanModeInput;
553
+ EnterWorktree: EnterWorktreeInput;
554
+ ExitWorktree: ExitWorktreeInput;
555
+ REPL: REPLInput;
556
+ Workflow: WorkflowInput;
557
+ }