@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.
@@ -0,0 +1,210 @@
1
+ import { Cause, Effect, Exit, Option, Result, Schema } from "effect";
2
+ import { DECISION_TAGS } from "../contract/decisions.js";
3
+ import { HOOK_IO } from "../contract/events.js";
4
+ import { CLAUDE_HOOK_EVENTS } from "../contract/hook-events.js";
5
+ import { TOOL_INPUTS } from "../contract/tool-inputs.js";
6
+ import { closedResponse, encodeDecision } from "../contract/wire.js";
7
+ import { isHookModule } from "../hook.js";
8
+ import { HOOKS_VERSION } from "../version.js";
9
+ import { HookContext } from "./context.js";
10
+ import { claudeEnvelope, matchField, matcherApplies, parseInput, resolveEvent } from "./input.js";
11
+
12
+ // src/runtime/runner.ts
13
+ /**
14
+ * The flag the build runs a bundle with to read its event and tools.
15
+ *
16
+ * @public
17
+ */
18
+ const DESCRIBE_FLAG = "--pluginfinity-describe";
19
+ const NOTHING = {
20
+ stdout: "",
21
+ stderr: "",
22
+ exitCode: 0
23
+ };
24
+ const NOOP = {
25
+ stdout: "{}\n",
26
+ stderr: "",
27
+ exitCode: 0
28
+ };
29
+ var HookLoadFailed = class extends Schema.TaggedError()("HookLoadFailed", { message: Schema.String }) {};
30
+ const load = (source) => Effect.gen(function* () {
31
+ if (typeof source !== "function") return source;
32
+ const loaded = yield* Effect.tryPromise({
33
+ try: source,
34
+ catch: (cause) => new HookLoadFailed({ message: cause instanceof Error ? cause.message : String(cause) })
35
+ });
36
+ const candidate = typeof loaded === "object" && loaded !== null && "default" in loaded ? loaded.default : loaded;
37
+ if (!isHookModule(candidate)) return yield* new HookLoadFailed({ message: "the default export is not a module hook (use Hook.<Event>.make)" });
38
+ return candidate;
39
+ });
40
+ const decodeInput = (ctx, module, event, input) => Effect.gen(function* () {
41
+ const decoded = yield* Schema.decodeUnknownEffect(HOOK_IO[event].input)(input).pipe(Effect.map((value) => ({
42
+ ...input,
43
+ ...value
44
+ })), Effect.catch((issue) => ctx.debug(`input does not match the ${event} schema: ${String(issue)}`).pipe(Effect.as(input))));
45
+ const tools = module.tools;
46
+ const toolInput = decoded.tool_input;
47
+ if (tools === void 0 || toolInput === void 0 || !tools.every((tool) => tool in TOOL_INPUTS)) return decoded;
48
+ const schemas = tools.map((tool) => TOOL_INPUTS[tool]);
49
+ return yield* Effect.firstSuccessOf(schemas.map((schema) => Schema.decodeUnknownEffect(schema)(toolInput))).pipe(Effect.map((typed) => ({
50
+ ...decoded,
51
+ tool_input: {
52
+ ...toolInput,
53
+ ...typed
54
+ }
55
+ })), Effect.catch(() => ctx.debug(`tool_input does not match ${tools.join(" or ")}; passed as sent`).pipe(Effect.as(decoded))));
56
+ });
57
+ var NotADecision = class extends Schema.TaggedError()("NotADecision", { message: Schema.String }) {};
58
+ const TAGS = new Set(DECISION_TAGS);
59
+ const isDecision = (value) => typeof value === "object" && value !== null && TAGS.has(value._tag);
60
+ const isThenable = (value) => typeof value === "object" && value !== null && typeof value.then === "function";
61
+ /** A handler's value as one Effect of a decision: a Result, an Effect, a promise (from an async handler) or a plain value. */
62
+ const lift = (value) => {
63
+ const checked = (inner) => isDecision(inner) ? Effect.succeed(inner) : Effect.fail(new NotADecision({ message: `the handler returned ${describe(inner)}, which is not a decision` }));
64
+ if (Result.isResult(value)) return Result.isSuccess(value) ? checked(value.success) : Effect.fail(value.failure);
65
+ if (Effect.isEffect(value)) return Effect.flatMap(value, checked);
66
+ if (isThenable(value)) return Effect.flatMap(Effect.tryPromise({
67
+ try: () => Promise.resolve(value),
68
+ catch: (cause) => cause
69
+ }), lift);
70
+ return checked(value);
71
+ };
72
+ const describe = (value) => value === void 0 ? "undefined" : value === null ? "null" : typeof value === "object" ? "an object" : typeof value;
73
+ /** Run `effect` with console and stdout writes captured, so a handler cannot corrupt the one response. */
74
+ const captured = (ctx, effect) => {
75
+ const lines = [];
76
+ const methods = [
77
+ "log",
78
+ "info",
79
+ "warn",
80
+ "error",
81
+ "debug"
82
+ ];
83
+ return Effect.acquireUseRelease(Effect.sync(() => {
84
+ const saved = {
85
+ console: methods.map((name) => console[name]),
86
+ write: process.stdout.write
87
+ };
88
+ for (const name of methods) console[name] = (...args) => {
89
+ lines.push(args.map(String).join(" "));
90
+ };
91
+ process.stdout.write = ((chunk) => {
92
+ lines.push(String(chunk).replace(/\n$/, ""));
93
+ return true;
94
+ });
95
+ return saved;
96
+ }), () => effect, (saved) => Effect.sync(() => {
97
+ methods.forEach((name, at) => {
98
+ console[name] = saved.console[at];
99
+ });
100
+ process.stdout.write = saved.write;
101
+ }).pipe(Effect.andThen(Effect.forEach(lines, (line) => ctx.debug(`handler output: ${line}`), { discard: true }))));
102
+ };
103
+ const toResult = (ctx, encoded) => Effect.gen(function* () {
104
+ if (encoded.debug !== void 0) yield* ctx.debug(encoded.debug);
105
+ if (encoded.log !== void 0) yield* ctx.log(encoded.log);
106
+ return {
107
+ stdout: encoded.stdout,
108
+ stderr: encoded.stderr,
109
+ exitCode: encoded.exitCode
110
+ };
111
+ });
112
+ const failed = (ctx, input, why) => Effect.gen(function* () {
113
+ yield* ctx.log(`failed during ${ctx.event === "" ? "an unknown event" : ctx.event}: ${why}`);
114
+ if (!(yield* ctx.failsClosed)) return NOTHING;
115
+ const closed = closedResponse({
116
+ host: ctx.host,
117
+ event: ctx.event,
118
+ plugin: ctx.plugin
119
+ }, input, 1);
120
+ return closed === void 0 ? NOTHING : yield* toResult(ctx, closed);
121
+ });
122
+ const firstLine = (cause) => {
123
+ const squashed = Cause.squash(cause);
124
+ return (squashed instanceof Error ? squashed.message : typeof squashed === "string" ? squashed : Cause.pretty(cause)).split("\n")[0] ?? "";
125
+ };
126
+ /**
127
+ * The whole life of a module hook: read the input, apply a run-time matcher,
128
+ * decode the input, run the handler with the services provided, and answer in
129
+ * the host's wire format. Every failure is logged and fails open, unless the
130
+ * entry or the hook asked to fail closed.
131
+ *
132
+ * @public
133
+ */
134
+ const runHook = (source, io) => Effect.gen(function* () {
135
+ if (io.argv.includes("--pluginfinity-describe")) {
136
+ const described = yield* Effect.result(load(source));
137
+ if (Result.isFailure(described)) return {
138
+ stdout: "",
139
+ stderr: `${described.failure.message}\n`,
140
+ exitCode: 1
141
+ };
142
+ const { event, tools } = described.success;
143
+ return {
144
+ stdout: `${JSON.stringify({
145
+ event,
146
+ ...tools === void 0 ? {} : { tools },
147
+ version: HOOKS_VERSION
148
+ })}\n`,
149
+ stderr: "",
150
+ exitCode: 0
151
+ };
152
+ }
153
+ const host = io.env.PLUGINFINITY_HOST === "copilot" ? "copilot" : "claude";
154
+ const text = yield* io.stdin;
155
+ const root = parseInput(text);
156
+ const event = resolveEvent(io.env, root ?? {});
157
+ const input = claudeEnvelope(host, event, root ?? {});
158
+ const ctx = yield* HookContext.make({
159
+ host,
160
+ event,
161
+ input,
162
+ env: io.env,
163
+ cwd: io.cwd,
164
+ script: io.script
165
+ });
166
+ yield* ctx.debug(`input: ${text.slice(0, 4e3)}`);
167
+ const matcher = io.env.PLUGINFINITY_MATCHER;
168
+ const field = matchField(event);
169
+ if (matcher !== void 0 && field !== void 0) {
170
+ const value = typeof input[field] === "string" ? input[field] : "";
171
+ if (!matcherApplies(matcher, value)) {
172
+ yield* ctx.debug(`matcher ${matcher} did not match ${value}`);
173
+ return NOTHING;
174
+ }
175
+ }
176
+ const loaded = yield* Effect.result(load(source));
177
+ if (Result.isFailure(loaded)) return yield* failed(ctx, input, `cannot load the hook: ${loaded.failure.message}`);
178
+ const module = loaded.success;
179
+ if (root === void 0) {
180
+ yield* ctx.log("malformed or empty JSON on stdin; skipping");
181
+ return NOOP;
182
+ }
183
+ if (event !== module.event || !CLAUDE_HOOK_EVENTS.includes(event)) {
184
+ yield* ctx.log(`a ${module.event} hook ran for ${event === "" ? "an unknown event" : event}; answered nothing`);
185
+ return NOOP;
186
+ }
187
+ if (module.tools !== void 0 && typeof input.tool_name === "string") {
188
+ const name = input.tool_name;
189
+ if (!module.tools.some((tool) => tool === name || Option.getOrUndefined(ctx.toolName(tool)) === name)) {
190
+ yield* ctx.debug(`a hook for ${module.tools.join(", ")} skipped ${name}`);
191
+ return NOTHING;
192
+ }
193
+ }
194
+ const wire = {
195
+ host,
196
+ event,
197
+ plugin: ctx.plugin,
198
+ asyncRewake: io.env.PLUGINFINITY_ASYNC_REWAKE === "1"
199
+ };
200
+ const handled = Effect.gen(function* () {
201
+ const decoded = yield* decodeInput(ctx, module, module.event, input);
202
+ const decision = yield* lift(module.handler(decoded));
203
+ return encodeDecision(wire, decision);
204
+ });
205
+ const exit = yield* Effect.exit(captured(ctx, Effect.suspend(() => handled))).pipe(Effect.provideService(HookContext, ctx));
206
+ if (Exit.isFailure(exit)) return yield* failed(ctx, input, firstLine(exit.cause));
207
+ return yield* toResult(ctx, exit.value);
208
+ });
209
+
210
+ export { DESCRIBE_FLAG, runHook };
package/testing.d.ts ADDED
@@ -0,0 +1,297 @@
1
+ import { Context, Data, Effect, FileSystem, Option, Path, Result, Schema, Scope } from "effect";
2
+ import { ChildProcessSpawner } from "effect/process";
3
+ /**
4
+ * A Claude Code hook event name.
5
+ *
6
+ * @public
7
+ */
8
+ declare const ClaudeHookEvent: Schema.Literals<readonly ["SessionStart", "Setup", "UserPromptSubmit", "UserPromptExpansion", "PreSkillShellCommand", "PreToolUse", "PermissionRequest", "PermissionDenied", "PostToolUse", "PostToolUseFailure", "PostToolBatch", "Notification", "MessageDisplay", "SubagentStart", "SubagentStop", "TaskCreated", "TaskCompleted", "Stop", "StopFailure", "TeammateIdle", "InstructionsLoaded", "ConfigChange", "CwdChanged", "DirectoryAdded", "FileChanged", "WorktreeCreate", "WorktreeRemove", "PreCompact", "PostCompact", "PreModelSwitch", "PostModelSwitch", "Elicitation", "ElicitationResult", "SessionEnd"]>;
9
+ /**
10
+ * The decoded `ClaudeHookEvent`.
11
+ *
12
+ * @public
13
+ */
14
+ type ClaudeHookEvent = typeof ClaudeHookEvent.Type;
15
+ /**
16
+ * A host pluginfinity builds hooks for.
17
+ *
18
+ * @public
19
+ */
20
+ type HookHost = "claude" | "copilot";
21
+ /**
22
+ * What a hook answers, in host-neutral terms. Each host's wire format is
23
+ * written from it by `encodeDecision`.
24
+ *
25
+ * @public
26
+ */
27
+ type Decision = Data.TaggedEnum<{
28
+ /** Change nothing. */
29
+ Noop: {};
30
+ /** Allow the action, with an optional reason and, on PreToolUse, a replacement tool input. */
31
+ Allow: {
32
+ readonly reason?: string;
33
+ readonly updatedInput?: Readonly<Record<string, unknown>>;
34
+ };
35
+ /** Refuse the action. */
36
+ Deny: {
37
+ readonly reason?: string;
38
+ };
39
+ /** Ask the user. */
40
+ Ask: {
41
+ readonly reason?: string;
42
+ };
43
+ /** Block the event's action (on Stop: keep working). */
44
+ Block: {
45
+ readonly reason?: string;
46
+ };
47
+ /** Add text to the model's context. */
48
+ Context: {
49
+ readonly text: string;
50
+ };
51
+ /** Show the user a message. */
52
+ SystemMessage: {
53
+ readonly text: string;
54
+ };
55
+ /** Wake the agent from a background hook (an `asyncRewake` entry only). */
56
+ Rewake: {
57
+ readonly message: string;
58
+ };
59
+ /** Send a host-specific JSON response verbatim, only on that host. */
60
+ Raw: {
61
+ readonly host: HookHost;
62
+ readonly json: Readonly<Record<string, unknown>>;
63
+ };
64
+ }>;
65
+ /**
66
+ * A `Decision` tag.
67
+ *
68
+ * @public
69
+ */
70
+ type DecisionTag = Decision["_tag"];
71
+ /**
72
+ * The events on which each host honours each answer, the one source `supports`,
73
+ * `ALLOWED_DECISIONS` and `AllowedTag` read. It mirrors the bash library's
74
+ * `hook_supports` and `okf/references/*-plugin-format.md`.
75
+ *
76
+ * @remarks
77
+ * `Allow`, `Ask` and `Deny` are honoured on `PreToolUse` by both hosts and, on
78
+ * Claude Code only, on `permission` events (and `Deny` also on `denyOnly`).
79
+ * `SystemMessage` is honoured on Claude Code on every event but
80
+ * `noSystemMessage`, and never on Copilot. `Noop`, `Raw` and `Rewake` work everywhere.
81
+ *
82
+ * @public
83
+ */
84
+ declare const ANSWER_EVENTS: {
85
+ readonly permission: readonly ["PreToolUse", "PreModelSwitch"];
86
+ readonly denyOnly: readonly ["PreSkillShellCommand"];
87
+ readonly noSystemMessage: readonly ["Setup", "InstructionsLoaded", "MessageDisplay", "Notification", "StopFailure", "ConfigChange", "DirectoryAdded", "WorktreeCreate", "WorktreeRemove", "PreCompact", "PostCompact", "SessionEnd", "Elicitation", "ElicitationResult"];
88
+ readonly context: {
89
+ readonly claude: readonly ["SessionStart", "SubagentStart", "PostModelSwitch", "UserPromptSubmit", "UserPromptExpansion", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PostToolBatch", "Stop", "SubagentStop"];
90
+ readonly copilot: readonly ["SessionStart", "SubagentStart", "PostToolUse", "Notification"];
91
+ };
92
+ readonly block: {
93
+ readonly claude: readonly ["UserPromptSubmit", "UserPromptExpansion", "PreSkillShellCommand", "PostToolUse", "PostToolBatch", "Stop", "SubagentStop", "ConfigChange", "PreCompact", "TaskCreated", "TaskCompleted", "TeammateIdle", "PreModelSwitch", "Elicitation", "ElicitationResult"];
94
+ readonly copilot: readonly ["Stop", "SubagentStop"];
95
+ };
96
+ };
97
+ /**
98
+ * The decision tags event `E` takes, as a type: the same set `ALLOWED_DECISIONS`
99
+ * holds, read from {@link ANSWER_EVENTS}.
100
+ *
101
+ * @public
102
+ */
103
+ type AllowedTag<E extends ClaudeHookEvent> = "Noop" | "Raw" | "Rewake" | (E extends (typeof ANSWER_EVENTS)["permission"][number] ? "Allow" | "Ask" : never) | (E extends (typeof ANSWER_EVENTS)["permission"][number] | (typeof ANSWER_EVENTS)["denyOnly"][number] ? "Deny" : never) | (E extends (typeof ANSWER_EVENTS)["context"]["claude"][number] | (typeof ANSWER_EVENTS)["context"]["copilot"][number] ? "Context" : never) | (E extends (typeof ANSWER_EVENTS)["block"]["claude"][number] | (typeof ANSWER_EVENTS)["block"]["copilot"][number] ? "Block" : never) | (E extends (typeof ANSWER_EVENTS)["noSystemMessage"][number] ? never : "SystemMessage");
104
+ /**
105
+ * The decisions event `E` takes.
106
+ *
107
+ * @public
108
+ */
109
+ type EventDecision<E extends ClaudeHookEvent> = Extract<Decision, {
110
+ readonly _tag: AllowedTag<E>;
111
+ }>;
112
+ /**
113
+ * What `lib/pluginfinity/facts.json` holds: what a program hook reads where a
114
+ * script sources `tools.sh`, `host.sh` and `env.sh`. Every field is optional,
115
+ * and a key this release does not know is ignored.
116
+ *
117
+ * @public
118
+ */
119
+ declare const Facts: Schema.Struct<{
120
+ readonly schema: Schema.optionalKey<Schema.Number>;
121
+ readonly host: Schema.optionalKey<Schema.String>;
122
+ readonly plugin: Schema.optionalKey<Schema.String>;
123
+ readonly tools: Schema.optionalKey<Schema.Struct<{
124
+ /** Claude Code tool name to the host's run-time name. */
125
+ readonly names: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
126
+ /** The plugin's name on Claude Code, which own MCP tools are written under. */
127
+ readonly plugin: Schema.optionalKey<Schema.String>;
128
+ /** The host's own MCP tool name, with `{plugin}`, `{server}` and `{tool}`. */
129
+ readonly mcp: Schema.optionalKey<Schema.String>;
130
+ readonly servers: Schema.optionalKey<Schema.$Array<Schema.String>>;
131
+ /** `keep` a name the table does not list, or treat it as having no name here. */
132
+ readonly unlisted: Schema.optionalKey<Schema.String>;
133
+ }>>;
134
+ readonly has: Schema.optionalKey<Schema.Struct<{
135
+ readonly skills: Schema.optionalKey<Schema.$Array<Schema.String>>;
136
+ readonly agents: Schema.optionalKey<Schema.$Array<Schema.String>>;
137
+ readonly monitors: Schema.optionalKey<Schema.$Array<Schema.String>>;
138
+ readonly servers: Schema.optionalKey<Schema.$Array<Schema.String>>;
139
+ }>>;
140
+ readonly env: Schema.optionalKey<Schema.Struct<{
141
+ /** Declared session variable to its default. */
142
+ readonly vars: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
143
+ }>>;
144
+ }>;
145
+ /**
146
+ * The decoded `Facts`.
147
+ *
148
+ * @public
149
+ */
150
+ type Facts = typeof Facts.Type;
151
+ /**
152
+ * A component kind `has` answers for.
153
+ *
154
+ * @public
155
+ */
156
+ type ComponentKind = "skill" | "agent" | "monitor" | "server";
157
+ /**
158
+ * What a hook knows about the call it answers, and the helpers the bash and
159
+ * Zig libraries give a hook, over the same files and variables.
160
+ *
161
+ * @public
162
+ */
163
+ interface HookContextShape {
164
+ /** The Claude event name. */
165
+ readonly event: string;
166
+ readonly host: HookHost;
167
+ /** The plugin's name on this host. */
168
+ readonly plugin: string;
169
+ /** The built plugin's root, from `PLUGINFINITY_ROOT`. */
170
+ readonly pluginRoot: string | undefined;
171
+ /** The input's `cwd` walked up to `.git`, else the host's project, else the working directory. */
172
+ readonly projectDir: Effect.Effect<string>;
173
+ /** The session's project: `CLAUDE_PROJECT_DIR` on Claude when set, else `projectDir`. */
174
+ readonly sessionDir: Effect.Effect<string>;
175
+ /** The host's run-time name for a Claude Code tool, or none when the host has none. */
176
+ readonly toolName: (name: string) => Option.Option<string>;
177
+ /** The run-time prefix of one of the plugin's own MCP servers. */
178
+ readonly toolPrefix: (server: string) => Option.Option<string>;
179
+ /** Whether this host's build ships a component. */
180
+ readonly has: (kind: ComponentKind, name: string) => boolean;
181
+ /** Whether the host honours a decision on this event. */
182
+ readonly supports: (tag: DecisionTag) => boolean;
183
+ /** The declared session variables, resolved. Empty when the build declares none. */
184
+ readonly env: Effect.Effect<ReadonlyMap<string, string>>;
185
+ /** Set a declared session variable (producer events only); a refusal is logged and never fails. */
186
+ readonly envSet: (name: string, value: string) => Effect.Effect<void>;
187
+ /** Append a line to the plugin's `error.log`. */
188
+ readonly log: (message: string) => Effect.Effect<void>;
189
+ /** Append a line to `debug.log` when `PLUGINFINITY_DEBUG=1`. */
190
+ readonly debug: (message: string) => Effect.Effect<void>;
191
+ /** From here on, a failure denies or blocks instead of failing open. */
192
+ readonly failClosed: Effect.Effect<void>;
193
+ /** Whether the entry or the hook asked to fail closed. */
194
+ readonly failsClosed: Effect.Effect<boolean>;
195
+ }
196
+ /**
197
+ * What `HookContext.make` is built from.
198
+ *
199
+ * @public
200
+ */
201
+ interface HookContextOptions {
202
+ readonly host: HookHost;
203
+ readonly event: string;
204
+ /** The input in Claude Code's shape. */
205
+ readonly input: Record<string, unknown>;
206
+ readonly env: Readonly<Record<string, string | undefined>>;
207
+ /** The process's working directory. */
208
+ readonly cwd: string;
209
+ /** The hook file's name, as log lines show it. */
210
+ readonly script: string;
211
+ /** The built plugin's root; defaults to `PLUGINFINITY_ROOT`. */
212
+ readonly pluginRoot?: string;
213
+ readonly now?: () => Date;
214
+ }
215
+ declare const HookContext_base: Context.ServiceClass<HookContext, "@pluginfinity/hooks/HookContext", HookContextShape>;
216
+ /**
217
+ * The hook context service a module hook's handler reads. The runner provides
218
+ * it; `HookContext.make` builds one from the process's facts.
219
+ *
220
+ * @public
221
+ */
222
+ declare class HookContext extends HookContext_base {
223
+ /** Build a hook context from the process's facts, environment and input. */
224
+ static readonly make: (options: HookContextOptions) => Effect.Effect<HookContextShape, never, FileSystem.FileSystem | Path.Path>;
225
+ }
226
+ /**
227
+ * The services a handler may require: the hook context and the Node platform's
228
+ * filesystem, path and child processes. The runner provides all of them.
229
+ *
230
+ * @public
231
+ */
232
+ type HookServices = HookContext | FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner;
233
+ /**
234
+ * What a handler may return: a decision, a `Result` of one, or an `Effect` of
235
+ * one. Any failure, typed or not, falls to the entry's fail policy.
236
+ *
237
+ * @public
238
+ */
239
+ type HandlerResult<E extends ClaudeHookEvent> = EventDecision<E> | Result.Result<EventDecision<E>, unknown> | Effect.Effect<EventDecision<E>, unknown, HookServices>;
240
+ /**
241
+ * The brand a module hook carries.
242
+ *
243
+ * @public
244
+ */
245
+ declare const HookModuleTypeId: "~@pluginfinity/hooks/HookModule";
246
+ /**
247
+ * A module hook: the default export of a hook file, the build's unit of a `module` entry.
248
+ *
249
+ * @public
250
+ */
251
+ interface HookModule<E extends ClaudeHookEvent = ClaudeHookEvent> {
252
+ readonly [HookModuleTypeId]: typeof HookModuleTypeId;
253
+ readonly event: E;
254
+ /** The tools the handler's `tool_input` is typed and decoded for, when it names any. */
255
+ readonly tools: ReadonlyArray<string> | undefined;
256
+ readonly handler: (input: never) => HandlerResult<E>;
257
+ }
258
+ /**
259
+ * How `runHookModule` runs a hook.
260
+ *
261
+ * @public
262
+ */
263
+ export interface RunHookModuleOptions {
264
+ /** The input in Claude Code's shape; `session_id`, `cwd` and `hook_event_name` are filled in when absent. */
265
+ readonly input: Readonly<Record<string, unknown>>;
266
+ /** Defaults to `claude`. */
267
+ readonly host?: HookHost;
268
+ /** Extra environment, such as `PLUGINFINITY_FAIL_CLOSED: "1"`. */
269
+ readonly env?: Readonly<Record<string, string>>;
270
+ /** The facts the build would write; `plugin` defaults to `fixture`. */
271
+ readonly facts?: Facts;
272
+ /** Session values already resolved for the session, as the SessionStart runner records them. */
273
+ readonly sessionEnv?: Readonly<Record<string, string>>;
274
+ }
275
+ /**
276
+ * What a hook answered.
277
+ *
278
+ * @public
279
+ */
280
+ export interface HookModuleAnswer {
281
+ readonly stdout: string;
282
+ readonly stderr: string;
283
+ readonly exitCode: number;
284
+ /** The decision the handler returned, or `undefined` when it failed or did not run. */
285
+ readonly decision: Decision | undefined;
286
+ readonly errorLog: string;
287
+ readonly debugLog: string;
288
+ }
289
+ /**
290
+ * Run `module` once, as its bundle would, in a fresh temporary plugin root,
291
+ * project and state directory that live as long as the scope.
292
+ *
293
+ * @public
294
+ */
295
+ export declare const runHookModule: <E extends HookModule["event"]>(module: HookModule<E>, options: RunHookModuleOptions) => Effect.Effect<HookModuleAnswer, never, Scope.Scope>;
296
+ export type { ANSWER_EVENTS, AllowedTag, ClaudeHookEvent, ComponentKind, Decision, DecisionTag, EventDecision, Facts, HandlerResult, HookContext, HookContextOptions, HookContextShape, HookHost, HookModule, HookModuleTypeId, HookServices };
297
+ //# sourceMappingURL=testing.d.ts.map
package/testing.js ADDED
@@ -0,0 +1,97 @@
1
+ import { NodeServices } from "@effect/platform-node";
2
+ import { Effect, FileSystem, Result } from "effect";
3
+ import { FACTS_SCHEMA_VERSION } from "./contract/facts.js";
4
+ import { runHook } from "./runtime/runner.js";
5
+
6
+ // src/testing.ts
7
+ /**
8
+ * Test a module hook in-process: run it against an input, on either host, with
9
+ * the facts and session values a build would give it, and read what it answers.
10
+ *
11
+ * @remarks
12
+ * This module is an entry point: API Extractor models it as its own surface, so
13
+ * every type its signatures name is re-exported here, type-only.
14
+ *
15
+ * @packageDocumentation
16
+ */
17
+ const SESSION = "test-session";
18
+ /**
19
+ * Run `module` once, as its bundle would, in a fresh temporary plugin root,
20
+ * project and state directory that live as long as the scope.
21
+ *
22
+ * @public
23
+ */
24
+ const runHookModule = (module, options) => Effect.gen(function* () {
25
+ const fs = yield* FileSystem.FileSystem;
26
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "pf-hook-test-" });
27
+ const pluginRoot = `${root}/plugin`;
28
+ const project = `${root}/project`;
29
+ const state = `${root}/state`;
30
+ const plugin = options.facts?.plugin ?? "fixture";
31
+ const host = options.host ?? "claude";
32
+ yield* fs.makeDirectory(`${pluginRoot}/lib/pluginfinity`, { recursive: true });
33
+ yield* fs.makeDirectory(`${project}/.git`, { recursive: true });
34
+ yield* fs.writeFileString(`${pluginRoot}/lib/pluginfinity/facts.json`, JSON.stringify({
35
+ schema: 1,
36
+ host,
37
+ plugin,
38
+ ...options.facts
39
+ }));
40
+ const sessionId = typeof options.input.session_id === "string" ? options.input.session_id : SESSION;
41
+ if (options.sessionEnv !== void 0) {
42
+ const dir = `${state}/pluginfinity/${plugin}/session/${sessionId}`;
43
+ yield* fs.makeDirectory(dir, { recursive: true });
44
+ const declared = {
45
+ ...options.facts?.env?.vars,
46
+ ...options.sessionEnv
47
+ };
48
+ const values = Object.keys(declared).map((name) => `${name}=${options.sessionEnv?.[name] ?? declared[name] ?? ""}\n`);
49
+ yield* fs.writeFileString(`${dir}/env`, values.join(""));
50
+ yield* fs.writeFileString(`${dir}/done`, "");
51
+ }
52
+ let decision;
53
+ const recorded = {
54
+ ...module,
55
+ handler: (input) => {
56
+ const value = module.handler(input);
57
+ const keep = (d) => {
58
+ decision = d;
59
+ return d;
60
+ };
61
+ if (Result.isResult(value)) return Result.map(value, keep);
62
+ if (Effect.isEffect(value)) return Effect.map(value, keep);
63
+ return keep(value);
64
+ }
65
+ };
66
+ const input = {
67
+ session_id: sessionId,
68
+ cwd: project,
69
+ hook_event_name: module.event,
70
+ ...options.input
71
+ };
72
+ const result = yield* runHook(recorded, {
73
+ argv: [],
74
+ env: {
75
+ PATH: process.env.PATH,
76
+ HOME: `${root}/home`,
77
+ XDG_STATE_HOME: state,
78
+ PLUGINFINITY_HOST: host,
79
+ PLUGINFINITY_PLUGIN: plugin,
80
+ PLUGINFINITY_EVENT: module.event,
81
+ PLUGINFINITY_ROOT: pluginRoot,
82
+ ...options.env
83
+ },
84
+ stdin: Effect.succeed(JSON.stringify(input)),
85
+ cwd: project,
86
+ script: "hook.mjs"
87
+ });
88
+ const read = (file) => fs.readFileString(`${state}/pluginfinity/${plugin}/${file}`).pipe(Effect.orElseSucceed(() => ""));
89
+ return {
90
+ ...result,
91
+ decision,
92
+ errorLog: yield* read("error.log"),
93
+ debugLog: yield* read("debug.log")
94
+ };
95
+ }).pipe(Effect.provide(NodeServices.layer), Effect.orDie);
96
+
97
+ export { runHookModule };
@@ -0,0 +1,11 @@
1
+ // This file is read by tools that parse documentation comments conforming to the TSDoc standard.
2
+ // It should be published with your NPM package. It should not be tracked by Git.
3
+ {
4
+ "tsdocVersion": "0.12",
5
+ "toolPackages": [
6
+ {
7
+ "packageName": "@microsoft/api-extractor",
8
+ "packageVersion": "7.60.2"
9
+ }
10
+ ]
11
+ }
package/version.js ADDED
@@ -0,0 +1,10 @@
1
+ // src/version.ts
2
+ /**
3
+ * This package's version. A build-time literal: the build replaces
4
+ * `process.env.__PACKAGE_VERSION__`, and unbuilt source reads `0.0.0`.
5
+ *
6
+ * @public
7
+ */
8
+ const HOOKS_VERSION = "0.7.1";
9
+
10
+ export { HOOKS_VERSION };
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.