agent-contracts-runtime 0.36.3 → 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":[]}
@@ -1,14 +1,17 @@
1
1
  // src/generator/index.ts
2
2
  import { readFile as readFile3, writeFile, mkdir, rm } from "fs/promises";
3
- import { resolve as resolve3, join as join2, relative } from "path";
3
+ import { resolve as resolve3, join as join3, relative } from "path";
4
4
  import { createHash } from "crypto";
5
5
  import YAML2 from "yaml";
6
6
 
7
7
  // src/generator/config.ts
8
+ import { existsSync } from "fs";
8
9
  import { readFile } from "fs/promises";
9
- import { resolve, dirname } from "path";
10
+ import { resolve, dirname, join, basename } from "path";
10
11
  import { z } from "zod";
11
12
  import YAML from "yaml";
13
+ var DEFAULT_CONFIG_PATH = "./agents.conf.yaml";
14
+ var LEGACY_CONFIG_FILENAME = "agent-runtime.config.yaml";
12
15
  var RecoverySchema = z.object({
13
16
  max_follow_ups: z.number().int().min(0).default(2),
14
17
  max_retries: z.number().int().min(0).default(0)
@@ -47,12 +50,40 @@ var RuntimeConfigSchema = z.object({
47
50
  model_mapping: ModelMappingSchema,
48
51
  logging: LoggingSchema
49
52
  });
50
- async function loadConfig(configPath) {
53
+ var CliSectionSchema = z.object({
54
+ dsl: z.string().optional(),
55
+ generated_dir: z.string().optional(),
56
+ plugins: z.array(z.string()).optional(),
57
+ bindings: z.array(z.string()).optional()
58
+ }).strict();
59
+ var ProjectConfigSchema = z.object({
60
+ dsl: z.string().optional(),
61
+ generated_dir: z.string().optional(),
62
+ bindings: z.array(z.string()).optional(),
63
+ active_guardrail_policy: z.string().optional(),
64
+ templates_dir: z.string().optional(),
65
+ plugins: z.array(z.string()).optional(),
66
+ recovery: RecoverySchema,
67
+ model_mapping: ModelMappingSchema,
68
+ logging: LoggingSchema,
69
+ cli: z.record(z.string(), CliSectionSchema).optional()
70
+ });
71
+ function resolveConfigFilePath(configPath) {
51
72
  const absPath = resolve(configPath);
52
- const raw = await readFile(absPath, "utf8");
53
- const parsed = YAML.parse(raw);
54
- const config = RuntimeConfigSchema.parse(parsed);
55
- const configDir = dirname(absPath);
73
+ if (existsSync(absPath)) {
74
+ return absPath;
75
+ }
76
+ const dir = dirname(absPath);
77
+ const base = basename(absPath);
78
+ if (base === "agents.conf.yaml") {
79
+ const legacyPath = join(dir, LEGACY_CONFIG_FILENAME);
80
+ if (existsSync(legacyPath)) {
81
+ return legacyPath;
82
+ }
83
+ }
84
+ return absPath;
85
+ }
86
+ function buildResolvedConfig(config, configDir) {
56
87
  const pl = config.logging.progress_log;
57
88
  return {
58
89
  ...config,
@@ -71,23 +102,45 @@ async function loadConfig(configPath) {
71
102
  }
72
103
  };
73
104
  }
105
+ async function loadConfig(configPath) {
106
+ const absPath = resolveConfigFilePath(configPath);
107
+ const raw = await readFile(absPath, "utf8");
108
+ const parsed = YAML.parse(raw);
109
+ const config = RuntimeConfigSchema.parse(parsed);
110
+ const configDir = dirname(absPath);
111
+ return buildResolvedConfig(config, configDir);
112
+ }
113
+ async function loadProjectConfig(configPath, cliName) {
114
+ const absPath = resolveConfigFilePath(configPath);
115
+ const raw = await readFile(absPath, "utf8");
116
+ const parsed = YAML.parse(raw);
117
+ const projectConfig = ProjectConfigSchema.parse(parsed);
118
+ const { cli: _cli, ...baseConfig } = projectConfig;
119
+ let merged = { ...baseConfig };
120
+ if (cliName && projectConfig.cli?.[cliName]) {
121
+ merged = { ...merged, ...projectConfig.cli[cliName] };
122
+ }
123
+ const config = RuntimeConfigSchema.parse(merged);
124
+ const configDir = dirname(absPath);
125
+ return buildResolvedConfig(config, configDir);
126
+ }
74
127
 
75
128
  // src/generator/template-engine.ts
76
129
  import { readFile as readFile2 } from "fs/promises";
77
- import { resolve as resolve2, join } from "path";
130
+ import { resolve as resolve2, join as join2 } from "path";
78
131
  import { fileURLToPath } from "url";
79
132
  import Handlebars from "handlebars";
80
- import { existsSync } from "fs";
133
+ import { existsSync as existsSync2 } from "fs";
81
134
  var __dirname = fileURLToPath(new URL(".", import.meta.url));
82
135
  function findPackageRoot() {
83
136
  let dir = __dirname;
84
137
  for (let i = 0; i < 5; i++) {
85
- if (existsSync(join(dir, "package.json"))) return dir;
138
+ if (existsSync2(join2(dir, "package.json"))) return dir;
86
139
  dir = resolve2(dir, "..");
87
140
  }
88
141
  return resolve2(__dirname, "..");
89
142
  }
90
- var BUILTIN_TEMPLATES_DIR = join(findPackageRoot(), "templates");
143
+ var BUILTIN_TEMPLATES_DIR = join2(findPackageRoot(), "templates");
91
144
  function toCamelCase(str) {
92
145
  return str.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
93
146
  }
@@ -197,11 +250,11 @@ hbs.registerHelper("stringArray", (arr) => {
197
250
  async function loadTemplate(name, customDir) {
198
251
  if (customDir) {
199
252
  try {
200
- return await readFile2(join(customDir, name), "utf8");
253
+ return await readFile2(join2(customDir, name), "utf8");
201
254
  } catch {
202
255
  }
203
256
  }
204
- return readFile2(join(BUILTIN_TEMPLATES_DIR, name), "utf8");
257
+ return readFile2(join2(BUILTIN_TEMPLATES_DIR, name), "utf8");
205
258
  }
206
259
  async function renderTemplate(name, context, customDir) {
207
260
  const source = await loadTemplate(name, customDir);
@@ -402,7 +455,7 @@ var CONTRACT_TEMPLATES = [
402
455
  { template: "contracts-index.ts.hbs", output: "index.ts" }
403
456
  ];
404
457
  async function generate(options = {}) {
405
- const configPath = options.configPath ?? "./agent-runtime.config.yaml";
458
+ const configPath = options.configPath ?? "./agents.conf.yaml";
406
459
  const config = await loadConfig(configPath);
407
460
  const templatesDir = options.templates ?? config.templatesDir;
408
461
  const checkMode = options.check ?? false;
@@ -421,7 +474,7 @@ async function generate(options = {}) {
421
474
  const generatedContents = /* @__PURE__ */ new Map();
422
475
  for (const { template, output } of CONTRACT_TEMPLATES) {
423
476
  const rendered = DO_NOT_EDIT_HEADER + await renderTemplate(template, contractCtx, templatesDir);
424
- const outPath = join2(config.generatedDir, output);
477
+ const outPath = join3(config.generatedDir, output);
425
478
  files_generated.push(relative(config.configDir, outPath));
426
479
  generatedContents.set(outPath, rendered);
427
480
  }
@@ -461,7 +514,7 @@ async function generate(options = {}) {
461
514
  const dslWithRules = guardrailRules ? { ...dsl, _guardrailRules: guardrailRules } : dsl;
462
515
  const dslDataContent = DO_NOT_EDIT_HEADER + `export const resolvedDsl: Record<string, unknown> = ${JSON.stringify(dslWithRules, null, 2)} as const;
463
516
  `;
464
- const outPath = join2(config.generatedDir, "dsl-data.ts");
517
+ const outPath = join3(config.generatedDir, "dsl-data.ts");
465
518
  files_generated.push(relative(config.configDir, outPath));
466
519
  generatedContents.set(outPath, dslDataContent);
467
520
  }
@@ -499,7 +552,7 @@ async function generate(options = {}) {
499
552
  generation_input_hash,
500
553
  files: files_generated
501
554
  };
502
- const manifestPath = join2(config.generatedDir, ".manifest.json");
555
+ const manifestPath = join3(config.generatedDir, ".manifest.json");
503
556
  await mkdir(resolve3(manifestPath, ".."), { recursive: true });
504
557
  await writeFile(manifestPath, JSON.stringify(manifest, null, 2) + "\n", "utf8");
505
558
  }
@@ -513,8 +566,8 @@ async function generate(options = {}) {
513
566
  };
514
567
  }
515
568
  async function checkFreshness(configPath) {
516
- const config = await loadConfig(configPath ?? "./agent-runtime.config.yaml");
517
- const manifestPath = join2(config.generatedDir, ".manifest.json");
569
+ const config = await loadConfig(configPath ?? "./agents.conf.yaml");
570
+ const manifestPath = join3(config.generatedDir, ".manifest.json");
518
571
  try {
519
572
  const raw = await readFile3(manifestPath, "utf8");
520
573
  const manifest = JSON.parse(raw);
@@ -528,10 +581,13 @@ async function checkFreshness(configPath) {
528
581
  }
529
582
 
530
583
  export {
584
+ DEFAULT_CONFIG_PATH,
585
+ ProjectConfigSchema,
531
586
  loadConfig,
587
+ loadProjectConfig,
532
588
  buildContractContext,
533
589
  buildGuardrailContext,
534
590
  generate,
535
591
  checkFreshness
536
592
  };
537
- //# sourceMappingURL=chunk-DSHUZSVV.js.map
593
+ //# sourceMappingURL=chunk-KQOZCJK6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/generator/index.ts","../src/generator/config.ts","../src/generator/template-engine.ts","../src/generator/context.ts"],"sourcesContent":["/**\n * Generator — orchestrates DSL-to-TypeScript code generation\n */\n\nimport { readFile, writeFile, mkdir, rm, stat } from \"node:fs/promises\";\nimport { resolve, join, relative } from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport YAML from \"yaml\";\nimport { loadConfig, type ResolvedConfig } from \"./config.js\";\nimport { renderTemplate } from \"./template-engine.js\";\nimport { buildContractContext, buildGuardrailContext } from \"./context.js\";\n\nexport interface GenerateOptions {\n clean?: boolean;\n check?: boolean;\n templates?: string;\n configPath?: string;\n}\n\nexport interface GenerateResult {\n files_generated: string[];\n dsl_hash: string;\n generation_input_hash: string;\n cleaned: boolean;\n check_mode: boolean;\n has_differences: boolean;\n}\n\nconst DO_NOT_EDIT_HEADER = `/**\n * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.\n *\n * Regenerate via: npx agent-runtime generate\n */\n\n`;\n\nasync function loadYaml(filePath: string): Promise<unknown> {\n const raw = await readFile(filePath, \"utf8\");\n return YAML.parse(raw);\n}\n\nfunction computeHash(data: string): string {\n return createHash(\"sha256\").update(data).digest(\"hex\");\n}\n\nfunction sortDeep(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortDeep);\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => [k, sortDeep(v)]),\n );\n }\n return value;\n}\n\nfunction canonicalStringify(obj: unknown): string {\n return JSON.stringify(sortDeep(obj));\n}\n\n/**\n * Load DSL via agent-contracts resolve() which handles extends, merge\n * operators ($replace/$append), and $ref resolution including\n * file.yaml#/json-pointer fragments.\n */\nasync function loadDsl(dslPath: string): Promise<Record<string, unknown>> {\n const { resolve: resolveDsl } = await import(\"agent-contracts\");\n const result = await resolveDsl(dslPath);\n return result.data;\n}\n\nconst CONTRACT_TEMPLATES = [\n { template: \"agents.ts.hbs\", output: \"agents.ts\" },\n { template: \"tasks.ts.hbs\", output: \"tasks.ts\" },\n { template: \"workflows.ts.hbs\", output: \"workflows.ts\" },\n { template: \"handoffs.ts.hbs\", output: \"handoffs.ts\" },\n { template: \"contracts-index.ts.hbs\", output: \"index.ts\" },\n];\n\nexport async function generate(options: GenerateOptions = {}): Promise<GenerateResult> {\n const configPath = options.configPath ?? \"./agents.conf.yaml\";\n const config = await loadConfig(configPath);\n\n const templatesDir = options.templates ?? config.templatesDir;\n const checkMode = options.check ?? false;\n const cleaned = options.clean ?? false;\n\n if (cleaned && !checkMode) {\n try {\n await rm(config.generatedDir, { recursive: true, force: true });\n } catch {\n // directory may not exist\n }\n }\n\n const dsl = await loadDsl(config.dslPath);\n const dslCanonical = canonicalStringify(dsl);\n const dslHash = computeHash(dslCanonical);\n\n const contractCtx = buildContractContext(dsl);\n\n const files_generated: string[] = [];\n const generatedContents: Map<string, string> = new Map();\n\n // Phase 1a: Contract files\n for (const { template, output } of CONTRACT_TEMPLATES) {\n const rendered = DO_NOT_EDIT_HEADER + await renderTemplate(template, contractCtx as unknown as Record<string, unknown>, templatesDir);\n const outPath = join(config.generatedDir, output);\n files_generated.push(relative(config.configDir, outPath));\n generatedContents.set(outPath, rendered);\n }\n\n // Resolve guardrail rules from bindings (before Phase 1b)\n let guardrailRules: Record<string, unknown> | undefined;\n if (config.bindingPaths.length > 0) {\n for (const bindingPath of config.bindingPaths) {\n const binding = await loadYaml(bindingPath);\n const guardrailCtx = buildGuardrailContext(dsl, binding, config.active_guardrail_policy);\n if (guardrailCtx.hasGuardrails) {\n guardrailRules = {\n commandRules: guardrailCtx.commandChecks.map((c) => ({\n guardrail_id: c.guardrail_id,\n pattern: c.pattern,\n action: c.action,\n message: c.message,\n })),\n fileRules: guardrailCtx.fileChecks.map((c) => ({\n guardrail_id: c.guardrail_id,\n pattern: c.pattern,\n action: c.action,\n message: c.message,\n ...(c.exclude_glob ? { exclude_glob: c.exclude_glob } : {}),\n })),\n contentRules: guardrailCtx.contentChecks.map((c) => ({\n guardrail_id: c.guardrail_id,\n pattern: c.pattern,\n action: c.action,\n message: c.message,\n ...(c.file_glob ? { file_glob: c.file_glob } : {}),\n ...(c.exclude_glob ? { exclude_glob: c.exclude_glob } : {}),\n })),\n };\n }\n }\n }\n\n // Phase 1b: Embedded DSL data + guardrail rules (for loadDslContext at runtime)\n {\n const dslWithRules = guardrailRules ? { ...dsl, _guardrailRules: guardrailRules } : dsl;\n const dslDataContent = DO_NOT_EDIT_HEADER +\n `export const resolvedDsl: Record<string, unknown> = ${JSON.stringify(dslWithRules, null, 2)} as const;\\n`;\n const outPath = join(config.generatedDir, \"dsl-data.ts\");\n files_generated.push(relative(config.configDir, outPath));\n generatedContents.set(outPath, dslDataContent);\n }\n\n // Compute generation input hash (DSL + binding + generator version)\n const generationInputParts = [dslCanonical];\n for (const bp of config.bindingPaths) {\n try {\n generationInputParts.push(await readFile(bp, \"utf8\"));\n } catch {\n // binding may not exist\n }\n }\n const generation_input_hash = computeHash(generationInputParts.join(\"\\n---\\n\"));\n\n // Check mode — compare without writing\n let has_differences = false;\n if (checkMode) {\n for (const [outPath, content] of generatedContents) {\n try {\n const existing = await readFile(outPath, \"utf8\");\n if (existing !== content) {\n has_differences = true;\n break;\n }\n } catch {\n has_differences = true;\n break;\n }\n }\n } else {\n // Write files\n for (const [outPath, content] of generatedContents) {\n const dir = resolve(outPath, \"..\");\n await mkdir(dir, { recursive: true });\n await writeFile(outPath, content, \"utf8\");\n }\n\n // Write manifest\n const manifest = {\n generated_at: new Date().toISOString(),\n dsl_hash: dslHash,\n generation_input_hash,\n files: files_generated,\n };\n const manifestPath = join(config.generatedDir, \".manifest.json\");\n await mkdir(resolve(manifestPath, \"..\"), { recursive: true });\n await writeFile(manifestPath, JSON.stringify(manifest, null, 2) + \"\\n\", \"utf8\");\n }\n\n return {\n files_generated,\n dsl_hash: dslHash,\n generation_input_hash,\n cleaned,\n check_mode: checkMode,\n has_differences,\n };\n}\n\nexport async function checkFreshness(configPath?: string): Promise<boolean> {\n const config = await loadConfig(configPath ?? \"./agents.conf.yaml\");\n const manifestPath = join(config.generatedDir, \".manifest.json\");\n\n try {\n const raw = await readFile(manifestPath, \"utf8\");\n const manifest = JSON.parse(raw) as { dsl_hash: string };\n\n const dsl = await loadDsl(config.dslPath);\n const dslCanonical = canonicalStringify(dsl);\n const currentHash = computeHash(dslCanonical);\n\n return manifest.dsl_hash === currentHash;\n } catch {\n return false;\n }\n}\n\nexport {\n loadConfig,\n loadProjectConfig,\n ProjectConfigSchema,\n DEFAULT_CONFIG_PATH,\n type ResolvedConfig,\n type ProjectConfig,\n} from \"./config.js\";\nexport { buildContractContext, buildGuardrailContext } from \"./context.js\";\n","/**\n * Generator configuration — loads and validates agents.conf.yaml / agent-runtime.config.yaml\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve, dirname, join, basename } from \"node:path\";\nimport { z } from \"zod\";\nimport YAML from \"yaml\";\n\nexport const DEFAULT_CONFIG_PATH = \"./agents.conf.yaml\";\nexport const LEGACY_CONFIG_FILENAME = \"agent-runtime.config.yaml\";\n\nconst RecoverySchema = z.object({\n max_follow_ups: z.number().int().min(0).default(2),\n max_retries: z.number().int().min(0).default(0),\n}).default(() => ({ max_follow_ups: 2, max_retries: 0 }));\n\nconst ModelClassEntrySchema = z.object({\n adapter: z.string(),\n model: z.string().optional(),\n});\n\nconst ModelMappingSchema = z.object({\n fast: ModelClassEntrySchema.optional(),\n standard: ModelClassEntrySchema.optional(),\n thinking: ModelClassEntrySchema.optional(),\n}).default({});\n\nconst ProgressLogSchema = z.object({\n destination: z.enum([\"stderr\", \"file\", \"both\", \"none\"]).default(\"stderr\"),\n file: z.string().optional(),\n naming: z.enum([\"single\", \"per-invocation\", \"daily\"]).default(\"single\"),\n}).default(() => ({ destination: \"stderr\" as const, naming: \"single\" as const }))\n .refine(\n (val) => {\n if ((val.destination === \"file\" || val.destination === \"both\") && !val.file) return false;\n return true;\n },\n { message: \"logging.progress_log.file is required when destination is 'file' or 'both'\" },\n );\n\nconst LoggingSchema = z.object({\n progress_log: ProgressLogSchema,\n}).default(() => ({ progress_log: { destination: \"stderr\" as const, naming: \"single\" as const } }));\n\nexport const RuntimeConfigSchema = z.object({\n dsl: z.string().default(\"./agent-contracts.yaml\"),\n generated_dir: z.string().default(\"./agent/generated\"),\n bindings: z.array(z.string()).default([]),\n active_guardrail_policy: z.string().optional(),\n templates_dir: z.string().optional(),\n plugins: z.array(z.string()).default([]),\n recovery: RecoverySchema,\n model_mapping: ModelMappingSchema,\n logging: LoggingSchema,\n});\n\nexport type RuntimeConfig = z.infer<typeof RuntimeConfigSchema>;\n\nconst CliSectionSchema = z.object({\n dsl: z.string().optional(),\n generated_dir: z.string().optional(),\n plugins: z.array(z.string()).optional(),\n bindings: z.array(z.string()).optional(),\n}).strict();\n\nexport const ProjectConfigSchema = z.object({\n dsl: z.string().optional(),\n generated_dir: z.string().optional(),\n bindings: z.array(z.string()).optional(),\n active_guardrail_policy: z.string().optional(),\n templates_dir: z.string().optional(),\n plugins: z.array(z.string()).optional(),\n recovery: RecoverySchema,\n model_mapping: ModelMappingSchema,\n logging: LoggingSchema,\n cli: z.record(z.string(), CliSectionSchema).optional(),\n});\n\nexport type ProjectConfig = z.infer<typeof ProjectConfigSchema>;\n\nexport interface ResolvedProgressLog {\n destination: \"stderr\" | \"file\" | \"both\" | \"none\";\n file: string | undefined;\n naming: \"single\" | \"per-invocation\" | \"daily\";\n}\n\nexport interface ResolvedConfig extends RuntimeConfig {\n configDir: string;\n dslPath: string;\n generatedDir: string;\n bindingPaths: string[];\n templatesDir: string | undefined;\n pluginPaths: string[];\n resolvedLogging: { progressLog: ResolvedProgressLog };\n}\n\nfunction resolveConfigFilePath(configPath: string): string {\n const absPath = resolve(configPath);\n if (existsSync(absPath)) {\n return absPath;\n }\n\n const dir = dirname(absPath);\n const base = basename(absPath);\n if (base === \"agents.conf.yaml\") {\n const legacyPath = join(dir, LEGACY_CONFIG_FILENAME);\n if (existsSync(legacyPath)) {\n return legacyPath;\n }\n }\n\n return absPath;\n}\n\nfunction buildResolvedConfig(config: RuntimeConfig, configDir: string): ResolvedConfig {\n const pl = config.logging.progress_log;\n\n return {\n ...config,\n configDir,\n dslPath: resolve(configDir, config.dsl),\n generatedDir: resolve(configDir, config.generated_dir),\n bindingPaths: config.bindings.map((b) => resolve(configDir, b)),\n templatesDir: config.templates_dir\n ? resolve(configDir, config.templates_dir)\n : undefined,\n pluginPaths: config.plugins,\n resolvedLogging: {\n progressLog: {\n destination: pl.destination,\n file: pl.file ? resolve(configDir, pl.file) : undefined,\n naming: pl.naming,\n },\n },\n };\n}\n\nexport async function loadConfig(configPath: string): Promise<ResolvedConfig> {\n const absPath = resolveConfigFilePath(configPath);\n const raw = await readFile(absPath, \"utf8\");\n const parsed = YAML.parse(raw);\n const config = RuntimeConfigSchema.parse(parsed);\n const configDir = dirname(absPath);\n\n return buildResolvedConfig(config, configDir);\n}\n\nexport async function loadProjectConfig(\n configPath: string,\n cliName?: string,\n): Promise<ResolvedConfig> {\n const absPath = resolveConfigFilePath(configPath);\n const raw = await readFile(absPath, \"utf8\");\n const parsed = YAML.parse(raw);\n const projectConfig = ProjectConfigSchema.parse(parsed);\n\n const { cli: _cli, ...baseConfig } = projectConfig;\n let merged = { ...baseConfig };\n\n if (cliName && projectConfig.cli?.[cliName]) {\n merged = { ...merged, ...projectConfig.cli[cliName] };\n }\n\n const config = RuntimeConfigSchema.parse(merged);\n const configDir = dirname(absPath);\n\n return buildResolvedConfig(config, configDir);\n}\n","/**\n * Handlebars template engine with custom helpers for TypeScript code generation\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport Handlebars from \"handlebars\";\n\nimport { existsSync } from \"node:fs\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\n\nfunction findPackageRoot(): string {\n let dir = __dirname;\n for (let i = 0; i < 5; i++) {\n if (existsSync(join(dir, \"package.json\"))) return dir;\n dir = resolve(dir, \"..\");\n }\n return resolve(__dirname, \"..\");\n}\n\nconst BUILTIN_TEMPLATES_DIR = join(findPackageRoot(), \"templates\");\n\nfunction toCamelCase(str: string): string {\n return str.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());\n}\n\nfunction toPascalCase(str: string): string {\n const camel = toCamelCase(str);\n return camel.charAt(0).toUpperCase() + camel.slice(1);\n}\n\nconst hbs = Handlebars.create();\n\nhbs.registerHelper(\"camelCase\", (str: string) => toCamelCase(str));\nhbs.registerHelper(\"PascalCase\", (str: string) => toPascalCase(str));\n\nhbs.registerHelper(\"eq\", (a: unknown, b: unknown) => a === b);\nhbs.registerHelper(\"notEmpty\", (arr: unknown) =>\n Array.isArray(arr) ? arr.length > 0 : !!arr,\n);\n\nhbs.registerHelper(\"json\", (value: unknown) =>\n new Handlebars.SafeString(JSON.stringify(value, null, 2)),\n);\n\nhbs.registerHelper(\"hasDependsOn\", (step: Record<string, unknown>) =>\n \"depends_on\" in step && Array.isArray(step.depends_on),\n);\n\nhbs.registerHelper(\"jsonInline\", (value: unknown) =>\n new Handlebars.SafeString(JSON.stringify(value)),\n);\n\nhbs.registerHelper(\"indent\", (text: string, spaces: number) => {\n if (typeof text !== \"string\") return text;\n const pad = \" \".repeat(spaces);\n return text\n .split(\"\\n\")\n .map((line, i) => (i === 0 ? line : pad + line))\n .join(\"\\n\");\n});\n\n/** Escape a JSON Schema pattern for safe inclusion in a JS regex literal (/.../). */\nfunction escapeRegexPatternForSource(pattern: string): string {\n return pattern.replace(/\\\\/g, \"\\\\\\\\\").replace(/\\//g, \"\\\\/\");\n}\n\nfunction appendStringValidations(base: string, schema: Record<string, unknown>): string {\n let result = base;\n if (schema.minLength !== undefined) result += `.min(${schema.minLength})`;\n if (schema.maxLength !== undefined) result += `.max(${schema.maxLength})`;\n if (schema.pattern !== undefined) {\n const escaped = escapeRegexPatternForSource(schema.pattern as string);\n result += `.regex(/${escaped}/)`;\n }\n return result;\n}\n\nfunction appendNumberValidations(\n base: string,\n schema: Record<string, unknown>,\n isInteger: boolean,\n): string {\n let result = base;\n if (isInteger) result += \".int()\";\n if (schema.minimum !== undefined) result += `.min(${schema.minimum})`;\n if (schema.maximum !== undefined) result += `.max(${schema.maximum})`;\n return result;\n}\n\nfunction appendArrayValidations(base: string, schema: Record<string, unknown>): string {\n let result = base;\n if (schema.minItems !== undefined) result += `.min(${schema.minItems})`;\n if (schema.maxItems !== undefined) result += `.max(${schema.maxItems})`;\n return result;\n}\n\nhbs.registerHelper(\"zodType\", function zodType(schema: Record<string, unknown>): string {\n if (!schema || typeof schema !== \"object\") return \"z.unknown()\";\n\n if (schema.enum) {\n const vals = (schema.enum as string[]).map((v) => `\"${v}\"`).join(\", \");\n return `z.enum([${vals}])`;\n }\n\n if (schema.const !== undefined) {\n return `z.literal(${JSON.stringify(schema.const)})`;\n }\n\n const type = schema.type as string | undefined;\n\n if (type === \"string\") return appendStringValidations(\"z.string()\", schema);\n if (type === \"integer\") return appendNumberValidations(\"z.number()\", schema, true);\n if (type === \"number\") return appendNumberValidations(\"z.number()\", schema, false);\n if (type === \"boolean\") return \"z.boolean()\";\n\n if (type === \"array\") {\n const items = schema.items as Record<string, unknown> | undefined;\n const inner = items ? zodType(items) : \"z.unknown()\";\n return appendArrayValidations(`z.array(${inner})`, schema);\n }\n\n if (type === \"object\") {\n const props = schema.properties as Record<string, Record<string, unknown>> | undefined;\n if (!props) return \"z.record(z.string(), z.unknown())\";\n\n const required = (schema.required as string[]) ?? [];\n const fields = Object.entries(props)\n .map(([key, val]) => {\n const base = zodType(val);\n const opt = required.includes(key) ? \"\" : \".optional()\";\n const safeKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : `\"${key}\"`;\n return ` ${safeKey}: ${base}${opt},`;\n })\n .join(\"\\n\");\n return `z.object({\\n${fields}\\n})`;\n }\n\n if (schema.allOf) {\n const parts = (schema.allOf as Record<string, unknown>[]).map(zodType);\n if (parts.length === 1) return parts[0];\n return parts.reduce((acc, part) => `${acc}.extend(${part}.shape)`);\n }\n\n return \"z.unknown()\";\n});\n\nhbs.registerHelper(\"regexEscape\", (str: string) => {\n if (typeof str !== \"string\") return str;\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n});\n\nhbs.registerHelper(\"stringArray\", (arr: unknown) => {\n if (!Array.isArray(arr)) return \"[]\";\n return \"[\" + arr.map((s) => `\"${s}\"`).join(\", \") + \"]\";\n});\n\n/**\n * Load a template by name, with custom dir override fallback to built-in.\n */\nasync function loadTemplate(\n name: string,\n customDir?: string,\n): Promise<string> {\n if (customDir) {\n try {\n return await readFile(join(customDir, name), \"utf8\");\n } catch {\n // fallback to built-in\n }\n }\n return readFile(join(BUILTIN_TEMPLATES_DIR, name), \"utf8\");\n}\n\nexport async function renderTemplate(\n name: string,\n context: Record<string, unknown>,\n customDir?: string,\n): Promise<string> {\n const source = await loadTemplate(name, customDir);\n const compiled = hbs.compile(source, { noEscape: true });\n return compiled(context);\n}\n\nexport { hbs, toCamelCase, toPascalCase };\n","/**\n * Build template contexts from resolved DSL data\n */\n\nimport { toCamelCase, toPascalCase } from \"./template-engine.js\";\n\nexport interface AgentEntry {\n id: string;\n varName: string;\n role_name: string;\n purpose: string;\n mode: string;\n dispatch_only: boolean;\n can_read_artifacts: string[];\n can_write_artifacts: string[];\n can_execute_tools: string[];\n can_invoke_agents: string[];\n can_return_handoffs: string[];\n responsibilities: string[];\n constraints: string[];\n rules: Array<{ id: string; description: string; severity: string }>;\n escalation_criteria: Array<{ condition: string; action: string }>;\n}\n\nexport interface TaskEntry {\n id: string;\n varName: string;\n description: string;\n target_agent: string;\n allowed_from_agents: string[];\n workflow: string;\n invocation_handoff: string;\n result_handoff: string;\n input_artifacts: string[];\n responsibilities: string[];\n completion_criteria: string[];\n optional: boolean;\n model_class?: string;\n}\n\nexport interface WorkflowStepEntry {\n type: string;\n task?: string;\n from_agent?: string;\n description?: string;\n optional?: boolean;\n max_retries?: number;\n max_follow_ups?: number;\n depends_on?: string[];\n gate_kind?: string;\n retry?: { condition: string; fix_task: string; revalidate_task?: string };\n}\n\nexport interface WorkflowEntry {\n id: string;\n varName: string;\n description: string;\n trigger: string;\n entry_conditions: string[];\n steps: WorkflowStepEntry[];\n}\n\nexport interface HandoffEntry {\n id: string;\n varName: string;\n pascalName: string;\n schemaName: string;\n description: string;\n schema: Record<string, unknown>;\n}\n\nexport interface ContractContext {\n agentEntries: AgentEntry[];\n taskEntries: TaskEntry[];\n workflowEntries: WorkflowEntry[];\n handoffEntries: HandoffEntry[];\n}\n\n/**\n * Determine if a task is optional by checking if any workflow step referencing it is optional.\n */\nfunction isTaskOptional(\n taskId: string,\n workflows: Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>,\n): boolean {\n for (const wf of Object.values(workflows)) {\n for (const step of wf.steps) {\n if (step.type === \"delegate\" && step.task === taskId && step.optional) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Compute max_retries from workflow step or fallback to 0.\n */\nfunction getMaxRetries(\n taskId: string,\n workflows: Record<string, { steps: Array<Record<string, unknown>> }>,\n): number {\n for (const wf of Object.values(workflows)) {\n for (const step of wf.steps) {\n if (step.type === \"delegate\" && step.task === taskId) {\n const retry = step.retry as { condition: string } | undefined;\n return retry ? 1 : 0;\n }\n }\n }\n return 0;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function buildContractContext(dsl: any): ContractContext {\n const agents = (dsl.agents ?? {}) as Record<string, Record<string, unknown>>;\n const tasks = (dsl.tasks ?? {}) as Record<string, Record<string, unknown>>;\n const workflows = (dsl.workflow ?? {}) as Record<string, Record<string, unknown>>;\n const handoffTypes = (dsl.handoff_types ?? {}) as Record<string, Record<string, unknown>>;\n\n const agentEntries: AgentEntry[] = Object.entries(agents).map(([id, agent]) => ({\n id,\n varName: toCamelCase(id),\n role_name: (agent.role_name as string) ?? id,\n purpose: (agent.purpose as string) ?? \"\",\n mode: (agent.mode as string) ?? \"read-write\",\n dispatch_only: (agent.dispatch_only as boolean) ?? false,\n can_read_artifacts: (agent.can_read_artifacts as string[]) ?? [],\n can_write_artifacts: (agent.can_write_artifacts as string[]) ?? [],\n can_execute_tools: (agent.can_execute_tools as string[]) ?? [],\n can_invoke_agents: (agent.can_invoke_agents as string[]) ?? [],\n can_return_handoffs: (agent.can_return_handoffs as string[]) ?? [],\n responsibilities: (agent.responsibilities as string[]) ?? [],\n constraints: (agent.constraints as string[]) ?? [],\n rules: (agent.rules as AgentEntry[\"rules\"]) ?? [],\n escalation_criteria: (agent.escalation_criteria as AgentEntry[\"escalation_criteria\"]) ?? [],\n }));\n\n const taskEntries: TaskEntry[] = Object.entries(tasks).map(([id, task]) => ({\n id,\n varName: toCamelCase(id),\n description: (task.description as string) ?? \"\",\n target_agent: (task.target_agent as string) ?? \"\",\n allowed_from_agents: (task.allowed_from_agents as string[]) ?? [],\n workflow: (task.workflow as string) ?? \"\",\n invocation_handoff: (task.invocation_handoff as string) ?? \"\",\n result_handoff: (task.result_handoff as string) ?? \"\",\n input_artifacts: (task.input_artifacts as string[]) ?? [],\n responsibilities: (task.responsibilities as string[]) ?? [],\n completion_criteria: (task.completion_criteria as string[]) ?? [],\n optional: isTaskOptional(id, workflows as Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>),\n ...(task.model_class ? { model_class: task.model_class as string } : {}),\n }));\n\n const workflowEntries: WorkflowEntry[] = Object.entries(workflows).map(\n ([id, wf]) => {\n const steps = ((wf.steps as Array<Record<string, unknown>>) ?? []).map((step) => {\n const entry: WorkflowStepEntry = { type: step.type as string };\n if (step.type === \"delegate\") {\n entry.task = step.task as string;\n entry.from_agent = step.from_agent as string;\n entry.description = (step.description as string | undefined) ?? \"\";\n const wfStep = step as Record<string, unknown>;\n entry.optional = isTaskOptional(\n step.task as string,\n workflows as Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>,\n );\n entry.max_retries = (wfStep.max_retries as number | undefined) ?? (wfStep.retry ? 1 : 0);\n entry.max_follow_ups = wfStep.max_follow_ups as number | undefined;\n if (wfStep.depends_on !== undefined) {\n entry.depends_on = wfStep.depends_on as string[];\n }\n if (wfStep.retry) {\n const r = wfStep.retry as Record<string, unknown>;\n entry.retry = {\n condition: r.condition as string,\n fix_task: r.fix_task as string,\n revalidate_task: r.revalidate_task as string | undefined,\n };\n }\n } else if (step.type === \"gate\") {\n entry.gate_kind = step.gate_kind as string;\n entry.description = (step.description as string | undefined) ?? \"\";\n if (step.depends_on !== undefined) {\n entry.depends_on = step.depends_on as string[];\n }\n }\n return entry;\n });\n\n return {\n id,\n varName: toCamelCase(id),\n description: (wf.description as string) ?? \"\",\n trigger: (wf.trigger as string) ?? \"\",\n entry_conditions: (wf.entry_conditions as string[]) ?? [],\n steps,\n };\n },\n );\n\n const handoffEntries: HandoffEntry[] = Object.entries(handoffTypes).map(\n ([id, ht]) => ({\n id,\n varName: toCamelCase(id),\n pascalName: toPascalCase(id),\n schemaName: toPascalCase(id) + \"Schema\",\n description: (ht.description as string) ?? \"\",\n schema: (ht.schema as Record<string, unknown>) ?? {},\n }),\n );\n\n return { agentEntries, taskEntries, workflowEntries, handoffEntries };\n}\n\nexport interface GuardrailCheckEntry {\n guardrail_id: string;\n description: string;\n severity: string;\n action: string;\n matcher_type: string;\n pattern: string;\n message: string;\n file_glob?: string;\n exclude_glob?: string;\n}\n\nexport interface GuardrailContext {\n commandChecks: GuardrailCheckEntry[];\n fileChecks: GuardrailCheckEntry[];\n contentChecks: GuardrailCheckEntry[];\n allChecks: GuardrailCheckEntry[];\n hasGuardrails: boolean;\n}\n\n/**\n * Build guardrail context from DSL guardrails, binding guardrail_impl, and active policy.\n * Mirrors the agent-contracts resolveChecks pattern.\n */\nexport function buildGuardrailContext(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n dsl: any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n binding: any,\n policyName?: string,\n): GuardrailContext {\n const empty: GuardrailContext = {\n commandChecks: [],\n fileChecks: [],\n contentChecks: [],\n allChecks: [],\n hasGuardrails: false,\n };\n\n if (!binding?.guardrail_impl) return empty;\n\n const guardrails = dsl.guardrails ?? {};\n const policies = dsl.guardrail_policies ?? {};\n const policy = policyName ? policies[policyName] : undefined;\n\n const allChecks: GuardrailCheckEntry[] = [];\n\n for (const [guardrailId, impl] of Object.entries(\n binding.guardrail_impl as Record<string, { checks: Array<Record<string, unknown>> }>,\n )) {\n const guardrail = guardrails[guardrailId] as Record<string, unknown> | undefined;\n const description = (guardrail?.description as string) ?? guardrailId;\n\n const policyRule = policy?.rules?.find(\n (r: Record<string, unknown>) => r.guardrail === guardrailId,\n );\n const severity = (policyRule?.severity as string) ?? \"warning\";\n const action = (policyRule?.action as string) ?? \"warn\";\n\n for (const check of impl.checks) {\n const matcher = check.matcher as Record<string, unknown> | undefined;\n if (!matcher) continue;\n\n allChecks.push({\n guardrail_id: guardrailId,\n description,\n severity,\n action,\n matcher_type: matcher.type as string,\n pattern: matcher.pattern as string,\n message: (check.message as string) ?? description,\n file_glob: matcher.file_glob as string | undefined,\n exclude_glob: matcher.exclude_glob as string | undefined,\n });\n }\n }\n\n return {\n commandChecks: allChecks.filter((c) => c.matcher_type === \"command_regex\"),\n fileChecks: allChecks.filter((c) => c.matcher_type === \"file_glob\"),\n contentChecks: allChecks.filter((c) => c.matcher_type === \"content_regex\"),\n allChecks,\n hasGuardrails: allChecks.length > 0,\n };\n}\n"],"mappings":";AAIA,SAAS,YAAAA,WAAU,WAAW,OAAO,UAAgB;AACrD,SAAS,WAAAC,UAAS,QAAAC,OAAM,gBAAgB;AACxC,SAAS,kBAAkB;AAC3B,OAAOC,WAAU;;;ACHjB,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AACzB,SAAS,SAAS,SAAS,MAAM,gBAAgB;AACjD,SAAS,SAAS;AAClB,OAAO,UAAU;AAEV,IAAM,sBAAsB;AAC5B,IAAM,yBAAyB;AAEtC,IAAM,iBAAiB,EAAE,OAAO;AAAA,EAC9B,gBAAgB,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC;AAAA,EACjD,aAAa,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC;AAChD,CAAC,EAAE,QAAQ,OAAO,EAAE,gBAAgB,GAAG,aAAa,EAAE,EAAE;AAExD,IAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,SAAS,EAAE,OAAO;AAAA,EAClB,OAAO,EAAE,OAAO,EAAE,SAAS;AAC7B,CAAC;AAED,IAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,MAAM,sBAAsB,SAAS;AAAA,EACrC,UAAU,sBAAsB,SAAS;AAAA,EACzC,UAAU,sBAAsB,SAAS;AAC3C,CAAC,EAAE,QAAQ,CAAC,CAAC;AAEb,IAAM,oBAAoB,EAAE,OAAO;AAAA,EACjC,aAAa,EAAE,KAAK,CAAC,UAAU,QAAQ,QAAQ,MAAM,CAAC,EAAE,QAAQ,QAAQ;AAAA,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