@open-mercato/ai-assistant 0.10.1-develop.7736.1.88e07906bf → 0.10.1-develop.7748.1.d745ba61aa

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.
Files changed (58) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/index.js +2 -0
  3. package/dist/index.js.map +2 -2
  4. package/dist/modules/ai_assistant/__integration__/TC-AI-ACTIONS-OWNER-008-pending-action-owner-and-tool-features.spec.js +186 -0
  5. package/dist/modules/ai_assistant/__integration__/TC-AI-ACTIONS-OWNER-008-pending-action-owner-and-tool-features.spec.js.map +7 -0
  6. package/dist/modules/ai_assistant/__integration__/TC-AI-ACTIONS-OWNER-009-approval-cards-ui.spec.js +149 -0
  7. package/dist/modules/ai_assistant/__integration__/TC-AI-ACTIONS-OWNER-009-approval-cards-ui.spec.js.map +7 -0
  8. package/dist/modules/ai_assistant/__integration__/helpers/aiAssistantFixtures.js +18 -0
  9. package/dist/modules/ai_assistant/__integration__/helpers/aiAssistantFixtures.js.map +2 -2
  10. package/dist/modules/ai_assistant/cli.js +7 -1
  11. package/dist/modules/ai_assistant/cli.js.map +2 -2
  12. package/dist/modules/ai_assistant/data/repositories/AiPendingActionRepository.js +21 -5
  13. package/dist/modules/ai_assistant/data/repositories/AiPendingActionRepository.js.map +2 -2
  14. package/dist/modules/ai_assistant/i18n/de.json +5 -0
  15. package/dist/modules/ai_assistant/i18n/en.json +5 -0
  16. package/dist/modules/ai_assistant/i18n/es.json +5 -0
  17. package/dist/modules/ai_assistant/i18n/ko.json +5 -0
  18. package/dist/modules/ai_assistant/i18n/pl.json +5 -0
  19. package/dist/modules/ai_assistant/lib/http-server.js +7 -2
  20. package/dist/modules/ai_assistant/lib/http-server.js.map +2 -2
  21. package/dist/modules/ai_assistant/lib/mcp-dev-server.js +16 -3
  22. package/dist/modules/ai_assistant/lib/mcp-dev-server.js.map +2 -2
  23. package/dist/modules/ai_assistant/lib/mcp-host-resolution.js +18 -0
  24. package/dist/modules/ai_assistant/lib/mcp-host-resolution.js.map +7 -0
  25. package/dist/modules/ai_assistant/lib/pending-action-executor.js +16 -0
  26. package/dist/modules/ai_assistant/lib/pending-action-executor.js.map +2 -2
  27. package/dist/modules/ai_assistant/lib/pending-action-messages.js +12 -0
  28. package/dist/modules/ai_assistant/lib/pending-action-messages.js.map +7 -0
  29. package/dist/modules/ai_assistant/lib/pending-action-recheck.js +17 -0
  30. package/dist/modules/ai_assistant/lib/pending-action-recheck.js.map +2 -2
  31. package/dist/modules/ai_assistant/lib/prepare-mutation.js +4 -2
  32. package/dist/modules/ai_assistant/lib/prepare-mutation.js.map +2 -2
  33. package/package.json +6 -6
  34. package/src/index.ts +1 -0
  35. package/src/modules/ai_assistant/__integration__/TC-AI-ACTIONS-OWNER-008-pending-action-owner-and-tool-features.spec.ts +228 -0
  36. package/src/modules/ai_assistant/__integration__/TC-AI-ACTIONS-OWNER-009-approval-cards-ui.spec.ts +181 -0
  37. package/src/modules/ai_assistant/__integration__/helpers/aiAssistantFixtures.ts +25 -0
  38. package/src/modules/ai_assistant/api/ai/actions/[id]/confirm/__tests__/route.test.ts +41 -0
  39. package/src/modules/ai_assistant/cli.ts +6 -0
  40. package/src/modules/ai_assistant/data/repositories/AiPendingActionRepository.ts +40 -15
  41. package/src/modules/ai_assistant/data/repositories/__tests__/AiPendingActionRepository.test.ts +105 -23
  42. package/src/modules/ai_assistant/i18n/de.json +5 -0
  43. package/src/modules/ai_assistant/i18n/en.json +5 -0
  44. package/src/modules/ai_assistant/i18n/es.json +5 -0
  45. package/src/modules/ai_assistant/i18n/ko.json +5 -0
  46. package/src/modules/ai_assistant/i18n/pl.json +5 -0
  47. package/src/modules/ai_assistant/lib/__tests__/mcp-dev-server.test.ts +20 -0
  48. package/src/modules/ai_assistant/lib/__tests__/mcp-host-resolution.test.ts +37 -0
  49. package/src/modules/ai_assistant/lib/__tests__/pending-action-executor.test.ts +84 -0
  50. package/src/modules/ai_assistant/lib/__tests__/pending-action-recheck.test.ts +54 -0
  51. package/src/modules/ai_assistant/lib/__tests__/prepare-mutation.test.ts +44 -5
  52. package/src/modules/ai_assistant/lib/http-server.ts +16 -2
  53. package/src/modules/ai_assistant/lib/mcp-dev-server.ts +28 -4
  54. package/src/modules/ai_assistant/lib/mcp-host-resolution.ts +32 -0
  55. package/src/modules/ai_assistant/lib/pending-action-executor.ts +19 -0
  56. package/src/modules/ai_assistant/lib/pending-action-messages.ts +15 -0
  57. package/src/modules/ai_assistant/lib/pending-action-recheck.ts +27 -0
  58. package/src/modules/ai_assistant/lib/prepare-mutation.ts +7 -0
@@ -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'\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\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 })\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
- "mappings": "AACA,SAAS,8BAA8B;AACvC,SAAS,8BAA8B;AACvC,SAAS,qCAAqC;AAM9C,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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,gBAAM,SAAS,OAAO,SAAS,WAAM,OAAO,MAAM,KAAK;AACvD,gBAAM,WAAW,OAAO,aAAa,gBAAgB;AACrD,kBAAQ;AAAA,YACN,KAAK,MAAM,IAAI,OAAO,IAAI,GAAG,QAAQ,KAAK,OAAO,UAAU,MAAM,MAAM;AAAA,UACzE;AAAA,QACF;AAAA,MACF;AACA,cAAQ,IAAI,EAAE;AAAA,IAChB;AAEA,QAAI,OAAO,SAAS,GAAG;AACrB,cAAQ,WAAW;AAAA,IACrB;AAAA,EACF;AACF;AAEA,MAAM,qBAAgC;AAAA,EACpC,SAAS;AAAA,EACT,MAAM,MAAM;AACV,UAAM,gBAAgB;AACtB,UAAM,YAAY,MAAM,uBAAuB;AAE/C,UAAM,EAAE,oBAAoB,SAAS,IAAI,MAAM,OAC7C,gCACF;AAEA,UAAM,KAAK,UAAU,QAAuD,IAAI;AAChF,UAAM,UAAU,MAAM,SAAS,EAAE,GAAG,CAAC;AAErC,YAAQ,IAAI,0CAA0C,OAAO;AAAA,EAC/D;AACF;AAEA,IAAO,cAAQ;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;",
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
+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AAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;",
6
6
  "names": ["filteredGraph"]
7
7
  }
@@ -96,13 +96,16 @@ class AiPendingActionRepository {
96
96
  }
