@aaac/runtime 0.1.15 → 0.1.17

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.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getBlockingViolations
3
- } from "../chunk-MGRZBGQL.js";
3
+ } from "../chunk-GZCEEIXQ.js";
4
4
  import {
5
5
  buildAdkFunctionTools
6
6
  } from "../chunk-LONLL3K2.js";
@@ -240,17 +240,23 @@ function createGuardrailHooksForAgent(agentId, perAgent) {
240
240
  }
241
241
  };
242
242
  }
243
+ function compileGuardrailPattern(pattern) {
244
+ if (pattern.startsWith("(?i)")) {
245
+ return new RegExp(pattern.slice(4), "i");
246
+ }
247
+ return new RegExp(pattern);
248
+ }
243
249
  function createGuardrailHooksFromRules(rules) {
244
250
  const commandChecks = rules.commandRules.map((rule) => ({
245
251
  guardrail_id: rule.guardrail_id,
246
- pattern: new RegExp(rule.pattern),
252
+ pattern: compileGuardrailPattern(rule.pattern),
247
253
  action: rule.action,
248
254
  message: rule.message
249
255
  }));
250
256
  const fileChecks = rules.fileRules;
251
257
  const contentChecks = rules.contentRules.map((rule) => ({
252
258
  guardrail_id: rule.guardrail_id,
253
- pattern: new RegExp(rule.pattern),
259
+ pattern: compileGuardrailPattern(rule.pattern),
254
260
  action: rule.action,
255
261
  message: rule.message,
256
262
  file_glob: rule.file_glob,
@@ -318,4 +324,4 @@ export {
318
324
  createGuardrailHooksForAgent,
319
325
  createGuardrailHooksFromRules
320
326
  };
321
- //# sourceMappingURL=chunk-MGRZBGQL.js.map
327
+ //# sourceMappingURL=chunk-GZCEEIXQ.js.map
@@ -1 +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 /** Agent id for per-agent guardrail filtering. */\n agentId?: string;\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 */\n/**\n * Create SDK hooks scoped to a single agent from a per-agent guardrail map.\n * Returns empty-passing hooks when the agent has no rules in the map.\n */\nexport function createGuardrailHooksForAgent(\n agentId: string,\n perAgent: Map<string, GuardrailRuleData>,\n): GuardrailHooks {\n const rules = perAgent.get(agentId);\n if (!rules) {\n return createGuardrailHooks({\n checkCommand: () => [],\n checkFilePath: () => [],\n checkContent: () => [],\n });\n }\n const hooks = createGuardrailHooksFromRules(rules);\n const baseRunChecks = hooks.runChecks;\n return {\n ...hooks,\n runChecks(ctx: HookContext) {\n return baseRunChecks({ ...ctx, agentId });\n },\n };\n}\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;AAA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AAU,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
+ {"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 /** Agent id for per-agent guardrail filtering. */\n agentId?: string;\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 */\n/**\n * Create SDK hooks scoped to a single agent from a per-agent guardrail map.\n * Returns empty-passing hooks when the agent has no rules in the map.\n */\nexport function createGuardrailHooksForAgent(\n agentId: string,\n perAgent: Map<string, GuardrailRuleData>,\n): GuardrailHooks {\n const rules = perAgent.get(agentId);\n if (!rules) {\n return createGuardrailHooks({\n checkCommand: () => [],\n checkFilePath: () => [],\n checkContent: () => [],\n });\n }\n const hooks = createGuardrailHooksFromRules(rules);\n const baseRunChecks = hooks.runChecks;\n return {\n ...hooks,\n runChecks(ctx: HookContext) {\n return baseRunChecks({ ...ctx, agentId });\n },\n };\n}\n\n/** Compile a guardrail regex pattern, supporting inline `(?i)` case-insensitivity prefix. */\nexport function compileGuardrailPattern(pattern: string): RegExp {\n if (pattern.startsWith(\"(?i)\")) {\n return new RegExp(pattern.slice(4), \"i\");\n }\n return new RegExp(pattern);\n}\n\nexport function createGuardrailHooksFromRules(rules: GuardrailRuleData): GuardrailHooks {\n const commandChecks = rules.commandRules.map((rule) => ({\n guardrail_id: rule.guardrail_id,\n pattern: compileGuardrailPattern(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: compileGuardrailPattern(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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;AAC1C,gBAAQ,KAAK;AAAA,UACX,cAAc,MAAM;AAAA,UACpB;AAAA,UACA,QAAQ,MAAM;AAAA,UACd,SAAS,SAAS,KAAK,MAAM;AAAA,QAC/B,CAAC;AAAA,MACH;AACA,aAAO;AAAA,IACT;AAAA,IAEA,cAAc,UAA0C;AACtD,YAAM,UAAkC,CAAC;AACzC,iBAAW,SAAS,YAAY;AAC9B,YAAI,MAAM,gBAAgB,UAAU,MAAM,cAAc,QAAQ,GAAG;AACjE;AAAA,QACF;AACA,cAAM,UAAU,UAAU,MAAM,SAAS,QAAQ;AACjD,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,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/index.d.ts CHANGED
@@ -745,6 +745,48 @@ interface GuardStatusResult {
745
745
  */
746
746
  declare function guardStatus(opts?: GuardStatusOptions): Promise<GuardStatusResult>;
747
747
 
748
+ /**
749
+ * Prompt Executor — natural language routing via LLM tool selection.
750
+ *
751
+ * Converts component operations into tool descriptions, sends them to an LLM
752
+ * for routing, and dispatches the selected operation through the existing
753
+ * component binding.
754
+ */
755
+
756
+ interface OperationToolDef {
757
+ name: string;
758
+ description: string;
759
+ inputSchema: Record<string, unknown>;
760
+ }
761
+ interface PromptResult {
762
+ selectedOperation: string;
763
+ mappedInput: Record<string, unknown>;
764
+ output?: unknown;
765
+ dryRun?: boolean;
766
+ model?: string;
767
+ }
768
+ interface PromptExecuteOptions {
769
+ dryRun?: boolean;
770
+ adapter: string;
771
+ model?: string;
772
+ }
773
+ /**
774
+ * Convert non-handler, non-prompt operations from ComponentIR into tool definitions
775
+ * for LLM routing.
776
+ */
777
+ declare function operationsToTools(ir: ComponentIR): OperationToolDef[];
778
+ /**
779
+ * Parse the LLM router response to extract selected operation and mapped input.
780
+ */
781
+ declare function parseRouterResponse(response: string, validNames: string[]): {
782
+ selectedOperation: string;
783
+ mappedInput: Record<string, unknown>;
784
+ };
785
+ /**
786
+ * Execute a natural language prompt by routing to the appropriate operation.
787
+ */
788
+ declare function executePrompt(message: string, ir: ComponentIR, binding: RuntimeBinding, ctx: AaacInvocationContext, opts: PromptExecuteOptions): Promise<PromptResult>;
789
+
748
790
  /**
749
791
  * @aaac/runtime — public API
750
792
  *
@@ -753,4 +795,4 @@ declare function guardStatus(opts?: GuardStatusOptions): Promise<GuardStatusResu
753
795
  /** Package version string. */
754
796
  declare const version: string;
755
797
 
756
- export { type AaacInvocationContext, type AaacObserver, type AaacPolicy, type AaacRuntime, AgentContractLike, AgentLogWriter, type AgentLogWriterOptions, type AgentPlugin, ArtifactBindingConfig, type ArtifactResolveOptions, type ArtifactResolveResult, type ComponentScope, type CreateAdapterOptions, type CreateComponentScopeOptions, type CreateProjectRuntimeOptions, DelegateStep, type DslContext, DslValidationError, type EvaluateGuardrailOptions, type EvaluateGuardrailResult, type ExecuteOptions, type ExecuteTaskOptions, type ExecuteWorkflowOptions, FileMemoryStore, type GuardStatusOptions, type GuardStatusResult, GuardrailCheckResult, GuardrailHooks, type GuardrailListEntry, type GuardrailResult, GuardrailRuleData, HandoffInput, HookResponse, LibraryToolDefinition, LibraryToolRegistry, type ListGuardrailsOptions, type ListGuardrailsResult, type LoadDslOptions, MemoryRef, MemoryStore, type MemoryStoreEntry, type NavigationContext, type NavigationContextOptions, ObserverEmitFn, type OperationHandler, type OperationMemoryRefConfig, PROJECT_CONFIG_FILENAME, type PermissionMode, type PluginLoadResult, PluginRegistry, type ProcessEditOptions, type ProcessTaskOptions, type ProcessWorkflowOptions, type ProgressSink, type ProgressSinkOptions, type ProjectRuntime, type PromptBuilderArgs, PromptBuilderOptions, type RequiredEntities, type ResolvedAdapterSelection, ResolvedComponent, ResolvedToolchain, type RunLogEvent, type Runtime, type RuntimeBinding, type RuntimeConfig, SdkAdapter, type SdkFunctionTool, StepCompleteEvent, StepResult, TaskContext, TaskContractLike, type TaskHookContext, TaskOutcome, TaskRunResult, WorkflowBuilder, type WorkflowHookContext, WorkflowRegistries, WorkflowResult, buildGuardrailRulesFromDsl, buildNavigationContext, buildRegistriesFromDsl, buildSdkFunctionTools, createAdapter, createComponentScope, createProgressSink, createProjectRuntime, createRuntime, createRuntimeBinding, emitProcessEdit, emitProcessTaskClose, emitProcessTaskOpen, emitProcessWorkflowClose, emitProcessWorkflowOpen, evaluateGuardrail, executeTask, executeWorkflow, findProjectConfig, guardStatus, jsonSchemaToZod, listGuardrails, loadDslContext, loadPlugins, loadPluginsFromDirectory, loadPluginsFromPaths, pluginRegistry, resolveArtifacts, version };
798
+ export { type AaacInvocationContext, type AaacObserver, type AaacPolicy, type AaacRuntime, AgentContractLike, AgentLogWriter, type AgentLogWriterOptions, type AgentPlugin, ArtifactBindingConfig, type ArtifactResolveOptions, type ArtifactResolveResult, type ComponentScope, type CreateAdapterOptions, type CreateComponentScopeOptions, type CreateProjectRuntimeOptions, DelegateStep, type DslContext, DslValidationError, type EvaluateGuardrailOptions, type EvaluateGuardrailResult, type ExecuteOptions, type ExecuteTaskOptions, type ExecuteWorkflowOptions, FileMemoryStore, type GuardStatusOptions, type GuardStatusResult, GuardrailCheckResult, GuardrailHooks, type GuardrailListEntry, type GuardrailResult, GuardrailRuleData, HandoffInput, HookResponse, LibraryToolDefinition, LibraryToolRegistry, type ListGuardrailsOptions, type ListGuardrailsResult, type LoadDslOptions, MemoryRef, MemoryStore, type MemoryStoreEntry, type NavigationContext, type NavigationContextOptions, ObserverEmitFn, type OperationHandler, type OperationMemoryRefConfig, type OperationToolDef, PROJECT_CONFIG_FILENAME, type PermissionMode, type PluginLoadResult, PluginRegistry, type ProcessEditOptions, type ProcessTaskOptions, type ProcessWorkflowOptions, type ProgressSink, type ProgressSinkOptions, type ProjectRuntime, type PromptBuilderArgs, PromptBuilderOptions, type PromptExecuteOptions, type PromptResult, type RequiredEntities, type ResolvedAdapterSelection, ResolvedComponent, ResolvedToolchain, type RunLogEvent, type Runtime, type RuntimeBinding, type RuntimeConfig, SdkAdapter, type SdkFunctionTool, StepCompleteEvent, StepResult, TaskContext, TaskContractLike, type TaskHookContext, TaskOutcome, TaskRunResult, WorkflowBuilder, type WorkflowHookContext, WorkflowRegistries, WorkflowResult, buildGuardrailRulesFromDsl, buildNavigationContext, buildRegistriesFromDsl, buildSdkFunctionTools, createAdapter, createComponentScope, createProgressSink, createProjectRuntime, createRuntime, createRuntimeBinding, emitProcessEdit, emitProcessTaskClose, emitProcessTaskOpen, emitProcessWorkflowClose, emitProcessWorkflowOpen, evaluateGuardrail, executePrompt, executeTask, executeWorkflow, findProjectConfig, guardStatus, jsonSchemaToZod, listGuardrails, loadDslContext, loadPlugins, loadPluginsFromDirectory, loadPluginsFromPaths, operationsToTools, parseRouterResponse, pluginRegistry, resolveArtifacts, version };
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  getWarnings,
8
8
  hasBlockingViolation,
9
9
  pluginRegistry
10
- } from "./chunk-MGRZBGQL.js";
10
+ } from "./chunk-GZCEEIXQ.js";
11
11
  import {
12
12
  buildSdkFunctionTools
13
13
  } from "./chunk-LONLL3K2.js";
@@ -3154,6 +3154,119 @@ async function guardStatus(opts = {}) {
3154
3154
  };
3155
3155
  }
3156
3156
 
3157
+ // src/lib/prompt-executor.ts
3158
+ import * as YAML5 from "yaml";
3159
+ function unwrapInputSchema(input) {
3160
+ if (!input) {
3161
+ return { type: "object", properties: {} };
3162
+ }
3163
+ if ("schema" in input && input.schema && typeof input.schema === "object") {
3164
+ return input.schema;
3165
+ }
3166
+ if ("$ref" in input) {
3167
+ return { type: "object", properties: {} };
3168
+ }
3169
+ return input;
3170
+ }
3171
+ function operationsToTools(ir) {
3172
+ return Object.entries(ir.operations).filter(([name, op]) => name !== "prompt" && !op.handler).map(([name, op]) => ({
3173
+ name,
3174
+ description: op.description,
3175
+ inputSchema: unwrapInputSchema(op.input)
3176
+ }));
3177
+ }
3178
+ function buildRouterPrompt(componentId, tools, message) {
3179
+ const toolDescriptions = tools.map((t) => {
3180
+ const schema = JSON.stringify(t.inputSchema, null, 2);
3181
+ return `### ${t.name}
3182
+ ${t.description}
3183
+ Input schema:
3184
+ \`\`\`json
3185
+ ${schema}
3186
+ \`\`\``;
3187
+ }).join("\n\n");
3188
+ return [
3189
+ `You are an operation router for the "${componentId}" CLI.`,
3190
+ `Understand the user request and call the appropriate operation.`,
3191
+ `Always select exactly one operation. Extract parameters from the user message.`,
3192
+ ``,
3193
+ `## Available Operations`,
3194
+ ``,
3195
+ toolDescriptions,
3196
+ ``,
3197
+ `## Response Format`,
3198
+ ``,
3199
+ `Respond with ONLY the following YAML:`,
3200
+ ``,
3201
+ "```yaml",
3202
+ `operation: <operation_name>`,
3203
+ `input:`,
3204
+ ` <key>: <value>`,
3205
+ "```",
3206
+ ``,
3207
+ `## User Request`,
3208
+ ``,
3209
+ message
3210
+ ].join("\n");
3211
+ }
3212
+ function parseRouterResponse(response, validNames) {
3213
+ const yamlMatch = response.match(/```(?:yaml)?\n([\s\S]*?)```/);
3214
+ const content = yamlMatch ? yamlMatch[1].trim() : response.trim();
3215
+ let parsed;
3216
+ try {
3217
+ parsed = YAML5.parse(content);
3218
+ } catch {
3219
+ const jsonMatch = response.match(/\{[\s\S]*"operation"[\s\S]*\}/);
3220
+ if (jsonMatch) {
3221
+ try {
3222
+ parsed = JSON.parse(jsonMatch[0]);
3223
+ } catch {
3224
+ }
3225
+ }
3226
+ }
3227
+ if (parsed?.operation && typeof parsed.operation === "string") {
3228
+ if (!validNames.includes(parsed.operation)) {
3229
+ throw new Error(
3230
+ `Router selected unknown operation "${parsed.operation}". Available: ${validNames.join(", ")}`
3231
+ );
3232
+ }
3233
+ return {
3234
+ selectedOperation: parsed.operation,
3235
+ mappedInput: parsed.input ?? {}
3236
+ };
3237
+ }
3238
+ throw new Error(
3239
+ `Could not parse operation routing from LLM response. Expected YAML with "operation" and "input" fields.
3240
+ Response:
3241
+ ${response.slice(0, 500)}`
3242
+ );
3243
+ }
3244
+ async function executePrompt(message, ir, binding, ctx, opts) {
3245
+ const tools = operationsToTools(ir);
3246
+ if (tools.length < 2) {
3247
+ throw new Error(
3248
+ `prompt command requires at least 2 routable operations, found ${tools.length}`
3249
+ );
3250
+ }
3251
+ const prompt = buildRouterPrompt(ir.info.id, tools, message);
3252
+ const adapter = await createAdapter(opts.adapter, { model: opts.model });
3253
+ const response = await adapter.send(prompt, { readonly: true });
3254
+ const { selectedOperation, mappedInput } = parseRouterResponse(
3255
+ response,
3256
+ tools.map((t) => t.name)
3257
+ );
3258
+ if (opts.dryRun) {
3259
+ return {
3260
+ selectedOperation,
3261
+ mappedInput,
3262
+ dryRun: true,
3263
+ model: opts.model
3264
+ };
3265
+ }
3266
+ const output = await binding.execute(selectedOperation, {}, mappedInput, ctx);
3267
+ return { selectedOperation, mappedInput, output };
3268
+ }
3269
+
3157
3270
  // src/index.ts
3158
3271
  var require2 = createRequire(import.meta.url);
3159
3272
  var pkg = require2("../package.json");
@@ -3205,6 +3318,7 @@ export {
3205
3318
  emitToolchainClose,
3206
3319
  emitToolchainOpen,
3207
3320
  evaluateGuardrail,
3321
+ executePrompt,
3208
3322
  executeTask,
3209
3323
  executeWorkflow,
3210
3324
  extractStructuredResult,
@@ -3222,7 +3336,9 @@ export {
3222
3336
  loadPlugins,
3223
3337
  loadPluginsFromDirectory,
3224
3338
  loadPluginsFromPaths,
3339
+ operationsToTools,
3225
3340
  parseGateEvaluationResponse,
3341
+ parseRouterResponse,
3226
3342
  pluginRegistry,
3227
3343
  renderAgentSystemPrompt,
3228
3344
  resolveArtifacts,