@r_masseater/cc-effect-hooks 0.0.0-stage → 0.2.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,823 @@
1
+ import { blockHook, readHookInput, runHookWith, writeHookOutput } from "@r_masseater/masseater-utils/plugin-kit";
2
+ import { Array, Effect, Layer, Number, Option, Record, Schema, String as String$1, pipe } from "effect";
3
+ // src/entities/hook/model/answers.ts
4
+ const allow = (reason) => ({ hookSpecificOutput: {
5
+ hookEventName: "PreToolUse",
6
+ permissionDecision: "allow",
7
+ permissionDecisionReason: reason
8
+ } });
9
+ const deny = (reason) => ({ hookSpecificOutput: {
10
+ hookEventName: "PreToolUse",
11
+ permissionDecision: "deny",
12
+ permissionDecisionReason: reason
13
+ } });
14
+ const addContext = (event, text) => ({ hookSpecificOutput: {
15
+ hookEventName: event,
16
+ additionalContext: text
17
+ } });
18
+ // src/entities/hook/model/define-hook.ts
19
+ const defineHook = (hook) => hook;
20
+ // src/entities/hook/model/shared.ts
21
+ const baseFields = {
22
+ session_id: Schema.String,
23
+ transcript_path: Schema.String,
24
+ cwd: Schema.String,
25
+ prompt_id: Schema.optionalKey(Schema.String),
26
+ permission_mode: Schema.optionalKey(Schema.String),
27
+ agent_id: Schema.optionalKey(Schema.String),
28
+ agent_type: Schema.optionalKey(Schema.String),
29
+ effort: Schema.Struct({ level: Schema.String }).pipe(Schema.optionalKey)
30
+ };
31
+ const McpServerProvenance = Schema.Struct({
32
+ name: Schema.String,
33
+ source: Schema.String
34
+ });
35
+ const PermissionBehavior = Schema.Literals([
36
+ "allow",
37
+ "deny",
38
+ "ask"
39
+ ]);
40
+ const PermissionUpdateDestination = Schema.Literals([
41
+ "userSettings",
42
+ "projectSettings",
43
+ "localSettings",
44
+ "session",
45
+ "cliArg"
46
+ ]);
47
+ const PermissionMode = Schema.Literals([
48
+ "default",
49
+ "acceptEdits",
50
+ "bypassPermissions",
51
+ "plan",
52
+ "dontAsk",
53
+ "auto"
54
+ ]);
55
+ const PermissionRuleValue = Schema.Struct({
56
+ toolName: Schema.String,
57
+ ruleContent: Schema.optionalKey(Schema.String)
58
+ });
59
+ const rulesFields = {
60
+ rules: Schema.Array(PermissionRuleValue),
61
+ behavior: PermissionBehavior,
62
+ destination: PermissionUpdateDestination
63
+ };
64
+ const directoriesFields = {
65
+ directories: Schema.Array(Schema.String),
66
+ destination: PermissionUpdateDestination
67
+ };
68
+ const PermissionUpdate = Schema.Union([
69
+ Schema.Struct({
70
+ type: Schema.Literal("addRules"),
71
+ ...rulesFields
72
+ }),
73
+ Schema.Struct({
74
+ type: Schema.Literal("replaceRules"),
75
+ ...rulesFields
76
+ }),
77
+ Schema.Struct({
78
+ type: Schema.Literal("removeRules"),
79
+ ...rulesFields
80
+ }),
81
+ Schema.Struct({
82
+ type: Schema.Literal("setMode"),
83
+ mode: PermissionMode,
84
+ destination: PermissionUpdateDestination
85
+ }),
86
+ Schema.Struct({
87
+ type: Schema.Literal("addDirectories"),
88
+ ...directoriesFields
89
+ }),
90
+ Schema.Struct({
91
+ type: Schema.Literal("removeDirectories"),
92
+ ...directoriesFields
93
+ })
94
+ ]);
95
+ const BackgroundTaskSummary = Schema.Struct({
96
+ id: Schema.String,
97
+ type: Schema.String,
98
+ status: Schema.String,
99
+ description: Schema.String,
100
+ command: Schema.optionalKey(Schema.String),
101
+ agent_type: Schema.optionalKey(Schema.String),
102
+ server: Schema.optionalKey(Schema.String),
103
+ tool: Schema.optionalKey(Schema.String),
104
+ name: Schema.optionalKey(Schema.String)
105
+ });
106
+ const SessionCronSummary = Schema.Struct({
107
+ id: Schema.String,
108
+ schedule: Schema.String,
109
+ recurring: Schema.Boolean,
110
+ prompt: Schema.String
111
+ });
112
+ const ElicitationAction = Schema.Literals([
113
+ "accept",
114
+ "decline",
115
+ "cancel"
116
+ ]);
117
+ const ElicitationMode = Schema.Literals(["form", "url"]);
118
+ const JsonObject$1 = Schema.Record(Schema.String, Schema.Unknown);
119
+ const CompactTrigger = Schema.Literals(["manual", "auto"]);
120
+ const OptionalString$2 = Schema.optionalKey(Schema.String);
121
+ const OptionalFinite$1 = Schema.optionalKey(Schema.Finite);
122
+ // src/entities/hook/model/event-parts.ts
123
+ const event = (name, fields) => Schema.Struct({
124
+ ...baseFields,
125
+ hook_event_name: Schema.Literal(name),
126
+ ...fields
127
+ }).annotate({ identifier: `${name}Input` });
128
+ const OptionalMcpServer = Schema.optionalKey(McpServerProvenance);
129
+ const PromptSource = Schema.Literals([
130
+ "user",
131
+ "sdk",
132
+ "system",
133
+ "loop_wakeup",
134
+ "schedule_wakeup",
135
+ "poll_event"
136
+ ]).pipe(Schema.optionalKey);
137
+ const BatchedToolCall = Schema.Struct({
138
+ tool_name: Schema.String,
139
+ tool_input: Schema.Unknown,
140
+ tool_use_id: Schema.String,
141
+ tool_response: Schema.optionalKey(Schema.Unknown)
142
+ });
143
+ const SkillCommand = Schema.Struct({ command: Schema.String });
144
+ const toolCall = {
145
+ tool_name: Schema.String,
146
+ tool_input: Schema.Unknown,
147
+ tool_use_id: Schema.String,
148
+ mcp_server: OptionalMcpServer
149
+ };
150
+ const modelSwitch = {
151
+ from_model: Schema.String,
152
+ to_model: Schema.String,
153
+ requested_model: Schema.String.pipe(Schema.NullOr),
154
+ context_tokens: Schema.Finite,
155
+ prompt_cache_warm: Schema.Boolean,
156
+ cache_ttl: Schema.Literals(["5m", "1h"]),
157
+ estimated_cache_write_usd: Schema.Finite,
158
+ pricing: Schema.Literals([
159
+ "configured",
160
+ "catalog",
161
+ "default"
162
+ ])
163
+ };
164
+ const stopping = {
165
+ stop_hook_active: Schema.Boolean,
166
+ last_assistant_message: OptionalString$2,
167
+ background_tasks: BackgroundTaskSummary.pipe(Schema.Array, Schema.optionalKey),
168
+ session_crons: SessionCronSummary.pipe(Schema.Array, Schema.optionalKey)
169
+ };
170
+ const subagent = {
171
+ agent_id: Schema.String,
172
+ agent_type: Schema.String
173
+ };
174
+ const task = {
175
+ task_id: Schema.String,
176
+ task_subject: Schema.String,
177
+ task_description: OptionalString$2,
178
+ teammate_name: OptionalString$2,
179
+ team_name: OptionalString$2
180
+ };
181
+ const subagentStart = Schema.Struct({
182
+ ...baseFields,
183
+ hook_event_name: Schema.Literal("SubagentStart"),
184
+ ...subagent
185
+ });
186
+ const subagentStop = Schema.Struct({
187
+ ...baseFields,
188
+ hook_event_name: Schema.Literal("SubagentStop"),
189
+ ...stopping,
190
+ ...subagent,
191
+ agent_transcript_path: Schema.String
192
+ });
193
+ // src/entities/hook/model/events.ts
194
+ const HookInputs = {
195
+ PreToolUse: event("PreToolUse", toolCall),
196
+ PostToolUse: event("PostToolUse", {
197
+ ...toolCall,
198
+ tool_response: Schema.Unknown,
199
+ duration_ms: OptionalFinite$1
200
+ }),
201
+ PostToolUseFailure: event("PostToolUseFailure", {
202
+ ...toolCall,
203
+ error: Schema.String,
204
+ is_interrupt: Schema.optionalKey(Schema.Boolean),
205
+ duration_ms: OptionalFinite$1
206
+ }),
207
+ PostToolBatch: event("PostToolBatch", { tool_calls: Schema.Array(BatchedToolCall) }),
208
+ Notification: event("Notification", {
209
+ message: Schema.String,
210
+ title: OptionalString$2,
211
+ notification_type: Schema.String
212
+ }),
213
+ UserPromptSubmit: event("UserPromptSubmit", {
214
+ prompt: Schema.String,
215
+ source: PromptSource,
216
+ session_title: OptionalString$2
217
+ }),
218
+ UserPromptExpansion: event("UserPromptExpansion", {
219
+ expansion_type: Schema.Literals(["slash_command", "mcp_prompt"]),
220
+ command_name: Schema.String,
221
+ command_args: Schema.String,
222
+ command_source: OptionalString$2,
223
+ prompt: Schema.String
224
+ }),
225
+ SessionStart: event("SessionStart", {
226
+ source: Schema.Literals([
227
+ "startup",
228
+ "resume",
229
+ "clear",
230
+ "compact",
231
+ "fork"
232
+ ]),
233
+ model: OptionalString$2,
234
+ session_title: OptionalString$2,
235
+ seconds_since_last_response: OptionalFinite$1,
236
+ context_tokens: OptionalFinite$1,
237
+ prompt_cache_likely_expired: Schema.optionalKey(Schema.Boolean),
238
+ estimated_cache_write_usd: OptionalFinite$1
239
+ }),
240
+ SessionEnd: event("SessionEnd", { reason: Schema.Literals([
241
+ "clear",
242
+ "resume",
243
+ "logout",
244
+ "prompt_input_exit",
245
+ "other"
246
+ ]) }),
247
+ Stop: event("Stop", stopping),
248
+ StopFailure: event("StopFailure", {
249
+ error: Schema.Literals([
250
+ "authentication_failed",
251
+ "oauth_org_not_allowed",
252
+ "account_on_hold",
253
+ "verification_required",
254
+ "billing_error",
255
+ "rate_limit",
256
+ "overloaded",
257
+ "invalid_request",
258
+ "model_not_found",
259
+ "server_error",
260
+ "unknown",
261
+ "max_output_tokens",
262
+ "cloud_credential_error"
263
+ ]),
264
+ error_details: OptionalString$2,
265
+ last_assistant_message: OptionalString$2
266
+ }),
267
+ SubagentStart: subagentStart.annotate({ identifier: "SubagentStartInput" }),
268
+ SubagentStop: subagentStop.annotate({ identifier: "SubagentStopInput" }),
269
+ PreCompact: event("PreCompact", {
270
+ trigger: CompactTrigger,
271
+ custom_instructions: Schema.String.pipe(Schema.NullOr)
272
+ }),
273
+ PostCompact: event("PostCompact", {
274
+ trigger: CompactTrigger,
275
+ compact_summary: Schema.String
276
+ }),
277
+ PreModelSwitch: event("PreModelSwitch", {
278
+ ...modelSwitch,
279
+ source: Schema.Literals([
280
+ "command",
281
+ "picker",
282
+ "sdk"
283
+ ])
284
+ }),
285
+ PostModelSwitch: event("PostModelSwitch", {
286
+ ...modelSwitch,
287
+ source: Schema.Literals([
288
+ "command",
289
+ "picker",
290
+ "sdk",
291
+ "auto",
292
+ "resume"
293
+ ])
294
+ }),
295
+ PermissionRequest: event("PermissionRequest", {
296
+ tool_name: Schema.String,
297
+ tool_input: Schema.Unknown,
298
+ permission_suggestions: PermissionUpdate.pipe(Schema.Array, Schema.optionalKey),
299
+ mcp_server: OptionalMcpServer
300
+ }),
301
+ PermissionDenied: event("PermissionDenied", {
302
+ ...toolCall,
303
+ reason: Schema.String
304
+ }),
305
+ Setup: event("Setup", { trigger: Schema.Literals(["init", "maintenance"]) }),
306
+ TeammateIdle: event("TeammateIdle", {
307
+ teammate_name: Schema.String,
308
+ team_name: Schema.String
309
+ }),
310
+ TaskCreated: event("TaskCreated", task),
311
+ TaskCompleted: event("TaskCompleted", task),
312
+ Elicitation: event("Elicitation", {
313
+ mcp_server_name: Schema.String,
314
+ message: Schema.String,
315
+ mode: ElicitationMode.pipe(Schema.optionalKey),
316
+ url: OptionalString$2,
317
+ elicitation_id: OptionalString$2,
318
+ requested_schema: JsonObject$1.pipe(Schema.optionalKey)
319
+ }),
320
+ ElicitationResult: event("ElicitationResult", {
321
+ mcp_server_name: Schema.String,
322
+ elicitation_id: OptionalString$2,
323
+ mode: ElicitationMode.pipe(Schema.optionalKey),
324
+ action: ElicitationAction,
325
+ content: JsonObject$1.pipe(Schema.optionalKey)
326
+ }),
327
+ ConfigChange: event("ConfigChange", {
328
+ source: Schema.Literals([
329
+ "user_settings",
330
+ "project_settings",
331
+ "local_settings",
332
+ "policy_settings",
333
+ "skills"
334
+ ]),
335
+ file_path: OptionalString$2
336
+ }),
337
+ WorktreeCreate: event("WorktreeCreate", { name: Schema.String }),
338
+ WorktreeRemove: event("WorktreeRemove", { worktree_path: Schema.String }),
339
+ InstructionsLoaded: event("InstructionsLoaded", {
340
+ file_path: Schema.String,
341
+ memory_type: Schema.Literals([
342
+ "User",
343
+ "Project",
344
+ "Local",
345
+ "Managed"
346
+ ]),
347
+ load_reason: Schema.Literals([
348
+ "session_start",
349
+ "nested_traversal",
350
+ "path_glob_match",
351
+ "include",
352
+ "compact"
353
+ ]),
354
+ globs: Schema.String.pipe(Schema.Array, Schema.optionalKey),
355
+ trigger_file_path: OptionalString$2,
356
+ parent_file_path: OptionalString$2
357
+ }),
358
+ CwdChanged: event("CwdChanged", {
359
+ old_cwd: Schema.String,
360
+ new_cwd: Schema.String
361
+ }),
362
+ FileChanged: event("FileChanged", {
363
+ file_path: Schema.String,
364
+ event: Schema.Literals([
365
+ "change",
366
+ "add",
367
+ "unlink"
368
+ ])
369
+ }),
370
+ DirectoryAdded: event("DirectoryAdded", {
371
+ directory: Schema.String,
372
+ source: Schema.Literals(["slash_command", "register_repo_root"])
373
+ }),
374
+ MessageDisplay: event("MessageDisplay", {
375
+ turn_id: Schema.String,
376
+ message_id: Schema.String,
377
+ index: Schema.Finite,
378
+ final: Schema.Boolean,
379
+ delta: Schema.String
380
+ }),
381
+ PreSkillShellCommand: event("PreSkillShellCommand", {
382
+ tool_name: Schema.String,
383
+ tool_input: SkillCommand,
384
+ tool_use_id: Schema.String,
385
+ command_name: Schema.String,
386
+ command_source: OptionalString$2,
387
+ invoked_by: Schema.Literals([
388
+ "user",
389
+ "claude",
390
+ "other"
391
+ ])
392
+ })
393
+ };
394
+ // src/entities/hook/model/outputs.ts
395
+ const JsonObject = Schema.Record(Schema.String, Schema.Unknown);
396
+ const PermissionDecision = Schema.Literals([...PermissionBehavior.literals, "defer"]);
397
+ const specific = (name, fields) => Schema.Struct({
398
+ hookEventName: Schema.Literal(name),
399
+ ...fields
400
+ });
401
+ const OptionalString$1 = Schema.optionalKey(Schema.String);
402
+ const OptionalBoolean$1 = Schema.optionalKey(Schema.Boolean);
403
+ const OptionalUnknown = Schema.optionalKey(Schema.Unknown);
404
+ const OptionalObject = JsonObject.pipe(Schema.optionalKey);
405
+ const AllowRequest = Schema.Struct({
406
+ behavior: Schema.Literal("allow"),
407
+ updatedInput: OptionalObject,
408
+ updatedPermissions: PermissionUpdate.pipe(Schema.Array, Schema.optionalKey)
409
+ });
410
+ const DenyRequest = Schema.Struct({
411
+ behavior: Schema.Literal("deny"),
412
+ message: OptionalString$1,
413
+ interrupt: OptionalBoolean$1
414
+ });
415
+ const context = { additionalContext: OptionalString$1 };
416
+ const watch = { watchPaths: Schema.String.pipe(Schema.Array, Schema.optionalKey) };
417
+ const elicitation = {
418
+ action: ElicitationAction.pipe(Schema.optionalKey),
419
+ content: OptionalObject
420
+ };
421
+ const OptionalDecision = PermissionDecision.pipe(Schema.optionalKey);
422
+ const HookSpecificOutputs = {
423
+ PreToolUse: specific("PreToolUse", {
424
+ permissionDecision: OptionalDecision,
425
+ permissionDecisionReason: OptionalString$1,
426
+ updatedInput: OptionalObject,
427
+ ...context
428
+ }),
429
+ PostToolUse: specific("PostToolUse", {
430
+ ...context,
431
+ classifierContext: OptionalString$1,
432
+ updatedToolOutput: OptionalUnknown,
433
+ updatedMCPToolOutput: OptionalUnknown
434
+ }),
435
+ PostToolUseFailure: specific("PostToolUseFailure", context),
436
+ PostToolBatch: specific("PostToolBatch", context),
437
+ Notification: specific("Notification", context),
438
+ UserPromptSubmit: specific("UserPromptSubmit", {
439
+ ...context,
440
+ sessionTitle: OptionalString$1,
441
+ suppressOriginalPrompt: OptionalBoolean$1
442
+ }),
443
+ UserPromptExpansion: specific("UserPromptExpansion", {
444
+ ...context,
445
+ suppressOriginalPrompt: OptionalBoolean$1
446
+ }),
447
+ SessionStart: specific("SessionStart", {
448
+ ...context,
449
+ ...watch,
450
+ initialUserMessage: OptionalString$1,
451
+ sessionTitle: OptionalString$1,
452
+ reloadSkills: OptionalBoolean$1
453
+ }),
454
+ Setup: specific("Setup", context),
455
+ Stop: specific("Stop", context),
456
+ SubagentStart: specific("SubagentStart", context),
457
+ SubagentStop: specific("SubagentStop", context),
458
+ PreModelSwitch: specific("PreModelSwitch", {
459
+ permissionDecision: PermissionBehavior.pipe(Schema.optionalKey),
460
+ permissionDecisionReason: OptionalString$1
461
+ }),
462
+ PostModelSwitch: specific("PostModelSwitch", context),
463
+ PermissionRequest: specific("PermissionRequest", { decision: Schema.Union([AllowRequest, DenyRequest]) }),
464
+ PermissionDenied: specific("PermissionDenied", { retry: OptionalBoolean$1 }),
465
+ Elicitation: specific("Elicitation", elicitation),
466
+ ElicitationResult: specific("ElicitationResult", elicitation),
467
+ CwdChanged: specific("CwdChanged", watch),
468
+ FileChanged: specific("FileChanged", watch),
469
+ WorktreeCreate: specific("WorktreeCreate", { worktreePath: Schema.String }),
470
+ MessageDisplay: specific("MessageDisplay", { displayContent: OptionalString$1 }),
471
+ PreSkillShellCommand: specific("PreSkillShellCommand", {
472
+ permissionDecision: OptionalDecision,
473
+ permissionDecisionReason: OptionalString$1,
474
+ updatedInput: OptionalObject
475
+ })
476
+ };
477
+ const commonFields = {
478
+ continue: OptionalBoolean$1,
479
+ suppressOutput: OptionalBoolean$1,
480
+ stopReason: OptionalString$1,
481
+ decision: Schema.Literals(["approve", "block"]).pipe(Schema.optionalKey),
482
+ systemMessage: OptionalString$1,
483
+ terminalSequence: OptionalString$1,
484
+ reason: OptionalString$1
485
+ };
486
+ const HookOutputSchema = Schema.Struct({
487
+ ...commonFields,
488
+ hookSpecificOutput: Schema.Union(Record.values(HookSpecificOutputs)).pipe(Schema.optionalKey)
489
+ });
490
+ // src/features/define-hook/model/run-hook.ts
491
+ const schemaOf = (on) => (event) => pipe(Option.fromUndefinedOr(on[event]), Option.map(() => HookInputs[event]));
492
+ const EVENTS = Record.keys(HookInputs);
493
+ const inputSchemaOf = (on) => {
494
+ const pick = schemaOf(on);
495
+ return Schema.Union(pipe(EVENTS, Array.map(pick), Array.getSomes));
496
+ };
497
+ const writeOutput = writeHookOutput(HookOutputSchema);
498
+ const answerOf = (output) => output;
499
+ const SILENT = "{}";
500
+ const encodeAnswer = Schema.encodeEffect(Schema.fromJsonString(HookOutputSchema));
501
+ const EventCall = Schema.Struct({
502
+ hook_event_name: Schema.Literals(EVENTS),
503
+ tool_name: Schema.optionalKey(Schema.String)
504
+ });
505
+ const eventCallOf = Schema.decodeUnknownOption(EventCall);
506
+ const taggedError$1 = Schema.TaggedError;
507
+ var ToolNotListed = class extends taggedError$1()("ToolNotListed", {
508
+ event: Schema.String,
509
+ tool: Schema.String
510
+ }) {};
511
+ const listed = (tools, tool) => pipe(Option.fromUndefinedOr(tool), Option.exists((name) => Array.contains(tools, name)));
512
+ const isFor = (on) => (input) => pipe(eventCallOf(input), Option.exists(({ hook_event_name: event, tool_name: tool }) => pipe(Option.fromUndefinedOr(on[event]), Option.flatMapNullishOr((trigger) => trigger.tools), Option.match({
513
+ onNone: () => true,
514
+ onSome: (tools) => listed(tools, tool)
515
+ }))));
516
+ const notListed = (input) => ToolNotListed.make({
517
+ event: input.hook_event_name,
518
+ tool: pipe(eventCallOf(input), Option.flatMapNullishOr(({ tool_name: tool }) => tool), Option.getOrElse(() => ""))
519
+ });
520
+ /** @internal */
521
+ const handle = (hook) => Effect.gen(function* handleEvent() {
522
+ const decoded = yield* readHookInput(inputSchemaOf(hook.on));
523
+ const input = yield* Effect.filterOrFail(Effect.succeed(decoded), isFor(hook.on), notListed);
524
+ const output = yield* hook.run(input);
525
+ const answer = answerOf(output);
526
+ if ((yield* encodeAnswer(answer).pipe(Effect.orDie)) === SILENT) return;
527
+ yield* writeOutput(answer);
528
+ });
529
+ /** @stability unstable */
530
+ const runHook = (hook, serviceName) => {
531
+ runHookWith({
532
+ serviceName,
533
+ services: Layer.empty
534
+ })(handle(hook));
535
+ };
536
+ /** @stability unstable */
537
+ const runHookWithServices = (hook, options) => {
538
+ runHookWith(options)(handle(hook));
539
+ };
540
+ // src/features/define-plugin/model/manifest.ts
541
+ const OptionalString = Schema.optionalKey(Schema.String);
542
+ const OptionalBoolean = Schema.optionalKey(Schema.Boolean);
543
+ const OptionalFinite = Schema.optionalKey(Schema.Finite);
544
+ const DefaultValue = Schema.Union([
545
+ Schema.String,
546
+ Schema.Finite,
547
+ Schema.Boolean,
548
+ Schema.Array(Schema.String)
549
+ ]);
550
+ const UserConfigOptionSchema = Schema.Struct({
551
+ type: Schema.Literals([
552
+ "string",
553
+ "number",
554
+ "boolean",
555
+ "directory",
556
+ "file"
557
+ ]),
558
+ title: Schema.String,
559
+ description: Schema.String,
560
+ required: OptionalBoolean,
561
+ default: DefaultValue.pipe(Schema.optionalKey),
562
+ options: Schema.String.pipe(Schema.Array, Schema.optionalKey),
563
+ multiple: OptionalBoolean,
564
+ sensitive: OptionalBoolean,
565
+ min: OptionalFinite,
566
+ max: OptionalFinite
567
+ });
568
+ const manifestFields = {
569
+ author: Schema.Struct({
570
+ name: Schema.String,
571
+ email: OptionalString,
572
+ url: OptionalString
573
+ }).pipe(Schema.optionalKey),
574
+ homepage: OptionalString,
575
+ repository: OptionalString,
576
+ license: OptionalString,
577
+ keywords: Schema.String.pipe(Schema.Array, Schema.optionalKey),
578
+ types: OptionalString,
579
+ userConfig: Schema.Record(Schema.String, UserConfigOptionSchema).pipe(Schema.optionalKey),
580
+ mcpServers: Schema.Record(Schema.String, Schema.Unknown).pipe(Schema.optionalKey)
581
+ };
582
+ const ManifestFieldsSchema = Schema.Struct(manifestFields);
583
+ const PluginManifestSchema = Schema.Struct({
584
+ name: Schema.String,
585
+ description: OptionalString,
586
+ ...manifestFields,
587
+ hooks: OptionalString
588
+ });
589
+ const CommandHook = Schema.Struct({
590
+ type: Schema.Literal("command"),
591
+ command: Schema.String,
592
+ args: Schema.Array(Schema.String),
593
+ timeout: OptionalFinite
594
+ });
595
+ const HookGroupSchema = Schema.Struct({
596
+ matcher: OptionalString,
597
+ hooks: Schema.Array(CommandHook)
598
+ });
599
+ const HooksFileSchema = Schema.Struct({ hooks: Schema.Record(Schema.String, Schema.Array(HookGroupSchema)) });
600
+ // src/features/define-plugin/model/definition.ts
601
+ const TriggerSchema = Schema.Struct({
602
+ timeout: Schema.optionalKey(Schema.Finite),
603
+ tools: Schema.String.pipe(Schema.NonEmptyArray, Schema.optionalKey),
604
+ matcher: Schema.optionalKey(Schema.String)
605
+ });
606
+ const optionalTrigger = () => Schema.optionalKey(TriggerSchema);
607
+ const TriggersSchema = Schema.Struct(pipe(HookInputs, Record.map(optionalTrigger)));
608
+ const HookDataSchema = Schema.Struct({
609
+ entry: Schema.String,
610
+ on: TriggersSchema,
611
+ timeout: Schema.optionalKey(Schema.Finite),
612
+ node: Schema.String.pipe(Schema.Array, Schema.optionalKey)
613
+ });
614
+ const PluginDataSchema = Schema.Struct({
615
+ entry: Schema.String,
616
+ hooks: HookDataSchema.pipe(Schema.Array, Schema.optionalKey),
617
+ hooksFile: Schema.optionalKey(Schema.String),
618
+ installDependencies: Schema.optionalKey(Schema.Boolean),
619
+ manifest: Schema.optionalKey(ManifestFieldsSchema)
620
+ });
621
+ const PluginModuleSchema = Schema.Struct({ default: PluginDataSchema });
622
+ // src/features/define-plugin/model/install-deps.ts
623
+ const INSTALL_DEPS_FILE = "hooks/install-deps.sh";
624
+ const INSTALL_DEPS_SCRIPT = `#!/bin/sh
625
+ set -u
626
+ root="\${CLAUDE_PLUGIN_ROOT:-$(dirname "$(dirname "$0")")}"
627
+ data="\${CLAUDE_PLUGIN_DATA:-}"
628
+ wait_seconds="\${HOOK_DEPS_WAIT_SECONDS:-8}"
629
+
630
+ installed() {
631
+ [ -d "$data/node_modules" ] && cmp -s "$root/package.json" "$data/installed.json"
632
+ }
633
+
634
+ provide() {
635
+ mkdir -p "$data"
636
+ installed && return 0
637
+ lock="$data/install.lock"
638
+ if [ -d "$lock" ] && [ -n "$(find "$lock" -maxdepth 0 -mmin +3)" ]; then
639
+ rm -rf "$lock"
640
+ fi
641
+ if mkdir "$lock" 2>/dev/null; then
642
+ cp "$root/package.json" "$data/package.json"
643
+ npm install --omit=dev --no-audit --no-fund --no-package-lock --prefix "$data" >/dev/null &&
644
+ cp "$root/package.json" "$data/installed.json"
645
+ rm -rf "$lock"
646
+ else
647
+ tries=$((wait_seconds * 5))
648
+ while [ "$tries" -gt 0 ] && ! installed; do
649
+ sleep 0.2
650
+ tries=$((tries - 1))
651
+ done
652
+ fi
653
+ installed
654
+ }
655
+
656
+ if [ ! -e "$root/node_modules" ]; then
657
+ [ -n "$data" ] || exit 0
658
+ provide || exit 0
659
+ ln -s "$data/node_modules" "$root/node_modules" 2>/dev/null
660
+ [ -e "$root/node_modules" ] || exit 0
661
+ fi
662
+
663
+ [ "$#" -gt 0 ] || exit 0
664
+ script="$1"
665
+ shift
666
+ exec node "$@" "$root/hooks/$script"
667
+ `;
668
+ // src/features/define-plugin/model/layout.ts
669
+ const WIDTH = 100;
670
+ const STEP = 2;
671
+ const AFTER_CLOSE = 1;
672
+ const CLOSING = /^\s*\]/u;
673
+ const TRAILING_COMMA = /,$/u;
674
+ const indentOf = (line) => String$1.length(line) - String$1.length(String$1.trimStart(line));
675
+ const isPrimitiveAt = (indent) => (line) => indentOf(line) === indent && !String$1.endsWith("{")(line) && !String$1.endsWith("[")(line);
676
+ const closeOf = (rest, indent) => Array.findFirstIndex(rest, (line) => indentOf(line) === indent && CLOSING.test(line));
677
+ const inlineOf = (head, rest, close) => {
678
+ const items = Array.take(rest, close);
679
+ const itemIndent = indentOf(head) + STEP;
680
+ const closing = pipe(Array.get(rest, close), Option.map(String$1.trim), Option.getOrElse(() => "]"));
681
+ const line = `${head}${pipe(items, Array.map((item) => pipe(String$1.trim(item), String$1.replace(TRAILING_COMMA, ""))), Array.join(", "))}${closing}`;
682
+ return Option.liftPredicate(line, () => Array.isReadonlyArrayNonEmpty(items) && pipe(items, Array.every(isPrimitiveAt(itemIndent))) && String$1.length(line) <= WIDTH);
683
+ };
684
+ const collapsed = (lines) => Array.matchLeft(lines, {
685
+ onEmpty: () => [],
686
+ onNonEmpty: (head, rest) => {
687
+ const inline = pipe(Option.liftPredicate(head, String$1.endsWith("[")), Option.flatMap(() => closeOf(rest, indentOf(head))), Option.flatMap((close) => pipe(inlineOf(head, rest, close), Option.map((line) => [line, ...collapsed(Array.drop(rest, close + AFTER_CLOSE))]))));
688
+ return Option.getOrElse(inline, () => [head, ...collapsed(rest)]);
689
+ }
690
+ });
691
+ const formatted = (json) => pipe(String$1.split(json, "\n"), collapsed, Array.join("\n"));
692
+ // src/features/define-plugin/model/plugin.ts
693
+ const DEFAULT_HOOKS_FILE = "hooks/hooks.json";
694
+ const MANIFEST_FILE = ".claude-plugin/plugin.json";
695
+ const PLUGIN_ROOT = `\${CLAUDE_PLUGIN_ROOT}`;
696
+ const INDENT = 2;
697
+ const INSTALL_TIMEOUT = 120;
698
+ const HOOKS_DIR = "hooks/";
699
+ const HOOKS_DIR_LENGTH = String$1.length(HOOKS_DIR);
700
+ const INSTALLER = `${PLUGIN_ROOT}/${INSTALL_DEPS_FILE}`;
701
+ const REGEX_SPECIAL = /[$()*+.?[\\\]^{|}]/gu;
702
+ const definePlugin = (plugin) => plugin;
703
+ const taggedError = Schema.TaggedError;
704
+ var HookOutsidePlugin = class extends taggedError()("HookOutsidePlugin", {
705
+ hook: Schema.String,
706
+ root: Schema.String
707
+ }) {};
708
+ const rootOf = (entry) => new URL(".", entry).href;
709
+ const moduleIn = (root, hook) => pipe(Option.liftPredicate(hook.entry, String$1.startsWith(root)), Option.map(String$1.slice(root.length)), Effect.fromOption, Effect.mapError(() => HookOutsidePlugin.make({
710
+ hook: hook.entry,
711
+ root
712
+ })));
713
+ const escaped = String$1.replaceAll(REGEX_SPECIAL, String.raw`\$&`);
714
+ const toolsMatcher = (tools) => `^(${pipe(tools, Array.map(escaped), Array.join("|"))})$`;
715
+ const matcherOf = (trigger) => pipe(Option.fromUndefinedOr(trigger.tools), Option.map(toolsMatcher), Option.orElse(() => Option.fromUndefinedOr(trigger.matcher)));
716
+ const triggerOf = (on) => (event) => pipe(Option.fromUndefinedOr(on[event]), Option.map((trigger) => [event, trigger]));
717
+ const triggersOf = (on) => pipe(Record.keys(HookInputs), Array.map(triggerOf(on)), Array.getSomes);
718
+ const timeoutOf = (hook, trigger) => Option.firstSomeOf([Option.fromUndefinedOr(trigger.timeout), Option.fromUndefinedOr(hook.timeout)]);
719
+ const nodeCommand = (hook, module, trigger) => ({
720
+ command: "node",
721
+ args: [...hook.node ?? [], `${PLUGIN_ROOT}/${module}`],
722
+ timeout: timeoutOf(hook, trigger)
723
+ });
724
+ const fromHooksDir = (module) => pipe(Option.liftPredicate(module, String$1.startsWith(HOOKS_DIR)), Option.map(String$1.slice(HOOKS_DIR_LENGTH)), Option.getOrElse(() => `../${module}`));
725
+ const installerCommand = (hook, module, trigger) => ({
726
+ command: "sh",
727
+ args: [
728
+ INSTALLER,
729
+ fromHooksDir(module),
730
+ ...hook.node ?? []
731
+ ],
732
+ timeout: Option.some(pipe(timeoutOf(hook, trigger), Option.getOrElse(() => INSTALL_TIMEOUT), Number.max(INSTALL_TIMEOUT)))
733
+ });
734
+ const groupOf = (trigger, { command, args, timeout }) => {
735
+ const entry = {
736
+ type: "command",
737
+ command,
738
+ args,
739
+ ...Option.match(timeout, {
740
+ onNone: () => ({}),
741
+ onSome: (seconds) => ({ timeout: seconds })
742
+ })
743
+ };
744
+ return {
745
+ ...Option.match(matcherOf(trigger), {
746
+ onNone: () => ({}),
747
+ onSome: (text) => ({ matcher: text })
748
+ }),
749
+ hooks: [entry]
750
+ };
751
+ };
752
+ const groupsOf = Effect.fn("groupsOf")(function* groupsOf(root, installs, hook) {
753
+ const module = yield* moduleIn(root, hook);
754
+ return pipe(triggersOf(hook.on), Array.map(([event, trigger]) => {
755
+ const command = pipe(Option.liftPredicate(event, (name) => installs && name === "SessionStart"), Option.match({
756
+ onNone: () => nodeCommand(hook, module, trigger),
757
+ onSome: () => installerCommand(hook, module, trigger)
758
+ }));
759
+ return [event, groupOf(trigger, command)];
760
+ }));
761
+ });
762
+ const startsSession = (hooks) => pipe(hooks, Array.some((hook) => Option.isSome(Option.fromUndefinedOr(hook.on.SessionStart))));
763
+ const installOnly = (installs, hooks) => pipe(Option.liftPredicate(installs, (value) => value && !startsSession(hooks)), Option.map(() => ["SessionStart", { hooks: [{
764
+ type: "command",
765
+ command: "sh",
766
+ args: [INSTALLER],
767
+ timeout: INSTALL_TIMEOUT
768
+ }] }]), Option.toArray);
769
+ const hooksFileOf = Effect.fn("hooksFileOf")(function* hooksFileOf(root, installs, hooks) {
770
+ const entries = yield* Effect.forEach(hooks, (hook) => groupsOf(root, installs, hook), { concurrency: 1 });
771
+ return pipe([installOnly(installs, hooks), ...entries], Array.flatten, Array.groupBy(([event]) => event), Record.map(Array.map(([, group]) => group)), (grouped) => ({ hooks: grouped }));
772
+ });
773
+ const encodeManifest = Schema.encodeEffect(Schema.fromJsonString(PluginManifestSchema, { space: INDENT }));
774
+ const encodeHooks = Schema.encodeEffect(Schema.fromJsonString(HooksFileSchema, { space: INDENT }));
775
+ const manifestOf = (plugin, { name, description }, named) => ({
776
+ name,
777
+ ...Option.match(Option.fromUndefinedOr(description), {
778
+ onNone: () => ({}),
779
+ onSome: (text) => ({ description: text })
780
+ }),
781
+ ...plugin.manifest,
782
+ ...Option.match(named, {
783
+ onNone: () => ({}),
784
+ onSome: (path) => ({ hooks: `./${path}` })
785
+ })
786
+ });
787
+ const hooksFileTextOf = Effect.fn("hooksFileTextOf")(function* hooksFileTextOf(root, installs, hooks) {
788
+ const file = yield* hooksFileOf(root, installs, hooks);
789
+ return yield* encodeHooks(file).pipe(Effect.orDie);
790
+ });
791
+ const pluginFiles = Effect.fn("pluginFiles")(function* pluginFiles(plugin, fields) {
792
+ const hooks = Option.liftPredicate(plugin.hooks ?? [], Array.isReadonlyArrayNonEmpty);
793
+ const installs = plugin.installDependencies === true;
794
+ const hooksPath = plugin.hooksFile ?? "hooks/hooks.json";
795
+ const named = pipe(hooks, Option.map(() => hooksPath), Option.filter((path) => path !== DEFAULT_HOOKS_FILE));
796
+ const manifest = yield* encodeManifest(manifestOf(plugin, fields, named)).pipe(Effect.orDie);
797
+ const hooksText = yield* pipe(hooks, Option.map((list) => hooksFileTextOf(rootOf(plugin.entry), installs, list)), Effect.transposeOption);
798
+ return [
799
+ {
800
+ path: MANIFEST_FILE,
801
+ text: `${formatted(manifest)}\n`
802
+ },
803
+ ...Option.match(hooksText, {
804
+ onNone: () => [],
805
+ onSome: (text) => [{
806
+ path: hooksPath,
807
+ text: `${formatted(text)}\n`
808
+ }]
809
+ }),
810
+ ...pipe(Option.liftPredicate(installs, Boolean), Option.map(() => ({
811
+ path: INSTALL_DEPS_FILE,
812
+ text: INSTALL_DEPS_SCRIPT
813
+ })), Option.toArray)
814
+ ];
815
+ });
816
+ const decodeModule = Schema.decodeUnknownEffect(PluginModuleSchema);
817
+ const moduleFiles = Effect.fn("moduleFiles")(function* moduleFiles(loaded, fields) {
818
+ const plugin = yield* decodeModule(loaded);
819
+ return yield* pluginFiles(plugin.default, fields);
820
+ });
821
+ export { DEFAULT_HOOKS_FILE, HookInputs, HookOutputSchema, HookOutsidePlugin, HooksFileSchema, ManifestFieldsSchema, PermissionUpdate, PluginManifestSchema, ToolNotListed, addContext, allow, blockHook, defineHook, definePlugin, deny, moduleFiles, pluginFiles, runHook, runHookWithServices };
822
+
823
+ //# sourceMappingURL=index.mjs.map