97
97
  async getById(id, ctx) {
98
98
  if (!id || !ctx?.tenantId) return null;
99
+ const owner = resolveOwnerScope(ctx);
100
+ if (!owner) return null;
99
101
  const row = await findOneWithDecryption(
100
102
  this.em,
101
103
  AiPendingAction,
102
104
  {
103
105
  id,
104
106
  tenantId: ctx.tenantId,
105
- organizationId: ctx.organizationId ?? null
107
+ organizationId: ctx.organizationId ?? null,
108
+ ...owner
106
109
  },
107
110
  {},
108
111
  {
@@ -114,6 +117,8 @@ class AiPendingActionRepository {
114
117
  }
115
118
  async listPendingForAgent(agentId, ctx, limit = 50) {
116
119
  if (!agentId || !ctx?.tenantId) return [];
120
+ const owner = resolveOwnerScope(ctx);
121
+ if (!owner) return [];
117
122
  const capped = Math.max(1, Math.min(Math.floor(limit), 200));
118
123
  const rows = await findWithDecryption(
119
124
  this.em,
@@ -122,7 +127,8 @@ class AiPendingActionRepository {
122
127
  tenantId: ctx.tenantId,
123
128
  organizationId: ctx.organizationId ?? null,
124
129
  agentId,
125
- status: "pending"
130
+ status: "pending",
131
+ ...owner
126
132
  },
127
133
  {
128
134
  orderBy: { createdAt: "desc" },
@@ -142,21 +148,23 @@ class AiPendingActionRepository {
142
148
  if (!id) {
143
149
  throw new Error("AiPendingActionRepository.setStatus requires id");
144
150
  }
151
+ const owner = resolveOwnerScope(ctx);
145
152
  return this.em.transactional(async (tx) => {
146
- const existing = await findOneWithDecryption(
153
+ const existing = owner ? await findOneWithDecryption(
147
154
  tx,
148
155
  AiPendingAction,
149
156
  {
150
157
  id,
151
158
  tenantId: ctx.tenantId,
152
- organizationId: ctx.organizationId ?? null
159
+ organizationId: ctx.organizationId ?? null,
160
+ ...owner
153
161
  },
154
162
  {},
155
163
  {
156
164
  tenantId: ctx.tenantId ?? null,
157
165
  organizationId: ctx.organizationId ?? null
158
166
  }
159
- );
167
+ ) : null;
160
168
  if (!existing) {
161
169
  throw new Error(`AiPendingAction not found: ${id}`);
162
170
  }
@@ -211,6 +219,14 @@ class AiPendingActionRepository {
211
219
  return rows;
212
220
  }
213
221
  }
222
+ const OWNER_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
223
+ function resolveOwnerScope(ctx) {
224
+ if (ctx.userId === null) return {};
225
+ if (typeof ctx.userId === "string" && OWNER_ID_PATTERN.test(ctx.userId)) {
226
+ return { createdByUserId: ctx.userId };
227
+ }
228
+ return null;
229
+ }
214
230
  function normalizeRecords(records) {
215
231
  if (!Array.isArray(records) || records.length === 0) return null;
216
232
  return records;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/ai_assistant/data/repositories/AiPendingActionRepository.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n findOneWithDecryption,\n findWithDecryption,\n} from '@open-mercato/shared/lib/encryption/find'\nimport { AiPendingAction } from '../entities'\nimport {\n AI_PENDING_ACTION_ALLOWED_TRANSITIONS,\n AiPendingActionStateError,\n resolveAiPendingActionTtlSeconds,\n type AiPendingActionExecutionResult,\n type AiPendingActionFailedRecord,\n type AiPendingActionFieldDiff,\n type AiPendingActionQueueMode,\n type AiPendingActionRecordDiff,\n type AiPendingActionStatus,\n} from '../../lib/pending-action-types'\n\nexport interface AiPendingActionContext {\n tenantId: string\n organizationId?: string | null\n userId?: string | null\n}\n\nexport interface AiPendingActionCreateInput {\n agentId: string\n toolName: string\n idempotencyKey: string\n createdByUserId: string\n normalizedInput: Record<string, unknown>\n conversationId?: string | null\n targetEntityType?: string | null\n targetRecordId?: string | null\n fieldDiff?: AiPendingActionFieldDiff[]\n records?: AiPendingActionRecordDiff[] | null\n sideEffectsSummary?: string | null\n recordVersion?: string | null\n attachmentIds?: string[]\n queueMode?: AiPendingActionQueueMode\n /** Optional explicit TTL in seconds; overrides the env/default TTL. */\n ttlSeconds?: number\n /** Optional explicit `now` for deterministic tests. */\n now?: Date\n}\n\nexport interface AiPendingActionCreateResult {\n row: AiPendingAction\n /**\n * True when `row` is an existing row returned as-is (a still-`pending`\n * row, or a `confirmed`/`executing` row whose mutation already ran) \u2014\n * i.e. no new row was inserted.\n */\n reused: boolean\n}\n\nexport interface AiPendingActionSetStatusExtra {\n resolvedByUserId?: string | null\n executionResult?: AiPendingActionExecutionResult | null\n failedRecords?: AiPendingActionFailedRecord[] | null\n /** Optional explicit `now` for deterministic tests. */\n now?: Date\n}\n\n/**\n * Persistent store for the Phase 3 WS-C mutation approval gate (Step 5.5).\n *\n * Responsibilities:\n * - Create new pending rows with a TTL-derived `expiresAt`, honoring\n * idempotency within the window (same `idempotencyKey` returns the same\n * row as long as it is still `pending`; any terminal state mints a new row).\n * - Tenant-scoped lookups for the confirm/cancel/reconnect routes and the\n * in-app UI's \"open actions\" list.\n * - State-machine enforcement: `setStatus` rejects illegal transitions via\n * {@link AiPendingActionStateError}. The runtime callers translate this\n * to a 409 Conflict response.\n * - `listExpired` for the cleanup worker (Step 5.12).\n *\n * Every read goes through `findOneWithDecryption` / `findWithDecryption`\n * because `normalized_input`, `field_diff` and `records` are declared in the\n * module's `encryption.ts` and are encrypted at rest when tenant data\n * encryption is enabled.\n */\nexport class AiPendingActionRepository {\n constructor(private readonly em: EntityManager) {}\n\n async create(\n input: AiPendingActionCreateInput,\n ctx: AiPendingActionContext,\n ): Promise<AiPendingActionCreateResult> {\n if (!ctx?.tenantId) {\n throw new Error('AiPendingActionRepository.create requires tenantId')\n }\n if (!input?.agentId) {\n throw new Error('AiPendingActionRepository.create requires agentId')\n }\n if (!input?.toolName) {\n throw new Error('AiPendingActionRepository.create requires toolName')\n }\n if (!input?.idempotencyKey) {\n throw new Error(\n 'AiPendingActionRepository.create requires idempotencyKey',\n )\n }\n if (!input?.createdByUserId) {\n throw new Error(\n 'AiPendingActionRepository.create requires createdByUserId',\n )\n }\n\n const now = input.now ?? new Date()\n const ttlSeconds = Math.max(\n 1,\n Math.floor(\n typeof input.ttlSeconds === 'number' && Number.isFinite(input.ttlSeconds)\n ? input.ttlSeconds\n : resolveAiPendingActionTtlSeconds(),\n ),\n )\n const expiresAt = new Date(now.getTime() + ttlSeconds * 1000)\n\n return this.em.transactional(async (tx) => {\n const existing = await findOneWithDecryption<AiPendingAction>(\n tx as unknown as EntityManager,\n AiPendingAction,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n idempotencyKey: input.idempotencyKey,\n } as any,\n { orderBy: { createdAt: 'desc' } as any },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (existing && existing.status === 'pending') {\n return { row: existing, reused: true }\n }\n // A `confirmed`/`executing` row represents a mutation that already\n // ran (or is running). Inserting a fresh row with the same key would\n // collide with the unique `(tenantId, organizationId,\n // idempotencyKey)` index \u2014 this happens whenever the model repeats\n // the same tool call with the same arguments after it already\n // succeeded. Return the existing row instead of inserting; the\n // caller (`prepareMutation`) uses `reused` to tell the model the\n // operation already ran rather than re-queuing it.\n //\n // This only holds within the row's own dedupe/TTL window\n // (`now < expiresAt`, per the spec's \"within the TTL\" dedupe\n // promise). Outside it, treat the row as stale: a legitimate repeat\n // of the same arguments later on would otherwise be refused forever,\n // and a process that died mid-execution would leave every retry\n // stuck reading a dead `executing` row.\n if (\n existing &&\n (existing.status === 'confirmed' || existing.status === 'executing') &&\n now.getTime() < existing.expiresAt.getTime()\n ) {\n return { row: existing, reused: true }\n }\n // A terminal (`failed`/`cancelled`/`expired`) row, or a stale\n // `confirmed`/`executing` row past its dedupe window, would also\n // collide on the same unique index when we insert a fresh one with\n // the same key \u2014 which happens whenever the operator clicks \"Fix\n // with AI\" and the model retries the SAME tool with the SAME args,\n // or simply repeats the same arguments later. Re-key the stale row\n // (instead of deleting it) so a retry can always proceed: the stale\n // row's own card keeps resolving to its terminal/prior state via a\n // GET by id, rather than 404ing.\n if (\n existing &&\n (existing.status === 'failed' ||\n existing.status === 'cancelled' ||\n existing.status === 'expired' ||\n existing.status === 'confirmed' ||\n existing.status === 'executing')\n ) {\n existing.idempotencyKey = `${existing.idempotencyKey}:superseded:${existing.id}`\n await tx.persist(existing).flush()\n }\n const row = tx.create(AiPendingAction, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n agentId: input.agentId,\n toolName: input.toolName,\n conversationId: input.conversationId ?? null,\n targetEntityType: input.targetEntityType ?? null,\n targetRecordId: input.targetRecordId ?? null,\n normalizedInput: input.normalizedInput ?? {},\n fieldDiff: Array.isArray(input.fieldDiff) ? input.fieldDiff : [],\n records: normalizeRecords(input.records),\n failedRecords: null,\n sideEffectsSummary: input.sideEffectsSummary ?? null,\n recordVersion: input.recordVersion ?? null,\n attachmentIds: Array.isArray(input.attachmentIds)\n ? input.attachmentIds\n : [],\n idempotencyKey: input.idempotencyKey,\n createdByUserId: input.createdByUserId,\n status: 'pending' as AiPendingActionStatus,\n queueMode: (input.queueMode ?? 'inline') as AiPendingActionQueueMode,\n executionResult: null,\n createdAt: now,\n expiresAt,\n resolvedAt: null,\n resolvedByUserId: null,\n } as unknown as AiPendingAction)\n await tx.persist(row).flush()\n return { row, reused: false }\n })\n }\n\n async getById(\n id: string,\n ctx: AiPendingActionContext,\n ): Promise<AiPendingAction | null> {\n if (!id || !ctx?.tenantId) return null\n const row = await findOneWithDecryption<AiPendingAction>(\n this.em,\n AiPendingAction,\n {\n id,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n return row ?? null\n }\n\n async listPendingForAgent(\n agentId: string,\n ctx: AiPendingActionContext,\n limit: number = 50,\n ): Promise<AiPendingAction[]> {\n if (!agentId || !ctx?.tenantId) return []\n const capped = Math.max(1, Math.min(Math.floor(limit), 200))\n const rows = await findWithDecryption<AiPendingAction>(\n this.em,\n AiPendingAction,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n agentId,\n status: 'pending',\n } as any,\n {\n orderBy: { createdAt: 'desc' } as any,\n limit: capped,\n },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n return rows\n }\n\n async setStatus(\n id: string,\n nextStatus: AiPendingActionStatus,\n ctx: AiPendingActionContext,\n extra?: AiPendingActionSetStatusExtra,\n ): Promise<AiPendingAction> {\n if (!ctx?.tenantId) {\n throw new Error('AiPendingActionRepository.setStatus requires tenantId')\n }\n if (!id) {\n throw new Error('AiPendingActionRepository.setStatus requires id')\n }\n return this.em.transactional(async (tx) => {\n const existing = await findOneWithDecryption<AiPendingAction>(\n tx as unknown as EntityManager,\n AiPendingAction,\n {\n id,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (!existing) {\n throw new Error(`AiPendingAction not found: ${id}`)\n }\n if (existing.status === nextStatus) {\n return existing\n }\n const allowed = AI_PENDING_ACTION_ALLOWED_TRANSITIONS[existing.status] ?? []\n if (!allowed.includes(nextStatus)) {\n throw new AiPendingActionStateError(existing.status, nextStatus)\n }\n const now = extra?.now ?? new Date()\n existing.status = nextStatus\n if (\n nextStatus === 'confirmed' ||\n nextStatus === 'cancelled' ||\n nextStatus === 'expired' ||\n nextStatus === 'failed'\n ) {\n existing.resolvedAt = existing.resolvedAt ?? now\n if (extra && Object.prototype.hasOwnProperty.call(extra, 'resolvedByUserId')) {\n existing.resolvedByUserId = extra.resolvedByUserId ?? null\n } else if (nextStatus === 'expired') {\n existing.resolvedByUserId = null\n }\n }\n if (extra && Object.prototype.hasOwnProperty.call(extra, 'executionResult')) {\n existing.executionResult = extra.executionResult ?? null\n }\n if (extra && Object.prototype.hasOwnProperty.call(extra, 'failedRecords')) {\n existing.failedRecords = normalizeFailedRecords(extra.failedRecords)\n }\n await tx.persist(existing).flush()\n return existing\n })\n }\n\n async listExpired(\n ctx: AiPendingActionContext,\n now: Date,\n limit: number = 100,\n ): Promise<AiPendingAction[]> {\n if (!ctx?.tenantId) return []\n const capped = Math.max(1, Math.min(Math.floor(limit), 500))\n const rows = await findWithDecryption<AiPendingAction>(\n this.em,\n AiPendingAction,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n status: 'pending',\n expiresAt: { $lt: now } as any,\n } as any,\n {\n orderBy: { expiresAt: 'asc' } as any,\n limit: capped,\n },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n return rows\n }\n}\n\nfunction normalizeRecords(\n records: AiPendingActionRecordDiff[] | null | undefined,\n): AiPendingActionRecordDiff[] | null {\n if (!Array.isArray(records) || records.length === 0) return null\n return records\n}\n\nfunction normalizeFailedRecords(\n failed: AiPendingActionFailedRecord[] | null | undefined,\n): AiPendingActionFailedRecord[] | null {\n if (!Array.isArray(failed) || failed.length === 0) return null\n return failed\n}\n\nexport default AiPendingActionRepository\n"],
5
- "mappings": "AACA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AAkEA,MAAM,0BAA0B;AAAA,EACrC,YAA6B,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAEjD,MAAM,OACJ,OACA,KACsC;AACtC,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,oDAAoD;AAAA,IACtE;AACA,QAAI,CAAC,OAAO,SAAS;AACnB,YAAM,IAAI,MAAM,mDAAmD;AAAA,IACrE;AACA,QAAI,CAAC,OAAO,UAAU;AACpB,YAAM,IAAI,MAAM,oDAAoD;AAAA,IACtE;AACA,QAAI,CAAC,OAAO,gBAAgB;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O;AAAA,EACT;AACF;AAEA,SAAS,iBACP,SACoC;AACpC,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,EAAG,QAAO;AAC5D,SAAO;AACT;AAEA,SAAS,uBACP,QACsC;AACtC,MAAI,CAAC,MAAM,QAAQ,MAAM,KAAK,OAAO,WAAW,EAAG,QAAO;AAC1D,SAAO;AACT;AAEA,IAAO,oCAAQ;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n findOneWithDecryption,\n findWithDecryption,\n} from '@open-mercato/shared/lib/encryption/find'\nimport { AiPendingAction } from '../entities'\nimport {\n AI_PENDING_ACTION_ALLOWED_TRANSITIONS,\n AiPendingActionStateError,\n resolveAiPendingActionTtlSeconds,\n type AiPendingActionExecutionResult,\n type AiPendingActionFailedRecord,\n type AiPendingActionFieldDiff,\n type AiPendingActionQueueMode,\n type AiPendingActionRecordDiff,\n type AiPendingActionStatus,\n} from '../../lib/pending-action-types'\n\nexport interface AiPendingActionContext {\n tenantId: string\n organizationId?: string | null\n userId?: string | null\n}\n\nexport interface AiPendingActionCreateInput {\n agentId: string\n toolName: string\n idempotencyKey: string\n createdByUserId: string\n normalizedInput: Record<string, unknown>\n conversationId?: string | null\n targetEntityType?: string | null\n targetRecordId?: string | null\n fieldDiff?: AiPendingActionFieldDiff[]\n records?: AiPendingActionRecordDiff[] | null\n sideEffectsSummary?: string | null\n recordVersion?: string | null\n attachmentIds?: string[]\n queueMode?: AiPendingActionQueueMode\n /** Optional explicit TTL in seconds; overrides the env/default TTL. */\n ttlSeconds?: number\n /** Optional explicit `now` for deterministic tests. */\n now?: Date\n}\n\nexport interface AiPendingActionCreateResult {\n row: AiPendingAction\n /**\n * True when `row` is an existing row returned as-is (a still-`pending`\n * row, or a `confirmed`/`executing` row whose mutation already ran) \u2014\n * i.e. no new row was inserted.\n */\n reused: boolean\n}\n\nexport interface AiPendingActionSetStatusExtra {\n resolvedByUserId?: string | null\n executionResult?: AiPendingActionExecutionResult | null\n failedRecords?: AiPendingActionFailedRecord[] | null\n /** Optional explicit `now` for deterministic tests. */\n now?: Date\n}\n\n/**\n * Persistent store for the Phase 3 WS-C mutation approval gate (Step 5.5).\n *\n * Responsibilities:\n * - Create new pending rows with a TTL-derived `expiresAt`, honoring\n * idempotency within the window (same `idempotencyKey` returns the same\n * row as long as it is still `pending`; any terminal state mints a new row).\n * - Tenant-scoped lookups for the confirm/cancel/reconnect routes and the\n * in-app UI's \"open actions\" list. `getById`, `listPendingForAgent` and\n * `setStatus` are also owner-scoped: they match the row's\n * `createdByUserId` against `ctx.userId`, so only the proposing user can\n * read or resolve it. System callers (the expiry sweeper) pass\n * `userId: null` to skip the owner filter; a missing or non-UUID\n * `userId` (for example an API-key subject) matches no row.\n * - State-machine enforcement: `setStatus` rejects illegal transitions via\n * {@link AiPendingActionStateError}. The runtime callers translate this\n * to a 409 Conflict response.\n * - `listExpired` for the cleanup worker (Step 5.12).\n *\n * Every read goes through `findOneWithDecryption` / `findWithDecryption`\n * because `normalized_input`, `field_diff` and `records` are declared in the\n * module's `encryption.ts` and are encrypted at rest when tenant data\n * encryption is enabled.\n */\nexport class AiPendingActionRepository {\n constructor(private readonly em: EntityManager) {}\n\n async create(\n input: AiPendingActionCreateInput,\n ctx: AiPendingActionContext,\n ): Promise<AiPendingActionCreateResult> {\n if (!ctx?.tenantId) {\n throw new Error('AiPendingActionRepository.create requires tenantId')\n }\n if (!input?.agentId) {\n throw new Error('AiPendingActionRepository.create requires agentId')\n }\n if (!input?.toolName) {\n throw new Error('AiPendingActionRepository.create requires toolName')\n }\n if (!input?.idempotencyKey) {\n throw new Error(\n 'AiPendingActionRepository.create requires idempotencyKey',\n )\n }\n if (!input?.createdByUserId) {\n throw new Error(\n 'AiPendingActionRepository.create requires createdByUserId',\n )\n }\n\n const now = input.now ?? new Date()\n const ttlSeconds = Math.max(\n 1,\n Math.floor(\n typeof input.ttlSeconds === 'number' && Number.isFinite(input.ttlSeconds)\n ? input.ttlSeconds\n : resolveAiPendingActionTtlSeconds(),\n ),\n )\n const expiresAt = new Date(now.getTime() + ttlSeconds * 1000)\n\n return this.em.transactional(async (tx) => {\n const existing = await findOneWithDecryption<AiPendingAction>(\n tx as unknown as EntityManager,\n AiPendingAction,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n idempotencyKey: input.idempotencyKey,\n } as any,\n { orderBy: { createdAt: 'desc' } as any },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (existing && existing.status === 'pending') {\n return { row: existing, reused: true }\n }\n // A `confirmed`/`executing` row represents a mutation that already\n // ran (or is running). Inserting a fresh row with the same key would\n // collide with the unique `(tenantId, organizationId,\n // idempotencyKey)` index \u2014 this happens whenever the model repeats\n // the same tool call with the same arguments after it already\n // succeeded. Return the existing row instead of inserting; the\n // caller (`prepareMutation`) uses `reused` to tell the model the\n // operation already ran rather than re-queuing it.\n //\n // This only holds within the row's own dedupe/TTL window\n // (`now < expiresAt`, per the spec's \"within the TTL\" dedupe\n // promise). Outside it, treat the row as stale: a legitimate repeat\n // of the same arguments later on would otherwise be refused forever,\n // and a process that died mid-execution would leave every retry\n // stuck reading a dead `executing` row.\n if (\n existing &&\n (existing.status === 'confirmed' || existing.status === 'executing') &&\n now.getTime() < existing.expiresAt.getTime()\n ) {\n return { row: existing, reused: true }\n }\n // A terminal (`failed`/`cancelled`/`expired`) row, or a stale\n // `confirmed`/`executing` row past its dedupe window, would also\n // collide on the same unique index when we insert a fresh one with\n // the same key \u2014 which happens whenever the operator clicks \"Fix\n // with AI\" and the model retries the SAME tool with the SAME args,\n // or simply repeats the same arguments later. Re-key the stale row\n // (instead of deleting it) so a retry can always proceed: the stale\n // row's own card keeps resolving to its terminal/prior state via a\n // GET by id, rather than 404ing.\n if (\n existing &&\n (existing.status === 'failed' ||\n existing.status === 'cancelled' ||\n existing.status === 'expired' ||\n existing.status === 'confirmed' ||\n existing.status === 'executing')\n ) {\n existing.idempotencyKey = `${existing.idempotencyKey}:superseded:${existing.id}`\n await tx.persist(existing).flush()\n }\n const row = tx.create(AiPendingAction, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n agentId: input.agentId,\n toolName: input.toolName,\n conversationId: input.conversationId ?? null,\n targetEntityType: input.targetEntityType ?? null,\n targetRecordId: input.targetRecordId ?? null,\n normalizedInput: input.normalizedInput ?? {},\n fieldDiff: Array.isArray(input.fieldDiff) ? input.fieldDiff : [],\n records: normalizeRecords(input.records),\n failedRecords: null,\n sideEffectsSummary: input.sideEffectsSummary ?? null,\n recordVersion: input.recordVersion ?? null,\n attachmentIds: Array.isArray(input.attachmentIds)\n ? input.attachmentIds\n : [],\n idempotencyKey: input.idempotencyKey,\n createdByUserId: input.createdByUserId,\n status: 'pending' as AiPendingActionStatus,\n queueMode: (input.queueMode ?? 'inline') as AiPendingActionQueueMode,\n executionResult: null,\n createdAt: now,\n expiresAt,\n resolvedAt: null,\n resolvedByUserId: null,\n } as unknown as AiPendingAction)\n await tx.persist(row).flush()\n return { row, reused: false }\n })\n }\n\n async getById(\n id: string,\n ctx: AiPendingActionContext,\n ): Promise<AiPendingAction | null> {\n if (!id || !ctx?.tenantId) return null\n const owner = resolveOwnerScope(ctx)\n if (!owner) return null\n const row = await findOneWithDecryption<AiPendingAction>(\n this.em,\n AiPendingAction,\n {\n id,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n ...owner,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n return row ?? null\n }\n\n async listPendingForAgent(\n agentId: string,\n ctx: AiPendingActionContext,\n limit: number = 50,\n ): Promise<AiPendingAction[]> {\n if (!agentId || !ctx?.tenantId) return []\n const owner = resolveOwnerScope(ctx)\n if (!owner) return []\n const capped = Math.max(1, Math.min(Math.floor(limit), 200))\n const rows = await findWithDecryption<AiPendingAction>(\n this.em,\n AiPendingAction,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n agentId,\n status: 'pending',\n ...owner,\n } as any,\n {\n orderBy: { createdAt: 'desc' } as any,\n limit: capped,\n },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n return rows\n }\n\n async setStatus(\n id: string,\n nextStatus: AiPendingActionStatus,\n ctx: AiPendingActionContext,\n extra?: AiPendingActionSetStatusExtra,\n ): Promise<AiPendingAction> {\n if (!ctx?.tenantId) {\n throw new Error('AiPendingActionRepository.setStatus requires tenantId')\n }\n if (!id) {\n throw new Error('AiPendingActionRepository.setStatus requires id')\n }\n const owner = resolveOwnerScope(ctx)\n return this.em.transactional(async (tx) => {\n const existing = owner\n ? await findOneWithDecryption<AiPendingAction>(\n tx as unknown as EntityManager,\n AiPendingAction,\n {\n id,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n ...owner,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n : null\n if (!existing) {\n throw new Error(`AiPendingAction not found: ${id}`)\n }\n if (existing.status === nextStatus) {\n return existing\n }\n const allowed = AI_PENDING_ACTION_ALLOWED_TRANSITIONS[existing.status] ?? []\n if (!allowed.includes(nextStatus)) {\n throw new AiPendingActionStateError(existing.status, nextStatus)\n }\n const now = extra?.now ?? new Date()\n existing.status = nextStatus\n if (\n nextStatus === 'confirmed' ||\n nextStatus === 'cancelled' ||\n nextStatus === 'expired' ||\n nextStatus === 'failed'\n ) {\n existing.resolvedAt = existing.resolvedAt ?? now\n if (extra && Object.prototype.hasOwnProperty.call(extra, 'resolvedByUserId')) {\n existing.resolvedByUserId = extra.resolvedByUserId ?? null\n } else if (nextStatus === 'expired') {\n existing.resolvedByUserId = null\n }\n }\n if (extra && Object.prototype.hasOwnProperty.call(extra, 'executionResult')) {\n existing.executionResult = extra.executionResult ?? null\n }\n if (extra && Object.prototype.hasOwnProperty.call(extra, 'failedRecords')) {\n existing.failedRecords = normalizeFailedRecords(extra.failedRecords)\n }\n await tx.persist(existing).flush()\n return existing\n })\n }\n\n async listExpired(\n ctx: AiPendingActionContext,\n now: Date,\n limit: number = 100,\n ): Promise<AiPendingAction[]> {\n if (!ctx?.tenantId) return []\n const capped = Math.max(1, Math.min(Math.floor(limit), 500))\n const rows = await findWithDecryption<AiPendingAction>(\n this.em,\n AiPendingAction,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n status: 'pending',\n expiresAt: { $lt: now } as any,\n } as any,\n {\n orderBy: { expiresAt: 'asc' } as any,\n limit: capped,\n },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n return rows\n }\n}\n\nconst OWNER_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nfunction resolveOwnerScope(ctx: AiPendingActionContext): { createdByUserId?: string } | null {\n if (ctx.userId === null) return {}\n if (typeof ctx.userId === 'string' && OWNER_ID_PATTERN.test(ctx.userId)) {\n return { createdByUserId: ctx.userId }\n }\n return null\n}\n\nfunction normalizeRecords(\n records: AiPendingActionRecordDiff[] | null | undefined,\n): AiPendingActionRecordDiff[] | null {\n if (!Array.isArray(records) || records.length === 0) return null\n return records\n}\n\nfunction normalizeFailedRecords(\n failed: AiPendingActionFailedRecord[] | null | undefined,\n): AiPendingActionFailedRecord[] | null {\n if (!Array.isArray(failed) || failed.length === 0) return null\n return failed\n}\n\nexport default AiPendingActionRepository\n"],
5
+ "mappings": "AACA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AAuEA,MAAM,0BAA0B;AAAA,EACrC,YAA6B,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAEjD,MAAM,OACJ,OACA,KACsC;AACtC,QAAI,CAAC,KAAK,UAAU;AA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UAAM,SAAS,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,MAAM,KAAK,GAAG,GAAG,CAAC;AAC3D,UAAM,OAAO,MAAM;AAAA,MACjB,KAAK;AAAA,MACL;AAAA,MACA;AAAA,QACE,UAAU,IAAI;AAAA,QACd,gBAAgB,IAAI,kBAAkB;AAAA,QACtC,QAAQ;AAAA,QACR,WAAW,EAAE,KAAK,IAAI;AAAA,MACxB;AAAA,MACA;AAAA,QACE,SAAS,EAAE,WAAW,MAAM;AAAA,QAC5B,OAAO;AAAA,MACT;AAAA,MACA;AAAA,QACE,UAAU,IAAI,YAAY;AAAA,QAC1B,gBAAgB,IAAI,kBAAkB;AAAA,MACxC;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;AAEA,MAAM,mBAAmB;AAEzB,SAAS,kBAAkB,KAAkE;AAC3F,MAAI,IAAI,WAAW,KAAM,QAAO,CAAC;AACjC,MAAI,OAAO,IAAI,WAAW,YAAY,iBAAiB,KAAK,IAAI,MAAM,GAAG;AACvE,WAAO,EAAE,iBAAiB,IAAI,OAAO;AAAA,EACvC;AACA,SAAO;AACT;AAEA,SAAS,iBACP,SACoC;AACpC,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,EAAG,QAAO;AAC5D,SAAO;AACT;AAEA,SAAS,uBACP,QACsC;AACtC,MAAI,CAAC,MAAM,QAAQ,MAAM,KAAK,OAAO,WAAW,EAAG,QAAO;AAC1D,SAAO;AACT;AAEA,IAAO,oCAAQ;",
6
6
  "names": []
7
7
  }
@@ -213,11 +213,14 @@
213
213
  "ai_assistant.chat.mutation_cards.confirmation.errorTitle": "Bestätigung fehlgeschlagen",
214
214
  "ai_assistant.chat.mutation_cards.confirmation.invalidStatusBody": "Diese Aktion wurde bereits bestätigt, abgebrochen oder ausgeführt.",
215
215
  "ai_assistant.chat.mutation_cards.confirmation.invalidStatusTitle": "Aktion bereits abgeschlossen",
216
+ "ai_assistant.chat.mutation_cards.confirmation.notFoundTitle": "Vorschlag nicht verfügbar",
216
217
  "ai_assistant.chat.mutation_cards.confirmation.schemaDriftBody": "Die Tool-Signatur hat sich seit der Vorschau geändert. Bitte den Assistenten um einen neuen Vorschlag.",
217
218
  "ai_assistant.chat.mutation_cards.confirmation.schemaDriftTitle": "Schema geändert",
218
219
  "ai_assistant.chat.mutation_cards.confirmation.staleVersionBody": "Ein oder mehrere Datensätze haben sich seit der Vorschau geändert. Bitte den Assistenten um einen neuen Vorschlag.",
219
220
  "ai_assistant.chat.mutation_cards.confirmation.staleVersionTitle": "Erneuter Vorschlag erforderlich",
220
221
  "ai_assistant.chat.mutation_cards.confirmation.title": "Aktion wird ausgeführt...",
222
+ "ai_assistant.chat.mutation_cards.confirmation.toolFeaturesDeniedBody": "Sie haben nicht mehr die Berechtigungen, die diese Änderung erfordert. Bitten Sie einen Administrator um Zugriff oder brechen Sie den Vorschlag ab.",
223
+ "ai_assistant.chat.mutation_cards.confirmation.toolFeaturesDeniedTitle": "Berechtigung erforderlich",
221
224
  "ai_assistant.chat.mutation_cards.diff.afterHeader": "Nachher",
222
225
  "ai_assistant.chat.mutation_cards.diff.beforeHeader": "Vorher",
223
226
  "ai_assistant.chat.mutation_cards.diff.empty": "Keine Feldänderungen für diesen Datensatz.",
@@ -229,6 +232,7 @@
229
232
  "ai_assistant.chat.mutation_cards.preview.handlerError": "Der Mutations-Handler meldete einen Fehler. Prüfen Sie die Details und schlagen Sie die Aktion ggf. erneut vor.",
230
233
  "ai_assistant.chat.mutation_cards.preview.reviewDetails": "Details ansehen",
231
234
  "ai_assistant.chat.mutation_cards.preview.title": "Vorgeschlagene Änderungen prüfen",
235
+ "ai_assistant.chat.mutation_cards.preview.unavailable": "Dieser Vorschlag ist nicht verfügbar. Er wurde möglicherweise bereits erledigt oder entfernt, oder eine andere Person hat ihn angefordert.",
232
236
  "ai_assistant.chat.mutation_cards.result.cancelledBody": "Sie haben diese vorgeschlagene Änderung abgebrochen. Es wurden keine Änderungen vorgenommen.",
233
237
  "ai_assistant.chat.mutation_cards.result.cancelledTitle": "Vorschlag abgebrochen",
234
238
  "ai_assistant.chat.mutation_cards.result.failureBody": "Die Änderung konnte nicht angewendet werden.",
@@ -321,6 +325,7 @@
321
325
  "ai_assistant.errors.pendingRecordNotPreviewed": "Dieser Datensatz war nicht Teil der genehmigten Vorschau und wurde daher nicht geändert.",
322
326
  "ai_assistant.errors.pendingRecordStale": "Die Datensatzversion hat sich seit der Vorschau geändert.",
323
327
  "ai_assistant.errors.pendingSingleRecordStale": "Die Datensatzversion hat sich seit der Vorschau geändert; schlagen Sie die Änderung neu vor.",
328
+ "ai_assistant.errors.toolFeaturesDenied": "Ihnen fehlt eine der vom Tool benötigten Berechtigungen: {features}",
324
329
  "ai_assistant.launcher.composerPlaceholder": "Fragen Sie mich etwas…",
325
330
  "ai_assistant.launcher.dialogDescription": "Wähle einen Assistenten. Mit ↑/↓ navigieren, Enter startet, Esc schließt.",
326
331
  "ai_assistant.launcher.dialogTitle": "AI assistants",
@@ -213,11 +213,14 @@
213
213
  "ai_assistant.chat.mutation_cards.confirmation.errorTitle": "Confirm failed",
214
214
  "ai_assistant.chat.mutation_cards.confirmation.invalidStatusBody": "This action has already been confirmed, cancelled, or executed.",
215
215
  "ai_assistant.chat.mutation_cards.confirmation.invalidStatusTitle": "Action already resolved",
216
+ "ai_assistant.chat.mutation_cards.confirmation.notFoundTitle": "Proposal not available",
216
217
  "ai_assistant.chat.mutation_cards.confirmation.schemaDriftBody": "The tool signature changed since this preview was generated. Ask the assistant to re-propose the change.",
217
218
  "ai_assistant.chat.mutation_cards.confirmation.schemaDriftTitle": "Schema changed",
218
219
  "ai_assistant.chat.mutation_cards.confirmation.staleVersionBody": "One or more records changed since this preview was generated. Ask the assistant to re-propose the change.",
219
220
  "ai_assistant.chat.mutation_cards.confirmation.staleVersionTitle": "Re-propose required",
220
221
  "ai_assistant.chat.mutation_cards.confirmation.title": "Applying action...",
222
+ "ai_assistant.chat.mutation_cards.confirmation.toolFeaturesDeniedBody": "You no longer have the permissions this change needs. Ask an administrator for access, or cancel the proposal.",
223
+ "ai_assistant.chat.mutation_cards.confirmation.toolFeaturesDeniedTitle": "Permission required",
221
224
  "ai_assistant.chat.mutation_cards.diff.afterHeader": "After",
222
225
  "ai_assistant.chat.mutation_cards.diff.beforeHeader": "Before",
223
226
  "ai_assistant.chat.mutation_cards.diff.empty": "No field changes for this record.",
@@ -229,6 +232,7 @@
229
232
  "ai_assistant.chat.mutation_cards.preview.handlerError": "The mutation handler reported an error. Review the details and re-propose if needed.",
230
233
  "ai_assistant.chat.mutation_cards.preview.reviewDetails": "Review details",
231
234
  "ai_assistant.chat.mutation_cards.preview.title": "Review proposed changes",
235
+ "ai_assistant.chat.mutation_cards.preview.unavailable": "This proposal is not available. It may have been resolved or removed, or it was requested by someone else.",
232
236
  "ai_assistant.chat.mutation_cards.result.cancelledBody": "You cancelled this proposed change. No changes were made.",
233
237
  "ai_assistant.chat.mutation_cards.result.cancelledTitle": "Proposal cancelled",
234
238
  "ai_assistant.chat.mutation_cards.result.failureBody": "The mutation could not be applied.",
@@ -321,6 +325,7 @@
321
325
  "ai_assistant.errors.pendingRecordNotPreviewed": "This record was not part of the approved preview, so it was not changed.",
322
326
  "ai_assistant.errors.pendingRecordStale": "Record version changed since preview.",
323
327
  "ai_assistant.errors.pendingSingleRecordStale": "Record version changed since preview; re-propose the mutation.",
328
+ "ai_assistant.errors.toolFeaturesDenied": "Caller lacks one of the tool's required features: {features}",
324
329
  "ai_assistant.launcher.composerPlaceholder": "Ask anything…",
325
330
  "ai_assistant.launcher.dialogDescription": "Pick an assistant. Use ↑/↓ to navigate, Enter to launch, Esc to close.",
326
331
  "ai_assistant.launcher.dialogTitle": "AI assistants",
@@ -213,11 +213,14 @@
213
213
  "ai_assistant.chat.mutation_cards.confirmation.errorTitle": "La confirmación falló",
214
214
  "ai_assistant.chat.mutation_cards.confirmation.invalidStatusBody": "Esta acción ya fue confirmada, cancelada o ejecutada.",
215
215
  "ai_assistant.chat.mutation_cards.confirmation.invalidStatusTitle": "Acción ya resuelta",
216
+ "ai_assistant.chat.mutation_cards.confirmation.notFoundTitle": "Propuesta no disponible",
216
217
  "ai_assistant.chat.mutation_cards.confirmation.schemaDriftBody": "La firma de la herramienta cambió desde esta vista previa. Pide al asistente que vuelva a proponer el cambio.",
217
218
  "ai_assistant.chat.mutation_cards.confirmation.schemaDriftTitle": "El esquema cambió",
218
219
  "ai_assistant.chat.mutation_cards.confirmation.staleVersionBody": "Uno o varios registros han cambiado desde que se generó esta vista previa. Pide al asistente que vuelva a proponer el cambio.",
219
220
  "ai_assistant.chat.mutation_cards.confirmation.staleVersionTitle": "Se requiere una nueva propuesta",
220
221
  "ai_assistant.chat.mutation_cards.confirmation.title": "Aplicando acción...",
222
+ "ai_assistant.chat.mutation_cards.confirmation.toolFeaturesDeniedBody": "Ya no tienes los permisos que requiere este cambio. Pide acceso a un administrador o cancela la propuesta.",
223
+ "ai_assistant.chat.mutation_cards.confirmation.toolFeaturesDeniedTitle": "Permiso requerido",
221
224
  "ai_assistant.chat.mutation_cards.diff.afterHeader": "Después",
222
225
  "ai_assistant.chat.mutation_cards.diff.beforeHeader": "Antes",
223
226
  "ai_assistant.chat.mutation_cards.diff.empty": "No hay cambios para este registro.",
@@ -229,6 +232,7 @@
229
232
  "ai_assistant.chat.mutation_cards.preview.handlerError": "El gestor de mutaciones informó un error. Revisa los detalles y vuelve a proponer la acción si es necesario.",
230
233
  "ai_assistant.chat.mutation_cards.preview.reviewDetails": "Ver detalles",
231
234
  "ai_assistant.chat.mutation_cards.preview.title": "Revisar los cambios propuestos",
235
+ "ai_assistant.chat.mutation_cards.preview.unavailable": "Esta propuesta no está disponible. Puede que se haya resuelto o eliminado, o que la haya solicitado otra persona.",
232
236
  "ai_assistant.chat.mutation_cards.result.cancelledBody": "Cancelaste este cambio propuesto. No se realizó ningún cambio.",
233
237
  "ai_assistant.chat.mutation_cards.result.cancelledTitle": "Propuesta cancelada",
234
238
  "ai_assistant.chat.mutation_cards.result.failureBody": "No se pudo aplicar la mutación.",
@@ -321,6 +325,7 @@
321
325
  "ai_assistant.errors.pendingRecordNotPreviewed": "Este registro no formaba parte de la vista previa aprobada, por lo que no se modificó.",
322
326
  "ai_assistant.errors.pendingRecordStale": "La versión del registro cambió desde la vista previa.",
323
327
  "ai_assistant.errors.pendingSingleRecordStale": "La versión del registro cambió desde la vista previa; vuelve a proponer el cambio.",
328
+ "ai_assistant.errors.toolFeaturesDenied": "Te falta uno de los permisos que requiere la herramienta: {features}",
324
329
  "ai_assistant.launcher.composerPlaceholder": "Pregunte lo que necesite…",
325
330
  "ai_assistant.launcher.dialogDescription": "Elige un asistente. Usa ↑/↓ para navegar, Enter para iniciar, Esc para cerrar.",
326
331
  "ai_assistant.launcher.dialogTitle": "AI assistants",
@@ -213,11 +213,14 @@
213
213
  "ai_assistant.chat.mutation_cards.confirmation.errorTitle": "확인에 실패했습니다",
214
214
  "ai_assistant.chat.mutation_cards.confirmation.invalidStatusBody": "이 작업은 이미 확인, 취소 또는 실행되었습니다.",
215
215
  "ai_assistant.chat.mutation_cards.confirmation.invalidStatusTitle": "이미 처리된 작업",
216
+ "ai_assistant.chat.mutation_cards.confirmation.notFoundTitle": "제안을 사용할 수 없음",
216
217
  "ai_assistant.chat.mutation_cards.confirmation.schemaDriftBody": "이 미리보기가 생성된 이후 도구 시그니처가 변경되었습니다. 어시스턴트에게 변경 사항을 다시 제안하도록 요청하세요.",
217
218
  "ai_assistant.chat.mutation_cards.confirmation.schemaDriftTitle": "스키마가 변경되었습니다",
218
219
  "ai_assistant.chat.mutation_cards.confirmation.staleVersionBody": "이 미리보기가 생성된 이후 하나 이상의 레코드가 변경되었습니다. 어시스턴트에게 변경 사항을 다시 제안하도록 요청하세요.",
219
220
  "ai_assistant.chat.mutation_cards.confirmation.staleVersionTitle": "다시 제안 필요",
220
221
  "ai_assistant.chat.mutation_cards.confirmation.title": "작업 적용 중...",
222
+ "ai_assistant.chat.mutation_cards.confirmation.toolFeaturesDeniedBody": "이 변경에 필요한 권한이 더 이상 없습니다. 관리자에게 접근 권한을 요청하거나 제안을 취소하세요.",
223
+ "ai_assistant.chat.mutation_cards.confirmation.toolFeaturesDeniedTitle": "권한 필요",
221
224
  "ai_assistant.chat.mutation_cards.diff.afterHeader": "이후",
222
225
  "ai_assistant.chat.mutation_cards.diff.beforeHeader": "이전",
223
226
  "ai_assistant.chat.mutation_cards.diff.empty": "이 레코드에 대한 필드 변경 사항이 없습니다.",
@@ -229,6 +232,7 @@
229
232
  "ai_assistant.chat.mutation_cards.preview.handlerError": "뮤테이션 핸들러가 오류를 보고했습니다. 세부 정보를 검토하고 필요하면 다시 제안하세요.",
230
233
  "ai_assistant.chat.mutation_cards.preview.reviewDetails": "세부 정보 검토",
231
234
  "ai_assistant.chat.mutation_cards.preview.title": "제안된 변경 사항 검토",
235
+ "ai_assistant.chat.mutation_cards.preview.unavailable": "이 제안을 사용할 수 없습니다. 이미 처리되었거나 삭제되었거나 다른 사람이 요청한 제안일 수 있습니다.",
232
236
  "ai_assistant.chat.mutation_cards.result.cancelledBody": "이 제안된 변경을 취소했습니다. 변경 사항이 적용되지 않았습니다.",
233
237
  "ai_assistant.chat.mutation_cards.result.cancelledTitle": "제안이 취소됨",
234
238
  "ai_assistant.chat.mutation_cards.result.failureBody": "뮤테이션을 적용할 수 없습니다.",
@@ -321,6 +325,7 @@
321
325
  "ai_assistant.errors.pendingRecordNotPreviewed": "이 레코드는 승인된 미리보기에 포함되지 않아 변경되지 않았습니다.",
322
326
  "ai_assistant.errors.pendingRecordStale": "미리보기 이후 레코드 버전이 변경되었습니다.",
323
327
  "ai_assistant.errors.pendingSingleRecordStale": "미리보기 이후 레코드 버전이 변경되었습니다. 변경을 다시 제안하세요.",
328
+ "ai_assistant.errors.toolFeaturesDenied": "도구에 필요한 권한 중 하나가 없습니다: {features}",
324
329
  "ai_assistant.launcher.composerPlaceholder": "무엇이든 물어보세요…",
325
330
  "ai_assistant.launcher.dialogDescription": "어시스턴트를 선택하세요. 탐색하려면 ↑/↓를 사용하고, 실행하려면 Enter를, 닫으려면 Esc를 사용하세요.",
326
331
  "ai_assistant.launcher.dialogTitle": "AI 어시스턴트",
@@ -213,11 +213,14 @@
213
213
  "ai_assistant.chat.mutation_cards.confirmation.errorTitle": "Potwierdzenie nie powiodło się",
214
214
  "ai_assistant.chat.mutation_cards.confirmation.invalidStatusBody": "Ta akcja została już potwierdzona, anulowana lub wykonana.",
215
215
  "ai_assistant.chat.mutation_cards.confirmation.invalidStatusTitle": "Akcja została już rozstrzygnięta",
216
+ "ai_assistant.chat.mutation_cards.confirmation.notFoundTitle": "Propozycja niedostępna",
216
217
  "ai_assistant.chat.mutation_cards.confirmation.schemaDriftBody": "Sygnatura narzędzia zmieniła się od czasu podglądu. Poproś asystenta o ponowną propozycję zmiany.",
217
218
  "ai_assistant.chat.mutation_cards.confirmation.schemaDriftTitle": "Zmienił się schemat",
218
219
  "ai_assistant.chat.mutation_cards.confirmation.staleVersionBody": "Co najmniej jeden rekord zmienił się od czasu wygenerowania podglądu. Poproś asystenta o ponowne zaproponowanie zmiany.",
219
220
  "ai_assistant.chat.mutation_cards.confirmation.staleVersionTitle": "Wymagana ponowna propozycja",
220
221
  "ai_assistant.chat.mutation_cards.confirmation.title": "Wykonywanie akcji...",
222
+ "ai_assistant.chat.mutation_cards.confirmation.toolFeaturesDeniedBody": "Nie masz już uprawnień wymaganych do tej zmiany. Poproś administratora o dostęp lub anuluj propozycję.",
223
+ "ai_assistant.chat.mutation_cards.confirmation.toolFeaturesDeniedTitle": "Wymagane uprawnienia",
221
224
  "ai_assistant.chat.mutation_cards.diff.afterHeader": "Po",
222
225
  "ai_assistant.chat.mutation_cards.diff.beforeHeader": "Przed",
223
226
  "ai_assistant.chat.mutation_cards.diff.empty": "Brak zmian pól dla tego rekordu.",
@@ -229,6 +232,7 @@
229
232
  "ai_assistant.chat.mutation_cards.preview.handlerError": "Handler mutacji zgłosił błąd. Sprawdź szczegóły i w razie potrzeby zaproponuj akcję ponownie.",
230
233
  "ai_assistant.chat.mutation_cards.preview.reviewDetails": "Pokaż szczegóły",
231
234
  "ai_assistant.chat.mutation_cards.preview.title": "Sprawdź proponowane zmiany",
235
+ "ai_assistant.chat.mutation_cards.preview.unavailable": "Ta propozycja jest niedostępna. Mogła zostać rozstrzygnięta lub usunięta albo zleciła ją inna osoba.",
232
236
  "ai_assistant.chat.mutation_cards.result.cancelledBody": "Anulowano tę proponowaną zmianę. Nie wprowadzono żadnych zmian.",
233
237
  "ai_assistant.chat.mutation_cards.result.cancelledTitle": "Propozycja anulowana",
234
238
  "ai_assistant.chat.mutation_cards.result.failureBody": "Nie udało się zastosować zmiany.",
@@ -321,6 +325,7 @@
321
325
  "ai_assistant.errors.pendingRecordNotPreviewed": "Ten rekord nie był częścią zatwierdzonego podglądu, więc nie został zmieniony.",
322
326
  "ai_assistant.errors.pendingRecordStale": "Rekord zmienił się od czasu podglądu.",
323
327
  "ai_assistant.errors.pendingSingleRecordStale": "Rekord zmienił się od czasu podglądu; zaproponuj zmianę ponownie.",
328
+ "ai_assistant.errors.toolFeaturesDenied": "Brakuje Ci jednego z uprawnień wymaganych przez narzędzie: {features}",
324
329
  "ai_assistant.launcher.composerPlaceholder": "Zapytaj o cokolwiek…",
325
330
  "ai_assistant.launcher.dialogDescription": "Wybierz asystenta. Nawiguj klawiszami ↑/↓, Enter uruchamia, Esc zamyka.",
326
331
  "ai_assistant.launcher.dialogTitle": "Asystenci AI",
@@ -11,6 +11,7 @@ import { jsonSchemaToZod } from "./schema-utils.js";
11
11
  import { buildMcpToolAnnotations } from "./mcp-tool-annotations.js";
12
12
  import { redactSecretForLog, deriveApiKeySessionId } from "./log-redaction.js";
13
13
  import { findApiKeyBySecret, findSessionApiKeyWithSecret } from "@open-mercato/core/modules/api_keys/services/apiKeyService";
14
+ import { isLoopbackHost, resolveMcpHost } from "./mcp-host-resolution.js";
14
15
  const logger = createLogger("ai_assistant").child({ component: "mcp-http" });
15
16
  async function resolveSessionContext(sessionToken, baseContext, debug) {
16
17
  try {
@@ -295,6 +296,7 @@ async function parseJsonBody(req) {
295
296
  }
296
297
  async function runMcpHttpServer(options) {
297
298
  const { config, container, port } = options;
299
+ const host = resolveMcpHost(options.host, void 0);
298
300
  await loadAllModuleTools();
299
301
  try {
300
302
  const { extractEntityGraph, cacheEntityGraph } = await import("./entity-graph.js");
@@ -437,9 +439,12 @@ async function runMcpHttpServer(options) {
437
439
  logger.info("Mode: stateless (new server per request)");
438
440
  logger.info("Server auth: API key validated against database (x-api-key header)");
439
441
  logger.info("User auth: session token (_sessionToken) preferred, falls back to API key roles");
442
+ if (!isLoopbackHost(host)) {
443
+ logger.warn("Binding beyond loopback \u2014 ensure a firewall and a strong, rotated MCP_SERVER_API_KEY", { host });
444
+ }
440
445
  return new Promise((resolve) => {
441
- httpServer.listen(port, () => {
442
- logger.info("Server listening", { port });
446
+ httpServer.listen(port, host, () => {
447
+ logger.info("Server listening", { host, port });
443
448
  });
444
449
  const shutdown = async () => {
445
450
  logger.info("Shutting down");