@pluginfinity/hooks 0.0.0-stage → 0.7.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 C. Spencer Beggs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,152 @@
1
+ import { Schema } from "effect";
2
+
3
+ // src/contract/build.ts
4
+ const text = (description) => Schema.String.annotate({ description });
5
+ const flag = (description) => Schema.Boolean.annotate({ description });
6
+ const num = (description) => Schema.Finite.annotate({ description });
7
+ const anything = (description) => Schema.Json.annotate({ description });
8
+ const record = (description) => Schema.Record(Schema.String, Schema.Unknown).annotate({ description });
9
+ const strings = (description) => Schema.Array(Schema.String).annotate({ description });
10
+ const oneOf = (values, description) => Schema.Literals(values).annotate({ description });
11
+ const opt = (schema) => Schema.optionalKey(schema);
12
+ /** The permission modes Claude Code reports. Manual mode arrives as `default`. */
13
+ const PERMISSION_MODES = [
14
+ "default",
15
+ "plan",
16
+ "acceptEdits",
17
+ "auto",
18
+ "dontAsk",
19
+ "bypassPermissions"
20
+ ];
21
+ const commonInput = {
22
+ session_id: text("Current session identifier."),
23
+ transcript_path: text("Path to the conversation JSON. Written asynchronously, so it can lag the current turn; on Stop and SubagentStop read last_assistant_message instead."),
24
+ cwd: text("Working directory when the hook is invoked. Follows Claude into a worktree or after a cd, while CLAUDE_PROJECT_DIR stays at the project root where the session started."),
25
+ prompt_id: opt(text("UUID of the user prompt being processed; matches the prompt.id attribute on OpenTelemetry events. Absent until the first user input.")),
26
+ scratchpad_dir: opt(text("Path to the session's scratchpad directory. Absent when the session has none or the temp directory is unavailable. Claude Code 2.1.257 or later.")),
27
+ permission_mode: opt(oneOf(PERMISSION_MODES, "Current permission mode. The mode labelled Manual arrives as default. Not every event carries this field.")),
28
+ effort: opt(Schema.Struct({ level: oneOf([
29
+ "low",
30
+ "medium",
31
+ "high",
32
+ "xhigh",
33
+ "max"
34
+ ], "The effort level that ran, including a skill's, subagent's or ultrathink level. CLAUDE_EFFORT holds the same value.") }).annotate({ description: "Present on events with a tool-use context, on models that support effort." })),
35
+ agent_id: opt(text("Unique identifier of the subagent or in-process teammate the hook fires in.")),
36
+ agent_type: opt(text("Agent name, such as Explore or a plugin-scoped my-plugin:reviewer. Present inside a subagent, or when the session runs with --agent; a subagent's type wins over the session's."))
37
+ };
38
+ /**
39
+ * One event's input: the common fields, `hook_event_name` pinned to the
40
+ * event, and the event's own fields. Unknown keys are allowed, since Claude
41
+ * Code adds fields between releases.
42
+ */
43
+ const input = (event, description, fields) => Schema.Struct({
44
+ ...commonInput,
45
+ hook_event_name: Schema.Literal(event).annotate({ description: `Always "${event}".` }),
46
+ ...fields
47
+ }).annotate({
48
+ title: `${event} hook input`,
49
+ description
50
+ });
51
+ const universal = {
52
+ continue: opt(flag("Default true. false stops Claude entirely after the hook runs, and beats an event-specific decision. It does not by itself block a PreToolUse tool call.")),
53
+ stopReason: opt(text("Shown to the user when continue is false. It stays in the conversation, so Claude sees it later.")),
54
+ suppressOutput: opt(flag("Accepted and has no effect.")),
55
+ systemMessage: opt(text("A warning shown to the user, not added to Claude's context. Capped at 10,000 characters; longer text is saved to a file and replaced by its path and a 2,000 character preview.")),
56
+ terminalSequence: opt(text("A terminal escape sequence Claude Code emits for the hook: only OSC 0, 1, 2, 9, 99, 777 and BEL. Anything else makes the field ignored. Interactive sessions only, and not from an async hook."))
57
+ };
58
+ const blockFields = (decision, reason) => ({
59
+ decision: opt(Schema.Literal("block").annotate({ description: decision })),
60
+ reason: opt(text(reason))
61
+ });
62
+ /**
63
+ * One event's output: the JSON object a hook may print to stdout (or return as
64
+ * an HTTP body) with exit code 0. A field the host discards on the event is
65
+ * absent from the schema and named in the description.
66
+ */
67
+ const output = (event, description, spec = {}) => {
68
+ const discards = new Set(spec.discards ?? []);
69
+ if (discards.has("continue")) discards.add("stopReason");
70
+ const kept = Object.fromEntries(Object.entries(universal).filter(([key]) => !discards.has(key)));
71
+ const names = spec.eventNames ?? [event];
72
+ const fields = {
73
+ ...kept,
74
+ ...spec.block === void 0 ? {} : blockFields(spec.block.decision, spec.block.reason),
75
+ ...spec.specific === void 0 ? {} : { hookSpecificOutput: opt(Schema.Struct({
76
+ hookEventName: (names.length === 1 ? Schema.Literal(names[0] ?? event) : Schema.Literals(names)).annotate({ description: `Required whenever hookSpecificOutput is present: ${names.map((name) => `"${name}"`).join(" or ")}.` }),
77
+ ...spec.specific
78
+ }).annotate({ description: `The ${event}-specific fields.` })) },
79
+ ...spec.extra
80
+ };
81
+ const dropped = [...discards].filter((key) => key !== "suppressOutput");
82
+ return Schema.Struct(fields).annotate({
83
+ title: `${event} hook output`,
84
+ description: dropped.length === 0 ? description : `${description} Claude Code discards ${dropped.join(", ")} on this event.`
85
+ });
86
+ };
87
+ /** `additionalContext`, with where the text lands on this event. */
88
+ const additionalContext = (where) => opt(text(`Text added to Claude's context ${where}, wrapped in a system reminder and not shown as a chat message. State facts rather than give commands. Capped at 10,000 characters.`));
89
+ const toolName = text("The tool being called: a built-in such as Bash, PowerShell, Edit, Write, Read, Glob, Grep, Agent, WebFetch or WebSearch, or an MCP tool named mcp__<server>__<tool> (mcp__plugin_<plugin>_<server>__<tool> for a plugin's own server).");
90
+ const toolInput = record("The arguments sent to the tool. The keys depend on the tool; see the tool-input schemas beside this file.");
91
+ const toolUseId = text("Identifier of this tool call.");
92
+ const mcpServer = opt(Schema.Struct({
93
+ name: text("The MCP server's name."),
94
+ source: text("Where the server's definition came from, such as plugin, sdk, user or project. Base trust decisions on this, not on the name or the tool-name prefix.")
95
+ }).annotate({ description: "Present for an MCP tool only. Claude Code 2.1.274 or later." }));
96
+ const destination = oneOf([
97
+ "session",
98
+ "localSettings",
99
+ "projectSettings",
100
+ "userSettings"
101
+ ], "Where the change is written: session is in memory only; the others are .claude/settings.local.json, .claude/settings.json and ~/.claude/settings.json.");
102
+ const rules = Schema.Array(Schema.Struct({
103
+ toolName: text("The tool the rule names, such as Bash or mcp__github__get_issue."),
104
+ ruleContent: opt(text("The rule's specifier, such as npm test for Bash(npm test). Omit it to match the whole tool; always omit it for an MCP tool."))
105
+ })).annotate({ description: "The permission rules to add, replace or remove." });
106
+ const behavior = oneOf([
107
+ "allow",
108
+ "deny",
109
+ "ask"
110
+ ], "The kind of rule.");
111
+ /** One permission update, as suggested to a PermissionRequest hook or returned by it. */
112
+ const PermissionUpdate = Schema.Union([
113
+ Schema.Struct({
114
+ type: oneOf([
115
+ "addRules",
116
+ "replaceRules",
117
+ "removeRules"
118
+ ], "addRules adds the rules; replaceRules replaces every rule of that behavior at the destination; removeRules removes the matching ones."),
119
+ rules,
120
+ behavior,
121
+ destination
122
+ }),
123
+ Schema.Struct({
124
+ type: Schema.Literal("setMode").annotate({ description: "Changes the permission mode." }),
125
+ mode: oneOf([...PERMISSION_MODES, "manual"], "The mode to switch to; manual is an alias for default. bypassPermissions only takes effect when the session was launched with bypass mode available."),
126
+ destination
127
+ }),
128
+ Schema.Struct({
129
+ type: oneOf(["addDirectories", "removeDirectories"], "Adds or removes working directories."),
130
+ directories: strings("Directory paths."),
131
+ destination
132
+ })
133
+ ]).annotate({ description: "A permission update entry; type decides its other fields." });
134
+ const backgroundTasks = opt(Schema.Array(Schema.Struct({
135
+ id: text("Task identifier."),
136
+ type: text("A task-type label such as shell, subagent, monitor, workflow, teammate, cloud session or MCP task."),
137
+ status: text("Current task status."),
138
+ description: opt(text("Free-text description, capped at 1000 characters.")),
139
+ command: opt(text("Shell command line. Only for shell tasks and monitor tasks that run a command.")),
140
+ agent_type: opt(text("Subagent type name. Only for subagent tasks.")),
141
+ server: opt(text("MCP server name. Only for monitor and MCP task tasks.")),
142
+ tool: opt(text("MCP tool name. Only for monitor and MCP task tasks.")),
143
+ name: opt(text("Workflow name. Only for workflow tasks."))
144
+ })).annotate({ description: "The session's in-flight background tasks; empty when nothing is running. With session_crons it tells a finished session from one paused waiting for background work." }));
145
+ const sessionCrons = opt(Schema.Array(Schema.Struct({
146
+ id: text("Cron task identifier."),
147
+ schedule: text("Cron expression, such as 0 9 * * 1-5."),
148
+ recurring: flag("false for a one-shot wakeup, true for a task that fires on every match."),
149
+ prompt: text("The prompt submitted when the cron fires, capped at 1000 characters.")
150
+ })).annotate({ description: "The session's scheduled wakeups, from CronCreate, ScheduleWakeup and /loop." }));
151
+
152
+ export { PERMISSION_MODES, PermissionUpdate, additionalContext, anything, backgroundTasks, flag, input, mcpServer, num, oneOf, opt, output, record, sessionCrons, strings, text, toolInput, toolName, toolUseId };
@@ -0,0 +1,132 @@
1
+ import { Data } from "effect";
2
+ import { CLAUDE_HOOK_EVENTS } from "./hook-events.js";
3
+
4
+ // src/contract/decisions.ts
5
+ /**
6
+ * The constructors for each `Decision`.
7
+ *
8
+ * @public
9
+ */
10
+ const makeDecision = Data.taggedEnum();
11
+ /**
12
+ * The events on which each host honours each answer, the one source `supports`,
13
+ * `ALLOWED_DECISIONS` and `AllowedTag` read. It mirrors the bash library's
14
+ * `hook_supports` and `okf/references/*-plugin-format.md`.
15
+ *
16
+ * @remarks
17
+ * `Allow`, `Ask` and `Deny` are honoured on `PreToolUse` by both hosts and, on
18
+ * Claude Code only, on `permission` events (and `Deny` also on `denyOnly`).
19
+ * `SystemMessage` is honoured on Claude Code on every event but
20
+ * `noSystemMessage`, and never on Copilot. `Noop`, `Raw` and `Rewake` work everywhere.
21
+ *
22
+ * @public
23
+ */
24
+ const ANSWER_EVENTS = {
25
+ permission: ["PreToolUse", "PreModelSwitch"],
26
+ denyOnly: ["PreSkillShellCommand"],
27
+ noSystemMessage: [
28
+ "Setup",
29
+ "InstructionsLoaded",
30
+ "MessageDisplay",
31
+ "Notification",
32
+ "StopFailure",
33
+ "ConfigChange",
34
+ "DirectoryAdded",
35
+ "WorktreeCreate",
36
+ "WorktreeRemove",
37
+ "PreCompact",
38
+ "PostCompact",
39
+ "SessionEnd",
40
+ "Elicitation",
41
+ "ElicitationResult"
42
+ ],
43
+ context: {
44
+ claude: [
45
+ "SessionStart",
46
+ "SubagentStart",
47
+ "PostModelSwitch",
48
+ "UserPromptSubmit",
49
+ "UserPromptExpansion",
50
+ "PreToolUse",
51
+ "PostToolUse",
52
+ "PostToolUseFailure",
53
+ "PostToolBatch",
54
+ "Stop",
55
+ "SubagentStop"
56
+ ],
57
+ copilot: [
58
+ "SessionStart",
59
+ "SubagentStart",
60
+ "PostToolUse",
61
+ "Notification"
62
+ ]
63
+ },
64
+ block: {
65
+ claude: [
66
+ "UserPromptSubmit",
67
+ "UserPromptExpansion",
68
+ "PreSkillShellCommand",
69
+ "PostToolUse",
70
+ "PostToolBatch",
71
+ "Stop",
72
+ "SubagentStop",
73
+ "ConfigChange",
74
+ "PreCompact",
75
+ "TaskCreated",
76
+ "TaskCompleted",
77
+ "TeammateIdle",
78
+ "PreModelSwitch",
79
+ "Elicitation",
80
+ "ElicitationResult"
81
+ ],
82
+ copilot: ["Stop", "SubagentStop"]
83
+ }
84
+ };
85
+ const has = (events, event) => events.includes(event);
86
+ /**
87
+ * Whether `host` honours a decision on `event`. It mirrors the bash library's
88
+ * `hook_supports` (and `okf/references/*-plugin-format.md`).
89
+ *
90
+ * @public
91
+ */
92
+ const supports = (host, tag, event) => {
93
+ switch (tag) {
94
+ case "Noop":
95
+ case "Raw":
96
+ case "Rewake": return true;
97
+ case "SystemMessage": return host === "claude" && !has(ANSWER_EVENTS.noSystemMessage, event);
98
+ case "Allow":
99
+ case "Deny":
100
+ case "Ask":
101
+ if (event === "PreToolUse") return true;
102
+ if (host !== "claude") return false;
103
+ return has(ANSWER_EVENTS.permission, event) || tag === "Deny" && has(ANSWER_EVENTS.denyOnly, event);
104
+ case "Context": return has(ANSWER_EVENTS.context[host], event);
105
+ case "Block": return has(ANSWER_EVENTS.block[host], event);
106
+ }
107
+ };
108
+ /**
109
+ * Every `Decision` tag.
110
+ *
111
+ * @public
112
+ */
113
+ const DECISION_TAGS = [
114
+ "Noop",
115
+ "Allow",
116
+ "Deny",
117
+ "Ask",
118
+ "Block",
119
+ "Context",
120
+ "SystemMessage",
121
+ "Rewake",
122
+ "Raw"
123
+ ];
124
+ /**
125
+ * The decisions a hook may give on each event: those either host honours
126
+ * there, plus `Noop`, `Raw` and `Rewake`, which every event takes.
127
+ *
128
+ * @public
129
+ */
130
+ const ALLOWED_DECISIONS = Object.fromEntries(CLAUDE_HOOK_EVENTS.map((event) => [event, DECISION_TAGS.filter((tag) => supports("claude", tag, event) || supports("copilot", tag, event))]));
131
+
132
+ export { ALLOWED_DECISIONS, ANSWER_EVENTS, DECISION_TAGS, makeDecision, supports };