@open-mercato/ai-assistant 0.10.1-develop.8231.1.ae76b1d2c5 → 0.10.1-develop.8258.1.62a94b74a2

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,2 +1,2 @@
1
- [build:ai-assistant] found 252 entry points
1
+ [build:ai-assistant] found 253 entry points
2
2
  [build:ai-assistant] built successfully
@@ -1,3 +1,4 @@
1
+ import { parseModuleCliOptions } from "@open-mercato/shared/lib/cli/parseModuleCliOptions";
1
2
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
2
3
  import { resetServerLoggerCache } from "@open-mercato/shared/lib/logger";
3
4
  import { installNextSubpathResolveHook } from "./lib/next-subpath-resolve-hook.js";
@@ -18,21 +19,7 @@ async function ensureBootstrap() {
18
19
  }
19
20
  }
20
21
  function parseArgs(rest) {
21
- const args = {};
22
- for (let i = 0; i < rest.length; i++) {
23
- const arg = rest[i];
24
- if (!arg?.startsWith("--")) continue;
25
- const [key, value] = arg.replace(/^--/, "").split("=");
26
- if (value !== void 0) {
27
- args[key] = value;
28
- } else if (rest[i + 1] && !rest[i + 1].startsWith("--")) {
29
- args[key] = rest[i + 1];
30
- i++;
31
- } else {
32
- args[key] = true;
33
- }
34
- }
35
- return args;
22
+ return parseModuleCliOptions(rest);
36
23
  }
37
24
  const mcpServe = {
38
25
  command: "mcp:serve",
@@ -198,9 +185,9 @@ Registered MCP Tools (${toolNames.length}):
198
185
  byModule.set(module, list);
199
186
  }
200
187
  const sortedModules = Array.from(byModule.keys()).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
