@pluginfinity/hooks 0.0.0-stage → 0.7.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,53 @@
1
+ import { Schema } from "effect";
2
+
3
+ // src/contract/hook-events.ts
4
+ /**
5
+ * Every Claude Code hook event, the vocabulary a plugin's `hooks` config is
6
+ * written in. Each target maps these to its own names.
7
+ *
8
+ * @public
9
+ */
10
+ const CLAUDE_HOOK_EVENTS = [
11
+ "SessionStart",
12
+ "Setup",
13
+ "UserPromptSubmit",
14
+ "UserPromptExpansion",
15
+ "PreSkillShellCommand",
16
+ "PreToolUse",
17
+ "PermissionRequest",
18
+ "PermissionDenied",
19
+ "PostToolUse",
20
+ "PostToolUseFailure",
21
+ "PostToolBatch",
22
+ "Notification",
23
+ "MessageDisplay",
24
+ "SubagentStart",
25
+ "SubagentStop",
26
+ "TaskCreated",
27
+ "TaskCompleted",
28
+ "Stop",
29
+ "StopFailure",
30
+ "TeammateIdle",
31
+ "InstructionsLoaded",
32
+ "ConfigChange",
33
+ "CwdChanged",
34
+ "DirectoryAdded",
35
+ "FileChanged",
36
+ "WorktreeCreate",
37
+ "WorktreeRemove",
38
+ "PreCompact",
39
+ "PostCompact",
40
+ "PreModelSwitch",
41
+ "PostModelSwitch",
42
+ "Elicitation",
43
+ "ElicitationResult",
44
+ "SessionEnd"
45
+ ];
46
+ /**
47
+ * A Claude Code hook event name.
48
+ *
49
+ * @public
50
+ */
51
+ const ClaudeHookEvent = Schema.Literals(CLAUDE_HOOK_EVENTS);
52
+
53
+ export { CLAUDE_HOOK_EVENTS, ClaudeHookEvent };
@@ -0,0 +1,91 @@
1
+ import { Schema } from "effect";
2
+ import { flag, num, oneOf, opt, record, strings, text } from "./build.js";
3
+
4
+ // src/contract/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 };
@@ -0,0 +1,106 @@
1
+ import { supports } from "./decisions.js";
2
+
3
+ // src/contract/wire.ts
4
+ const out = (body, extra = {}) => ({
5
+ stdout: `${JSON.stringify(body)}\n`,
6
+ stderr: "",
7
+ exitCode: 0,
8
+ ...extra
9
+ });
10
+ const silent = (extra) => ({
11
+ stdout: "",
12
+ stderr: "",
13
+ exitCode: 0,
14
+ ...extra
15
+ });
16
+ const blockedBy = (plugin) => `Blocked by ${plugin ?? "a plugin"}`;
17
+ const permission = (context, decision, reason, updatedInput) => {
18
+ const event = context.event === "" ? "PreToolUse" : context.event;
19
+ let debug;
20
+ let input = updatedInput;
21
+ if (input !== void 0 && event !== "PreToolUse") {
22
+ debug = `hook_allow: ${event} takes no updated input; sent the decision without it`;
23
+ input = void 0;
24
+ }
25
+ const body = {
26
+ permissionDecision: decision,
27
+ ...reason === "" ? {} : { permissionDecisionReason: reason },
28
+ ...input === void 0 ? {} : { [context.host === "copilot" ? "modifiedArgs" : "updatedInput"]: input }
29
+ };
30
+ const wire = context.host === "copilot" ? body : { hookSpecificOutput: {
31
+ hookEventName: event,
32
+ ...body
33
+ } };
34
+ return out(wire, debug === void 0 ? {} : { debug });
35
+ };
36
+ const HELPER = {
37
+ Noop: "hook_noop",
38
+ Allow: "hook_allow",
39
+ Deny: "hook_deny",
40
+ Ask: "hook_ask",
41
+ Block: "hook_block",
42
+ Context: "hook_context",
43
+ SystemMessage: "hook_system_message",
44
+ Rewake: "hook_rewake",
45
+ Raw: "hook_raw"
46
+ };
47
+ /**
48
+ * Write a decision in the host's wire format, the same bytes the bash hook
49
+ * library prints for the matching helper. A decision the host does not honour
50
+ * on the event answers `{}` with a debug line.
51
+ *
52
+ * @public
53
+ */
54
+ const encodeDecision = (context, decision) => {
55
+ if (!supports(context.host, decision._tag, context.event)) return out({}, { debug: `${HELPER[decision._tag]} does nothing on ${context.host} for ${context.event}` });
56
+ switch (decision._tag) {
57
+ case "Noop": return out({});
58
+ case "Allow": return permission(context, "allow", decision.reason ?? "", decision.updatedInput);
59
+ case "Deny": return permission(context, "deny", decision.reason || blockedBy(context.plugin), void 0);
60
+ case "Ask": return permission(context, "ask", decision.reason ?? "", void 0);
61
+ case "Block": return out({
62
+ decision: "block",
63
+ reason: decision.reason || blockedBy(context.plugin)
64
+ });
65
+ case "Context": return out(context.host === "copilot" ? { additionalContext: decision.text } : { hookSpecificOutput: {
66
+ hookEventName: context.event,
67
+ additionalContext: decision.text
68
+ } });
69
+ case "SystemMessage": return out({ systemMessage: decision.text });
70
+ case "Rewake":
71
+ if (context.asyncRewake !== true) return silent({ log: "hook_rewake: this entry does not set asyncRewake; ignored" });
72
+ return {
73
+ stdout: "",
74
+ stderr: `${decision.message}\n`,
75
+ exitCode: 2
76
+ };
77
+ case "Raw":
78
+ if (decision.host !== context.host) return silent({ debug: `hook_raw for ${decision.host} skipped on ${context.host}` });
79
+ return out(decision.json);
80
+ }
81
+ };
82
+ const NO_CLOSED_RESPONSE = /* @__PURE__ */ new Set(["TaskCompleted", "TeammateIdle"]);
83
+ /**
84
+ * The answer of an entry that fails closed when its hook failed before
85
+ * answering: a deny where the event takes one, else a block, else nothing.
86
+ * As in the bash library, a Stop or SubagentStop hook sends nothing while
87
+ * `stop_hook_active` is true (a block would loop), and TaskCompleted and
88
+ * TeammateIdle send nothing (a block sends a teammate back to a hook that will
89
+ * not run).
90
+ *
91
+ * @public
92
+ */
93
+ const closedResponse = (context, input, code) => {
94
+ const { event, host } = context;
95
+ if (NO_CLOSED_RESPONSE.has(event)) return void 0;
96
+ if ((event === "Stop" || event === "SubagentStop") && isStopActive(input)) return void 0;
97
+ const reason = `${context.plugin ?? "a plugin"} hook failed (exit ${code})`;
98
+ if (supports(host, "Deny", event)) return permission(context, "deny", reason, void 0);
99
+ if (supports(host, "Block", event)) return out({
100
+ decision: "block",
101
+ reason
102
+ });
103
+ };
104
+ const isStopActive = (input) => typeof input === "object" && input !== null && input.stop_hook_active === true;
105
+
106
+ export { closedResponse, encodeDecision };
@@ -0,0 +1,78 @@
1
+ import { Schema } from "effect";
2
+ import { HOOK_IO } from "./events.js";
3
+ import { CLAUDE_HOOK_EVENTS } from "./hook-events.js";
4
+ import { TOOL_INPUTS } from "./tool-inputs.js";
5
+
6
+ // src/contract/zig.ts
7
+ const KEYWORDS = new Set("addrspace align allowzero and anyframe anytype asm async await break callconv catch comptime const continue defer else enum errdefer error export extern fn for if inline linksection noalias noinline nosuspend opaque or orelse packed pub resume return struct suspend switch test threadlocal try union unreachable usingnamespace var volatile while".split(" "));
8
+ const identifier = (name) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) && !KEYWORDS.has(name) ? name : `@"${name}"`;
9
+ const COMMON = /* @__PURE__ */ new Set([
10
+ "session_id",
11
+ "transcript_path",
12
+ "cwd",
13
+ "prompt_id",
14
+ "scratchpad_dir",
15
+ "permission_mode",
16
+ "effort",
17
+ "agent_id",
18
+ "agent_type"
19
+ ]);
20
+ const zigType = (schema, indent) => {
21
+ if (Array.isArray(schema.anyOf)) {
22
+ const variants = schema.anyOf;
23
+ const present = variants.filter((variant) => variant.type !== "null");
24
+ const [only] = present;
25
+ return present.length === 1 && variants.length === 2 && only !== void 0 ? `?${zigType(only, indent)}` : "std.json.Value";
26
+ }
27
+ if (Array.isArray(schema.enum)) return "[]const u8";
28
+ if (schema.type === "string") return "[]const u8";
29
+ if (schema.type === "number") return "f64";
30
+ if (schema.type === "boolean") return "bool";
31
+ if (schema.type === "array") return `[]const ${zigType(schema.items ?? {}, indent)}`;
32
+ if (schema.type === "object" && schema.properties !== void 0) return zigStruct(schema, indent, false);
33
+ return "std.json.Value";
34
+ };
35
+ const zigStruct = (schema, indent, event) => {
36
+ const inner = `${indent} `;
37
+ const required = new Set(schema.required ?? []);
38
+ return `struct {\n${Object.entries(schema.properties).map(([name, field]) => {
39
+ const type = zigType(field, inner);
40
+ const optional = !required.has(name) || event && COMMON.has(name);
41
+ const doc = typeof field.description === "string" ? `${inner}/// ${field.description}\n` : "";
42
+ const spelled = optional ? `${type.startsWith("?") ? type : `?${type}`} = null` : type;
43
+ return `${doc}${inner}${identifier(name)}: ${spelled},\n`;
44
+ }).join("")}${indent}}`;
45
+ };
46
+ const declaration = (name, schema, indent, event) => {
47
+ const json = Schema.toJsonSchemaDocument(schema).schema;
48
+ return `${typeof json.description === "string" ? `${indent}/// ${json.description}\n` : ""}${indent}pub const ${identifier(name)} = ${zigStruct(json, indent, event)};\n`;
49
+ };
50
+ /**
51
+ * The Zig source of `zig/src/events.zig`: a struct for each Claude Code hook
52
+ * event's input and, under `tools`, for each built-in tool's `tool_input`. The
53
+ * text is what `zig fmt` would write, so a regeneration that changes nothing
54
+ * writes the same bytes.
55
+ *
56
+ * @public
57
+ */
58
+ const hookEventsZig = () => [
59
+ "//! Generated from the hook event schemas in @pluginfinity/core. Do not edit:",
60
+ "//! run `pnpm --filter @pluginfinity/hooks run hook-io:zig`.",
61
+ "//!",
62
+ "//! One struct per Claude Code hook event, as `Hook.as` reads it. The fields every",
63
+ "//! event may carry are optional, since a host other than Claude Code sends fewer;",
64
+ "//! an event's own fields are required where Claude Code always sends them. A",
65
+ "//! field whose values are a documented set is text, so a value added later still",
66
+ "//! parses, and a free-form field is a `std.json.Value`.",
67
+ "",
68
+ "const std = @import(\"std\");",
69
+ "",
70
+ ...CLAUDE_HOOK_EVENTS.map((event) => declaration(event, HOOK_IO[event].input, "", true)),
71
+ "/// The `tool_input` of each built-in tool, as `Hook.toolInput` reads it.",
72
+ "pub const tools = struct {",
73
+ Object.entries(TOOL_INPUTS).map(([tool, schema]) => declaration(tool, schema, " ", false)).join("\n").trimEnd(),
74
+ "};",
75
+ ""
76
+ ].join("\n");
77
+
78
+ export { hookEventsZig };