@pluginfinity/core 0.3.3 → 0.4.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.
@@ -0,0 +1,502 @@
1
+ import { Schema } from "effect";
2
+ import { PermissionUpdate, additionalContext, anything, backgroundTasks, flag, input, mcpServer, num, oneOf, opt, output, record, sessionCrons, strings, text, toolInput, toolName, toolUseId } from "./build.js";
3
+
4
+ // src/hook-io/events.ts
5
+ const NOTHING_READ = "Claude Code reads no decision from this event; a hook here is for side effects.";
6
+ const sessionTitle = opt(text("The session's custom title, present only when one was set (--name, /rename, a hook's sessionTitle or the Agent SDK). A generated title does not appear here."));
7
+ const taskFields = {
8
+ task_id: text("Identifier of the task."),
9
+ task_subject: text("Title of the task."),
10
+ task_description: opt(text("Detailed description of the task.")),
11
+ teammate_name: opt(text("Name of the teammate acting on the task.")),
12
+ team_name: opt(text("Deprecated: a session-derived team name that will be removed."))
13
+ };
14
+ const stopFields = {
15
+ stop_hook_active: flag("true when Claude Code is already continuing because of a stop hook. Check it before blocking again; after eight continuations in a row Claude Code overrides the block."),
16
+ last_assistant_message: opt(text("The text of the final response. Use it instead of reading transcript_path, which can lag the turn.")),
17
+ background_tasks: backgroundTasks,
18
+ session_crons: sessionCrons
19
+ };
20
+ const stopOutput = (event, who) => output(event, `Decides whether ${who} stops. Exit code 2 blocks the stop too, with stderr as the reason.`, {
21
+ block: {
22
+ decision: `Prevents ${who} from stopping. Omit it to allow the stop.`,
23
+ reason: `Required with decision: tells ${who} why to continue, as its next instruction.`
24
+ },
25
+ specific: { additionalContext: additionalContext(`at the end of the turn. The conversation continues so ${who} can act on it, shown as hook feedback rather than a hook error, under the same loop protections as a block`) }
26
+ });
27
+ const modelFields = (sources, sourceDescription) => ({
28
+ from_model: text("Model ID the switch changes from."),
29
+ to_model: text("Model ID the switch changes to. The matcher compares against this model's canonical name."),
30
+ requested_model: Schema.NullOr(Schema.String).annotate({ description: "The model the request named: an alias such as opus, a full model ID, or null for the default model or a change Claude Code made on its own." }),
31
+ source: oneOf(sources, sourceDescription),
32
+ context_tokens: num("Tokens the next request re-sends as its prompt. 0 before the first response."),
33
+ prompt_cache_warm: flag("Whether the current model's prompt cache is likely still warm, so the switch forfeits it."),
34
+ cache_ttl: oneOf(["5m", "1h"], "Prompt cache lifetime of the main conversation at the time of the switch."),
35
+ estimated_cache_write_usd: num("Estimated cost in US dollars of writing context_tokens to the prompt cache on to_model. An estimate only."),
36
+ pricing: oneOf([
37
+ "configured",
38
+ "catalog",
39
+ "default"
40
+ ], "How the estimate was priced: your organization's rates, list price, or an assumed default rate.")
41
+ });
42
+ const elicitationOutput = (event, accept) => output(event, "Answers, changes, declines or cancels an MCP elicitation. Print nothing to leave it as it is. Exit code 2 declines, and a hookSpecificOutput without an action is ignored.", {
43
+ discards: ["continue", "systemMessage"],
44
+ block: {
45
+ decision: "Declines, the same as action decline, and overrides an action in the same output. Read from Claude Code 2.1.284; ignored from 2.1.105 until then.",
46
+ reason: "Accepted and discarded: neither the user nor the server sees it."
47
+ },
48
+ specific: {
49
+ action: oneOf([
50
+ "accept",
51
+ "decline",
52
+ "cancel"
53
+ ], `accept ${accept}; decline and cancel send that to the server.`),
54
+ content: opt(record("With accept: the form field values, keyed by the property names of requested_schema. It replaces the whole content object."))
55
+ }
56
+ });
57
+ /**
58
+ * The input and output schema of every Claude Code hook event: the JSON a hook
59
+ * receives and the JSON it may answer with.
60
+ *
61
+ * @public
62
+ */
63
+ const HOOK_IO = {
64
+ SessionStart: {
65
+ input: input("SessionStart", "A session begins or resumes. Only command and mcp_tool hooks run here. CLAUDE_ENV_FILE is set: append export lines to carry variables into later Bash commands.", {
66
+ source: oneOf([
67
+ "startup",
68
+ "resume",
69
+ "clear",
70
+ "compact",
71
+ "fork"
72
+ ], "How the session started; the matcher filters on it. resume covers --resume, --continue and /resume; fork is a new session forked from an existing one."),
73
+ model: opt(text("The active model identifier. Often omitted, for example after /clear; check before reading.")),
74
+ session_title: sessionTitle,
75
+ seconds_since_last_response: opt(num("Wall-clock seconds since the last response in the resumed transcript. Only on resume or fork. Claude Code 2.1.251 or later.")),
76
+ context_tokens: opt(num("Tokens the first request of the resumed session re-sends. Only on resume or fork.")),
77
+ prompt_cache_likely_expired: opt(flag("true when the last response is older than the prompt cache lifetime. Only on resume or fork.")),
78
+ estimated_cache_write_usd: opt(num("Estimated cost in US dollars of writing context_tokens to the prompt cache. Only on resume or fork."))
79
+ }),
80
+ output: output("SessionStart", "Adds context and sets up the session. Cannot block. Plain-text stdout is added to Claude's context too, so a hook that only adds context need not print JSON.", { specific: {
81
+ additionalContext: additionalContext("at the start of the conversation, before the first prompt"),
82
+ initialUserMessage: opt(text("Used as the first user message in non-interactive mode (-p), even when no prompt was passed.")),
83
+ sessionTitle: opt(text("Sets the session title, like /rename. Applies when source is startup, resume or fork. Check session_title first to avoid overwriting one.")),
84
+ watchPaths: opt(strings("Absolute paths to watch for FileChanged events during this session.")),
85
+ reloadSkills: opt(flag("true re-scans the skill and command directories after the SessionStart hooks, for skills a hook just installed."))
86
+ } })
87
+ },
88
+ Setup: {
89
+ input: input("Setup", "Claude Code was launched with --init-only, or with --init or --maintenance in -p mode. Only command hooks run here. CLAUDE_ENV_FILE is set.", { trigger: oneOf(["init", "maintenance"], "Which flag triggered setup; the matcher filters on it.") }),
90
+ output: output("Setup", `${NOTHING_READ} Execution continues on any exit code, and hookSpecificOutput is discarded too.`, { discards: ["continue", "systemMessage"] })
91
+ },
92
+ UserPromptSubmit: {
93
+ input: input("UserPromptSubmit", "A prompt was submitted, before Claude processes it. Also fires on turns Claude Code starts itself: a scheduled task, a background subagent reporting back, a message from another session. Default timeout 30 seconds. No matcher.", {
94
+ prompt: text("The submitted text. A typed skill or command arrives as typed, not expanded. Pasted content arrives expanded in place."),
95
+ session_title: sessionTitle
96
+ }),
97
+ output: output("UserPromptSubmit", "Adds context to a prompt or rejects it. Exit code 2 rejects it too, with stderr as the reason. Plain-text stdout is added to Claude's context.", {
98
+ block: {
99
+ decision: "Rejects the prompt. Omit it to let the prompt through.",
100
+ reason: "Shown to the user, not added to context."
101
+ },
102
+ specific: {
103
+ additionalContext: additionalContext("alongside the submitted prompt"),
104
+ sessionTitle: opt(text("Sets the session title, for naming a session from its prompt.")),
105
+ suppressOriginalPrompt: opt(flag("true leaves the prompt text out of the block message. The prompt can still appear in local transcript files."))
106
+ }
107
+ })
108
+ },
109
+ UserPromptExpansion: {
110
+ input: input("UserPromptExpansion", "A command the user typed expands into a prompt, before it reaches Claude. This covers typing /skillname directly, which never fires PreToolUse. The matcher filters on command_name.", {
111
+ expansion_type: oneOf(["slash_command", "mcp_prompt"], "slash_command for a skill or custom command, mcp_prompt for an MCP server prompt."),
112
+ command_name: text("The command's name, plugin-scoped for a plugin skill, such as my-plugin:example-skill."),
113
+ command_args: text("The arguments typed after the command."),
114
+ command_source: text("Where the command comes from, such as plugin."),
115
+ prompt: text("The line as the user typed it.")
116
+ }),
117
+ output: output("UserPromptExpansion", "Blocks the expansion or adds context. Exit code 2 blocks too, with stderr shown to the user.", {
118
+ block: {
119
+ decision: "Prevents the command from expanding. Omit it to allow it.",
120
+ reason: "Shown to the user."
121
+ },
122
+ specific: { additionalContext: additionalContext("alongside the expanded prompt") }
123
+ })
124
+ },
125
+ PreSkillShellCommand: {
126
+ input: input("PreSkillShellCommand", "A shell command a skill or command injects is about to run while it loads. PreToolUse does not fire for these. Claude Code 2.1.332 or later; an older version warns about an unknown event. Match Bash|PowerShell. prompt and agent hooks cannot run here and block every command they match.", {
127
+ tool_name: oneOf(["Bash", "PowerShell"], "The tool that runs the command; the matcher filters on it."),
128
+ tool_input: Schema.Struct({ command: text("The shell command as it would run.") }).annotate({ description: "The command to run." }),
129
+ tool_use_id: text("ID of this command. It names no tool call in the transcript."),
130
+ command_name: text("Name of the skill or command that is loading, such as pr-summary or my-plugin:deploy."),
131
+ command_source: text("Where it comes from, such as userSettings, projectSettings, policySettings, plugin or builtin."),
132
+ invoked_by: oneOf([
133
+ "user",
134
+ "claude",
135
+ "other"
136
+ ], "user when the name was typed or sent by an SDK app, claude when Claude or a scheduled task invoked the skill, other otherwise.")
137
+ }),
138
+ output: output("PreSkillShellCommand", "Can only block the command; the skill still loads, with a note in place of the command's output. Exit code 2 blocks too. continue: false makes invoking the skill fail and none of its commands run.", {
139
+ block: {
140
+ decision: "Blocks the command.",
141
+ reason: "The reason for the block."
142
+ },
143
+ eventNames: ["PreToolUse", "PreSkillShellCommand"],
144
+ specific: {
145
+ permissionDecision: opt(oneOf([
146
+ "allow",
147
+ "deny",
148
+ "ask",
149
+ "defer"
150
+ ], "deny blocks the command. allow changes nothing: the command runs unless another hook blocks it. ask and defer are treated as deny.")),
151
+ permissionDecisionReason: opt(text("The reason for a block.")),
152
+ updatedInput: opt(record("Not supported here: any updatedInput blocks the command, the same as deny."))
153
+ }
154
+ })
155
+ },
156
+ PreToolUse: {
157
+ input: input("PreToolUse", "Claude created a tool call, before it runs. The matcher filters on tool_name. Does not fire for a skill's injected shell commands (PreSkillShellCommand), for files referenced with @, or for EndConversation.", {
158
+ tool_name: toolName,
159
+ tool_input: toolInput,
160
+ tool_use_id: toolUseId,
161
+ mcp_server: mcpServer
162
+ }),
163
+ output: output("PreToolUse", "Allows, denies, asks about or defers the tool call, and can rewrite its input. Exit code 2 denies, with stderr shown to Claude. When hooks disagree, deny beats defer, which beats ask, which beats allow. Printing nothing leaves the call to the normal permission flow.", {
164
+ specific: {
165
+ permissionDecision: opt(oneOf([
166
+ "allow",
167
+ "deny",
168
+ "ask",
169
+ "defer"
170
+ ], "allow skips the permission prompt (deny and ask rules still apply); deny prevents the call; ask prompts the user; defer ends the turn so the call can resume later, in -p mode with a single tool call only.")),
171
+ permissionDecisionReason: opt(text("For deny, shown to Claude. For ask, shown to the user in the prompt. For allow and defer, written to the debug log only.")),
172
+ updatedInput: opt(record("Replaces the tool's whole input before it runs, so include the unchanged fields. Pair with allow to auto-approve or ask to show the user. Ignored with defer.")),
173
+ additionalContext: additionalContext("next to the tool result")
174
+ },
175
+ extra: {
176
+ decision: opt(oneOf(["approve", "block"], "Deprecated on this event: maps to allow and deny. Use hookSpecificOutput.permissionDecision.")),
177
+ reason: opt(text("Deprecated on this event. Use hookSpecificOutput.permissionDecisionReason."))
178
+ }
179
+ })
180
+ },
181
+ PermissionRequest: {
182
+ input: input("PermissionRequest", "Claude Code is about to ask the user for permission to use a tool. The matcher filters on tool_name. There is no tool_use_id. agent hooks are skipped on this event.", {
183
+ tool_name: toolName,
184
+ tool_input: toolInput,
185
+ mcp_server: mcpServer,
186
+ permission_suggestions: opt(Schema.Array(PermissionUpdate).annotate({ description: "The permission updates Claude Code suggests, such as adding an allow rule. Not an exact list of the options the user sees. A hook may echo one back as updatedPermissions." }))
187
+ }),
188
+ output: output("PermissionRequest", "Grants or denies the request on the user's behalf. Exit code 2 is not read as a decision here: return the decision object.", { specific: { decision: opt(Schema.Struct({
189
+ behavior: oneOf(["allow", "deny"], "allow grants the permission, deny refuses it. A hook cannot approve what a deny rule refuses."),
190
+ updatedInput: opt(record("allow only: replaces the tool's whole input. The result is checked against deny and ask rules again.")),
191
+ updatedPermissions: opt(Schema.Array(PermissionUpdate).annotate({ description: "allow only: permission updates to apply, such as an allow rule so the user is not asked again." })),
192
+ message: opt(text("deny only: tells Claude why the permission was denied.")),
193
+ interrupt: opt(flag("deny only: true stops Claude."))
194
+ }).annotate({ description: "The decision." })) } })
195
+ },
196
+ PermissionDenied: {
197
+ input: input("PermissionDenied", "The auto mode classifier denied a tool call. Does not fire when the user denies a dialog, a PreToolUse hook blocks, or a deny rule matches. The matcher filters on tool_name.", {
198
+ tool_name: toolName,
199
+ tool_input: toolInput,
200
+ tool_use_id: toolUseId,
201
+ mcp_server: mcpServer,
202
+ reason: text("The denial reason: usually the matched policy in square brackets, or text saying the classifier produced no verdict.")
203
+ }),
204
+ output: output("PermissionDenied", "Can tell the model it may retry. The denial itself stands; the exit code and stderr are ignored.", { specific: { retry: opt(flag("true adds a message telling the model it may retry the tool call. Ignored when the classifier produced no verdict.")) } })
205
+ },
206
+ PostToolUse: {
207
+ input: input("PostToolUse", "A tool call completed successfully. The matcher filters on tool_name. Does not fire when a Bash command or outside process rewrites a file; use FileChanged for that.", {
208
+ tool_name: toolName,
209
+ tool_input: toolInput,
210
+ tool_response: anything("The tool's result. A structured object whose shape depends on the tool (Write returns filePath and type; Bash returns stdout, stderr, interrupted and isImage); the error text as a string for a failed call."),
211
+ tool_use_id: toolUseId,
212
+ duration_ms: opt(num("Tool execution time in milliseconds, excluding permission prompts and PreToolUse hooks.")),
213
+ mcp_server: mcpServer
214
+ }),
215
+ output: output("PostToolUse", "Gives Claude feedback after a tool ran, or replaces what Claude sees of its output. The tool has already run. Exit code 2 shows stderr to Claude.", {
216
+ block: {
217
+ decision: "Adds the reason next to the tool result. Claude still sees the original output.",
218
+ reason: "Shown to Claude."
219
+ },
220
+ specific: {
221
+ additionalContext: additionalContext("next to the tool result"),
222
+ classifierContext: opt(text("A short note about this result for the auto mode classifier, not for Claude. Capped at 2,000 characters per tool call. Do not copy untrusted tool output into it. Claude Code 2.1.236 or later.")),
223
+ updatedToolOutput: opt(anything("Replaces the tool's output before Claude sees it. Must match the tool's output shape, or it is ignored for a built-in tool. Changes only what Claude sees.")),
224
+ updatedMCPToolOutput: opt(anything("Replaces the output for MCP tools only. Prefer updatedToolOutput."))
225
+ }
226
+ })
227
+ },
228
+ PostToolUseFailure: {
229
+ input: input("PostToolUseFailure", "A tool that started executing failed. Does not fire for a call rejected before it ran (unknown tool, invalid input, permission denial). The matcher filters on tool_name.", {
230
+ tool_name: toolName,
231
+ tool_input: toolInput,
232
+ tool_use_id: toolUseId,
233
+ mcp_server: mcpServer,
234
+ error: text("What went wrong, generally the text Claude receives. For Bash and PowerShell the first line is Exit code N. Treat the rest as display text, not a stable format."),
235
+ is_interrupt: opt(flag("true when the failure reached Claude Code as an abort rather than an error the tool reported.")),
236
+ duration_ms: opt(num("Tool execution time in milliseconds."))
237
+ }),
238
+ output: output("PostToolUseFailure", "Adds context for Claude after a failure. Exit code 2 shows stderr to Claude. The docs disagree on blocking: their summary table lists this event under top-level decision, while this event's own section offers only additionalContext, so decision is modelled as optional and should not be relied on.", {
239
+ block: {
240
+ decision: "Listed in the docs' summary table only; not confirmed by this event's own section.",
241
+ reason: "The reason, if decision is read at all."
242
+ },
243
+ specific: { additionalContext: additionalContext("next to the error") }
244
+ })
245
+ },
246
+ PostToolBatch: {
247
+ input: input("PostToolBatch", "Every tool call in a batch of parallel calls has resolved, before the next model request. Fires once per batch. No matcher.", { tool_calls: Schema.Array(Schema.Struct({
248
+ tool_name: toolName,
249
+ tool_input: toolInput,
250
+ tool_use_id: toolUseId,
251
+ tool_response: anything("What the model receives for this call: a serialized string or a content-block array, not the structured object PostToolUse gets.")
252
+ })).annotate({ description: "Every tool call in the batch." }) }),
253
+ output: output("PostToolBatch", "Adds context once before the next model call, or stops the agentic loop. Exit code 2 stops it too, with stderr as the message.", {
254
+ block: {
255
+ decision: "Stops the agentic loop before the next model call.",
256
+ reason: "Shown as a warning in the transcript, and it stays in the conversation."
257
+ },
258
+ specific: { additionalContext: additionalContext("once, before the next model call") }
259
+ })
260
+ },
261
+ Notification: {
262
+ input: input("Notification", "Claude Code sends a notification. The matcher filters on notification_type.", {
263
+ message: text("The notification text."),
264
+ title: opt(text("The notification title. For plugin_notification it is the mod's name unless the mod set one.")),
265
+ notification_type: text("Which notification fired, such as permission_prompt, idle_prompt, auth_success, auth_storage_failure, elicitation_dialog, elicitation_url_dialog, elicitation_complete, elicitation_response, agent_needs_input, agent_completed, quota_auto_resume_fired, quota_auto_resume_stale, quota_auto_resume_disabled or plugin_notification. The list grows between releases.")
266
+ }),
267
+ output: output("Notification", `${NOTHING_READ} The exit code and stderr are ignored; terminalSequence is still emitted.`, { discards: ["continue", "systemMessage"] })
268
+ },
269
+ MessageDisplay: {
270
+ input: input("MessageDisplay", "Assistant message text is being displayed. Interactive runs call the hook once per batch of completed lines; -p and Agent SDK runs call it once per message. Default timeout 10 seconds; keep it fast. No matcher.", {
271
+ turn_id: text("UUID of the current turn."),
272
+ message_id: text("UUID of the message being displayed, stable across its batches. Not the API msg_ id."),
273
+ index: num("Zero-based index of this batch within the message."),
274
+ final: flag("true on the message's last batch. Use this, not a non-empty delta, as the end-of-message signal."),
275
+ delta: text("The newly completed lines since the prior batch, newlines included. The whole message in -p and SDK runs.")
276
+ }),
277
+ output: output("MessageDisplay", "Replaces what is shown on screen. Display only: the transcript and what Claude sees keep the original. If the hook fails or times out the original text is displayed.", {
278
+ discards: ["continue", "systemMessage"],
279
+ specific: { displayContent: opt(text("Text displayed in place of delta. Omit it to display the original.")) }
280
+ })
281
+ },
282
+ SubagentStart: {
283
+ input: input("SubagentStart", "Claude spawned or resumed a subagent, or an in-process teammate handles a new message. The matcher filters on agent_type; anchor a plugin-scoped name, as in ^my-plugin:reviewer$.", {
284
+ agent_id: text("Unique identifier of the subagent."),
285
+ agent_type: text("The agent name: a built-in such as Explore, a custom agent's name, or a plugin-scoped my-plugin:reviewer.")
286
+ }),
287
+ output: output("SubagentStart", "Adds context to the subagent. Cannot block its creation; exit code 2 only shows stderr to the user.", { specific: { additionalContext: additionalContext("at the start of the subagent's conversation, before its first prompt") } })
288
+ },
289
+ SubagentStop: {
290
+ input: input("SubagentStop", "A subagent finished responding. Also fires for Claude Code's internal agents, where agent_type may be an empty string. The matcher filters on agent_type.", {
291
+ ...stopFields,
292
+ agent_id: text("Unique identifier of the subagent."),
293
+ agent_type: text("The agent name the matcher filters on. May be an empty string for an internal agent."),
294
+ agent_transcript_path: text("The subagent's own transcript. transcript_path is the main session's.")
295
+ }),
296
+ output: stopOutput("SubagentStop", "the subagent")
297
+ },
298
+ TaskCreated: {
299
+ input: input("TaskCreated", "A task is being created with the TaskCreate tool. No matcher.", taskFields),
300
+ output: output("TaskCreated", "Can cancel the task. Exit code 2 cancels it too, with stderr returned to Claude as the tool's error. continue: false is ignored.", {
301
+ discards: ["continue"],
302
+ block: {
303
+ decision: "Deletes the task.",
304
+ reason: "Returned to Claude as the tool's error."
305
+ }
306
+ })
307
+ },
308
+ TaskCompleted: {
309
+ input: input("TaskCompleted", "A task is being marked completed, through TaskUpdate or when a teammate finishes its turn with tasks in progress. No matcher.", taskFields),
310
+ output: output("TaskCompleted", "Can keep the task open. Exit code 2 keeps it open too, with stderr fed back to the model. continue: false lets a teammate go idle with the task still in progress, and is ignored on a TaskUpdate call. onFailure has no effect on this event.", { block: {
311
+ decision: "Keeps the task open.",
312
+ reason: "Given to Claude, which keeps working."
313
+ } })
314
+ },
315
+ Stop: {
316
+ input: input("Stop", "The main agent finished responding. Does not run after a user interrupt; an API error fires StopFailure instead. No matcher.", stopFields),
317
+ output: stopOutput("Stop", "Claude")
318
+ },
319
+ StopFailure: {
320
+ input: input("StopFailure", "The turn ended because of an API error. Runs instead of Stop. The matcher filters on error.", {
321
+ error: text("The error type: rate_limit, authentication_failed, oauth_org_not_allowed, account_on_hold, billing_error, invalid_request, model_not_found, server_error (including HTTP 529), max_output_tokens, cloud_credential_error or unknown."),
322
+ error_details: opt(text("More detail about the error, when available.")),
323
+ last_assistant_message: opt(text("The rendered error text shown in the conversation, not Claude's own output."))
324
+ }),
325
+ output: output("StopFailure", `${NOTHING_READ} The output and exit code are ignored, apart from terminalSequence.`, { discards: ["continue", "systemMessage"] })
326
+ },
327
+ TeammateIdle: {
328
+ input: input("TeammateIdle", "An agent team teammate is about to go idle after its turn. No matcher.", {
329
+ teammate_name: text("Name of the teammate about to go idle."),
330
+ team_name: opt(text("Deprecated: a session-derived team name that will be removed."))
331
+ }),
332
+ output: output("TeammateIdle", "Can keep the teammate working. Exit code 2 does too, with stderr as feedback. continue: false lets it go idle even if another hook blocks. onFailure has no effect on this event.", { block: {
333
+ decision: "Keeps the teammate working.",
334
+ reason: "Given to the teammate."
335
+ } })
336
+ },
337
+ InstructionsLoaded: {
338
+ input: input("InstructionsLoaded", "A CLAUDE.md or .claude/rules/*.md file was loaded into context, at session start or lazily. Runs asynchronously. The matcher filters on load_reason.", {
339
+ file_path: text("Absolute path of the instruction file that was loaded."),
340
+ memory_type: oneOf([
341
+ "User",
342
+ "Project",
343
+ "Local",
344
+ "Managed"
345
+ ], "Scope of the file."),
346
+ load_reason: oneOf([
347
+ "session_start",
348
+ "nested_traversal",
349
+ "path_glob_match",
350
+ "include",
351
+ "compact"
352
+ ], "Why the file was loaded. compact fires when files are re-loaded after a compaction."),
353
+ globs: opt(strings("Path globs from the file's paths frontmatter. Only for path_glob_match loads.")),
354
+ trigger_file_path: opt(text("The file whose access triggered a lazy load.")),
355
+ parent_file_path: opt(text("The instruction file that included this one. Only for include loads."))
356
+ }),
357
+ output: output("InstructionsLoaded", `${NOTHING_READ} It cannot block or change the load.`, { discards: ["continue", "systemMessage"] })
358
+ },
359
+ ConfigChange: {
360
+ input: input("ConfigChange", "A settings, managed policy or skill file changed during the session. The matcher filters on source.", {
361
+ source: oneOf([
362
+ "user_settings",
363
+ "project_settings",
364
+ "local_settings",
365
+ "policy_settings",
366
+ "skills"
367
+ ], "Which kind of configuration changed."),
368
+ file_path: opt(text("Path of the file that changed."))
369
+ }),
370
+ output: output("ConfigChange", "Can stop the change from applying to the running session. Exit code 2 blocks it too. A policy_settings change cannot be blocked. A blocked change shows no message to the user or Claude.", {
371
+ discards: ["continue", "systemMessage"],
372
+ block: {
373
+ decision: "Prevents the change from being applied.",
374
+ reason: "Accepted but never shown."
375
+ }
376
+ })
377
+ },
378
+ CwdChanged: {
379
+ input: input("CwdChanged", "A shell command in the main conversation changed the working directory. CLAUDE_ENV_FILE is set, and its variables are cleared at the next CwdChanged. No matcher.", {
380
+ old_cwd: text("The previous working directory."),
381
+ new_cwd: text("The new working directory.")
382
+ }),
383
+ output: output("CwdChanged", "Cannot block the change. systemMessage is shown as a brief terminal notification. The docs do not say where watchPaths sits in the output; it is modelled under hookSpecificOutput, as on SessionStart.", {
384
+ discards: ["continue"],
385
+ specific: { watchPaths: opt(strings("Absolute paths. Replaces the dynamic FileChanged watch list; an empty array clears it. Paths from a matcher stay watched.")) }
386
+ })
387
+ },
388
+ DirectoryAdded: {
389
+ input: input("DirectoryAdded", "A working directory was added mid-session. The add has already completed and the hook runs in the background. The matcher filters on source.", {
390
+ directory: text("Absolute path of the directory that was added."),
391
+ source: oneOf(["slash_command", "register_repo_root"], "slash_command for /add-dir, register_repo_root for the SDK control request.")
392
+ }),
393
+ output: output("DirectoryAdded", `${NOTHING_READ} systemMessage is not shown to the user here: for /add-dir it is given to Claude as context on the next turn, and for the SDK request it goes to the debug log.`, { discards: ["continue"] })
394
+ },
395
+ FileChanged: {
396
+ input: input("FileChanged", "A watched file changed on disk, whatever changed it. The matcher is split on | into literal filenames to watch, not treated as a regex. CLAUDE_ENV_FILE is set.", {
397
+ file_path: text("Absolute path of the file that changed."),
398
+ event: oneOf([
399
+ "change",
400
+ "add",
401
+ "unlink"
402
+ ], "What happened: modified, created or deleted.")
403
+ }),
404
+ output: output("FileChanged", "Cannot block the change. systemMessage is shown as a brief terminal notification. The docs do not say where watchPaths sits in the output; it is modelled under hookSpecificOutput, as on SessionStart.", {
405
+ discards: ["continue"],
406
+ specific: { watchPaths: opt(strings("Absolute paths. Replaces the dynamic watch list. Paths from a matcher stay watched.")) }
407
+ })
408
+ },
409
+ WorktreeCreate: {
410
+ input: input("WorktreeCreate", "Claude Code is creating a worktree. A hook here replaces the default git worktree behaviour entirely, and .worktreeinclude is not processed. No matcher.", { name: text("A slug for the new worktree, user-specified or generated, such as bold-oak-a3f2.") }),
411
+ output: output("WorktreeCreate", "Returns the created worktree's path. A command hook does not print JSON: it prints the path as the last non-empty line of stdout, with everything else on stderr. Only an HTTP hook returns this object. Any non-zero exit, or no path, fails creation.", {
412
+ discards: ["continue", "systemMessage"],
413
+ specific: { worktreePath: opt(text("HTTP hooks only: the absolute, normalized path of the created worktree, not passing through a symlink.")) }
414
+ })
415
+ },
416
+ WorktreeRemove: {
417
+ input: input("WorktreeRemove", "Claude Code is cleaning up a worktree a WorktreeCreate hook created. No matcher.", { worktree_path: text("Absolute path of the worktree being removed, as WorktreeCreate returned it.") }),
418
+ output: output("WorktreeRemove", "No decision is read from JSON. Only the exit code counts: non-zero fails the removal if the directory still exists afterwards.", { discards: ["continue", "systemMessage"] })
419
+ },
420
+ PreCompact: {
421
+ input: input("PreCompact", "Claude Code is about to compact the conversation. The matcher filters on trigger.", {
422
+ trigger: oneOf(["manual", "auto"], "manual for /compact, auto for automatic or idle compaction."),
423
+ custom_instructions: Schema.NullOr(Schema.String).annotate({ description: "What the user passed to /compact; null when they passed nothing, and always null for auto." })
424
+ }),
425
+ output: output("PreCompact", "Can block compaction. Exit code 2 blocks it too. When the hook exits 0 without blocking, its plain stdout becomes instructions for the compaction summary.", {
426
+ discards: ["continue", "systemMessage"],
427
+ block: {
428
+ decision: "Blocks compaction.",
429
+ reason: "The reason; for a manual /compact it is shown to the user."
430
+ }
431
+ })
432
+ },
433
+ PostCompact: {
434
+ input: input("PostCompact", "A compaction completed. The matcher filters on trigger.", {
435
+ trigger: oneOf(["manual", "auto"], "manual after /compact, auto after automatic or idle compaction."),
436
+ compact_summary: text("The conversation summary the compaction generated.")
437
+ }),
438
+ output: output("PostCompact", NOTHING_READ, { discards: ["continue", "systemMessage"] })
439
+ },
440
+ PreModelSwitch: {
441
+ input: input("PreModelSwitch", "A model switch the user or a client requested is about to apply. Claude Code 2.1.251 or later. The matcher compares against the canonical name of to_model; when none can be determined every hook runs, so check to_model too. Default timeout 30 seconds, and a timeout blocks the switch.", modelFields([
442
+ "command",
443
+ "picker",
444
+ "sdk"
445
+ ], "Where the request came from: command for /model <name>, /config or fast mode; picker for a model picker; sdk for an Agent SDK host or Remote Control.")),
446
+ output: output("PreModelSwitch", "Cancels the switch, asks the user to confirm it, or lets it proceed. Exit code 2 cancels it, with stderr shown to the user. When hooks disagree, deny beats ask, which beats allow. systemMessage is shown whatever the decision.", {
447
+ block: {
448
+ decision: "Cancels the switch.",
449
+ reason: "The reason for cancelling."
450
+ },
451
+ specific: {
452
+ permissionDecision: opt(oneOf([
453
+ "allow",
454
+ "deny",
455
+ "ask"
456
+ ], "allow proceeds and skips Claude Code's own confirmation; deny cancels; ask prompts the user, and is treated as a refusal everywhere but /model in an interactive session. defer is not accepted.")),
457
+ permissionDecisionReason: opt(text("For deny, shown to the user. For ask, shown in the confirmation prompt. Ignored for allow."))
458
+ }
459
+ })
460
+ },
461
+ PostModelSwitch: {
462
+ input: input("PostModelSwitch", "The session's model changed, including changes Claude Code makes on its own. Claude Code 2.1.251 or later. The matcher compares against the canonical name of to_model. Default timeout 30 seconds.", modelFields([
463
+ "command",
464
+ "picker",
465
+ "sdk",
466
+ "auto",
467
+ "resume"
468
+ ], "As on PreModelSwitch, plus auto for a fallback or other change Claude Code made itself and resume for the model restored on resume.")),
469
+ output: output("PostModelSwitch", "Adds context for the new model. Cannot block: the model has already changed. Plain-text stdout is delivered as context too.", { specific: { additionalContext: additionalContext("with the next request after the switch") } })
470
+ },
471
+ Elicitation: {
472
+ input: input("Elicitation", "An MCP server requests user input during a tool call. The matcher filters on mcp_server_name.", {
473
+ mcp_server_name: text("Name of the MCP server asking."),
474
+ message: text("What the server is asking for."),
475
+ mode: opt(oneOf(["form", "url"], "form for a form request, url for a browser-based one.")),
476
+ url: opt(text("The URL to open. Only in url mode.")),
477
+ elicitation_id: opt(text("Identifier of the request.")),
478
+ requested_schema: opt(record("The JSON Schema of the form. Its property names are the keys an answer's content uses."))
479
+ }),
480
+ output: elicitationOutput("Elicitation", "answers for the user and skips the dialog (in url mode the URL never opens)")
481
+ },
482
+ ElicitationResult: {
483
+ input: input("ElicitationResult", "The user responded to an MCP elicitation, before the response goes to the server. Does not run when an Elicitation hook answered. The matcher filters on mcp_server_name.", {
484
+ mcp_server_name: text("Name of the MCP server."),
485
+ action: oneOf([
486
+ "accept",
487
+ "decline",
488
+ "cancel"
489
+ ], "What the user did. Check it is accept before returning accept, or a declined request becomes an accepted one."),
490
+ mode: opt(oneOf(["form", "url"], "The request's mode.")),
491
+ elicitation_id: opt(text("Identifier of the request.")),
492
+ content: opt(record("The values the user submitted."))
493
+ }),
494
+ output: elicitationOutput("ElicitationResult", "sends your content in place of the user's values")
495
+ },
496
+ SessionEnd: {
497
+ input: input("SessionEnd", "The session is ending. A plugin's SessionEnd hooks share a 1.5 second budget that a plugin entry's timeout does not raise. The matcher filters on reason.", { reason: text("Why the session ended: clear, resume, logout, prompt_input_exit or other.") }),
498
+ output: output("SessionEnd", `${NOTHING_READ} It cannot stop the session ending.`, { discards: ["continue", "systemMessage"] })
499
+ }
500
+ };
501
+
502
+ export { HOOK_IO };
@@ -0,0 +1,37 @@
1
+ import { Schema } from "effect";
2
+ import { CLAUDE_HOOK_EVENTS } from "../hooks.js";
3
+ import { HOOK_IO } from "./events.js";
4
+ import { TOOL_INPUTS } from "./tool-inputs.js";
5
+ import { hookEventsZig } from "./zig.js";
6
+
7
+ // src/hook-io/index.ts
8
+ const DIALECT = "https://json-schema.org/draft/2020-12/schema";
9
+ const render = (schema) => {
10
+ const document = Schema.toJsonSchemaDocument(schema);
11
+ const definitions = Object.keys(document.definitions).length === 0 ? {} : { $defs: document.definitions };
12
+ return `${JSON.stringify({
13
+ $schema: DIALECT,
14
+ ...document.schema,
15
+ ...definitions
16
+ }, null, " ")}\n`;
17
+ };
18
+ /**
19
+ * The JSON Schema documents for every Claude Code hook event, one for its
20
+ * input and one for its output, and one for each built-in tool's
21
+ * `tool_input`. The text is deterministic, so a regeneration that changes
22
+ * nothing writes the same bytes.
23
+ *
24
+ * @public
25
+ */
26
+ const hookSchemaFiles = () => [...CLAUDE_HOOK_EVENTS.flatMap((event) => [{
27
+ name: `${event}.input.schema.json`,
28
+ content: render(HOOK_IO[event].input)
29
+ }, {
30
+ name: `${event}.output.schema.json`,
31
+ content: render(HOOK_IO[event].output)
32
+ }]), ...Object.entries(TOOL_INPUTS).map(([tool, schema]) => ({
33
+ name: `tool-input.${tool}.schema.json`,
34
+ content: render(schema)
35
+ }))];
36
+
37
+ export { HOOK_IO, TOOL_INPUTS, hookEventsZig, hookSchemaFiles };
@@ -0,0 +1,91 @@
1
+ import { Schema } from "effect";
2
+ import { flag, num, oneOf, opt, record, strings, text } from "./build.js";
3
+
4
+ // src/hook-io/tool-inputs.ts
5
+ const tool = (name, description, fields) => Schema.Struct(fields).annotate({
6
+ title: `${name} tool_input`,
7
+ description
8
+ });
9
+ const shell = (name, example) => tool(name, `Arguments of the ${name} tool, which executes ${example}.`, {
10
+ command: text("The command to execute."),
11
+ description: opt(text("What the command does.")),
12
+ timeout: opt(num("Timeout in milliseconds. A value above the maximum is reduced to it.")),
13
+ run_in_background: opt(flag("Whether to run the command in the background."))
14
+ });
15
+ const filePath = (verb) => text(`Absolute path of the file to ${verb}. Claude Code expands ~ and relative paths before hooks run. On Windows it arrives with backslashes: normalize separators before comparing.`);
16
+ /**
17
+ * The documented `tool_input` shape of each built-in tool, by tool name.
18
+ *
19
+ * @public
20
+ */
21
+ const TOOL_INPUTS = {
22
+ Bash: shell("Bash", "shell commands"),
23
+ PowerShell: shell("PowerShell", "PowerShell commands; match Bash|PowerShell in a hook that inspects shell commands"),
24
+ Write: tool("Write", "Arguments of the Write tool, which creates or overwrites a file.", {
25
+ file_path: filePath("write"),
26
+ content: text("Content to write to the file.")
27
+ }),
28
+ Edit: tool("Edit", "Arguments of the Edit tool, which replaces a string in an existing file.", {
29
+ file_path: filePath("edit"),
30
+ old_string: text("Text to find and replace."),
31
+ new_string: text("Replacement text."),
32
+ replace_all: opt(flag("Whether to replace every occurrence."))
33
+ }),
34
+ Read: tool("Read", "Arguments of the Read tool, which reads file contents.", {
35
+ file_path: filePath("read"),
36
+ offset: opt(num("Line number to start reading from.")),
37
+ limit: opt(num("Number of lines to read."))
38
+ }),
39
+ Glob: tool("Glob", "Arguments of the Glob tool, which finds files matching a glob pattern.", {
40
+ pattern: text("Glob pattern to match files against."),
41
+ path: opt(text("Directory to search in. Defaults to the current working directory."))
42
+ }),
43
+ Grep: tool("Grep", "Arguments of the Grep tool, which searches file contents with regular expressions.", {
44
+ pattern: text("Regular expression to search for."),
45
+ path: opt(text("File or directory to search in.")),
46
+ glob: opt(text("Glob pattern to filter files.")),
47
+ output_mode: opt(oneOf([
48
+ "content",
49
+ "files_with_matches",
50
+ "count"
51
+ ], "Defaults to files_with_matches.")),
52
+ "-i": opt(flag("Case insensitive search.")),
53
+ multiline: opt(flag("Enable multiline matching."))
54
+ }),
55
+ WebFetch: tool("WebFetch", "Arguments of the WebFetch tool, which fetches and processes web content.", {
56
+ url: text("URL to fetch content from."),
57
+ prompt: text("Prompt to run on the fetched content."),
58
+ offset: opt(num("Characters to skip from the start of the page. Claude Code 2.1.290 or later."))
59
+ }),
60
+ WebSearch: tool("WebSearch", "Arguments of the WebSearch tool, which searches the web.", {
61
+ query: text("Search query."),
62
+ allowed_domains: opt(strings("Only include results from these domains.")),
63
+ blocked_domains: opt(strings("Exclude results from these domains.")),
64
+ mode: opt(oneOf(["standard", "extended"], "standard requests a lighter search, extended the full one. Claude Code 2.1.282 or later."))
65
+ }),
66
+ Agent: tool("Agent", "Arguments of the Agent tool, which spawns a subagent.", {
67
+ prompt: text("The task for the agent to perform."),
68
+ description: opt(text("Short description of the task.")),
69
+ subagent_type: opt(text("Type of specialized agent to use, such as Explore.")),
70
+ model: opt(text("Model alias to override the default, such as sonnet."))
71
+ }),
72
+ AskUserQuestion: tool("AskUserQuestion", "Arguments of the AskUserQuestion tool, which asks the user one to four multiple-choice questions. To answer from a PreToolUse hook, return allow with updatedInput holding the original questions plus answers.", {
73
+ questions: Schema.Array(Schema.Struct({
74
+ question: text("The question text."),
75
+ header: text("A short header."),
76
+ options: Schema.Array(Schema.Struct({
77
+ label: text("The option's label."),
78
+ description: opt(text("What the option means."))
79
+ })).annotate({ description: "The choices." }),
80
+ multiSelect: opt(flag("Whether several options may be chosen."))
81
+ })).annotate({ description: "The questions to present." }),
82
+ answers: opt(record("Maps question text to the chosen option label; multi-select answers join labels with commas. Claude never sets it: supply it through updatedInput."))
83
+ }),
84
+ ExitPlanMode: tool("ExitPlanMode", "Arguments of the ExitPlanMode tool, which presents a plan for approval. Claude Code injects the plan content and path before hooks see the input.", {
85
+ plan: opt(text("Plan content in Markdown, injected from the plan file.")),
86
+ planFilePath: opt(text("Path to the plan file, injected.")),
87
+ allowedPrompts: opt(Schema.Array(Schema.Unknown).annotate({ description: "Deprecated: accepted and ignored." }))
88
+ })
89
+ };
90
+
91
+ export { TOOL_INPUTS };