201
- for (const module of sortedModules) {
202
- const tools = byModule.get(module);
203
- console.log(`${module} (${tools.length} tools):`);
188
+ for (const moduleName of sortedModules) {
189
+ const tools = byModule.get(moduleName);
190
+ console.log(`${moduleName} (${tools.length} tools):`);
204
191
  for (const name of tools.sort((a, b) => a < b ? -1 : a > b ? 1 : 0)) {
205
192
  const tool = registry.getTool(name);
206
193
  if (!tool) continue;
@@ -224,7 +211,7 @@ const entityGraph = {
224
211
  const args = parseArgs(rest);
225
212
  const format = String(args.format ?? "triples");
226
213
  const entity = args.entity ? String(args.entity) : void 0;
227
- const module = args.module ? String(args.module) : void 0;
214
+ const moduleName = args.module ? String(args.module) : void 0;
228
215
  await ensureBootstrap();
229
216
  const { getOrm } = await import("@open-mercato/shared/lib/db/mikro");
230
217
  const { extractEntityGraph, formatGraphAsTriples, filterGraphByEntity, filterGraphByModule } = await import("./lib/entity-graph.js");
@@ -236,10 +223,10 @@ const entityGraph = {
236
223
  edges = filterGraphByEntity(graph, entity);
237
224
  console.log(`[Entity Graph] Filtered by entity: ${entity}`);
238
225
  }
239
- if (module) {
226
+ if (moduleName) {
240
227
  const filteredGraph2 = { ...graph, edges };
241
- edges = filterGraphByModule(filteredGraph2, module);
242
- console.log(`[Entity Graph] Filtered by module: ${module}`);
228
+ edges = filterGraphByModule(filteredGraph2, moduleName);
229
+ console.log(`[Entity Graph] Filtered by module: ${moduleName}`);
243
230
  }
244
231
  const filteredGraph = { ...graph, edges };
245
232
  if (format === "json") {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/ai_assistant/cli.ts"],
4
- "sourcesContent": ["import type { ModuleCli } from '@open-mercato/shared/modules/registry'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { resetServerLoggerCache } from '@open-mercato/shared/lib/logger'\nimport { installNextSubpathResolveHook } from './lib/next-subpath-resolve-hook'\nimport { resolveMcpHost } from './lib/mcp-host-resolution'\n/**\n * Ensure app bootstrap is called before creating DI container.\n * Uses the shared generated-bootstrap loader so the command works both from\n * the monorepo app and from standalone apps installed through npm packages.\n */\nasync function ensureBootstrap(): Promise<void> {\n // These commands run outside Next.js, but the API route modules the\n // operation runner imports on a tool call say `from 'next/server'`, which\n // plain Node cannot resolve (#6118). Install the retry-with-`.js` hook before\n // anything below can pull a route module in.\n installNextSubpathResolveHook()\n\n // First check if DI is already available\n try {\n const { getDiRegistrars } = await import('@open-mercato/shared/lib/di/container')\n getDiRegistrars()\n return // DI already available\n } catch {\n // DI not available, need to bootstrap\n }\n\n try {\n const { bootstrapFromAppRoot } = await import('@open-mercato/shared/lib/bootstrap/dynamicLoader')\n await bootstrapFromAppRoot()\n } catch (error) {\n console.error('[MCP] Bootstrap failed:', error instanceof Error ? error.message : error)\n // Continue - some contexts may not have bootstrap available\n }\n}\n\nfunction parseArgs(rest: string[]): Record<string, string | boolean> {\n const args: Record<string, string | boolean> = {}\n for (let i = 0; i < rest.length; i++) {\n const arg = rest[i]\n if (!arg?.startsWith('--')) continue\n\n const [key, value] = arg.replace(/^--/, '').split('=')\n if (value !== undefined) {\n args[key] = value\n } else if (rest[i + 1] && !rest[i + 1]!.startsWith('--')) {\n args[key] = rest[i + 1]!\n i++\n } else {\n args[key] = true\n }\n }\n return args\n}\n\nconst mcpServe: ModuleCli = {\n command: 'mcp:serve',\n async run(rest) {\n // stdout carries the MCP JSON-RPC protocol (StdioServerTransport) \u2014 route all\n // facade logs to stderr and rebuild any pino root created earlier in this process.\n process.env.OM_LOG_DESTINATION = 'stderr'\n resetServerLoggerCache()\n const args = parseArgs(rest)\n // Prefer the OPEN_MERCATO_API_KEY env var so the secret never has to be\n // placed on the command line (argv is world-readable via ps / /proc).\n // The --api-key flag stays supported for backward compatibility.\n const apiKey = String(args['api-key'] ?? args.apiKey ?? '') || process.env.OPEN_MERCATO_API_KEY || null\n const tenantId = String(args.tenant ?? args.tenantId ?? '') || null\n const organizationId = String(args.org ?? args.organizationId ?? '') || null\n const userId = String(args.user ?? args.userId ?? '') || null\n const debug = args.debug === true || args.debug === 'true'\n const allowUnauthenticatedSuperadmin =\n args['allow-unauthenticated-superadmin'] === true ||\n args['allow-unauthenticated-superadmin'] === 'true'\n\n // Either API key or tenant is required\n if (!apiKey && !tenantId) {\n console.error('Usage: mercato ai_assistant mcp:serve [options]')\n console.error('')\n console.error('Authentication (choose one):')\n console.error(' OPEN_MERCATO_API_KEY env API key secret (recommended \u2014 keeps the secret off argv)')\n console.error(' --api-key <secret> API key secret for authentication (visible in process listings)')\n console.error(' --tenant <id> Tenant ID (for manual context)')\n console.error('')\n console.error('Options (with --tenant):')\n console.error(' --org <id> Organization ID (optional)')\n console.error(' --user <id> User ID for ACL (required unless --allow-unauthenticated-superadmin is set)')\n console.error('')\n console.error('Common options:')\n console.error(' --debug Enable debug logging')\n console.error(' --allow-unauthenticated-superadmin')\n console.error(' DEV/TEST ONLY: run as superadmin with no per-user ACL when')\n console.error(' no --user (and no --api-key) is supplied. Never use in production.')\n console.error('')\n console.error('Examples:')\n console.error(' OPEN_MERCATO_API_KEY=omk_xxxx.yyyy... mercato ai_assistant mcp:serve')\n console.error(' mercato ai_assistant mcp:serve --api-key omk_xxxx.yyyy...')\n console.error(' mercato ai_assistant mcp:serve --tenant 123e4567-e89b-12d3-a456-426614174000 --user <user-id>')\n console.error(' mercato ai_assistant mcp:serve --tenant 123e4567-e89b-12d3-a456-426614174000 --allow-unauthenticated-superadmin')\n return\n }\n\n await ensureBootstrap()\n const container = await createRequestContainer()\n\n const { runMcpServer } = await import('./lib/mcp-server')\n\n if (apiKey) {\n await runMcpServer({\n config: {\n name: 'open-mercato-mcp',\n version: '0.1.0',\n debug,\n },\n container,\n apiKeySecret: apiKey,\n })\n } else {\n await runMcpServer({\n config: {\n name: 'open-mercato-mcp',\n version: '0.1.0',\n debug,\n },\n container,\n context: {\n tenantId,\n organizationId,\n userId,\n },\n allowUnauthenticatedSuperadmin,\n })\n }\n },\n}\n\nconst MCP_DEFAULT_PORT = 3001\n\nconst mcpServeHttp: ModuleCli = {\n command: 'mcp:serve-http',\n async run(rest) {\n const args = parseArgs(rest)\n const portArg = parseInt(String(args.port ?? ''), 10)\n const port = !portArg || isNaN(portArg) ? MCP_DEFAULT_PORT : portArg\n const debug = args.debug === true || args.debug === 'true'\n const host = resolveMcpHost(\n typeof args.host === 'string' ? args.host : undefined,\n process.env.MCP_HTTP_HOST,\n )\n\n await ensureBootstrap()\n const container = await createRequestContainer()\n\n const { runMcpHttpServer } = await import('./lib/http-server')\n\n await runMcpHttpServer({\n config: {\n name: 'open-mercato-mcp',\n version: '0.1.0',\n debug,\n },\n container,\n port,\n host,\n })\n },\n}\n\nconst mcpDev: ModuleCli = {\n command: 'mcp:dev',\n async run() {\n await ensureBootstrap()\n const { runMcpDevServer } = await import('./lib/mcp-dev-server')\n await runMcpDevServer()\n },\n}\n\nconst mcpEnsureApiKey: ModuleCli = {\n command: 'mcp:ensure-api-key',\n async run(rest) {\n const args = parseArgs(rest)\n // A bare `--file` (no value) parses to boolean true \u2014 treat it as missing\n // rather than provisioning into a file literally named \"true\".\n const fileArg = typeof args.file === 'string' ? args.file.trim() : ''\n const filePath =\n fileArg || process.env.MCP_SERVER_API_KEY_FILE?.trim() || process.env.MCP_API_KEY_FILE?.trim() || ''\n if (!filePath) {\n console.error('Usage: mercato ai_assistant mcp:ensure-api-key --file <path> [options]')\n console.error('')\n console.error('Ensures a valid MCP server API key exists in the database and that its')\n console.error('plaintext secret is stored in <path> (the idempotency anchor). The secret')\n console.error('is never printed; consumers such as the OpenCode container read the file.')\n console.error('')\n console.error('Options:')\n console.error(' --file <path> Secret file path (or MCP_SERVER_API_KEY_FILE env)')\n console.error(' --name <name> API key name (default __mcp_server__)')\n console.error(' --email <email> Owner user email (default OM_INIT_SUPERADMIN_EMAIL, then superadmin@acme.com)')\n console.error(' --rotate Force rotation even when the file secret is still valid')\n process.exitCode = 1\n return\n }\n\n const keyName = typeof args.name === 'string' && args.name.length > 0 ? args.name : undefined\n const ownerEmail = typeof args.email === 'string' && args.email.length > 0 ? args.email : undefined\n const rotate = args.rotate === true || args.rotate === 'true'\n\n await ensureBootstrap()\n const container = await createRequestContainer()\n const em = container.resolve<import('@mikro-orm/postgresql').EntityManager>('em')\n const rbac = container.resolve('rbacService') as import('@open-mercato/core/modules/auth/services/rbacService').RbacService\n\n const { ensureMcpApiKey } = await import('./lib/mcp-ensure-api-key')\n const result = await ensureMcpApiKey({ em, filePath, keyName, ownerEmail, rotate, rbac })\n const message = result.status === 'valid' ? 'Existing key is valid' : 'New key created'\n console.log(`[mcp:ensure-api-key] ${message} (id=${result.keyId}, prefix=${result.keyPrefix})`)\n },\n}\n\nconst listTools: ModuleCli = {\n command: 'mcp:list-tools',\n async run(rest) {\n const args = parseArgs(rest)\n const verbose = args.verbose === true || args.verbose === 'true'\n\n // Ensure bootstrap runs so modules are registered for API discovery\n await ensureBootstrap()\n\n const { loadAllModuleTools } = await import('./lib/tool-loader')\n await loadAllModuleTools()\n\n const { getToolRegistry } = await import('./lib/tool-registry')\n const registry = getToolRegistry()\n const toolNames = registry.listToolNames()\n\n if (toolNames.length === 0) {\n console.log('\\nNo MCP tools registered.')\n console.log('Tools can be registered by modules using registerMcpTool().\\n')\n return\n }\n\n console.log(`\\nRegistered MCP Tools (${toolNames.length}):\\n`)\n\n // Group tools by module\n const byModule = new Map<string, string[]>()\n for (const name of toolNames) {\n const [module] = name.split('.')\n const list = byModule.get(module) ?? []\n list.push(name)\n byModule.set(module, list)\n }\n\n // Sort modules alphabetically\n const sortedModules = Array.from(byModule.keys()).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))\n\n for (const module of sortedModules) {\n const tools = byModule.get(module)!\n console.log(`${module} (${tools.length} tools):`)\n\n for (const name of tools.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {\n const tool = registry.getTool(name)\n if (!tool) continue\n\n if (verbose) {\n console.log(` ${name}`)\n console.log(` ${tool.description}`)\n if (tool.requiredFeatures?.length) {\n console.log(` Requires: ${tool.requiredFeatures.join(', ')}`)\n }\n } else {\n console.log(` - ${name}`)\n }\n }\n console.log('')\n }\n },\n}\n\nconst entityGraph: ModuleCli = {\n command: 'entity-graph',\n async run(rest) {\n const args = parseArgs(rest)\n const format = String(args.format ?? 'triples') as 'json' | 'triples'\n const entity = args.entity ? String(args.entity) : undefined\n const module = args.module ? String(args.module) : undefined\n\n await ensureBootstrap()\n\n const { getOrm } = await import('@open-mercato/shared/lib/db/mikro')\n const { extractEntityGraph, formatGraphAsTriples, filterGraphByEntity, filterGraphByModule } = await import(\n './lib/entity-graph'\n )\n\n console.log('[Entity Graph] Extracting from MikroORM metadata...')\n\n const orm = await getOrm()\n const graph = await extractEntityGraph(orm)\n\n // Apply filters\n let edges = graph.edges\n\n if (entity) {\n edges = filterGraphByEntity(graph, entity)\n console.log(`[Entity Graph] Filtered by entity: ${entity}`)\n }\n\n if (module) {\n const filteredGraph = { ...graph, edges }\n edges = filterGraphByModule(filteredGraph, module)\n console.log(`[Entity Graph] Filtered by module: ${module}`)\n }\n\n const filteredGraph = { ...graph, edges }\n\n if (format === 'json') {\n console.log(JSON.stringify(filteredGraph, null, 2))\n } else {\n const triples = formatGraphAsTriples(filteredGraph)\n console.log('')\n for (const triple of triples) {\n console.log(triple)\n }\n }\n\n console.log(`\\n[Entity Graph] ${graph.nodes.length} entities, ${edges.length} relationships`)\n },\n}\n\nconst runPendingActionCleanup: ModuleCli = {\n command: 'run-pending-action-cleanup',\n async run() {\n await ensureBootstrap()\n const container = await createRequestContainer()\n\n const { runPendingActionCleanup: runCleanup } = await import(\n './workers/ai-pending-action-cleanup'\n )\n\n const em = container.resolve<import('@mikro-orm/postgresql').EntityManager>('em')\n const summary = await runCleanup({ em })\n\n console.log('[ai-pending-action-cleanup] Sweep complete:', summary)\n },\n}\n\nconst testTools: ModuleCli = {\n command: 'test-tools',\n async run(rest) {\n const args = parseArgs(rest)\n const json = args.json === true || args.json === 'true'\n const moduleFilter =\n typeof args.module === 'string' && args.module.length > 0 ? args.module : null\n const includeMutations = args['no-mutations'] !== true && args['no-mutations'] !== 'true'\n const tenantId =\n typeof args.tenant === 'string' && args.tenant.length > 0 ? args.tenant : null\n const organizationId =\n typeof args.org === 'string' && args.org.length > 0 ? args.org : null\n\n await ensureBootstrap()\n const { runToolTests } = await import('./lib/tool-test-runner')\n const report = await runToolTests({\n tenantId,\n organizationId,\n moduleFilter,\n includeMutations,\n })\n\n if (json) {\n // Wrap in markers so a Playwright spec (or any caller) can extract the\n // JSON payload without being thrown off by bootstrap log lines emitted\n // to stdout by other modules during DI container creation.\n console.log('---TOOL_TEST_REPORT_BEGIN---')\n console.log(JSON.stringify(report))\n console.log('---TOOL_TEST_REPORT_END---')\n } else {\n console.log('')\n console.log(\n `AI tool test report \u2014 tenant=${report.tenantId ?? '<none>'} org=${\n report.organizationId ?? '<none>'\n }`,\n )\n console.log(\n `total=${report.total} pass=${report.passed} fail=${report.failed} skip=${report.skipped}`,\n )\n const byModule = new Map<string, typeof report.records>()\n for (const record of report.records) {\n const list = byModule.get(record.module) ?? []\n list.push(record)\n byModule.set(record.module, list)\n }\n const sortedModules = Array.from(byModule.keys()).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))\n for (const moduleId of sortedModules) {\n const list = byModule.get(moduleId)!\n console.log('')\n console.log(`${moduleId} (${list.length}):`)\n for (const record of list) {\n const marker =\n record.status === 'pass' ? '\u2713' : record.status === 'fail' ? '\u2717' : '\u00B7'\n const reason = record.reason ? ` \u2014 ${record.reason}` : ''\n const mutation = record.isMutation ? ' [mutation]' : ''\n console.log(\n ` ${marker} ${record.tool}${mutation} (${record.durationMs}ms)${reason}`,\n )\n }\n }\n console.log('')\n }\n\n if (report.failed > 0) {\n process.exitCode = 1\n }\n },\n}\n\nconst runTokenUsagePrune: ModuleCli = {\n command: 'run-token-usage-prune',\n async run() {\n await ensureBootstrap()\n const container = await createRequestContainer()\n\n const { runTokenUsagePrune: runPrune } = await import(\n './workers/ai-token-usage-prune'\n )\n\n const em = container.resolve<import('@mikro-orm/postgresql').EntityManager>('em')\n const summary = await runPrune({ em })\n\n console.log('[ai-token-usage-prune] Prune complete:', summary)\n },\n}\n\nexport default [\n mcpServe,\n mcpServeHttp,\n mcpDev,\n mcpEnsureApiKey,\n listTools,\n entityGraph,\n runPendingActionCleanup,\n runTokenUsagePrune,\n testTools,\n]\n"],
5
- "m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A,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;",
4
+ "sourcesContent": ["import { parseModuleCliOptions } from '@open-mercato/shared/lib/cli/parseModuleCliOptions'\nimport type { ModuleCli } from '@open-mercato/shared/modules/registry'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { resetServerLoggerCache } from '@open-mercato/shared/lib/logger'\nimport { installNextSubpathResolveHook } from './lib/next-subpath-resolve-hook'\nimport { resolveMcpHost } from './lib/mcp-host-resolution'\n/**\n * Ensure app bootstrap is called before creating DI container.\n * Uses the shared generated-bootstrap loader so the command works both from\n * the monorepo app and from standalone apps installed through npm packages.\n */\nasync function ensureBootstrap(): Promise<void> {\n // These commands run outside Next.js, but the API route modules the\n // operation runner imports on a tool call say `from 'next/server'`, which\n // plain Node cannot resolve (#6118). Install the retry-with-`.js` hook before\n // anything below can pull a route module in.\n installNextSubpathResolveHook()\n\n // First check if DI is already available\n try {\n const { getDiRegistrars } = await import('@open-mercato/shared/lib/di/container')\n getDiRegistrars()\n return // DI already available\n } catch {\n // DI not available, need to bootstrap\n }\n\n try {\n const { bootstrapFromAppRoot } = await import('@open-mercato/shared/lib/bootstrap/dynamicLoader')\n await bootstrapFromAppRoot()\n } catch (error) {\n console.error('[MCP] Bootstrap failed:', error instanceof Error ? error.message : error)\n // Continue - some contexts may not have bootstrap available\n }\n}\n\nfunction parseArgs(rest: string[]): Record<string, string | boolean> {\n return parseModuleCliOptions(rest)\n}\n\nconst mcpServe: ModuleCli = {\n command: 'mcp:serve',\n async run(rest) {\n // stdout carries the MCP JSON-RPC protocol (StdioServerTransport) \u2014 route all\n // facade logs to stderr and rebuild any pino root created earlier in this process.\n process.env.OM_LOG_DESTINATION = 'stderr'\n resetServerLoggerCache()\n const args = parseArgs(rest)\n // Prefer the OPEN_MERCATO_API_KEY env var so the secret never has to be\n // placed on the command line (argv is world-readable via ps / /proc).\n // The --api-key flag stays supported for backward compatibility.\n const apiKey = String(args['api-key'] ?? args.apiKey ?? '') || process.env.OPEN_MERCATO_API_KEY || null\n const tenantId = String(args.tenant ?? args.tenantId ?? '') || null\n const organizationId = String(args.org ?? args.organizationId ?? '') || null\n const userId = String(args.user ?? args.userId ?? '') || null\n const debug = args.debug === true || args.debug === 'true'\n const allowUnauthenticatedSuperadmin =\n args['allow-unauthenticated-superadmin'] === true ||\n args['allow-unauthenticated-superadmin'] === 'true'\n\n // Either API key or tenant is required\n if (!apiKey && !tenantId) {\n console.error('Usage: mercato ai_assistant mcp:serve [options]')\n console.error('')\n console.error('Authentication (choose one):')\n console.error(' OPEN_MERCATO_API_KEY env API key secret (recommended \u2014 keeps the secret off argv)')\n console.error(' --api-key <secret> API key secret for authentication (visible in process listings)')\n console.error(' --tenant <id> Tenant ID (for manual context)')\n console.error('')\n console.error('Options (with --tenant):')\n console.error(' --org <id> Organization ID (optional)')\n console.error(' --user <id> User ID for ACL (required unless --allow-unauthenticated-superadmin is set)')\n console.error('')\n console.error('Common options:')\n console.error(' --debug Enable debug logging')\n console.error(' --allow-unauthenticated-superadmin')\n console.error(' DEV/TEST ONLY: run as superadmin with no per-user ACL when')\n console.error(' no --user (and no --api-key) is supplied. Never use in production.')\n console.error('')\n console.error('Examples:')\n console.error(' OPEN_MERCATO_API_KEY=omk_xxxx.yyyy... mercato ai_assistant mcp:serve')\n console.error(' mercato ai_assistant mcp:serve --api-key omk_xxxx.yyyy...')\n console.error(' mercato ai_assistant mcp:serve --tenant 123e4567-e89b-12d3-a456-426614174000 --user <user-id>')\n console.error(' mercato ai_assistant mcp:serve --tenant 123e4567-e89b-12d3-a456-426614174000 --allow-unauthenticated-superadmin')\n return\n }\n\n await ensureBootstrap()\n const container = await createRequestContainer()\n\n const { runMcpServer } = await import('./lib/mcp-server')\n\n if (apiKey) {\n await runMcpServer({\n config: {\n name: 'open-mercato-mcp',\n version: '0.1.0',\n debug,\n },\n container,\n apiKeySecret: apiKey,\n })\n } else {\n await runMcpServer({\n config: {\n name: 'open-mercato-mcp',\n version: '0.1.0',\n debug,\n },\n container,\n context: {\n tenantId,\n organizationId,\n userId,\n },\n allowUnauthenticatedSuperadmin,\n })\n }\n },\n}\n\nconst MCP_DEFAULT_PORT = 3001\n\nconst mcpServeHttp: ModuleCli = {\n command: 'mcp:serve-http',\n async run(rest) {\n const args = parseArgs(rest)\n const portArg = parseInt(String(args.port ?? ''), 10)\n const port = !portArg || isNaN(portArg) ? MCP_DEFAULT_PORT : portArg\n const debug = args.debug === true || args.debug === 'true'\n const host = resolveMcpHost(\n typeof args.host === 'string' ? args.host : undefined,\n process.env.MCP_HTTP_HOST,\n )\n\n await ensureBootstrap()\n const container = await createRequestContainer()\n\n const { runMcpHttpServer } = await import('./lib/http-server')\n\n await runMcpHttpServer({\n config: {\n name: 'open-mercato-mcp',\n version: '0.1.0',\n debug,\n },\n container,\n port,\n host,\n })\n },\n}\n\nconst mcpDev: ModuleCli = {\n command: 'mcp:dev',\n async run() {\n await ensureBootstrap()\n const { runMcpDevServer } = await import('./lib/mcp-dev-server')\n await runMcpDevServer()\n },\n}\n\nconst mcpEnsureApiKey: ModuleCli = {\n command: 'mcp:ensure-api-key',\n async run(rest) {\n const args = parseArgs(rest)\n // A bare `--file` (no value) parses to boolean true \u2014 treat it as missing\n // rather than provisioning into a file literally named \"true\".\n const fileArg = typeof args.file === 'string' ? args.file.trim() : ''\n const filePath =\n fileArg || process.env.MCP_SERVER_API_KEY_FILE?.trim() || process.env.MCP_API_KEY_FILE?.trim() || ''\n if (!filePath) {\n console.error('Usage: mercato ai_assistant mcp:ensure-api-key --file <path> [options]')\n console.error('')\n console.error('Ensures a valid MCP server API key exists in the database and that its')\n console.error('plaintext secret is stored in <path> (the idempotency anchor). The secret')\n console.error('is never printed; consumers such as the OpenCode container read the file.')\n console.error('')\n console.error('Options:')\n console.error(' --file <path> Secret file path (or MCP_SERVER_API_KEY_FILE env)')\n console.error(' --name <name> API key name (default __mcp_server__)')\n console.error(' --email <email> Owner user email (default OM_INIT_SUPERADMIN_EMAIL, then superadmin@acme.com)')\n console.error(' --rotate Force rotation even when the file secret is still valid')\n process.exitCode = 1\n return\n }\n\n const keyName = typeof args.name === 'string' && args.name.length > 0 ? args.name : undefined\n const ownerEmail = typeof args.email === 'string' && args.email.length > 0 ? args.email : undefined\n const rotate = args.rotate === true || args.rotate === 'true'\n\n await ensureBootstrap()\n const container = await createRequestContainer()\n const em = container.resolve<import('@mikro-orm/postgresql').EntityManager>('em')\n const rbac = container.resolve('rbacService') as import('@open-mercato/core/modules/auth/services/rbacService').RbacService\n\n const { ensureMcpApiKey } = await import('./lib/mcp-ensure-api-key')\n const result = await ensureMcpApiKey({ em, filePath, keyName, ownerEmail, rotate, rbac })\n const message = result.status === 'valid' ? 'Existing key is valid' : 'New key created'\n console.log(`[mcp:ensure-api-key] ${message} (id=${result.keyId}, prefix=${result.keyPrefix})`)\n },\n}\n\nconst listTools: ModuleCli = {\n command: 'mcp:list-tools',\n async run(rest) {\n const args = parseArgs(rest)\n const verbose = args.verbose === true || args.verbose === 'true'\n\n // Ensure bootstrap runs so modules are registered for API discovery\n await ensureBootstrap()\n\n const { loadAllModuleTools } = await import('./lib/tool-loader')\n await loadAllModuleTools()\n\n const { getToolRegistry } = await import('./lib/tool-registry')\n const registry = getToolRegistry()\n const toolNames = registry.listToolNames()\n\n if (toolNames.length === 0) {\n console.log('\\nNo MCP tools registered.')\n console.log('Tools can be registered by modules using registerMcpTool().\\n')\n return\n }\n\n console.log(`\\nRegistered MCP Tools (${toolNames.length}):\\n`)\n\n // Group tools by module\n const byModule = new Map<string, string[]>()\n for (const name of toolNames) {\n const [module] = name.split('.')\n const list = byModule.get(module) ?? []\n list.push(name)\n byModule.set(module, list)\n }\n\n // Sort modules alphabetically\n const sortedModules = Array.from(byModule.keys()).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))\n\n for (const moduleName of sortedModules) {\n const tools = byModule.get(moduleName)!\n console.log(`${moduleName} (${tools.length} tools):`)\n\n for (const name of tools.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {\n const tool = registry.getTool(name)\n if (!tool) continue\n\n if (verbose) {\n console.log(` ${name}`)\n console.log(` ${tool.description}`)\n if (tool.requiredFeatures?.length) {\n console.log(` Requires: ${tool.requiredFeatures.join(', ')}`)\n }\n } else {\n console.log(` - ${name}`)\n }\n }\n console.log('')\n }\n },\n}\n\nconst entityGraph: ModuleCli = {\n command: 'entity-graph',\n async run(rest) {\n const args = parseArgs(rest)\n const format = String(args.format ?? 'triples') as 'json' | 'triples'\n const entity = args.entity ? String(args.entity) : undefined\n const moduleName = args.module ? String(args.module) : undefined\n\n await ensureBootstrap()\n\n const { getOrm } = await import('@open-mercato/shared/lib/db/mikro')\n const { extractEntityGraph, formatGraphAsTriples, filterGraphByEntity, filterGraphByModule } = await import(\n './lib/entity-graph'\n )\n\n console.log('[Entity Graph] Extracting from MikroORM metadata...')\n\n const orm = await getOrm()\n const graph = await extractEntityGraph(orm)\n\n // Apply filters\n let edges = graph.edges\n\n if (entity) {\n edges = filterGraphByEntity(graph, entity)\n console.log(`[Entity Graph] Filtered by entity: ${entity}`)\n }\n\n if (moduleName) {\n const filteredGraph = { ...graph, edges }\n edges = filterGraphByModule(filteredGraph, moduleName)\n console.log(`[Entity Graph] Filtered by module: ${moduleName}`)\n }\n\n const filteredGraph = { ...graph, edges }\n\n if (format === 'json') {\n console.log(JSON.stringify(filteredGraph, null, 2))\n } else {\n const triples = formatGraphAsTriples(filteredGraph)\n console.log('')\n for (const triple of triples) {\n console.log(triple)\n }\n }\n\n console.log(`\\n[Entity Graph] ${graph.nodes.length} entities, ${edges.length} relationships`)\n },\n}\n\nconst runPendingActionCleanup: ModuleCli = {\n command: 'run-pending-action-cleanup',\n async run() {\n await ensureBootstrap()\n const container = await createRequestContainer()\n\n const { runPendingActionCleanup: runCleanup } = await import(\n './workers/ai-pending-action-cleanup'\n )\n\n const em = container.resolve<import('@mikro-orm/postgresql').EntityManager>('em')\n const summary = await runCleanup({ em })\n\n console.log('[ai-pending-action-cleanup] Sweep complete:', summary)\n },\n}\n\nconst testTools: ModuleCli = {\n command: 'test-tools',\n async run(rest) {\n const args = parseArgs(rest)\n const json = args.json === true || args.json === 'true'\n const moduleFilter =\n typeof args.module === 'string' && args.module.length > 0 ? args.module : null\n const includeMutations = args['no-mutations'] !== true && args['no-mutations'] !== 'true'\n const tenantId =\n typeof args.tenant === 'string' && args.tenant.length > 0 ? args.tenant : null\n const organizationId =\n typeof args.org === 'string' && args.org.length > 0 ? args.org : null\n\n await ensureBootstrap()\n const { runToolTests } = await import('./lib/tool-test-runner')\n const report = await runToolTests({\n tenantId,\n organizationId,\n moduleFilter,\n includeMutations,\n })\n\n if (json) {\n // Wrap in markers so a Playwright spec (or any caller) can extract the\n // JSON payload without being thrown off by bootstrap log lines emitted\n // to stdout by other modules during DI container creation.\n console.log('---TOOL_TEST_REPORT_BEGIN---')\n console.log(JSON.stringify(report))\n console.log('---TOOL_TEST_REPORT_END---')\n } else {\n console.log('')\n console.log(\n `AI tool test report \u2014 tenant=${report.tenantId ?? '<none>'} org=${\n report.organizationId ?? '<none>'\n }`,\n )\n console.log(\n `total=${report.total} pass=${report.passed} fail=${report.failed} skip=${report.skipped}`,\n )\n const byModule = new Map<string, typeof report.records>()\n for (const record of report.records) {\n const list = byModule.get(record.module) ?? []\n list.push(record)\n byModule.set(record.module, list)\n }\n const sortedModules = Array.from(byModule.keys()).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))\n for (const moduleId of sortedModules) {\n const list = byModule.get(moduleId)!\n console.log('')\n console.log(`${moduleId} (${list.length}):`)\n for (const record of list) {\n const marker =\n record.status === 'pass' ? '\u2713' : record.status === 'fail' ? '\u2717' : '\u00B7'\n const reason = record.reason ? ` \u2014 ${record.reason}` : ''\n const mutation = record.isMutation ? ' [mutation]' : ''\n console.log(\n ` ${marker} ${record.tool}${mutation} (${record.durationMs}ms)${reason}`,\n )\n }\n }\n console.log('')\n }\n\n if (report.failed > 0) {\n process.exitCode = 1\n }\n },\n}\n\nconst runTokenUsagePrune: ModuleCli = {\n command: 'run-token-usage-prune',\n async run() {\n await ensureBootstrap()\n const container = await createRequestContainer()\n\n const { runTokenUsagePrune: runPrune } = await import(\n './workers/ai-token-usage-prune'\n )\n\n const em = container.resolve<import('@mikro-orm/postgresql').EntityManager>('em')\n const summary = await runPrune({ em })\n\n console.log('[ai-token-usage-prune] Prune complete:', summary)\n },\n}\n\nexport default [\n mcpServe,\n mcpServeHttp,\n mcpDev,\n mcpEnsureApiKey,\n listTools,\n entityGraph,\n runPendingActionCleanup,\n runTokenUsagePrune,\n testTools,\n]\n"],
5
+ "mappings": "AAAA,SAAS,6BAA6B;AAEtC,SAAS,8BAA8B;AACvC,SAAS,8BAA8B;AACvC,SAAS,qCAAqC;AAC9C,SAAS,sBAAsB;AAM/B,eAAe,kBAAiC;AAK9C,gCAA8B;AAG9B,MAAI;AACF,UAAM,EAAE,gBAAgB,IAAI,MAAM,OAAO,uCAAuC;AAChF,oBAAgB;AAChB;AAAA,EACF,QAAQ;AAAA,EAER;AAEA,MAAI;AACF,UAAM,EAAE,qBAAqB,IAAI,MAAM,OAAO,kDAAkD;AAChG,UAAM,qBAAqB;AAAA,EAC7B,SAAS,OAAO;AACd,YAAQ,MAAM,2BAA2B,iBAAiB,QAAQ,MAAM,UAAU,KAAK;AAAA,EAEzF;AACF;AAEA,SAAS,UAAU,MAAkD;AACnE,SAAO,sBAAsB,IAAI;AACnC;AAEA,MAAM,WAAsB;AAAA,EAC1B,SAAS;AAAA,EACT,MAAM,IAAI,MAAM;AAGd,YAAQ,IAAI,qBAAqB;AACjC,2BAAuB;AACvB,UAAM,OAAO,UAAU,IAAI;AAI3B,UAAM,SAAS,OAAO,KAAK,SAAS,KAAK,KAAK,UAAU,EAAE,KAAK,QAAQ,IAAI,wBAAwB;AACnG,UAAM,WAAW,OAAO,KAAK,UAAU,KAAK,YAAY,EAAE,KAAK;AAC/D,UAAM,iBAAiB,OAAO,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;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;",
6
6
  "names": ["filteredGraph"]
7
7
  }
@@ -9,6 +9,7 @@ import {
9
9
  import { toolRegistry } from "./tool-registry.js";
10
10
  import { toSafeZodSchema } from "./schema-utils.js";
11
11
  import { prepareMutation } from "./prepare-mutation.js";
12
+ import { resolveStagedToolInput } from "./tool-input.js";
12
13
  const logger = createLogger("ai_assistant");
13
14
  class AgentPolicyError extends Error {
14
15
  constructor(code, message) {
@@ -113,11 +114,15 @@ function adaptToolToAiSdk(tool, ctx, mutation, container, effectiveMutationPolic
113
114
  if (mutation && requiresApprovalNow) {
114
115
  try {
115
116
  const toolCallArgs = args && typeof args === "object" && !Array.isArray(args) ? { ...args } : {};
117
+ const stagedInput = resolveStagedToolInput(tool.inputSchema, toolCallArgs);
118
+ if (!stagedInput.success) {
119
+ throw new Error(stagedInput.error);
120
+ }
116
121
  const { uiPart, pendingAction, reused } = await prepareMutation(
117
122
  {
118
123
  agent: mutation.agent,
119
124
  tool: mutation.tool,
120
- toolCallArgs,
125
+ toolCallArgs: stagedInput.input,
121
126
  conversationId: mutation.conversationId,
122
127
  mutationPolicyOverride: mutation.mutationPolicyOverride
123
128
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/ai_assistant/lib/agent-tools.ts"],
4
- "sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport { dynamicTool, type Tool } from 'ai'\nimport type { AwilixContainer } from 'awilix'\nimport type { ZodType } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { AiAgentDefinition, AiAgentMutationPolicy } from './ai-agent-definition'\nimport type { AiChatRequestContext, AiUiPart } from './attachment-bridge-types'\nimport type { AiToolDefinition, McpToolContext } from './types'\nimport type {\n AiPendingActionExecutionResult,\n AiPendingActionStatus,\n} from './pending-action-types'\nimport { loadAgentRegistry } from './agent-registry'\nimport {\n checkAgentPolicy,\n resolveEffectiveMutationPolicy,\n type AgentPolicyDenyCode,\n} from './agent-policy'\nimport { toolRegistry } from './tool-registry'\nimport { toSafeZodSchema } from './schema-utils'\nimport { prepareMutation } from './prepare-mutation'\n\nconst logger = createLogger('ai_assistant')\n\n/**\n * Error thrown by `resolveAiAgentTools` (and downstream `runAiAgentText`) when\n * the agent-level policy check denies a request. Carries the structured deny\n * code so HTTP dispatchers can map it to a stable status and JSON body.\n */\nexport class AgentPolicyError extends Error {\n readonly code: AgentPolicyDenyCode\n\n constructor(code: AgentPolicyDenyCode, message: string) {\n super(message)\n this.name = 'AgentPolicyError'\n this.code = code\n }\n}\n\nexport interface ResolveAiAgentToolsInput {\n agentId: string\n authContext: AiChatRequestContext\n pageContext?: Record<string, unknown>\n attachmentIds?: string[]\n /**\n * Execution mode the caller intends to run the agent in. Defaults to\n * `'chat'` to preserve the existing chat dispatcher contract. Object-mode\n * callers (see `runAiAgentObject`) MUST pass `'object'` so the policy gate\n * can reject chat-only agents early with `execution_mode_not_supported`.\n */\n requestedExecutionMode?: 'chat' | 'object'\n /**\n * Optional tenant-scoped mutation-policy DOWNGRADE. When supplied, the\n * effective policy evaluated by `checkAgentPolicy` is the most restrictive\n * of `{ agent.mutationPolicy, mutationPolicyOverride }`. Escalation is\n * rejected at the route layer; this helper trusts callers to pass only\n * values produced by the override repository.\n */\n mutationPolicyOverride?: AiAgentMutationPolicy | null\n /**\n * DI container used by the `prepareMutation` tool-call wrapper (Step 5.6).\n * When present AND the agent's effective mutation policy is non-read-only,\n * `isMutation: true` tools are intercepted: the runtime creates an\n * `AiPendingAction` row and enqueues a `mutation-preview-card` UI part in\n * the returned {@link ResolvedAgentTools.uiPartQueue} instead of running the\n * tool's handler. When absent, mutation tools degrade-gracefully to the\n * pre-5.6 pass-through adapter \u2014 existing read-only agents are unaffected.\n */\n container?: AwilixContainer\n /**\n * Optional chat-turn correlation id used when hashing the\n * `AiPendingAction.idempotencyKey` so retries of the same mutation collapse\n * to a single row. The chat dispatcher supplies the OpenCode / AI SDK turn\n * id here; when omitted the hash falls back to `null` which still preserves\n * per-tenant/org uniqueness within the TTL window.\n */\n conversationId?: string | null\n}\n\n/**\n * Queue of UI parts the mutation-preview wrapper accumulates during a turn.\n * The chat/object dispatcher flushes these on the next emission boundary\n * (spec \u00A79 allows either direct streaming or this queue pattern \u2014 we ship the\n * queue in Step 5.6 and the chat dispatcher will drain it in Step 5.10 when\n * the `mutation-preview-card` component registers). BC: callers that ignore\n * the field are unaffected.\n */\nexport interface AiUiPartQueue {\n /** Pushed by the mutation wrapper; drained by the dispatcher in order. */\n enqueue: (part: AiUiPart) => void\n drain: () => AiUiPart[]\n size: () => number\n}\n\nfunction createAiUiPartQueue(): AiUiPartQueue {\n const buffer: AiUiPart[] = []\n return {\n enqueue: (part) => {\n buffer.push(part)\n },\n drain: () => {\n const snapshot = buffer.slice()\n buffer.length = 0\n return snapshot\n },\n size: () => buffer.length,\n }\n}\n\nexport interface ResolvedAgentTools {\n agent: AiAgentDefinition\n tools: Record<string, Tool<unknown, unknown>>\n /**\n * Per-request UI-part queue the chat dispatcher drains between streamText\n * chunks (Step 5.10 contract). Always present; empty when no mutation-tool\n * calls fire during the turn.\n */\n uiPartQueue: AiUiPartQueue\n}\n\nfunction toPolicyAuthContext(ctx: AiChatRequestContext): {\n userFeatures: string[]\n isSuperAdmin: boolean\n} {\n return {\n userFeatures: ctx.features,\n isSuperAdmin: ctx.isSuperAdmin,\n }\n}\n\n/**\n * Sanitize a dotted tool name (e.g. `search.hybrid_search`) into a format\n * accepted by all major LLM providers. OpenAI requires tool names to match\n * `^[a-zA-Z0-9_-]+$`; dots are replaced with double underscores (`__`).\n * Anthropic and Google accept both formats, so this is safe across providers.\n */\nexport function sanitizeToolNameForModel(name: string): string {\n return name.replace(/\\./g, '__')\n}\n\nexport function desanitizeToolNameForDisplay(name: string): string {\n return name.replace(/__/g, '.')\n}\n\nfunction formatToolResult(result: unknown): string {\n if (result === null || result === undefined) return 'No result returned'\n if (typeof result === 'string') return result\n if (typeof result === 'number' || typeof result === 'boolean') return String(result)\n try {\n return JSON.stringify(result, null, 2)\n } catch {\n return String(result)\n }\n}\n\nfunction buildToolHandlerContext(\n ctx: AiChatRequestContext,\n container?: AwilixContainer,\n tool?: AiToolDefinition,\n): McpToolContext {\n return {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: ctx.userId,\n container: (container ?? undefined) as unknown as McpToolContext['container'],\n userFeatures: ctx.features,\n isSuperAdmin: ctx.isSuperAdmin,\n ...(tool ? { tool } : {}),\n }\n}\n\ninterface MutationInterceptorOptions {\n agent: AiAgentDefinition\n tool: AiToolDefinition\n container: AwilixContainer\n ctx: AiChatRequestContext\n mutationPolicyOverride: AiAgentMutationPolicy | null\n conversationId: string | null\n uiPartQueue: AiUiPartQueue\n}\n\nfunction formatPendingActionToolResult(\n agent: AiAgentDefinition,\n tool: AiToolDefinition,\n pendingActionId: string,\n expiresAt: Date,\n reused: boolean,\n status: AiPendingActionStatus,\n executionResult: AiPendingActionExecutionResult | null,\n): string {\n // A reused `confirmed`/`executing` row means this exact mutation already\n // ran (or is running) under the same idempotency key \u2014 tell the model so\n // it does not resubmit, instead of always claiming a fresh approval is\n // pending (issue #7550).\n if (reused && (status === 'confirmed' || status === 'executing')) {\n const resultStatus = status === 'executing' ? 'executing' : 'already-executed'\n return formatToolResult({\n status: resultStatus,\n agentId: agent.id,\n toolName: tool.name,\n pendingActionId,\n executionResult: executionResult ?? null,\n message:\n resultStatus === 'executing'\n ? `Mutation \"${tool.name}\" is already executing from a prior confirmed call. Do NOT submit it again; wait for the result.`\n : `Mutation \"${tool.name}\" already ran for this input (idempotency key reused). Do NOT submit it again \u2014 see executionResult for the prior outcome.`,\n })\n }\n return formatToolResult({\n status: 'pending-confirmation',\n agentId: agent.id,\n toolName: tool.name,\n pendingActionId,\n expiresAt: expiresAt.toISOString(),\n message: `Awaiting user confirmation for mutation \"${tool.name}\". The action will NOT run until the user approves it.`,\n })\n}\n\n/**\n * Per-call gating decision for the destructive-confirm-required policy.\n * Honors a static boolean OR a predicate evaluated against the actual\n * tool-call args, so a multi-operation tool (e.g.\n * `customers.manage_deal_comment` with `operation: 'create' | 'update'\n * | 'delete'`) can gate only its destructive branches without being\n * split into multiple tools.\n */\nfunction resolveIsDestructive(\n isDestructive: boolean | ((input: unknown) => boolean) | undefined,\n args: unknown,\n): boolean {\n if (typeof isDestructive === 'function') {\n try {\n return isDestructive(args) === true\n } catch {\n // If the predicate throws (e.g. unexpected input shape), default to\n // gating \u2014 fail-safe for destructive policy.\n return true\n }\n }\n return isDestructive === true\n}\n\nfunction adaptToolToAiSdk(\n tool: AiToolDefinition,\n ctx: AiChatRequestContext,\n mutation: MutationInterceptorOptions | null,\n container?: AwilixContainer,\n effectiveMutationPolicy?: 'read-only' | 'confirm-required' | 'destructive-confirm-required',\n): Tool<unknown, unknown> {\n const safeSchema = toSafeZodSchema(tool.inputSchema as ZodType)\n const handlerContext = buildToolHandlerContext(ctx, container, tool)\n return dynamicTool({\n description: tool.description,\n inputSchema: safeSchema,\n execute: async (args: unknown) => {\n // Per-call gating decision. Under `destructive-confirm-required`,\n // tools with a predicate `isDestructive(args)` may flip per call \u2014\n // e.g. comment delete gates while comment create runs direct.\n const requiresApprovalNow = (() => {\n if (!mutation) return false\n if (effectiveMutationPolicy === 'confirm-required') return true\n if (effectiveMutationPolicy === 'destructive-confirm-required') {\n return resolveIsDestructive(mutation.tool.isDestructive, args)\n }\n return false\n })()\n if (mutation && requiresApprovalNow) {\n try {\n const toolCallArgs =\n args && typeof args === 'object' && !Array.isArray(args)\n ? { ...(args as Record<string, unknown>) }\n : {}\n const { uiPart, pendingAction, reused } = await prepareMutation(\n {\n agent: mutation.agent,\n tool: mutation.tool,\n toolCallArgs,\n conversationId: mutation.conversationId,\n mutationPolicyOverride: mutation.mutationPolicyOverride,\n },\n {\n tenantId: mutation.ctx.tenantId,\n organizationId: mutation.ctx.organizationId,\n userId: mutation.ctx.userId,\n features: mutation.ctx.features,\n isSuperAdmin: mutation.ctx.isSuperAdmin,\n container: mutation.container,\n },\n )\n mutation.uiPartQueue.enqueue(uiPart)\n return formatPendingActionToolResult(\n mutation.agent,\n mutation.tool,\n pendingAction.id,\n pendingAction.expiresAt,\n reused,\n pendingAction.status,\n pendingAction.executionResult ?? null,\n )\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(\n `Tool \"${tool.name}\" could not be prepared for confirmation: ${message}`,\n )\n }\n }\n try {\n // Create a fresh container per tool call so the EM is never stale.\n const freshContainer = await createRequestContainer()\n const freshContext: McpToolContext = {\n ...handlerContext,\n container: freshContainer as unknown as McpToolContext['container'],\n }\n const { executeTool } = await import('./tool-executor')\n const execResult = await executeTool(tool.name, args, freshContext)\n if (!execResult.success) {\n throw new Error(execResult.error || 'Tool execution failed')\n }\n return formatToolResult(execResult.result)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(`Tool \"${tool.name}\" failed: ${message}`)\n }\n },\n })\n}\n\n/**\n * Resolves the agent's whitelisted tools into an AI SDK `tools` map, enforcing\n * the same policy gate as the HTTP dispatcher. Throws {@link AgentPolicyError}\n * on agent-level deny; tool-level denies are skipped with a logger warning\n * because the agent author whitelisted a tool the caller is not currently\n * permitted to execute (deterministic non-failure \u2014 the remaining tools still\n * reach the model).\n */\nexport async function resolveAiAgentTools(\n input: ResolveAiAgentToolsInput,\n): Promise<ResolvedAgentTools> {\n await loadAgentRegistry()\n // The agent registry alone is not enough: the policy gate below resolves\n // every allowlisted name against the TOOL registry, and rejects what it\n // cannot find as `tool_unknown`. Loading it here \u2014 rather than in the half\n // dozen entry points that happened to remember \u2014 is what makes an agent's\n // allowlist mean the same thing on every path.\n try {\n const { ensureModuleToolsLoaded } = await import('./tool-loader')\n await ensureModuleToolsLoaded()\n } catch (error) {\n // A registry that failed to load leaves the agent toolless, which the\n // caller already handles; it must not take the whole turn down.\n logger.error('Could not load module tools; agent will resolve to its known tools only', {\n agentId: input.agentId,\n err: error,\n })\n }\n\n const policyAuth = toPolicyAuthContext(input.authContext)\n const mutationPolicyOverride = input.mutationPolicyOverride ?? null\n const agentDecision = checkAgentPolicy({\n agentId: input.agentId,\n authContext: policyAuth,\n requestedExecutionMode: input.requestedExecutionMode ?? 'chat',\n mutationPolicyOverride,\n })\n if (!agentDecision.ok) {\n throw new AgentPolicyError(agentDecision.code, agentDecision.message)\n }\n\n const { agent } = agentDecision\n const tools: Record<string, Tool<unknown, unknown>> = {}\n const uiPartQueue = createAiUiPartQueue()\n const effectiveMutationPolicy = resolveEffectiveMutationPolicy(\n agent.mutationPolicy,\n mutationPolicyOverride,\n agent.id,\n )\n const canInterceptMutations =\n effectiveMutationPolicy !== 'read-only' && typeof input.container !== 'undefined'\n\n for (const toolName of agent.allowedTools) {\n const toolDecision = checkAgentPolicy({\n agentId: input.agentId,\n authContext: policyAuth,\n toolName,\n mutationPolicyOverride,\n })\n if (!toolDecision.ok) {\n logger.warn('Skipping tool for agent', { toolName, agentId: agent.id, reason: toolDecision.message })\n continue\n }\n\n const record = (toolDecision.tool ?? toolRegistry.getTool(toolName)) as\n | AiToolDefinition\n | undefined\n if (!record) {\n logger.warn('Tool vanished from registry between policy checks; skipping', { toolName })\n continue\n }\n\n try {\n // For any mutation tool whose policy isn't read-only, prepare the\n // interceptor options once. The actual gate-vs-run-direct decision\n // happens at call time inside `adaptToolToAiSdk` because under\n // `destructive-confirm-required` `isDestructive` may be a predicate\n // evaluated against the per-call args (e.g. a multi-operation\n // tool with `operation: 'create' | 'update' | 'delete'` gates only\n // the destructive branch).\n const mutationOptions: MutationInterceptorOptions | null =\n record.isMutation === true && canInterceptMutations && input.container\n ? {\n agent,\n tool: record,\n container: input.container,\n ctx: input.authContext,\n mutationPolicyOverride,\n conversationId: input.conversationId ?? null,\n uiPartQueue,\n }\n : null\n // Sanitize tool name for model API compatibility: OpenAI requires\n // names matching ^[a-zA-Z0-9_-]+$ (no dots). Replace dots with\n // double underscores so `search.hybrid_search` becomes\n // `search__hybrid_search`. The AI SDK uses the record key as the\n // tool name sent to the model; the original dotted name stays on\n // the `tool` object for logging and prepareMutation hashing.\n const modelSafeToolName = sanitizeToolNameForModel(toolName)\n tools[modelSafeToolName] = adaptToolToAiSdk(\n record,\n input.authContext,\n mutationOptions,\n input.container,\n effectiveMutationPolicy,\n )\n } catch (error) {\n logger.error('Failed to adapt tool for agent', { toolName, agentId: agent.id, err: error })\n }\n }\n\n return { agent, tools, uiPartQueue }\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,mBAA8B;AAGvC,SAAS,8BAA8B;AAQvC,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB;AAChC,SAAS,uBAAuB;AAEhC,MAAM,SAAS,aAAa,cAAc;AAOnC,MAAM,yBAAyB,MAAM;AAAA,EAG1C,YAAY,MAA2B,SAAiB;AACtD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAyDA,SAAS,sBAAqC;AAC5C,QAAM,SAAqB,CAAC;AAC5B,SAAO;AAAA,IACL,SAAS,CAAC,SAAS;AACjB,aAAO,KAAK,IAAI;AAAA,IAClB;AAAA,IACA,OAAO,MAAM;AACX,YAAM,WAAW,OAAO,MAAM;AAC9B,aAAO,SAAS;AAChB,aAAO;AAAA,IACT;AAAA,IACA,MAAM,MAAM,OAAO;AAAA,EACrB;AACF;AAaA,SAAS,oBAAoB,KAG3B;AACA,SAAO;AAAA,IACL,cAAc,IAAI;AAAA,IAClB,cAAc,IAAI;AAAA,EACpB;AACF;AAQO,SAAS,yBAAyB,MAAsB;AAC7D,SAAO,KAAK,QAAQ,OAAO,IAAI;AACjC;AAEO,SAAS,6BAA6B,MAAsB;AACjE,SAAO,KAAK,QAAQ,OAAO,GAAG;AAChC;AAEA,SAAS,iBAAiB,QAAyB;AACjD,MAAI,WAAW,QAAQ,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;AACxC,QAAM,0BAA0B;AAAA,IAC9B,MAAM;AAAA,IACN;AAAA,IACA,MAAM;AAAA,EACR;AACA,QAAM,wBACJ,4BAA4B,eAAe,OAAO,MAAM,cAAc;AAExE,aAAW,YAAY,MAAM,cAAc;AACzC,UAAM,eAAe,iBAAiB;AAAA,MACpC,SAAS,MAAM;AAAA,MACf,aAAa;AAAA,MACb;AAAA,MACA;AAAA,IACF,CAAC;AACD,QAAI,CAAC,aAAa,IAAI;AACpB,aAAO,KAAK,2BAA2B,EAAE,UAAU,SAAS,MAAM,IAAI,QAAQ,aAAa,QAAQ,CAAC;AACpG;AAAA,IACF;AAEA,UAAM,SAAU,aAAa,QAAQ,aAAa,QAAQ,QAAQ;AAGlE,QAAI,CAAC,QAAQ;AACX,aAAO,KAAK,+DAA+D,EAAE,SAAS,CAAC;AACvF;AAAA,IACF;AAEA,QAAI;AAQF,YAAM,kBACJ,OAAO,eAAe,QAAQ,yBAAyB,MAAM,YACzD;AAAA,QACE;AAAA,QACA,MAAM;AAAA,QACN,WAAW,MAAM;AAAA,QACjB,KAAK,MAAM;AAAA,QACX;AAAA,QACA,gBAAgB,MAAM,kBAAkB;AAAA,QACxC;AAAA,MACF,IACA;AAON,YAAM,oBAAoB,yBAAyB,QAAQ;AAC3D,YAAM,iBAAiB,IAAI;AAAA,QACzB;AAAA,QACA,MAAM;AAAA,QACN;AAAA,QACA,MAAM;AAAA,QACN;AAAA,MACF;AAAA,IACF,SAAS,OAAO;AACd,aAAO,MAAM,kCAAkC,EAAE,UAAU,SAAS,MAAM,IAAI,KAAK,MAAM,CAAC;AAAA,IAC5F;AAAA,EACF;AAEA,SAAO,EAAE,OAAO,OAAO,YAAY;AACrC;",
4
+ "sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport { dynamicTool, type Tool } from 'ai'\nimport type { AwilixContainer } from 'awilix'\nimport type { ZodType } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { AiAgentDefinition, AiAgentMutationPolicy } from './ai-agent-definition'\nimport type { AiChatRequestContext, AiUiPart } from './attachment-bridge-types'\nimport type { AiToolDefinition, McpToolContext } from './types'\nimport type {\n AiPendingActionExecutionResult,\n AiPendingActionStatus,\n} from './pending-action-types'\nimport { loadAgentRegistry } from './agent-registry'\nimport {\n checkAgentPolicy,\n resolveEffectiveMutationPolicy,\n type AgentPolicyDenyCode,\n} from './agent-policy'\nimport { toolRegistry } from './tool-registry'\nimport { toSafeZodSchema } from './schema-utils'\nimport { prepareMutation } from './prepare-mutation'\nimport { resolveStagedToolInput } from './tool-input'\n\nconst logger = createLogger('ai_assistant')\n\n/**\n * Error thrown by `resolveAiAgentTools` (and downstream `runAiAgentText`) when\n * the agent-level policy check denies a request. Carries the structured deny\n * code so HTTP dispatchers can map it to a stable status and JSON body.\n */\nexport class AgentPolicyError extends Error {\n readonly code: AgentPolicyDenyCode\n\n constructor(code: AgentPolicyDenyCode, message: string) {\n super(message)\n this.name = 'AgentPolicyError'\n this.code = code\n }\n}\n\nexport interface ResolveAiAgentToolsInput {\n agentId: string\n authContext: AiChatRequestContext\n pageContext?: Record<string, unknown>\n attachmentIds?: string[]\n /**\n * Execution mode the caller intends to run the agent in. Defaults to\n * `'chat'` to preserve the existing chat dispatcher contract. Object-mode\n * callers (see `runAiAgentObject`) MUST pass `'object'` so the policy gate\n * can reject chat-only agents early with `execution_mode_not_supported`.\n */\n requestedExecutionMode?: 'chat' | 'object'\n /**\n * Optional tenant-scoped mutation-policy DOWNGRADE. When supplied, the\n * effective policy evaluated by `checkAgentPolicy` is the most restrictive\n * of `{ agent.mutationPolicy, mutationPolicyOverride }`. Escalation is\n * rejected at the route layer; this helper trusts callers to pass only\n * values produced by the override repository.\n */\n mutationPolicyOverride?: AiAgentMutationPolicy | null\n /**\n * DI container used by the `prepareMutation` tool-call wrapper (Step 5.6).\n * When present AND the agent's effective mutation policy is non-read-only,\n * `isMutation: true` tools are intercepted: the runtime creates an\n * `AiPendingAction` row and enqueues a `mutation-preview-card` UI part in\n * the returned {@link ResolvedAgentTools.uiPartQueue} instead of running the\n * tool's handler. When absent, mutation tools degrade-gracefully to the\n * pre-5.6 pass-through adapter \u2014 existing read-only agents are unaffected.\n */\n container?: AwilixContainer\n /**\n * Optional chat-turn correlation id used when hashing the\n * `AiPendingAction.idempotencyKey` so retries of the same mutation collapse\n * to a single row. The chat dispatcher supplies the OpenCode / AI SDK turn\n * id here; when omitted the hash falls back to `null` which still preserves\n * per-tenant/org uniqueness within the TTL window.\n */\n conversationId?: string | null\n}\n\n/**\n * Queue of UI parts the mutation-preview wrapper accumulates during a turn.\n * The chat/object dispatcher flushes these on the next emission boundary\n * (spec \u00A79 allows either direct streaming or this queue pattern \u2014 we ship the\n * queue in Step 5.6 and the chat dispatcher will drain it in Step 5.10 when\n * the `mutation-preview-card` component registers). BC: callers that ignore\n * the field are unaffected.\n */\nexport interface AiUiPartQueue {\n /** Pushed by the mutation wrapper; drained by the dispatcher in order. */\n enqueue: (part: AiUiPart) => void\n drain: () => AiUiPart[]\n size: () => number\n}\n\nfunction createAiUiPartQueue(): AiUiPartQueue {\n const buffer: AiUiPart[] = []\n return {\n enqueue: (part) => {\n buffer.push(part)\n },\n drain: () => {\n const snapshot = buffer.slice()\n buffer.length = 0\n return snapshot\n },\n size: () => buffer.length,\n }\n}\n\nexport interface ResolvedAgentTools {\n agent: AiAgentDefinition\n tools: Record<string, Tool<unknown, unknown>>\n /**\n * Per-request UI-part queue the chat dispatcher drains between streamText\n * chunks (Step 5.10 contract). Always present; empty when no mutation-tool\n * calls fire during the turn.\n */\n uiPartQueue: AiUiPartQueue\n}\n\nfunction toPolicyAuthContext(ctx: AiChatRequestContext): {\n userFeatures: string[]\n isSuperAdmin: boolean\n} {\n return {\n userFeatures: ctx.features,\n isSuperAdmin: ctx.isSuperAdmin,\n }\n}\n\n/**\n * Sanitize a dotted tool name (e.g. `search.hybrid_search`) into a format\n * accepted by all major LLM providers. OpenAI requires tool names to match\n * `^[a-zA-Z0-9_-]+$`; dots are replaced with double underscores (`__`).\n * Anthropic and Google accept both formats, so this is safe across providers.\n */\nexport function sanitizeToolNameForModel(name: string): string {\n return name.replace(/\\./g, '__')\n}\n\nexport function desanitizeToolNameForDisplay(name: string): string {\n return name.replace(/__/g, '.')\n}\n\nfunction formatToolResult(result: unknown): string {\n if (result === null || result === undefined) return 'No result returned'\n if (typeof result === 'string') return result\n if (typeof result === 'number' || typeof result === 'boolean') return String(result)\n try {\n return JSON.stringify(result, null, 2)\n } catch {\n return String(result)\n }\n}\n\nfunction buildToolHandlerContext(\n ctx: AiChatRequestContext,\n container?: AwilixContainer,\n tool?: AiToolDefinition,\n): McpToolContext {\n return {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: ctx.userId,\n container: (container ?? undefined) as unknown as McpToolContext['container'],\n userFeatures: ctx.features,\n isSuperAdmin: ctx.isSuperAdmin,\n ...(tool ? { tool } : {}),\n }\n}\n\ninterface MutationInterceptorOptions {\n agent: AiAgentDefinition\n tool: AiToolDefinition\n container: AwilixContainer\n ctx: AiChatRequestContext\n mutationPolicyOverride: AiAgentMutationPolicy | null\n conversationId: string | null\n uiPartQueue: AiUiPartQueue\n}\n\nfunction formatPendingActionToolResult(\n agent: AiAgentDefinition,\n tool: AiToolDefinition,\n pendingActionId: string,\n expiresAt: Date,\n reused: boolean,\n status: AiPendingActionStatus,\n executionResult: AiPendingActionExecutionResult | null,\n): string {\n // A reused `confirmed`/`executing` row means this exact mutation already\n // ran (or is running) under the same idempotency key \u2014 tell the model so\n // it does not resubmit, instead of always claiming a fresh approval is\n // pending (issue #7550).\n if (reused && (status === 'confirmed' || status === 'executing')) {\n const resultStatus = status === 'executing' ? 'executing' : 'already-executed'\n return formatToolResult({\n status: resultStatus,\n agentId: agent.id,\n toolName: tool.name,\n pendingActionId,\n executionResult: executionResult ?? null,\n message:\n resultStatus === 'executing'\n ? `Mutation \"${tool.name}\" is already executing from a prior confirmed call. Do NOT submit it again; wait for the result.`\n : `Mutation \"${tool.name}\" already ran for this input (idempotency key reused). Do NOT submit it again \u2014 see executionResult for the prior outcome.`,\n })\n }\n return formatToolResult({\n status: 'pending-confirmation',\n agentId: agent.id,\n toolName: tool.name,\n pendingActionId,\n expiresAt: expiresAt.toISOString(),\n message: `Awaiting user confirmation for mutation \"${tool.name}\". The action will NOT run until the user approves it.`,\n })\n}\n\n/**\n * Per-call gating decision for the destructive-confirm-required policy.\n * Honors a static boolean OR a predicate evaluated against the actual\n * tool-call args, so a multi-operation tool (e.g.\n * `customers.manage_deal_comment` with `operation: 'create' | 'update'\n * | 'delete'`) can gate only its destructive branches without being\n * split into multiple tools.\n */\nfunction resolveIsDestructive(\n isDestructive: boolean | ((input: unknown) => boolean) | undefined,\n args: unknown,\n): boolean {\n if (typeof isDestructive === 'function') {\n try {\n return isDestructive(args) === true\n } catch {\n // If the predicate throws (e.g. unexpected input shape), default to\n // gating \u2014 fail-safe for destructive policy.\n return true\n }\n }\n return isDestructive === true\n}\n\nfunction adaptToolToAiSdk(\n tool: AiToolDefinition,\n ctx: AiChatRequestContext,\n mutation: MutationInterceptorOptions | null,\n container?: AwilixContainer,\n effectiveMutationPolicy?: 'read-only' | 'confirm-required' | 'destructive-confirm-required',\n): Tool<unknown, unknown> {\n const safeSchema = toSafeZodSchema(tool.inputSchema as ZodType)\n const handlerContext = buildToolHandlerContext(ctx, container, tool)\n return dynamicTool({\n description: tool.description,\n inputSchema: safeSchema,\n execute: async (args: unknown) => {\n // Per-call gating decision. Under `destructive-confirm-required`,\n // tools with a predicate `isDestructive(args)` may flip per call \u2014\n // e.g. comment delete gates while comment create runs direct.\n const requiresApprovalNow = (() => {\n if (!mutation) return false\n if (effectiveMutationPolicy === 'confirm-required') return true\n if (effectiveMutationPolicy === 'destructive-confirm-required') {\n return resolveIsDestructive(mutation.tool.isDestructive, args)\n }\n return false\n })()\n if (mutation && requiresApprovalNow) {\n try {\n const toolCallArgs =\n args && typeof args === 'object' && !Array.isArray(args)\n ? { ...(args as Record<string, unknown>) }\n : {}\n const stagedInput = resolveStagedToolInput(tool.inputSchema, toolCallArgs)\n if (!stagedInput.success) {\n throw new Error(stagedInput.error)\n }\n const { uiPart, pendingAction, reused } = await prepareMutation(\n {\n agent: mutation.agent,\n tool: mutation.tool,\n toolCallArgs: stagedInput.input,\n conversationId: mutation.conversationId,\n mutationPolicyOverride: mutation.mutationPolicyOverride,\n },\n {\n tenantId: mutation.ctx.tenantId,\n organizationId: mutation.ctx.organizationId,\n userId: mutation.ctx.userId,\n features: mutation.ctx.features,\n isSuperAdmin: mutation.ctx.isSuperAdmin,\n container: mutation.container,\n },\n )\n mutation.uiPartQueue.enqueue(uiPart)\n return formatPendingActionToolResult(\n mutation.agent,\n mutation.tool,\n pendingAction.id,\n pendingAction.expiresAt,\n reused,\n pendingAction.status,\n pendingAction.executionResult ?? null,\n )\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(\n `Tool \"${tool.name}\" could not be prepared for confirmation: ${message}`,\n )\n }\n }\n try {\n // Create a fresh container per tool call so the EM is never stale.\n const freshContainer = await createRequestContainer()\n const freshContext: McpToolContext = {\n ...handlerContext,\n container: freshContainer as unknown as McpToolContext['container'],\n }\n const { executeTool } = await import('./tool-executor')\n const execResult = await executeTool(tool.name, args, freshContext)\n if (!execResult.success) {\n throw new Error(execResult.error || 'Tool execution failed')\n }\n return formatToolResult(execResult.result)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(`Tool \"${tool.name}\" failed: ${message}`)\n }\n },\n })\n}\n\n/**\n * Resolves the agent's whitelisted tools into an AI SDK `tools` map, enforcing\n * the same policy gate as the HTTP dispatcher. Throws {@link AgentPolicyError}\n * on agent-level deny; tool-level denies are skipped with a logger warning\n * because the agent author whitelisted a tool the caller is not currently\n * permitted to execute (deterministic non-failure \u2014 the remaining tools still\n * reach the model).\n */\nexport async function resolveAiAgentTools(\n input: ResolveAiAgentToolsInput,\n): Promise<ResolvedAgentTools> {\n await loadAgentRegistry()\n // The agent registry alone is not enough: the policy gate below resolves\n // every allowlisted name against the TOOL registry, and rejects what it\n // cannot find as `tool_unknown`. Loading it here \u2014 rather than in the half\n // dozen entry points that happened to remember \u2014 is what makes an agent's\n // allowlist mean the same thing on every path.\n try {\n const { ensureModuleToolsLoaded } = await import('./tool-loader')\n await ensureModuleToolsLoaded()\n } catch (error) {\n // A registry that failed to load leaves the agent toolless, which the\n // caller already handles; it must not take the whole turn down.\n logger.error('Could not load module tools; agent will resolve to its known tools only', {\n agentId: input.agentId,\n err: error,\n })\n }\n\n const policyAuth = toPolicyAuthContext(input.authContext)\n const mutationPolicyOverride = input.mutationPolicyOverride ?? null\n const agentDecision = checkAgentPolicy({\n agentId: input.agentId,\n authContext: policyAuth,\n requestedExecutionMode: input.requestedExecutionMode ?? 'chat',\n mutationPolicyOverride,\n })\n if (!agentDecision.ok) {\n throw new AgentPolicyError(agentDecision.code, agentDecision.message)\n }\n\n const { agent } = agentDecision\n const tools: Record<string, Tool<unknown, unknown>> = {}\n const uiPartQueue = createAiUiPartQueue()\n const effectiveMutationPolicy = resolveEffectiveMutationPolicy(\n agent.mutationPolicy,\n mutationPolicyOverride,\n agent.id,\n )\n const canInterceptMutations =\n effectiveMutationPolicy !== 'read-only' && typeof input.container !== 'undefined'\n\n for (const toolName of agent.allowedTools) {\n const toolDecision = checkAgentPolicy({\n agentId: input.agentId,\n authContext: policyAuth,\n toolName,\n mutationPolicyOverride,\n })\n if (!toolDecision.ok) {\n logger.warn('Skipping tool for agent', { toolName, agentId: agent.id, reason: toolDecision.message })\n continue\n }\n\n const record = (toolDecision.tool ?? toolRegistry.getTool(toolName)) as\n | AiToolDefinition\n | undefined\n if (!record) {\n logger.warn('Tool vanished from registry between policy checks; skipping', { toolName })\n continue\n }\n\n try {\n // For any mutation tool whose policy isn't read-only, prepare the\n // interceptor options once. The actual gate-vs-run-direct decision\n // happens at call time inside `adaptToolToAiSdk` because under\n // `destructive-confirm-required` `isDestructive` may be a predicate\n // evaluated against the per-call args (e.g. a multi-operation\n // tool with `operation: 'create' | 'update' | 'delete'` gates only\n // the destructive branch).\n const mutationOptions: MutationInterceptorOptions | null =\n record.isMutation === true && canInterceptMutations && input.container\n ? {\n agent,\n tool: record,\n container: input.container,\n ctx: input.authContext,\n mutationPolicyOverride,\n conversationId: input.conversationId ?? null,\n uiPartQueue,\n }\n : null\n // Sanitize tool name for model API compatibility: OpenAI requires\n // names matching ^[a-zA-Z0-9_-]+$ (no dots). Replace dots with\n // double underscores so `search.hybrid_search` becomes\n // `search__hybrid_search`. The AI SDK uses the record key as the\n // tool name sent to the model; the original dotted name stays on\n // the `tool` object for logging and prepareMutation hashing.\n const modelSafeToolName = sanitizeToolNameForModel(toolName)\n tools[modelSafeToolName] = adaptToolToAiSdk(\n record,\n input.authContext,\n mutationOptions,\n input.container,\n effectiveMutationPolicy,\n )\n } catch (error) {\n logger.error('Failed to adapt tool for agent', { toolName, agentId: agent.id, err: error })\n }\n }\n\n return { agent, tools, uiPartQueue }\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,mBAA8B;AAGvC,SAAS,8BAA8B;AAQvC,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB;AAChC,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AAEvC,MAAM,SAAS,aAAa,cAAc;AAOnC,MAAM,yBAAyB,MAAM;AAAA,EAG1C,YAAY,MAA2B,SAAiB;AACtD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAyDA,SAAS,sBAAqC;AAC5C,QAAM,SAAqB,CAAC;AAC5B,SAAO;AAAA,IACL,SAAS,CAAC,SAAS;AACjB,aAAO,KAAK,IAAI;AAAA,IAClB;AAAA,IACA,OAAO,MAAM;AACX,YAAM,WAAW,OAAO,MAAM;AAC9B,aAAO,SAAS;AAChB,aAAO;AA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MACF,IACA;AAON,YAAM,oBAAoB,yBAAyB,QAAQ;AAC3D,YAAM,iBAAiB,IAAI;AAAA,QACzB;AAAA,QACA,MAAM;AAAA,QACN;AAAA,QACA,MAAM;AAAA,QACN;AAAA,MACF;AAAA,IACF,SAAS,OAAO;AACd,aAAO,MAAM,kCAAkC,EAAE,UAAU,SAAS,MAAM,IAAI,KAAK,MAAM,CAAC;AAAA,IAC5F;AAAA,EACF;AAEA,SAAO,EAAE,OAAO,OAAO,YAAY;AACrC;",
6
6
  "names": []
7
7
  }
@@ -1,16 +1,8 @@
1
1
  import { createLogger } from "@open-mercato/shared/lib/logger";
2
2
  import { getToolRegistry } from "./tool-registry.js";
3
3
  import { hasRequiredFeatures } from "./auth.js";
4
+ import { parseToolInput } from "./tool-input.js";
4
5
  const logger = createLogger("ai_assistant");
5
- function sanitizeEmptyStrings(input) {
6
- if (!input || typeof input !== "object" || Array.isArray(input)) return input;
7
- const result = {};
8
- for (const [key, value] of Object.entries(input)) {
9
- if (typeof value === "string" && value.trim() === "") continue;
10
- result[key] = value;
11
- }
12
- return result;
13
- }
14
6
  async function executeTool(toolName, input, context) {
15
7
  const registry = getToolRegistry();
16
8
  const tool = registry.getTool(toolName);
@@ -37,16 +29,11 @@ async function executeTool(toolName, input, context) {
37
29
  };
38
30
  }
39
31
  }
40
- const sanitizedInput = sanitizeEmptyStrings(input);
41
- const parseResult = tool.inputSchema.safeParse(sanitizedInput);
32
+ const parseResult = parseToolInput(tool.inputSchema, input);
42
33
  if (!parseResult.success) {
43
- const issues = parseResult.error.issues ?? [];
44
- const errorMessages = issues.map(
45
- (issue) => `${issue.path.join(".")}: ${issue.message}`
46
- ).join("; ");
47
34
  return {
48
35
  success: false,
49
- error: `Invalid input: ${errorMessages || "Validation failed"}`,
36
+ error: parseResult.error,
50
37
  errorCode: "VALIDATION_ERROR"
51
38
  };
52
39
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/ai_assistant/lib/tool-executor.ts"],
4
- "sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { McpToolContext, ToolExecutionResult } from './types'\nimport { getToolRegistry } from './tool-registry'\nimport { hasRequiredFeatures } from './auth'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\n\nconst logger = createLogger('ai_assistant')\n\n/**\n * Strip empty strings from object values so LLM-generated `\"\"` for optional\n * fields becomes `undefined` (passes `.optional()` Zod validators).\n */\nfunction sanitizeEmptyStrings(input: unknown): unknown {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return input\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (typeof value === 'string' && value.trim() === '') continue\n result[key] = value\n }\n return result\n}\n\n/**\n * Execute a tool with full context and ACL checks.\n */\nexport async function executeTool(\n toolName: string,\n input: unknown,\n context: McpToolContext\n): Promise<ToolExecutionResult> {\n const registry = getToolRegistry()\n const tool = registry.getTool(toolName)\n\n if (!tool) {\n return {\n success: false,\n error: `Tool \"${toolName}\" not found`,\n errorCode: 'NOT_FOUND',\n }\n }\n\n // ACL check\n if (tool.requiredFeatures?.length) {\n const rbacService = context.container.resolve<RbacService>('rbacService')\n const hasAccess = hasRequiredFeatures(\n tool.requiredFeatures,\n context.userFeatures,\n context.isSuperAdmin,\n rbacService\n )\n\n if (!hasAccess) {\n return {\n success: false,\n error: `Insufficient permissions for tool \"${toolName}\". Required: ${tool.requiredFeatures.join(', ')}`,\n errorCode: 'UNAUTHORIZED',\n }\n }\n }\n\n // LLMs often send empty strings for optional fields (e.g., `personId: \"\"`).\n // Strip empty strings to `undefined` before Zod parsing so `.uuid().optional()`\n // fields pass validation when the model meant \"omit this field\".\n const sanitizedInput = sanitizeEmptyStrings(input)\n\n // Input validation\n const parseResult = tool.inputSchema.safeParse(sanitizedInput)\n if (!parseResult.success) {\n // Use any cast for Zod v4 compatibility\n const issues = (parseResult.error as any).issues ?? []\n const errorMessages = issues\n .map((issue: { path: PropertyKey[]; message: string }) =>\n `${issue.path.join('.')}: ${issue.message}`\n )\n .join('; ')\n return {\n success: false,\n error: `Invalid input: ${errorMessages || 'Validation failed'}`,\n errorCode: 'VALIDATION_ERROR',\n }\n }\n\n // Execute tool. Attach `tool` to the context so handlers that build an\n // `AiToolExecutionContext` (e.g. via `createAiApiOperationRunner`) keep their\n // route-gate coverage check working.\n const handlerContext: McpToolContext = { ...context, tool }\n try {\n const result = await tool.handler(parseResult.data, handlerContext)\n return { success: true, result }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.error('Error executing tool', { toolName, err: error })\n return {\n success: false,\n error: message,\n errorCode: 'EXECUTION_ERROR',\n }\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAE7B,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AAGpC,MAAM,SAAS,aAAa,cAAc;AAM1C,SAAS,qBAAqB,OAAyB;AACrD,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,EAAG,QAAO;AACxE,QAAM,SAAkC,CAAC;AACzC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAgC,GAAG;AAC3E,QAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,GAAI;AACtD,WAAO,GAAG,IAAI;AAAA,EAChB;AACA,SAAO;AACT;AAKA,eAAsB,YACpB,UACA,OACA,SAC8B;AAC9B,QAAM,WAAW,gBAAgB;AACjC,QAAM,OAAO,SAAS,QAAQ,QAAQ;AAEtC,MAAI,CAAC,MAAM;AACT,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO,SAAS,QAAQ;AAAA,MACxB,WAAW;AAAA,IACb;AAAA,EACF;AAGA,MAAI,KAAK,kBAAkB,QAAQ;AACjC,UAAM,cAAc,QAAQ,UAAU,QAAqB,aAAa;AACxE,UAAM,YAAY;AAAA,MAChB,KAAK;AAAA,MACL,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR;AAAA,IACF;AAEA,QAAI,CAAC,WAAW;AACd,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,sCAAsC,QAAQ,gBAAgB,KAAK,iBAAiB,KAAK,IAAI,CAAC;AAAA,QACrG,WAAW;AAAA,MACb;AAAA,IACF;AAAA,EACF;AAKA,QAAM,iBAAiB,qBAAqB,KAAK;AAGjD,QAAM,cAAc,KAAK,YAAY,UAAU,cAAc;AAC7D,MAAI,CAAC,YAAY,SAAS;AAExB,UAAM,SAAU,YAAY,MAAc,UAAU,CAAC;AACrD,UAAM,gBAAgB,OACnB;AAAA,MAAI,CAAC,UACJ,GAAG,MAAM,KAAK,KAAK,GAAG,CAAC,KAAK,MAAM,OAAO;AAAA,IAC3C,EACC,KAAK,IAAI;AACZ,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO,kBAAkB,iBAAiB,mBAAmB;AAAA,MAC7D,WAAW;AAAA,IACb;AAAA,EACF;AAKA,QAAM,iBAAiC,EAAE,GAAG,SAAS,KAAK;AAC1D,MAAI;AACF,UAAM,SAAS,MAAM,KAAK,QAAQ,YAAY,MAAM,cAAc;AAClE,WAAO,EAAE,SAAS,MAAM,OAAO;AAAA,EACjC,SAAS,OAAO;AACd,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,WAAO,MAAM,wBAAwB,EAAE,UAAU,KAAK,MAAM,CAAC;AAC7D,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO;AAAA,MACP,WAAW;AAAA,IACb;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { McpToolContext, ToolExecutionResult } from './types'\nimport { getToolRegistry } from './tool-registry'\nimport { hasRequiredFeatures } from './auth'\nimport { parseToolInput } from './tool-input'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\n\nconst logger = createLogger('ai_assistant')\n\n/**\n * Execute a tool with full context and ACL checks.\n */\nexport async function executeTool(\n toolName: string,\n input: unknown,\n context: McpToolContext\n): Promise<ToolExecutionResult> {\n const registry = getToolRegistry()\n const tool = registry.getTool(toolName)\n\n if (!tool) {\n return {\n success: false,\n error: `Tool \"${toolName}\" not found`,\n errorCode: 'NOT_FOUND',\n }\n }\n\n // ACL check\n if (tool.requiredFeatures?.length) {\n const rbacService = context.container.resolve<RbacService>('rbacService')\n const hasAccess = hasRequiredFeatures(\n tool.requiredFeatures,\n context.userFeatures,\n context.isSuperAdmin,\n rbacService\n )\n\n if (!hasAccess) {\n return {\n success: false,\n error: `Insufficient permissions for tool \"${toolName}\". Required: ${tool.requiredFeatures.join(', ')}`,\n errorCode: 'UNAUTHORIZED',\n }\n }\n }\n\n const parseResult = parseToolInput(tool.inputSchema, input)\n if (!parseResult.success) {\n return {\n success: false,\n error: parseResult.error,\n errorCode: 'VALIDATION_ERROR',\n }\n }\n\n // Execute tool. Attach `tool` to the context so handlers that build an\n // `AiToolExecutionContext` (e.g. via `createAiApiOperationRunner`) keep their\n // route-gate coverage check working.\n const handlerContext: McpToolContext = { ...context, tool }\n try {\n const result = await tool.handler(parseResult.data, handlerContext)\n return { success: true, result }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.error('Error executing tool', { toolName, err: error })\n return {\n success: false,\n error: message,\n errorCode: 'EXECUTION_ERROR',\n }\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAE7B,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AACpC,SAAS,sBAAsB;AAG/B,MAAM,SAAS,aAAa,cAAc;AAK1C,eAAsB,YACpB,UACA,OACA,SAC8B;AAC9B,QAAM,WAAW,gBAAgB;AACjC,QAAM,OAAO,SAAS,QAAQ,QAAQ;AAEtC,MAAI,CAAC,MAAM;AACT,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO,SAAS,QAAQ;AAAA,MACxB,WAAW;AAAA,IACb;AAAA,EACF;AAGA,MAAI,KAAK,kBAAkB,QAAQ;AACjC,UAAM,cAAc,QAAQ,UAAU,QAAqB,aAAa;AACxE,UAAM,YAAY;AAAA,MAChB,KAAK;AAAA,MACL,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR;AAAA,IACF;AAEA,QAAI,CAAC,WAAW;AACd,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,sCAAsC,QAAQ,gBAAgB,KAAK,iBAAiB,KAAK,IAAI,CAAC;AAAA,QACrG,WAAW;AAAA,MACb;AAAA,IACF;AAAA,EACF;AAEA,QAAM,cAAc,eAAe,KAAK,aAAa,KAAK;AAC1D,MAAI,CAAC,YAAY,SAAS;AACxB,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO,YAAY;AAAA,MACnB,WAAW;AAAA,IACb;AAAA,EACF;AAKA,QAAM,iBAAiC,EAAE,GAAG,SAAS,KAAK;AAC1D,MAAI;AACF,UAAM,SAAS,MAAM,KAAK,QAAQ,YAAY,MAAM,cAAc;AAClE,WAAO,EAAE,SAAS,MAAM,OAAO;AAAA,EACjC,SAAS,OAAO;AACd,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,WAAO,MAAM,wBAAwB,EAAE,UAAU,KAAK,MAAM,CAAC;AAC7D,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO;AAAA,MACP,WAAW;AAAA,IACb;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,32 @@
1
+ function stripEmptyStrings(input) {
2
+ const result = {};
3
+ for (const [key, value] of Object.entries(input)) {
4
+ if (typeof value === "string" && value.trim() === "") continue;
5
+ result[key] = value;
6
+ }
7
+ return result;
8
+ }
9
+ function sanitizeEmptyStrings(input) {
10
+ if (!input || typeof input !== "object" || Array.isArray(input)) return input;
11
+ return stripEmptyStrings(input);
12
+ }
13
+ function parseToolInput(inputSchema, input) {
14
+ const parseResult = inputSchema.safeParse(sanitizeEmptyStrings(input));
15
+ if (!parseResult.success) {
16
+ const errorMessages = parseResult.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
17
+ return { success: false, error: `Invalid input: ${errorMessages || "Validation failed"}` };
18
+ }
19
+ return { success: true, data: parseResult.data };
20
+ }
21
+ function resolveStagedToolInput(inputSchema, input) {
22
+ if (inputSchema.safeParse(input).success) return { success: true, input };
23
+ const sanitizedInput = stripEmptyStrings(input);
24
+ const parseResult = parseToolInput(inputSchema, sanitizedInput);
25
+ if (!parseResult.success) return parseResult;
26
+ return { success: true, input: sanitizedInput };
27
+ }
28
+ export {
29
+ parseToolInput,
30
+ resolveStagedToolInput
31
+ };
32
+ //# sourceMappingURL=tool-input.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/ai_assistant/lib/tool-input.ts"],
4
+ "sourcesContent": ["import type { AiToolDefinition } from './types'\n\nexport type ToolInputParseResult =\n | { success: true; data: unknown }\n | { success: false; error: string }\n\nexport type StagedToolInputResult =\n | { success: true; input: Record<string, unknown> }\n | { success: false; error: string }\n\nfunction stripEmptyStrings(input: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(input)) {\n if (typeof value === 'string' && value.trim() === '') continue\n result[key] = value\n }\n return result\n}\n\n/**\n * Strip empty strings from object values so LLM-generated `\"\"` for optional\n * fields becomes `undefined` (passes `.optional()` Zod validators).\n */\nfunction sanitizeEmptyStrings(input: unknown): unknown {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return input\n return stripEmptyStrings(input as Record<string, unknown>)\n}\n\n/**\n * Sanitize model-generated tool input and validate it against the tool's\n * schema, the way direct tool execution does before calling the handler.\n */\nexport function parseToolInput(\n inputSchema: AiToolDefinition['inputSchema'],\n input: unknown,\n): ToolInputParseResult {\n const parseResult = inputSchema.safeParse(sanitizeEmptyStrings(input))\n if (!parseResult.success) {\n const errorMessages = parseResult.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ')\n return { success: false, error: `Invalid input: ${errorMessages || 'Validation failed'}` }\n }\n return { success: true, data: parseResult.data }\n}\n\n/**\n * Resolve the input to stage for an approval-gated mutation. Input the tool\n * schema already accepts is staged as sent, matching the confirm-time\n * re-parse. Anything else gets the same blank-string cleanup and validation\n * as direct execution, so input that could only fail after approval is\n * refused before a pending action is created.\n */\nexport function resolveStagedToolInput(\n inputSchema: AiToolDefinition['inputSchema'],\n input: Record<string, unknown>,\n): StagedToolInputResult {\n if (inputSchema.safeParse(input).success) return { success: true, input }\n const sanitizedInput = stripEmptyStrings(input)\n const parseResult = parseToolInput(inputSchema, sanitizedInput)\n if (!parseResult.success) return parseResult\n return { success: true, input: sanitizedInput }\n}\n"],
5
+ "mappings": "AAUA,SAAS,kBAAkB,OAAyD;AAClF,QAAM,SAAkC,CAAC;AACzC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,GAAG;AAChD,QAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,GAAI;AACtD,WAAO,GAAG,IAAI;AAAA,EAChB;AACA,SAAO;AACT;AAMA,SAAS,qBAAqB,OAAyB;AACrD,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,EAAG,QAAO;AACxE,SAAO,kBAAkB,KAAgC;AAC3D;AAMO,SAAS,eACd,aACA,OACsB;AACtB,QAAM,cAAc,YAAY,UAAU,qBAAqB,KAAK,CAAC;AACrE,MAAI,CAAC,YAAY,SAAS;AACxB,UAAM,gBAAgB,YAAY,MAAM,OACrC,IAAI,CAAC,UAAU,GAAG,MAAM,KAAK,KAAK,GAAG,CAAC,KAAK,MAAM,OAAO,EAAE,EAC1D,KAAK,IAAI;AACZ,WAAO,EAAE,SAAS,OAAO,OAAO,kBAAkB,iBAAiB,mBAAmB,GAAG;AAAA,EAC3F;AACA,SAAO,EAAE,SAAS,MAAM,MAAM,YAAY,KAAK;AACjD;AASO,SAAS,uBACd,aACA,OACuB;AACvB,MAAI,YAAY,UAAU,KAAK,EAAE,QAAS,QAAO,EAAE,SAAS,MAAM,MAAM;AACxE,QAAM,iBAAiB,kBAAkB,KAAK;AAC9C,QAAM,cAAc,eAAe,aAAa,cAAc;AAC9D,MAAI,CAAC,YAAY,QAAS,QAAO;AACjC,SAAO,EAAE,SAAS,MAAM,OAAO,eAAe;AAChD;",
6
+ "names": []
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/ai-assistant",
3
- "version": "0.10.1-develop.8231.1.ae76b1d2c5",
3
+ "version": "0.10.1-develop.8258.1.62a94b74a2",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "engines": {
@@ -103,16 +103,16 @@
103
103
  "zod-to-json-schema": "^3.25.2"
104
104
  },
105
105
  "peerDependencies": {
106
- "@open-mercato/shared": "0.10.1-develop.8231.1.ae76b1d2c5",
107
- "@open-mercato/ui": "0.10.1-develop.8231.1.ae76b1d2c5",
106
+ "@open-mercato/shared": "0.10.1-develop.8258.1.62a94b74a2",
107
+ "@open-mercato/ui": "0.10.1-develop.8258.1.62a94b74a2",
108
108
  "react": "^19.0.0",
109
109
  "react-dom": "^19.0.0",
110
110
  "zod": ">=3.23.0"
111
111
  },
112
112
  "devDependencies": {
113
- "@open-mercato/cli": "0.10.1-develop.8231.1.ae76b1d2c5",
114
- "@open-mercato/shared": "0.10.1-develop.8231.1.ae76b1d2c5",
115
- "@open-mercato/ui": "0.10.1-develop.8231.1.ae76b1d2c5",
113
+ "@open-mercato/cli": "0.10.1-develop.8258.1.62a94b74a2",
114
+ "@open-mercato/shared": "0.10.1-develop.8258.1.62a94b74a2",
115
+ "@open-mercato/ui": "0.10.1-develop.8258.1.62a94b74a2",
116
116
  "@types/react": "^19.2.18",
117
117
  "@types/react-dom": "^19.2.5",
118
118
  "react": "19.2.8",
@@ -1,3 +1,4 @@
1
+ import { parseModuleCliOptions } from '@open-mercato/shared/lib/cli/parseModuleCliOptions'
1
2
  import type { ModuleCli } from '@open-mercato/shared/modules/registry'
2
3
  import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
3
4
  import { resetServerLoggerCache } from '@open-mercato/shared/lib/logger'
@@ -34,22 +35,7 @@ async function ensureBootstrap(): Promise<void> {
34
35
  }
35
36
 
36
37
  function parseArgs(rest: string[]): Record<string, string | boolean> {
37
- const args: Record<string, string | boolean> = {}
38
- for (let i = 0; i < rest.length; i++) {
39
- const arg = rest[i]
40
- if (!arg?.startsWith('--')) continue
41
-
42
- const [key, value] = arg.replace(/^--/, '').split('=')
43
- if (value !== undefined) {
44
- args[key] = value
45
- } else if (rest[i + 1] && !rest[i + 1]!.startsWith('--')) {
46
- args[key] = rest[i + 1]!
47
- i++
48
- } else {
49
- args[key] = true
50
- }
51
- }
52
- return args
38
+ return parseModuleCliOptions(rest)
53
39
  }
54
40
 
55
41
  const mcpServe: ModuleCli = {
@@ -251,9 +237,9 @@ const listTools: ModuleCli = {
251
237
  // Sort modules alphabetically
252
238
  const sortedModules = Array.from(byModule.keys()).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
253
239
 
254
- for (const module of sortedModules) {
255
- const tools = byModule.get(module)!
256
- console.log(`${module} (${tools.length} tools):`)
240
+ for (const moduleName of sortedModules) {
241
+ const tools = byModule.get(moduleName)!
242
+ console.log(`${moduleName} (${tools.length} tools):`)
257
243
 
258
244
  for (const name of tools.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {
259
245
  const tool = registry.getTool(name)
@@ -280,7 +266,7 @@ const entityGraph: ModuleCli = {
280
266
  const args = parseArgs(rest)
281
267
  const format = String(args.format ?? 'triples') as 'json' | 'triples'
282
268
  const entity = args.entity ? String(args.entity) : undefined
283
- const module = args.module ? String(args.module) : undefined
269
+ const moduleName = args.module ? String(args.module) : undefined
284
270
 
285
271
  await ensureBootstrap()
286
272
 
@@ -302,10 +288,10 @@ const entityGraph: ModuleCli = {
302
288
  console.log(`[Entity Graph] Filtered by entity: ${entity}`)
303
289
  }
304
290
 
305
- if (module) {
291
+ if (moduleName) {
306
292
  const filteredGraph = { ...graph, edges }
307
- edges = filterGraphByModule(filteredGraph, module)
308
- console.log(`[Entity Graph] Filtered by module: ${module}`)
293
+ edges = filterGraphByModule(filteredGraph, moduleName)
294
+ console.log(`[Entity Graph] Filtered by module: ${moduleName}`)
309
295
  }
310
296
 
311
297
  const filteredGraph = { ...graph, edges }
@@ -4,6 +4,7 @@ import type { ToolExecutionOptions } from 'ai'
4
4
  import { resolveAiAgentTools } from '../agent-tools'
5
5
  import { resetAgentRegistryForTests, seedAgentRegistryForTests } from '../agent-registry'
6
6
  import { registerMcpTool, toolRegistry } from '../tool-registry'
7
+ import { toSafeZodSchema } from '../schema-utils'
7
8
  import type { AiToolDefinition } from '../types'
8
9
  import type { AiAgentDefinition } from '../ai-agent-definition'
9
10
 
@@ -122,3 +123,118 @@ describe('agent approval paths alongside the direct HTTP refusal', () => {
122
123
  expect(prepareMutationMock).not.toHaveBeenCalled()
123
124
  })
124
125
  })
126
+
127
+ describe('confirm-required mutation input validation', () => {
128
+ const inputSchema = z.object({
129
+ personId: z.string().uuid().optional(),
130
+ note: z.string().min(1),
131
+ subtitle: z.string().max(255).nullable().optional(),
132
+ })
133
+ let handler: jest.Mock
134
+
135
+ beforeEach(() => {
136
+ jest.clearAllMocks()
137
+ resetAgentRegistryForTests()
138
+ toolRegistry.clear()
139
+ handler = jest.fn(async () => ({ written: true }))
140
+ const tool: AiToolDefinition = {
141
+ name: 'test.mutation',
142
+ description: 'Mutation fixture',
143
+ inputSchema,
144
+ isMutation: true,
145
+ requiredFeatures: ['test.records.manage'],
146
+ handler,
147
+ }
148
+ registerMcpTool(tool, { moduleId: 'test' })
149
+ prepareMutationMock.mockResolvedValue({
150
+ uiPart: { type: 'mutation-preview-card', data: { pendingActionId: 'action-1' } },
151
+ pendingAction: { id: 'action-1', expiresAt: new Date('2099-01-01'), status: 'pending' },
152
+ reused: false,
153
+ })
154
+ seedAgent()
155
+ })
156
+
157
+ afterEach(() => {
158
+ resetAgentRegistryForTests()
159
+ toolRegistry.clear()
160
+ })
161
+
162
+ it('refuses to stage a pending action whose input fails the tool schema', async () => {
163
+ const args = { personId: 'not-a-uuid', note: '' }
164
+ expect(toSafeZodSchema(inputSchema).safeParse(args).success).toBe(true)
165
+ const resolved = await resolveAiAgentTools({ agentId: 'test.assistant', authContext, container })
166
+
167
+ await expect(resolved.tools.test__mutation.execute?.(args, executionOptions)).rejects.toThrow(
168
+ /could not be prepared for confirmation: Invalid input: .*personId.*note/,
169
+ )
170
+
171
+ expect(prepareMutationMock).not.toHaveBeenCalled()
172
+ expect(handler).not.toHaveBeenCalled()
173
+ expect(resolved.uiPartQueue.drain()).toEqual([])
174
+ })
175
+
176
+ it('refuses schema-invalid input when a destructive-confirm-required predicate gates the call', async () => {
177
+ toolRegistry.clear()
178
+ const tool: AiToolDefinition = {
179
+ name: 'test.mutation',
180
+ description: 'Mutation fixture',
181
+ inputSchema,
182
+ isMutation: true,
183
+ isDestructive: () => true,
184
+ requiredFeatures: ['test.records.manage'],
185
+ handler,
186
+ }
187
+ registerMcpTool(tool, { moduleId: 'test' })
188
+ seedAgent({ mutationPolicy: 'destructive-confirm-required' })
189
+ const resolved = await resolveAiAgentTools({ agentId: 'test.assistant', authContext, container })
190
+
191
+ await expect(
192
+ resolved.tools.test__mutation.execute?.({ personId: 'not-a-uuid', note: 'hello' }, executionOptions),
193
+ ).rejects.toThrow(/could not be prepared for confirmation: Invalid input: personId/)
194
+
195
+ expect(prepareMutationMock).not.toHaveBeenCalled()
196
+ expect(handler).not.toHaveBeenCalled()
197
+ })
198
+
199
+ it('refuses the same input on the direct path when the predicate does not gate the call', async () => {
200
+ toolRegistry.clear()
201
+ const tool: AiToolDefinition = {
202
+ name: 'test.mutation',
203
+ description: 'Mutation fixture',
204
+ inputSchema,
205
+ isMutation: true,
206
+ isDestructive: () => false,
207
+ requiredFeatures: ['test.records.manage'],
208
+ handler,
209
+ }
210
+ registerMcpTool(tool, { moduleId: 'test' })
211
+ seedAgent({ mutationPolicy: 'destructive-confirm-required' })
212
+ const resolved = await resolveAiAgentTools({ agentId: 'test.assistant', authContext, container })
213
+
214
+ await expect(
215
+ resolved.tools.test__mutation.execute?.({ personId: 'not-a-uuid', note: 'hello' }, executionOptions),
216
+ ).rejects.toThrow(/failed: Invalid input: personId/)
217
+
218
+ expect(prepareMutationMock).not.toHaveBeenCalled()
219
+ expect(handler).not.toHaveBeenCalled()
220
+ })
221
+
222
+ it('stages sanitized input with blank optional values dropped', async () => {
223
+ const resolved = await resolveAiAgentTools({ agentId: 'test.assistant', authContext, container })
224
+
225
+ await resolved.tools.test__mutation.execute?.({ personId: '', note: 'hello' }, executionOptions)
226
+
227
+ expect(prepareMutationMock).toHaveBeenCalledTimes(1)
228
+ const stagedArgs = prepareMutationMock.mock.calls[0]?.[0].toolCallArgs
229
+ expect(stagedArgs).toEqual({ note: 'hello' })
230
+ expect(inputSchema.safeParse(stagedArgs).success).toBe(true)
231
+ })
232
+
233
+ it('stages input the schema already accepts as sent, blank values included', async () => {
234
+ const resolved = await resolveAiAgentTools({ agentId: 'test.assistant', authContext, container })
235
+
236
+ await resolved.tools.test__mutation.execute?.({ note: 'hello', subtitle: '' }, executionOptions)
237
+
238
+ expect(prepareMutationMock.mock.calls[0]?.[0].toolCallArgs).toEqual({ note: 'hello', subtitle: '' })
239
+ })
240
+ })
@@ -19,6 +19,7 @@ import {
19
19
  import { toolRegistry } from './tool-registry'
20
20
  import { toSafeZodSchema } from './schema-utils'
21
21
  import { prepareMutation } from './prepare-mutation'
22
+ import { resolveStagedToolInput } from './tool-input'
22
23
 
23
24
  const logger = createLogger('ai_assistant')
24
25
 
@@ -270,11 +271,15 @@ function adaptToolToAiSdk(
270
271
  args && typeof args === 'object' && !Array.isArray(args)
271
272
  ? { ...(args as Record<string, unknown>) }
272
273
  : {}
274
+ const stagedInput = resolveStagedToolInput(tool.inputSchema, toolCallArgs)
275
+ if (!stagedInput.success) {
276
+ throw new Error(stagedInput.error)
277
+ }
273
278
  const { uiPart, pendingAction, reused } = await prepareMutation(
274
279
  {
275
280
  agent: mutation.agent,
276
281
  tool: mutation.tool,
277
- toolCallArgs,
282
+ toolCallArgs: stagedInput.input,
278
283
  conversationId: mutation.conversationId,
279
284
  mutationPolicyOverride: mutation.mutationPolicyOverride,
280
285
  },
@@ -2,24 +2,11 @@ import { createLogger } from '@open-mercato/shared/lib/logger'
2
2
  import type { McpToolContext, ToolExecutionResult } from './types'
3
3
  import { getToolRegistry } from './tool-registry'
4
4
  import { hasRequiredFeatures } from './auth'
5
+ import { parseToolInput } from './tool-input'
5
6
  import type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'
6
7
 
7
8
  const logger = createLogger('ai_assistant')
8
9
 
9
- /**
10
- * Strip empty strings from object values so LLM-generated `""` for optional
11
- * fields becomes `undefined` (passes `.optional()` Zod validators).
12
- */
13
- function sanitizeEmptyStrings(input: unknown): unknown {
14
- if (!input || typeof input !== 'object' || Array.isArray(input)) return input
15
- const result: Record<string, unknown> = {}
16
- for (const [key, value] of Object.entries(input as Record<string, unknown>)) {
17
- if (typeof value === 'string' && value.trim() === '') continue
18
- result[key] = value
19
- }
20
- return result
21
- }
22
-
23
10
  /**
24
11
  * Execute a tool with full context and ACL checks.
25
12
  */
@@ -58,24 +45,11 @@ export async function executeTool(
58
45
  }
59
46
  }
60
47
 
61
- // LLMs often send empty strings for optional fields (e.g., `personId: ""`).
62
- // Strip empty strings to `undefined` before Zod parsing so `.uuid().optional()`
63
- // fields pass validation when the model meant "omit this field".
64
- const sanitizedInput = sanitizeEmptyStrings(input)
65
-
66
- // Input validation
67
- const parseResult = tool.inputSchema.safeParse(sanitizedInput)
48
+ const parseResult = parseToolInput(tool.inputSchema, input)
68
49
  if (!parseResult.success) {
69
- // Use any cast for Zod v4 compatibility
70
- const issues = (parseResult.error as any).issues ?? []
71
- const errorMessages = issues
72
- .map((issue: { path: PropertyKey[]; message: string }) =>
73
- `${issue.path.join('.')}: ${issue.message}`
74
- )
75
- .join('; ')
76
50
  return {
77
51
  success: false,
78
- error: `Invalid input: ${errorMessages || 'Validation failed'}`,
52
+ error: parseResult.error,
79
53
  errorCode: 'VALIDATION_ERROR',
80
54
  }
81
55
  }
@@ -0,0 +1,63 @@
1
+ import type { AiToolDefinition } from './types'
2
+
3
+ export type ToolInputParseResult =
4
+ | { success: true; data: unknown }
5
+ | { success: false; error: string }
6
+
7
+ export type StagedToolInputResult =
8
+ | { success: true; input: Record<string, unknown> }
9
+ | { success: false; error: string }
10
+
11
+ function stripEmptyStrings(input: Record<string, unknown>): Record<string, unknown> {
12
+ const result: Record<string, unknown> = {}
13
+ for (const [key, value] of Object.entries(input)) {
14
+ if (typeof value === 'string' && value.trim() === '') continue
15
+ result[key] = value
16
+ }
17
+ return result
18
+ }
19
+
20
+ /**
21
+ * Strip empty strings from object values so LLM-generated `""` for optional
22
+ * fields becomes `undefined` (passes `.optional()` Zod validators).
23
+ */
24
+ function sanitizeEmptyStrings(input: unknown): unknown {
25
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return input
26
+ return stripEmptyStrings(input as Record<string, unknown>)
27
+ }
28
+
29
+ /**
30
+ * Sanitize model-generated tool input and validate it against the tool's
31
+ * schema, the way direct tool execution does before calling the handler.
32
+ */
33
+ export function parseToolInput(
34
+ inputSchema: AiToolDefinition['inputSchema'],
35
+ input: unknown,
36
+ ): ToolInputParseResult {
37
+ const parseResult = inputSchema.safeParse(sanitizeEmptyStrings(input))
38
+ if (!parseResult.success) {
39
+ const errorMessages = parseResult.error.issues
40
+ .map((issue) => `${issue.path.join('.')}: ${issue.message}`)
41
+ .join('; ')
42
+ return { success: false, error: `Invalid input: ${errorMessages || 'Validation failed'}` }
43
+ }
44
+ return { success: true, data: parseResult.data }
45
+ }
46
+
47
+ /**
48
+ * Resolve the input to stage for an approval-gated mutation. Input the tool
49
+ * schema already accepts is staged as sent, matching the confirm-time
50
+ * re-parse. Anything else gets the same blank-string cleanup and validation
51
+ * as direct execution, so input that could only fail after approval is
52
+ * refused before a pending action is created.
53
+ */
54
+ export function resolveStagedToolInput(
55
+ inputSchema: AiToolDefinition['inputSchema'],
56
+ input: Record<string, unknown>,
57
+ ): StagedToolInputResult {
58
+ if (inputSchema.safeParse(input).success) return { success: true, input }
59
+ const sanitizedInput = stripEmptyStrings(input)
60
+ const parseResult = parseToolInput(inputSchema, sanitizedInput)
61
+ if (!parseResult.success) return parseResult
62
+ return { success: true, input: sanitizedInput }
63
+ }