agent-contracts-runtime 0.36.4 → 0.36.5

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,302 @@
1
+ // src/lib/plugin.ts
2
+ var PluginRegistry = class {
3
+ plugins = [];
4
+ register(plugin) {
5
+ if (this.plugins.some((p) => p.id === plugin.id)) {
6
+ throw new Error(`Plugin "${plugin.id}" is already registered`);
7
+ }
8
+ this.plugins.push(plugin);
9
+ }
10
+ getAll() {
11
+ return this.plugins;
12
+ }
13
+ async runBeforeTask(taskId, context) {
14
+ let ctx = context;
15
+ for (const plugin of this.plugins) {
16
+ if (!plugin.beforeTask || ctx === null) continue;
17
+ ctx = await plugin.beforeTask(taskId, ctx);
18
+ }
19
+ return ctx;
20
+ }
21
+ async runAfterTask(taskId, outcome) {
22
+ let result = outcome;
23
+ for (const plugin of this.plugins) {
24
+ if (!plugin.afterTask) continue;
25
+ result = await plugin.afterTask(taskId, result);
26
+ }
27
+ return result;
28
+ }
29
+ applyContextEnhancers(taskId, context) {
30
+ let ctx = context;
31
+ for (const plugin of this.plugins) {
32
+ if (!plugin.contextEnhancer) continue;
33
+ ctx = plugin.contextEnhancer(taskId, ctx);
34
+ }
35
+ return ctx;
36
+ }
37
+ /**
38
+ * Try plugin promptBuilder hooks. Returns custom prompt if any plugin provides one,
39
+ * or null to use the default buildTaskPrompt.
40
+ */
41
+ applyPromptBuilder(args) {
42
+ for (const plugin of this.plugins) {
43
+ if (!plugin.promptBuilder) continue;
44
+ const result = plugin.promptBuilder(args);
45
+ if (result !== null) return result;
46
+ }
47
+ return null;
48
+ }
49
+ applyPromptEnhancers(taskId, prompt, context) {
50
+ let enhanced = prompt;
51
+ for (const plugin of this.plugins) {
52
+ if (!plugin.promptEnhancer) continue;
53
+ enhanced = plugin.promptEnhancer(taskId, enhanced, context);
54
+ }
55
+ return enhanced;
56
+ }
57
+ evaluateCommandGuardrails(command) {
58
+ const results = [];
59
+ for (const plugin of this.plugins) {
60
+ if (!plugin.customGuardrails?.evaluateCommand) continue;
61
+ results.push(...plugin.customGuardrails.evaluateCommand(command));
62
+ }
63
+ return results;
64
+ }
65
+ evaluateFilePathGuardrails(filePath) {
66
+ const results = [];
67
+ for (const plugin of this.plugins) {
68
+ if (!plugin.customGuardrails?.evaluateFilePath) continue;
69
+ results.push(...plugin.customGuardrails.evaluateFilePath(filePath));
70
+ }
71
+ return results;
72
+ }
73
+ evaluateFileContentGuardrails(filePath, content) {
74
+ const results = [];
75
+ for (const plugin of this.plugins) {
76
+ if (!plugin.customGuardrails?.evaluateFileContent) continue;
77
+ results.push(...plugin.customGuardrails.evaluateFileContent(filePath, content));
78
+ }
79
+ return results;
80
+ }
81
+ async runBeforeWorkflow(workflowId, userRequest) {
82
+ for (const plugin of this.plugins) {
83
+ if (!plugin.beforeWorkflow) continue;
84
+ await plugin.beforeWorkflow(workflowId, userRequest);
85
+ }
86
+ }
87
+ async runAfterWorkflow(workflowId, result) {
88
+ for (const plugin of this.plugins) {
89
+ if (!plugin.afterWorkflow) continue;
90
+ await plugin.afterWorkflow(workflowId, result);
91
+ }
92
+ }
93
+ };
94
+ var pluginRegistry = new PluginRegistry();
95
+
96
+ // src/lib/guardrail-hooks.ts
97
+ function globFragmentToRegex(fragment) {
98
+ let out = "";
99
+ for (const ch of fragment) {
100
+ if (ch === "*") out += "[^/]*";
101
+ else if (ch === "?") out += "[^/]";
102
+ else if (".+^$|()[]\\".includes(ch)) out += "\\" + ch;
103
+ else out += ch;
104
+ }
105
+ return out;
106
+ }
107
+ function matchGlob(pattern, path) {
108
+ let regex = "";
109
+ let i = 0;
110
+ while (i < pattern.length) {
111
+ if (pattern[i] === "*" && pattern[i + 1] === "*" && pattern[i + 2] === "/") {
112
+ regex += "(?:.+/)?";
113
+ i += 3;
114
+ } else if (pattern[i] === "*" && pattern[i + 1] === "*") {
115
+ regex += ".*";
116
+ i += 2;
117
+ } else if (pattern[i] === "*") {
118
+ regex += "[^/]*";
119
+ i += 1;
120
+ } else if (pattern[i] === "?") {
121
+ regex += "[^/]";
122
+ i += 1;
123
+ } else if (pattern[i] === "{") {
124
+ const end = pattern.indexOf("}", i);
125
+ if (end !== -1) {
126
+ const alts = pattern.slice(i + 1, end).split(",").map(globFragmentToRegex);
127
+ regex += "(?:" + alts.join("|") + ")";
128
+ i = end + 1;
129
+ } else {
130
+ regex += "\\{";
131
+ i += 1;
132
+ }
133
+ } else if (".+^$|()[]\\".includes(pattern[i])) {
134
+ regex += "\\" + pattern[i];
135
+ i += 1;
136
+ } else {
137
+ regex += pattern[i];
138
+ i += 1;
139
+ }
140
+ }
141
+ return new RegExp("^" + regex + "$").test(path);
142
+ }
143
+ function getBlockingViolations(results) {
144
+ return results.filter((r) => !r.passed && r.action === "block");
145
+ }
146
+ function getWarnings(results) {
147
+ return results.filter((r) => !r.passed && r.action === "warn");
148
+ }
149
+ function hasBlockingViolation(results) {
150
+ return results.some((r) => !r.passed && r.action === "block");
151
+ }
152
+ function pluginResultToCheckResult(r) {
153
+ return {
154
+ guardrail_id: r.guardrail_id,
155
+ passed: !r.matched,
156
+ action: r.action,
157
+ message: r.matched ? r.message : ""
158
+ };
159
+ }
160
+ function createGuardrailHooks(checks) {
161
+ function runChecks(ctx) {
162
+ const results = [];
163
+ if (ctx.command) {
164
+ results.push(...checks.checkCommand(ctx.command));
165
+ results.push(
166
+ ...pluginRegistry.evaluateCommandGuardrails(ctx.command).map(pluginResultToCheckResult)
167
+ );
168
+ }
169
+ if (ctx.filePath) {
170
+ results.push(...checks.checkFilePath(ctx.filePath));
171
+ results.push(
172
+ ...pluginRegistry.evaluateFilePathGuardrails(ctx.filePath).map(pluginResultToCheckResult)
173
+ );
174
+ }
175
+ if (ctx.filePath && ctx.content) {
176
+ results.push(...checks.checkContent(ctx.filePath, ctx.content));
177
+ results.push(
178
+ ...pluginRegistry.evaluateFileContentGuardrails(ctx.filePath, ctx.content).map(pluginResultToCheckResult)
179
+ );
180
+ }
181
+ return results;
182
+ }
183
+ function beforeShellExecution(input) {
184
+ const command = input.command ?? "";
185
+ if (!command) return {};
186
+ const results = runChecks({ command });
187
+ const blocks = getBlockingViolations(results);
188
+ const warns = getWarnings(results);
189
+ if (blocks.length > 0) {
190
+ const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join("\n");
191
+ return { permission: "deny", user_message: msg, agent_message: msg };
192
+ }
193
+ if (warns.length > 0) {
194
+ return {
195
+ additionalContext: warns.map((r) => `[${r.guardrail_id}] ${r.message}`).join("\n")
196
+ };
197
+ }
198
+ return {};
199
+ }
200
+ function preToolUse(input) {
201
+ const filePath = input.tool_input?.file_path ?? input.tool_input?.path ?? "";
202
+ if (!filePath) return {};
203
+ const results = runChecks({ filePath });
204
+ const blocks = getBlockingViolations(results);
205
+ if (blocks.length > 0) {
206
+ const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join("\n");
207
+ return { permission: "deny", user_message: msg, agent_message: msg };
208
+ }
209
+ return {};
210
+ }
211
+ function afterFileEdit(input) {
212
+ const filePath = input.file_path ?? "";
213
+ const content = input.content ?? "";
214
+ if (!filePath) return {};
215
+ const results = runChecks({ filePath, content });
216
+ const blocks = getBlockingViolations(results);
217
+ if (blocks.length > 0) {
218
+ const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join("\n");
219
+ return { permission: "deny", user_message: msg, agent_message: msg };
220
+ }
221
+ return {};
222
+ }
223
+ return { beforeShellExecution, preToolUse, afterFileEdit, runChecks };
224
+ }
225
+ function createGuardrailHooksFromRules(rules) {
226
+ const commandChecks = rules.commandRules.map((rule) => ({
227
+ guardrail_id: rule.guardrail_id,
228
+ pattern: new RegExp(rule.pattern),
229
+ action: rule.action,
230
+ message: rule.message
231
+ }));
232
+ const fileChecks = rules.fileRules;
233
+ const contentChecks = rules.contentRules.map((rule) => ({
234
+ guardrail_id: rule.guardrail_id,
235
+ pattern: new RegExp(rule.pattern),
236
+ action: rule.action,
237
+ message: rule.message,
238
+ file_glob: rule.file_glob,
239
+ exclude_glob: rule.exclude_glob
240
+ }));
241
+ return createGuardrailHooks({
242
+ checkCommand(command) {
243
+ const results = [];
244
+ for (const check of commandChecks) {
245
+ const passed = !check.pattern.test(command);
246
+ results.push({
247
+ guardrail_id: check.guardrail_id,
248
+ passed,
249
+ action: check.action,
250
+ message: passed ? "" : check.message
251
+ });
252
+ }
253
+ return results;
254
+ },
255
+ checkFilePath(filePath) {
256
+ const results = [];
257
+ for (const check of fileChecks) {
258
+ if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {
259
+ continue;
260
+ }
261
+ const matched = matchGlob(check.pattern, filePath);
262
+ results.push({
263
+ guardrail_id: check.guardrail_id,
264
+ passed: !matched,
265
+ action: check.action,
266
+ message: matched ? check.message : ""
267
+ });
268
+ }
269
+ return results;
270
+ },
271
+ checkContent(filePath, content) {
272
+ const results = [];
273
+ for (const check of contentChecks) {
274
+ if (check.file_glob && !matchGlob(check.file_glob, filePath)) {
275
+ continue;
276
+ }
277
+ if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {
278
+ continue;
279
+ }
280
+ const matched = check.pattern.test(content);
281
+ results.push({
282
+ guardrail_id: check.guardrail_id,
283
+ passed: !matched,
284
+ action: check.action,
285
+ message: matched ? check.message : ""
286
+ });
287
+ }
288
+ return results;
289
+ }
290
+ });
291
+ }
292
+
293
+ export {
294
+ PluginRegistry,
295
+ pluginRegistry,
296
+ getBlockingViolations,
297
+ getWarnings,
298
+ hasBlockingViolation,
299
+ createGuardrailHooks,
300
+ createGuardrailHooksFromRules
301
+ };
302
+ //# sourceMappingURL=chunk-JDXRLHY3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/plugin.ts","../src/lib/guardrail-hooks.ts"],"sourcesContent":["/**\n * Plugin Interface — extension points for user code injection\n */\n\nimport type { TaskContext, TaskOutcome, AgentContractLike, TaskContractLike, PromptBuilderOptions } from \"./task-runner.js\";\nimport type { WorkflowResult } from \"./workflow-runner.js\";\n\nexport interface GuardrailResult {\n matched: boolean;\n guardrail_id: string;\n severity: \"critical\" | \"mandatory\" | \"warning\" | \"info\";\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface PromptBuilderArgs {\n agent: AgentContractLike;\n task: TaskContractLike;\n context: TaskContext;\n options?: PromptBuilderOptions;\n}\n\nexport interface AgentPlugin {\n readonly id: string;\n beforeTask?(taskId: string, context: TaskContext): Promise<TaskContext | null>;\n afterTask?(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;\n /**\n * Enrich the structured TaskContext before prompt generation.\n * Unlike beforeTask (which can skip a task by returning null),\n * this hook is purely for context augmentation.\n */\n contextEnhancer?(taskId: string, context: TaskContext): TaskContext;\n /**\n * Lightweight prompt post-processor. Applied after the prompt is built.\n * Use for appending instructions or modifying sections.\n */\n promptEnhancer?(taskId: string, prompt: string, context: TaskContext): string;\n /**\n * Full prompt builder override. If provided and returns a non-null string,\n * replaces the default buildTaskPrompt output entirely.\n * Receives the agent/task contracts and context so the plugin can build\n * a completely custom prompt.\n */\n promptBuilder?(args: PromptBuilderArgs): string | null;\n customGuardrails?: {\n evaluateCommand?(command: string): GuardrailResult[];\n evaluateFilePath?(filePath: string): GuardrailResult[];\n evaluateFileContent?(filePath: string, content: string): GuardrailResult[];\n };\n beforeWorkflow?(workflowId: string, userRequest: string): Promise<void>;\n afterWorkflow?(workflowId: string, result: WorkflowResult): Promise<void>;\n}\n\nexport class PluginRegistry {\n private plugins: AgentPlugin[] = [];\n\n register(plugin: AgentPlugin): void {\n if (this.plugins.some((p) => p.id === plugin.id)) {\n throw new Error(`Plugin \"${plugin.id}\" is already registered`);\n }\n this.plugins.push(plugin);\n }\n\n getAll(): readonly AgentPlugin[] {\n return this.plugins;\n }\n\n async runBeforeTask(taskId: string, context: TaskContext): Promise<TaskContext | null> {\n let ctx: TaskContext | null = context;\n for (const plugin of this.plugins) {\n if (!plugin.beforeTask || ctx === null) continue;\n ctx = await plugin.beforeTask(taskId, ctx);\n }\n return ctx;\n }\n\n async runAfterTask(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome> {\n let result = outcome;\n for (const plugin of this.plugins) {\n if (!plugin.afterTask) continue;\n result = await plugin.afterTask(taskId, result);\n }\n return result;\n }\n\n applyContextEnhancers(taskId: string, context: TaskContext): TaskContext {\n let ctx = context;\n for (const plugin of this.plugins) {\n if (!plugin.contextEnhancer) continue;\n ctx = plugin.contextEnhancer(taskId, ctx);\n }\n return ctx;\n }\n\n /**\n * Try plugin promptBuilder hooks. Returns custom prompt if any plugin provides one,\n * or null to use the default buildTaskPrompt.\n */\n applyPromptBuilder(args: PromptBuilderArgs): string | null {\n for (const plugin of this.plugins) {\n if (!plugin.promptBuilder) continue;\n const result = plugin.promptBuilder(args);\n if (result !== null) return result;\n }\n return null;\n }\n\n applyPromptEnhancers(taskId: string, prompt: string, context: TaskContext): string {\n let enhanced = prompt;\n for (const plugin of this.plugins) {\n if (!plugin.promptEnhancer) continue;\n enhanced = plugin.promptEnhancer(taskId, enhanced, context);\n }\n return enhanced;\n }\n\n evaluateCommandGuardrails(command: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateCommand) continue;\n results.push(...plugin.customGuardrails.evaluateCommand(command));\n }\n return results;\n }\n\n evaluateFilePathGuardrails(filePath: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFilePath) continue;\n results.push(...plugin.customGuardrails.evaluateFilePath(filePath));\n }\n return results;\n }\n\n evaluateFileContentGuardrails(filePath: string, content: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFileContent) continue;\n results.push(...plugin.customGuardrails.evaluateFileContent(filePath, content));\n }\n return results;\n }\n\n async runBeforeWorkflow(workflowId: string, userRequest: string): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.beforeWorkflow) continue;\n await plugin.beforeWorkflow(workflowId, userRequest);\n }\n }\n\n async runAfterWorkflow(workflowId: string, result: WorkflowResult): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.afterWorkflow) continue;\n await plugin.afterWorkflow(workflowId, result);\n }\n }\n}\n\nexport const pluginRegistry = new PluginRegistry();\n","/**\n * SDK Guardrail Hook Bridge — generic adapter from guardrail check functions\n * + plugin guardrails to SDK-compatible hook responses.\n *\n * Embedded guardrail rules are converted via createGuardrailHooksFromRules(),\n * which delegates to createGuardrailHooks(). All hook logic lives here.\n */\n\nimport { pluginRegistry } from \"./plugin.js\";\n\nexport interface GuardrailCheckResult {\n guardrail_id: string;\n passed: boolean;\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface HookResponse {\n permission?: \"deny\";\n user_message?: string;\n agent_message?: string;\n additionalContext?: string;\n}\n\nexport interface GuardrailRule {\n guardrail_id: string;\n pattern: string;\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n file_glob?: string;\n exclude_glob?: string;\n}\n\nexport interface GuardrailRuleData {\n commandRules: GuardrailRule[];\n fileRules: GuardrailRule[];\n contentRules: GuardrailRule[];\n}\n\nexport interface GuardrailCheckFunctions {\n checkCommand: (command: string) => GuardrailCheckResult[];\n checkFilePath: (filePath: string) => GuardrailCheckResult[];\n checkContent: (filePath: string, content: string) => GuardrailCheckResult[];\n}\n\nfunction globFragmentToRegex(fragment: string): string {\n let out = \"\";\n for (const ch of fragment) {\n if (ch === \"*\") out += \"[^/]*\";\n else if (ch === \"?\") out += \"[^/]\";\n else if (\".+^$|()[]\\\\\".includes(ch)) out += \"\\\\\" + ch;\n else out += ch;\n }\n return out;\n}\n\nexport function matchGlob(pattern: string, path: string): boolean {\n let regex = \"\";\n let i = 0;\n while (i < pattern.length) {\n if (pattern[i] === \"*\" && pattern[i + 1] === \"*\" && pattern[i + 2] === \"/\") {\n regex += \"(?:.+/)?\";\n i += 3;\n } else if (pattern[i] === \"*\" && pattern[i + 1] === \"*\") {\n regex += \".*\";\n i += 2;\n } else if (pattern[i] === \"*\") {\n regex += \"[^/]*\";\n i += 1;\n } else if (pattern[i] === \"?\") {\n regex += \"[^/]\";\n i += 1;\n } else if (pattern[i] === \"{\") {\n const end = pattern.indexOf(\"}\", i);\n if (end !== -1) {\n const alts = pattern.slice(i + 1, end).split(\",\").map(globFragmentToRegex);\n regex += \"(?:\" + alts.join(\"|\") + \")\";\n i = end + 1;\n } else {\n regex += \"\\\\{\";\n i += 1;\n }\n } else if (\".+^$|()[]\\\\\".includes(pattern[i])) {\n regex += \"\\\\\" + pattern[i];\n i += 1;\n } else {\n regex += pattern[i];\n i += 1;\n }\n }\n return new RegExp(\"^\" + regex + \"$\").test(path);\n}\n\nexport interface HookContext {\n command?: string;\n filePath?: string;\n content?: string;\n}\n\nexport interface GuardrailHooks {\n beforeShellExecution: (input: { command?: string }) => HookResponse;\n preToolUse: (input: {\n tool_name?: string;\n tool_input?: { file_path?: string; path?: string };\n }) => HookResponse;\n afterFileEdit: (input: { file_path?: string; content?: string }) => HookResponse;\n runChecks: (ctx: HookContext) => GuardrailCheckResult[];\n}\n\nexport function getBlockingViolations(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"block\");\n}\n\nexport function getWarnings(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"warn\");\n}\n\nexport function hasBlockingViolation(results: GuardrailCheckResult[]): boolean {\n return results.some((r) => !r.passed && r.action === \"block\");\n}\n\nfunction pluginResultToCheckResult(r: {\n matched: boolean;\n guardrail_id: string;\n action: string;\n message: string;\n}): GuardrailCheckResult {\n return {\n guardrail_id: r.guardrail_id,\n passed: !r.matched,\n action: r.action as GuardrailCheckResult[\"action\"],\n message: r.matched ? r.message : \"\",\n };\n}\n\n/**\n * Create SDK hook functions from generated guardrail check functions.\n *\n * Merges DSL-generated checks with plugin-registered guardrails and\n * returns hook functions in the format expected by the Claude SDK,\n * plus a generic runChecks() for programmatic use.\n */\nexport function createGuardrailHooks(checks: GuardrailCheckFunctions): GuardrailHooks {\n function runChecks(ctx: HookContext): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n\n if (ctx.command) {\n results.push(...checks.checkCommand(ctx.command));\n results.push(\n ...pluginRegistry.evaluateCommandGuardrails(ctx.command).map(pluginResultToCheckResult),\n );\n }\n\n if (ctx.filePath) {\n results.push(...checks.checkFilePath(ctx.filePath));\n results.push(\n ...pluginRegistry.evaluateFilePathGuardrails(ctx.filePath).map(pluginResultToCheckResult),\n );\n }\n\n if (ctx.filePath && ctx.content) {\n results.push(...checks.checkContent(ctx.filePath, ctx.content));\n results.push(\n ...pluginRegistry\n .evaluateFileContentGuardrails(ctx.filePath, ctx.content)\n .map(pluginResultToCheckResult),\n );\n }\n\n return results;\n }\n\n function beforeShellExecution(input: { command?: string }): HookResponse {\n const command = input.command ?? \"\";\n if (!command) return {};\n\n const results = runChecks({ command });\n const blocks = getBlockingViolations(results);\n const warns = getWarnings(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n if (warns.length > 0) {\n return {\n additionalContext: warns.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\"),\n };\n }\n\n return {};\n }\n\n function preToolUse(input: {\n tool_name?: string;\n tool_input?: { file_path?: string; path?: string };\n }): HookResponse {\n const filePath = input.tool_input?.file_path ?? input.tool_input?.path ?? \"\";\n if (!filePath) return {};\n\n const results = runChecks({ filePath });\n const blocks = getBlockingViolations(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n return {};\n }\n\n function afterFileEdit(input: { file_path?: string; content?: string }): HookResponse {\n const filePath = input.file_path ?? \"\";\n const content = input.content ?? \"\";\n if (!filePath) return {};\n\n const results = runChecks({ filePath, content });\n const blocks = getBlockingViolations(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n return {};\n }\n\n return { beforeShellExecution, preToolUse, afterFileEdit, runChecks };\n}\n\n/**\n * Create SDK hook functions from embedded guardrail rule data.\n */\nexport function createGuardrailHooksFromRules(rules: GuardrailRuleData): GuardrailHooks {\n const commandChecks = rules.commandRules.map((rule) => ({\n guardrail_id: rule.guardrail_id,\n pattern: new RegExp(rule.pattern),\n action: rule.action,\n message: rule.message,\n }));\n\n const fileChecks = rules.fileRules;\n\n const contentChecks = rules.contentRules.map((rule) => ({\n guardrail_id: rule.guardrail_id,\n pattern: new RegExp(rule.pattern),\n action: rule.action,\n message: rule.message,\n file_glob: rule.file_glob,\n exclude_glob: rule.exclude_glob,\n }));\n\n return createGuardrailHooks({\n checkCommand(command: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of commandChecks) {\n const passed = !check.pattern.test(command);\n results.push({\n guardrail_id: check.guardrail_id,\n passed,\n action: check.action,\n message: passed ? \"\" : check.message,\n });\n }\n return results;\n },\n\n checkFilePath(filePath: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of fileChecks) {\n if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {\n continue;\n }\n const matched = matchGlob(check.pattern, filePath);\n results.push({\n guardrail_id: check.guardrail_id,\n passed: !matched,\n action: check.action,\n message: matched ? check.message : \"\",\n });\n }\n return results;\n },\n\n checkContent(filePath: string, content: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of contentChecks) {\n if (check.file_glob && !matchGlob(check.file_glob, filePath)) {\n continue;\n }\n if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {\n continue;\n }\n const matched = check.pattern.test(content);\n results.push({\n guardrail_id: check.guardrail_id,\n passed: !matched,\n action: check.action,\n message: matched ? check.message : \"\",\n });\n }\n return results;\n },\n });\n}\n"],"mappings":";AAqDO,IAAM,iBAAN,MAAqB;AAAA,EAClB,UAAyB,CAAC;AAAA,EAElC,SAAS,QAA2B;AAClC,QAAI,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO,EAAE,GAAG;AAChD,YAAM,IAAI,MAAM,WAAW,OAAO,EAAE,yBAAyB;AAAA,IAC/D;AACA,SAAK,QAAQ,KAAK,MAAM;AAAA,EAC1B;AAAA,EAEA,SAAiC;AAC/B,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,cAAc,QAAgB,SAAmD;AACrF,QAAI,MAA0B;AAC9B,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,cAAc,QAAQ,KAAM;AACxC,YAAM,MAAM,OAAO,WAAW,QAAQ,GAAG;AAAA,IAC3C;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,aAAa,QAAgB,SAA4C;AAC7E,QAAI,SAAS;AACb,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,UAAW;AACvB,eAAS,MAAM,OAAO,UAAU,QAAQ,MAAM;AAAA,IAChD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,sBAAsB,QAAgB,SAAmC;AACvE,QAAI,MAAM;AACV,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,gBAAiB;AAC7B,YAAM,OAAO,gBAAgB,QAAQ,GAAG;AAAA,IAC1C;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,mBAAmB,MAAwC;AACzD,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,cAAe;AAC3B,YAAM,SAAS,OAAO,cAAc,IAAI;AACxC,UAAI,WAAW,KAAM,QAAO;AAAA,IAC9B;AACA,WAAO;AAAA,EACT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,UACX,cAAc,MAAM;AAAA,UACpB,QAAQ,CAAC;AAAA,UACT,QAAQ,MAAM;AAAA,UACd,SAAS,UAAU,MAAM,UAAU;AAAA,QACrC,CAAC;AAAA,MACH;AACA,aAAO;AAAA,IACT;AAAA,IAEA,aAAa,UAAkB,SAAyC;AACtE,YAAM,UAAkC,CAAC;AACzC,iBAAW,SAAS,eAAe;AACjC,YAAI,MAAM,aAAa,CAAC,UAAU,MAAM,WAAW,QAAQ,GAAG;AAC5D;AAAA,QACF;AACA,YAAI,MAAM,gBAAgB,UAAU,MAAM,cAAc,QAAQ,GAAG;AACjE;AAAA,QACF;AACA,cAAM,UAAU,MAAM,QAAQ,KAAK,OAAO;AAC1C,gBAAQ,KAAK;AAAA,UACX,cAAc,MAAM;AAAA,UACpB,QAAQ,CAAC;AAAA,UACT,QAAQ,MAAM;AAAA,UACd,SAAS,UAAU,MAAM,UAAU;AAAA,QACrC,CAAC;AAAA,MACH;AACA,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AACH;","names":[]}
package/dist/cli/index.js CHANGED
@@ -1,12 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  buildTaskPrompt,
4
- createGuardrailHooksFromRules,
5
4
  createProgressSink,
6
5
  loadPlugins,
7
- pluginRegistry,
8
6
  runWorkflow
9
- } from "../chunk-VMCNFGEY.js";
7
+ } from "../chunk-ADNNYJAU.js";
8
+ import {
9
+ createGuardrailHooksFromRules,
10
+ pluginRegistry
11
+ } from "../chunk-JDXRLHY3.js";
10
12
  import {
11
13
  checkFreshness,
12
14
  generate,
@@ -2025,14 +2027,15 @@ function loadReferenceDoc() {
2025
2027
  }
2026
2028
  return void 0;
2027
2029
  }
2028
- async function createImplementAdapter(adapterName, projectDir, model) {
2030
+ async function createImplementAdapter(adapterName, projectDir, model, guardrailHooks) {
2029
2031
  switch (adapterName) {
2030
2032
  case "claude": {
2031
2033
  const { ClaudeAgentSdkAdapter } = await import("../adapters/claude-agent-sdk.js");
2032
2034
  return new ClaudeAgentSdkAdapter({
2033
2035
  cwd: projectDir,
2034
2036
  permissionMode: "bypassPermissions",
2035
- model
2037
+ model,
2038
+ guardrailHooks
2036
2039
  });
2037
2040
  }
2038
2041
  case "mock": {
@@ -2078,9 +2081,19 @@ async function runImplement(description, options) {
2078
2081
  }
2079
2082
  };
2080
2083
  }
2084
+ let guardrailHooks;
2085
+ const rawRules = resolvedDsl._guardrailRules;
2086
+ if (rawRules && (rawRules.commandRules?.length || rawRules.fileRules?.length || rawRules.contentRules?.length)) {
2087
+ guardrailHooks = createGuardrailHooksFromRules(rawRules);
2088
+ }
2081
2089
  let adapter;
2082
2090
  try {
2083
- adapter = await createImplementAdapter(options.adapter, projectDir, options.model);
2091
+ adapter = await createImplementAdapter(
2092
+ options.adapter,
2093
+ projectDir,
2094
+ options.model,
2095
+ guardrailHooks
2096
+ );
2084
2097
  } catch (err) {
2085
2098
  return { status: "failed", exitCode: 12, error: m.adapterError(err.message) };
2086
2099
  }
@@ -2200,13 +2213,14 @@ var ja2 = {
2200
2213
  function msg2() {
2201
2214
  return isJapanese2() ? ja2 : en2;
2202
2215
  }
2203
- async function createAuditAdapter(adapterName, projectDir, model) {
2216
+ async function createAuditAdapter(adapterName, projectDir, model, guardrailHooks) {
2204
2217
  switch (adapterName) {
2205
2218
  case "claude": {
2206
2219
  const { ClaudeAgentSdkAdapter } = await import("../adapters/claude-agent-sdk.js");
2207
2220
  return new ClaudeAgentSdkAdapter({
2208
2221
  cwd: projectDir,
2209
- model
2222
+ model,
2223
+ guardrailHooks
2210
2224
  });
2211
2225
  }
2212
2226
  case "mock": {
@@ -2269,9 +2283,19 @@ Focus the audit on the "${options.focus}" layer only.` : "";
2269
2283
  }
2270
2284
  };
2271
2285
  }
2286
+ let guardrailHooks;
2287
+ const rawRules = resolvedDsl._guardrailRules;
2288
+ if (rawRules && (rawRules.commandRules?.length || rawRules.fileRules?.length || rawRules.contentRules?.length)) {
2289
+ guardrailHooks = createGuardrailHooksFromRules(rawRules);
2290
+ }
2272
2291
  let adapter;
2273
2292
  try {
2274
- adapter = await createAuditAdapter(options.adapter, projectDir, options.model);
2293
+ adapter = await createAuditAdapter(
2294
+ options.adapter,
2295
+ projectDir,
2296
+ options.model,
2297
+ guardrailHooks
2298
+ );
2275
2299
  } catch (err) {
2276
2300
  return { status: "failed", exitCode: 12, error: m.adapterError(err.message) };
2277
2301
  }
@@ -2363,7 +2387,7 @@ function formatAuditResult(result) {
2363
2387
  // src/cli/index.ts
2364
2388
  import YAML2 from "yaml";
2365
2389
  register();
2366
- var VERSION = "0.36.2";
2390
+ var VERSION = "0.36.5";
2367
2391
  async function loadGeneratedContracts(configPath) {
2368
2392
  const config = await loadConfig(configPath);
2369
2393
  const basePath = `${config.generatedDir}/index`;