@open-mercato/ai-assistant 0.6.7 → 0.6.8-canary.320.1.bf889f49e4

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 (149) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/AGENTS.md +22 -63
  3. package/dist/modules/ai_assistant/__integration__/TC-AI-MODERATION-008-settings-and-audit.spec.js +80 -0
  4. package/dist/modules/ai_assistant/__integration__/TC-AI-MODERATION-008-settings-and-audit.spec.js.map +7 -0
  5. package/dist/modules/ai_assistant/__integration__/TC-AI-MODERATION-009-ui.spec.js +124 -0
  6. package/dist/modules/ai_assistant/__integration__/TC-AI-MODERATION-009-ui.spec.js.map +7 -0
  7. package/dist/modules/ai_assistant/__integration__/TC-AI-RUNTIME-OVERRIDES-006-model-picker.spec.js +2 -0
  8. package/dist/modules/ai_assistant/__integration__/TC-AI-RUNTIME-OVERRIDES-006-model-picker.spec.js.map +2 -2
  9. package/dist/modules/ai_assistant/__integration__/helpers/aiAssistantFixtures.js +30 -0
  10. package/dist/modules/ai_assistant/__integration__/helpers/aiAssistantFixtures.js.map +2 -2
  11. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/models/route.js +7 -3
  12. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/models/route.js.map +2 -2
  13. package/dist/modules/ai_assistant/api/ai/chat/route.js +7 -0
  14. package/dist/modules/ai_assistant/api/ai/chat/route.js.map +2 -2
  15. package/dist/modules/ai_assistant/api/moderation-flags/route.js +121 -0
  16. package/dist/modules/ai_assistant/api/moderation-flags/route.js.map +7 -0
  17. package/dist/modules/ai_assistant/api/settings/allowlist/route.js +10 -10
  18. package/dist/modules/ai_assistant/api/settings/allowlist/route.js.map +2 -2
  19. package/dist/modules/ai_assistant/api/settings/route.js +34 -13
  20. package/dist/modules/ai_assistant/api/settings/route.js.map +2 -2
  21. package/dist/modules/ai_assistant/api/tools/route.js +2 -2
  22. package/dist/modules/ai_assistant/api/tools/route.js.map +2 -2
  23. package/dist/modules/ai_assistant/backend/config/ai-assistant/agents/AiAgentSettingsPageClient.js +121 -15
  24. package/dist/modules/ai_assistant/backend/config/ai-assistant/agents/AiAgentSettingsPageClient.js.map +2 -2
  25. package/dist/modules/ai_assistant/backend/config/ai-assistant/allowlist/AiTenantAllowlistPageClient.js +2 -2
  26. package/dist/modules/ai_assistant/backend/config/ai-assistant/allowlist/AiTenantAllowlistPageClient.js.map +2 -2
  27. package/dist/modules/ai_assistant/backend/config/ai-assistant/moderation-flags/AiModerationFlagsPageClient.js +139 -0
  28. package/dist/modules/ai_assistant/backend/config/ai-assistant/moderation-flags/AiModerationFlagsPageClient.js.map +7 -0
  29. package/dist/modules/ai_assistant/backend/config/ai-assistant/moderation-flags/page.js +10 -0
  30. package/dist/modules/ai_assistant/backend/config/ai-assistant/moderation-flags/page.js.map +7 -0
  31. package/dist/modules/ai_assistant/backend/config/ai-assistant/moderation-flags/page.meta.js +26 -0
  32. package/dist/modules/ai_assistant/backend/config/ai-assistant/moderation-flags/page.meta.js.map +7 -0
  33. package/dist/modules/ai_assistant/backend/config/ai-assistant/playground/AiPlaygroundPageClient.js +4 -4
  34. package/dist/modules/ai_assistant/backend/config/ai-assistant/playground/AiPlaygroundPageClient.js.map +2 -2
  35. package/dist/modules/ai_assistant/data/entities.js +42 -0
  36. package/dist/modules/ai_assistant/data/entities.js.map +2 -2
  37. package/dist/modules/ai_assistant/data/repositories/AiAgentRuntimeOverrideRepository.js +3 -1
  38. package/dist/modules/ai_assistant/data/repositories/AiAgentRuntimeOverrideRepository.js.map +2 -2
  39. package/dist/modules/ai_assistant/data/repositories/AiModerationFlagRepository.js +44 -0
  40. package/dist/modules/ai_assistant/data/repositories/AiModerationFlagRepository.js.map +7 -0
  41. package/dist/modules/ai_assistant/di.js +6 -2
  42. package/dist/modules/ai_assistant/di.js.map +2 -2
  43. package/dist/modules/ai_assistant/events.js +6 -0
  44. package/dist/modules/ai_assistant/events.js.map +2 -2
  45. package/dist/modules/ai_assistant/i18n/de.json +42 -0
  46. package/dist/modules/ai_assistant/i18n/en.json +42 -0
  47. package/dist/modules/ai_assistant/i18n/es.json +42 -0
  48. package/dist/modules/ai_assistant/i18n/ko.json +527 -0
  49. package/dist/modules/ai_assistant/i18n/pl.json +42 -0
  50. package/dist/modules/ai_assistant/lib/agent-runtime.js +166 -11
  51. package/dist/modules/ai_assistant/lib/agent-runtime.js.map +2 -2
  52. package/dist/modules/ai_assistant/lib/ai-agent-definition.js.map +2 -2
  53. package/dist/modules/ai_assistant/lib/ai-overrides.js.map +1 -1
  54. package/dist/modules/ai_assistant/lib/auth.js +6 -7
  55. package/dist/modules/ai_assistant/lib/auth.js.map +2 -2
  56. package/dist/modules/ai_assistant/lib/entity-graph.js +3 -3
  57. package/dist/modules/ai_assistant/lib/entity-graph.js.map +2 -2
  58. package/dist/modules/ai_assistant/lib/generated-registry-loader.js +55 -10
  59. package/dist/modules/ai_assistant/lib/generated-registry-loader.js.map +2 -2
  60. package/dist/modules/ai_assistant/lib/in-process-client.js +2 -2
  61. package/dist/modules/ai_assistant/lib/in-process-client.js.map +2 -2
  62. package/dist/modules/ai_assistant/lib/llm-adapters/anthropic.js +3 -0
  63. package/dist/modules/ai_assistant/lib/llm-adapters/anthropic.js.map +2 -2
  64. package/dist/modules/ai_assistant/lib/llm-adapters/openai.js +8 -1
  65. package/dist/modules/ai_assistant/lib/llm-adapters/openai.js.map +2 -2
  66. package/dist/modules/ai_assistant/lib/mcp-server.js +2 -3
  67. package/dist/modules/ai_assistant/lib/mcp-server.js.map +2 -2
  68. package/dist/modules/ai_assistant/lib/model-factory.js +6 -1
  69. package/dist/modules/ai_assistant/lib/model-factory.js.map +2 -2
  70. package/dist/modules/ai_assistant/lib/moderation-flag-recorder.js +43 -0
  71. package/dist/modules/ai_assistant/lib/moderation-flag-recorder.js.map +7 -0
  72. package/dist/modules/ai_assistant/lib/moderation-policy.js +24 -0
  73. package/dist/modules/ai_assistant/lib/moderation-policy.js.map +7 -0
  74. package/dist/modules/ai_assistant/lib/moderation.js +109 -0
  75. package/dist/modules/ai_assistant/lib/moderation.js.map +7 -0
  76. package/dist/modules/ai_assistant/lib/openai-compatible-presets.js +2 -0
  77. package/dist/modules/ai_assistant/lib/openai-compatible-presets.js.map +2 -2
  78. package/dist/modules/ai_assistant/lib/tool-input-schema.js +13 -0
  79. package/dist/modules/ai_assistant/lib/tool-input-schema.js.map +7 -0
  80. package/dist/modules/ai_assistant/lib/tool-search.js +4 -12
  81. package/dist/modules/ai_assistant/lib/tool-search.js.map +2 -2
  82. package/dist/modules/ai_assistant/migrations/Migration20260610134045_ai_assistant.js +19 -0
  83. package/dist/modules/ai_assistant/migrations/Migration20260610134045_ai_assistant.js.map +7 -0
  84. package/generated/entities/ai_agent_runtime_override/index.ts +1 -0
  85. package/generated/entities/ai_moderation_flag/index.ts +9 -0
  86. package/generated/entities.ids.generated.ts +2 -1
  87. package/generated/entity-fields-registry.ts +13 -1
  88. package/package.json +13 -12
  89. package/src/modules/ai_assistant/__integration__/TC-AI-MODERATION-008-settings-and-audit.spec.ts +126 -0
  90. package/src/modules/ai_assistant/__integration__/TC-AI-MODERATION-009-ui.spec.ts +161 -0
  91. package/src/modules/ai_assistant/__integration__/TC-AI-RUNTIME-OVERRIDES-006-model-picker.spec.ts +4 -0
  92. package/src/modules/ai_assistant/__integration__/helpers/aiAssistantFixtures.ts +48 -0
  93. package/src/modules/ai_assistant/api/ai/agents/[agentId]/models/__tests__/route.test.ts +83 -0
  94. package/src/modules/ai_assistant/api/ai/agents/[agentId]/models/route.ts +21 -4
  95. package/src/modules/ai_assistant/api/ai/chat/route.ts +10 -0
  96. package/src/modules/ai_assistant/api/moderation-flags/__tests__/route.test.ts +122 -0
  97. package/src/modules/ai_assistant/api/moderation-flags/route.ts +137 -0
  98. package/src/modules/ai_assistant/api/settings/__tests__/route.test.ts +58 -8
  99. package/src/modules/ai_assistant/api/settings/allowlist/route.ts +10 -12
  100. package/src/modules/ai_assistant/api/settings/route.ts +33 -10
  101. package/src/modules/ai_assistant/api/tools/route.ts +2 -2
  102. package/src/modules/ai_assistant/backend/config/ai-assistant/agents/AiAgentSettingsPageClient.tsx +161 -15
  103. package/src/modules/ai_assistant/backend/config/ai-assistant/allowlist/AiTenantAllowlistPageClient.tsx +2 -2
  104. package/src/modules/ai_assistant/backend/config/ai-assistant/moderation-flags/AiModerationFlagsPageClient.tsx +186 -0
  105. package/src/modules/ai_assistant/backend/config/ai-assistant/moderation-flags/page.meta.ts +24 -0
  106. package/src/modules/ai_assistant/backend/config/ai-assistant/moderation-flags/page.tsx +12 -0
  107. package/src/modules/ai_assistant/backend/config/ai-assistant/playground/AiPlaygroundPageClient.tsx +4 -4
  108. package/src/modules/ai_assistant/data/entities.ts +56 -0
  109. package/src/modules/ai_assistant/data/repositories/AiAgentRuntimeOverrideRepository.ts +4 -0
  110. package/src/modules/ai_assistant/data/repositories/AiModerationFlagRepository.ts +79 -0
  111. package/src/modules/ai_assistant/di.ts +5 -1
  112. package/src/modules/ai_assistant/events.ts +21 -0
  113. package/src/modules/ai_assistant/i18n/de.json +42 -0
  114. package/src/modules/ai_assistant/i18n/en.json +42 -0
  115. package/src/modules/ai_assistant/i18n/es.json +42 -0
  116. package/src/modules/ai_assistant/i18n/ko.json +527 -0
  117. package/src/modules/ai_assistant/i18n/pl.json +42 -0
  118. package/src/modules/ai_assistant/lib/__tests__/agent-runtime-object.test.ts +30 -0
  119. package/src/modules/ai_assistant/lib/__tests__/agent-runtime-tool-loop-onstepfinish.test.ts +163 -0
  120. package/src/modules/ai_assistant/lib/__tests__/agent-runtime.test.ts +86 -0
  121. package/src/modules/ai_assistant/lib/__tests__/auth.test.ts +2 -5
  122. package/src/modules/ai_assistant/lib/__tests__/generated-registry-loader.test.ts +128 -1
  123. package/src/modules/ai_assistant/lib/__tests__/input-moderation-gate.test.ts +121 -0
  124. package/src/modules/ai_assistant/lib/__tests__/llm-adapters-anthropic.test.ts +13 -0
  125. package/src/modules/ai_assistant/lib/__tests__/llm-adapters-openai.test.ts +41 -0
  126. package/src/modules/ai_assistant/lib/__tests__/model-factory.test.ts +60 -0
  127. package/src/modules/ai_assistant/lib/__tests__/moderation-flag-recorder.test.ts +76 -0
  128. package/src/modules/ai_assistant/lib/__tests__/moderation-policy.test.ts +86 -0
  129. package/src/modules/ai_assistant/lib/__tests__/moderation.test.ts +114 -0
  130. package/src/modules/ai_assistant/lib/__tests__/tool-input-schema.test.ts +52 -0
  131. package/src/modules/ai_assistant/lib/agent-runtime.ts +273 -2
  132. package/src/modules/ai_assistant/lib/ai-agent-definition.ts +29 -0
  133. package/src/modules/ai_assistant/lib/ai-overrides.ts +3 -3
  134. package/src/modules/ai_assistant/lib/auth.ts +6 -15
  135. package/src/modules/ai_assistant/lib/entity-graph.ts +3 -3
  136. package/src/modules/ai_assistant/lib/generated-registry-loader.ts +107 -12
  137. package/src/modules/ai_assistant/lib/in-process-client.ts +2 -2
  138. package/src/modules/ai_assistant/lib/llm-adapters/anthropic.ts +10 -0
  139. package/src/modules/ai_assistant/lib/llm-adapters/openai.ts +32 -1
  140. package/src/modules/ai_assistant/lib/mcp-server.ts +2 -3
  141. package/src/modules/ai_assistant/lib/model-factory.ts +33 -0
  142. package/src/modules/ai_assistant/lib/moderation-flag-recorder.ts +75 -0
  143. package/src/modules/ai_assistant/lib/moderation-policy.ts +77 -0
  144. package/src/modules/ai_assistant/lib/moderation.ts +179 -0
  145. package/src/modules/ai_assistant/lib/openai-compatible-presets.ts +2 -0
  146. package/src/modules/ai_assistant/lib/tool-input-schema.ts +33 -0
  147. package/src/modules/ai_assistant/lib/tool-search.ts +4 -17
  148. package/src/modules/ai_assistant/migrations/.snapshot-open-mercato.json +388 -16
  149. package/src/modules/ai_assistant/migrations/Migration20260610134045_ai_assistant.ts +21 -0
@@ -1,2 +1,2 @@
1
- [build:ai-assistant] found 220 entry points
1
+ [build:ai-assistant] found 232 entry points
2
2
  [build:ai-assistant] built successfully
package/AGENTS.md CHANGED
@@ -413,7 +413,7 @@ Per-agent provider/model overrides are edited from `/backend/config/ai-assistant
413
413
  | `PUT /api/ai_assistant/settings/allowlist` | Persists the tenant snapshot. Body validates against env first — out-of-env entries are rejected with `provider_not_in_env_allowlist` / `model_not_in_env_allowlist` 400 codes. Tenant allowlist may NEVER widen the env allowlist. |
414
414
  | `DELETE /api/ai_assistant/settings/allowlist` | Soft-deletes the row; runtime falls back to env-only enforcement. Idempotent — `{ cleared: false }` when no active row exists. |
415
415
  | `PUT /api/ai_assistant/settings` (runtime override) | Re-validates against the **effective** allowlist when an `org_id`/tenant snapshot is available, so admins can't store an override that the tenant allowlist would later reject. |
416
- | `GET /api/ai_assistant/ai/agents/:id/models` | Picker response is clipped to the effective allowlist. The `<ModelPicker>` therefore only offers tenant-permitted values out of the box. |
416
+ | `GET /api/ai_assistant/ai/agents/:id/models` | Picker response is clipped to the effective allowlist. The `<ModelPicker>` therefore only offers tenant-permitted values out of the box. A failed tenant-scoped lookup returns 200 with a non-authoritative `degraded` list. |
417
417
  | `POST /api/ai_assistant/ai/chat?provider=&model=` | Chat dispatcher rejects out-of-effective-allowlist query params with the same `provider_not_allowlisted` / `model_not_allowlisted` codes. The error message names "the effective allowlist (env ∩ tenant)" when the tenant snapshot contributes a narrowing. |
418
418
  | `createModelFactory(...).resolveModel({ tenantAllowlist })` | The factory accepts an optional snapshot and intersects it with env at resolution time, so a stale tenant override or higher-priority source can never escape the effective set. Falls back via `allowlist_fallback` (same telemetry shape as Phase 1780-5). |
419
419
 
@@ -880,6 +880,16 @@ yarn mcp:serve
880
880
 
881
881
  Typed pending-action lifecycle events live in `src/modules/ai_assistant/events.ts` and are emitted via the shared `emitAiAssistantEvent` helper (`createModuleEvents`). The three ids are FROZEN per `BACKWARD_COMPATIBILITY.md` §5 and MUST NOT be renamed; payload fields are additive-only. `ai.action.confirmed` fires from `executePendingActionConfirm` with `{ pendingActionId, agentId, toolName, status, tenantId, organizationId, userId, resolvedByUserId, resolvedAt, executionResult, failedRecords? }`; `ai.action.cancelled` fires from `executePendingActionCancel` with the same shape plus an optional `reason`; `ai.action.expired` fires from the cancel helper's TTL short-circuit (and the Step 5.12 cleanup worker) with `resolvedByUserId: null` and additional `expiresAt` / `expiredAt` timestamps. All three use `category: 'system'` and `entity: 'ai_pending_action'`.
882
882
 
883
+ `ai_assistant.moderation_flag.created` (`entity: 'ai_moderation_flag'`) fires best-effort from the input-moderation gate; payload carries flagged category names only, never prompt content.
884
+
885
+ ## Input moderation & safety identifiers
886
+
887
+ Guide: [`moderation.mdx`](../../apps/docs/docs/framework/ai-assistant/moderation.mdx) + spec `.ai/specs/2026-06-04-ai-input-moderation-and-safety-identifiers.md`. Envs: `OM_AI_INPUT_MODERATION`, `OM_AI_MODERATION_MODEL`.
888
+
889
+ - Enforced surfaces (`untrustedInput`) fail **closed**; opt-in surfaces fail **open**.
890
+ - Flagged categories are audit-only — never send them to the client.
891
+ - The audit write is best-effort and MUST NOT block the rejection.
892
+
883
893
  ## Rules for the OpenCode Client
884
894
 
885
895
  Located in `lib/opencode-client.ts`. Use these methods when interacting with OpenCode:
@@ -1479,6 +1489,10 @@ Agents that need multi-step tool loops configure the `loop` block on `AiAgentDef
1479
1489
 
1480
1490
  **Backward compatibility**: additive. With `MCP_SERVER_API_KEY_FILE` unset the OpenCode entrypoint behaves byte-for-byte as before; host-MCP mode (`yarn mcp:serve` + `MCP_SERVER_API_KEY`) is unchanged. Spec: `.ai/specs/2026-07-07-windows-one-command-agentic-dev-environment.md`.
1481
1491
 
1492
+ ### 2026-08-05 - @app module entries are compiled, not loaded as raw TS
1493
+
1494
+ `compileAndImportGenerated` (`lib/generated-registry-loader.ts`) now compiles every `@app` local module entry a generated registry references into `<appRoot>/.mercato/generated/app-modules/`, via the new exported `compileAppSourceFile` in `@open-mercato/shared/lib/bootstrap/dynamicLoader` (the esbuild bundle + dependency cache `loadBootstrapData` already used; packages stay external). The 2026-06-24 fix below only rewrote the specifier to an absolute `.ts` path, which holds while the target's whole graph stays inside what Node's type stripping accepts — a real module's does not (`./di` is extensionless, `./data/entities` carries decorators), so the first app-local `ai-tools.ts` killed the whole tool registry. Uncompilable modules log and fall back to the raw path. Additive: the artifact map is an optional third `rewriteGeneratedAliasImports` arg.
1495
+
1482
1496
  ### 2026-06-24 - MCP dev server loads ai-tools for @app local modules (#3524)
1483
1497
 
1484
1498
  **What changed** (`lib/generated-registry-loader.ts`):
@@ -1585,20 +1599,9 @@ Note: the guard is intentionally NOT added to `mcp-client.ts` `connectHttp`, whi
1585
1599
  - Removed auto-discovered module AI tools from `ai-tools.generated.ts`
1586
1600
  - Token savings: from ~10+ tool schemas to exactly 2, with fixed footprint regardless of API surface growth
1587
1601
 
1588
- **Files created**:
1589
- - `lib/codemode-tools.ts` — `search` and `execute` tool definitions
1590
- - `lib/sandbox.ts` — `node:vm` sandbox executor with security restrictions
1591
- - `lib/truncate.ts` — Response size limiter (40K chars / ~10K tokens)
1602
+ **Files created**: `lib/codemode-tools.ts` (the two tool definitions), `lib/sandbox.ts` (`node:vm` executor), `lib/truncate.ts` (40K-char response limiter) — all three described under "Rules for Code Mode Internals" above.
1592
1603
 
1593
- **Files modified**:
1594
- - `lib/api-endpoint-index.ts` — Added `getRawOpenApiSpec()` for raw spec caching
1595
- - `lib/tool-loader.ts` — Loads Code Mode tools instead of legacy tools + module tools
1596
- - `lib/http-server.ts` — Pre-caches raw OpenAPI spec at startup
1597
- - `lib/mcp-server.ts` — Generates entity graph and caches spec for stdio mode
1598
-
1599
- **Files kept but unused**:
1600
- - `lib/api-discovery-tools.ts` — Old find_api/call_api (no longer imported, deleted in #1876)
1601
- - `lib/entity-graph-tools.ts` — Old discover_schema (no longer imported, deleted in #1876)
1604
+ **Files modified**: `lib/api-endpoint-index.ts` (raw spec caching), `lib/tool-loader.ts`, `lib/http-server.ts`, `lib/mcp-server.ts`. The superseded `lib/api-discovery-tools.ts` and `lib/entity-graph-tools.ts` were later deleted in #1876.
1602
1605
 
1603
1606
  ### 2026-01-17 - Session Persistence Fix
1604
1607
 
@@ -1613,62 +1616,18 @@ Note: the guard is intentionally NOT added to `mcp-client.ts` `connectHttp`, whi
1613
1616
  2. **React stale closure**: `handleSubmit` callback captured initial `null` sessionId value.
1614
1617
 
1615
1618
  **Fixes applied**:
1616
- - `opencode-handlers.ts`: Removed Promise.race, await only SSE eventPromise
1617
- - `useCommandPalette.ts`: Added `opencodeSessionIdRef` (ref) alongside state to avoid stale closures
1618
-
1619
- **Files modified**:
1620
- - `src/modules/ai_assistant/lib/opencode-handlers.ts` - Fixed Promise.race completion bug
1621
- - `src/frontend/hooks/useCommandPalette.ts` - Added ref pattern for sessionId
1622
-
1623
- **Diagnostic logging added** (can be removed after verification):
1624
- - `[handleSubmit] DIAGNOSTIC` - Session check before routing
1625
- - `[sendAgenticMessage] DIAGNOSTIC` - Request payload before fetch
1626
- - `[startAgenticChat] DIAGNOSTIC` - Done event handling
1627
- - `[AI Chat] DIAGNOSTIC` - Backend request received
1619
+ - `lib/opencode-handlers.ts`: removed `Promise.race`, await only the SSE eventPromise
1620
+ - `src/frontend/hooks/useCommandPalette.ts`: added `opencodeSessionIdRef` alongside state to avoid stale closures
1628
1621
 
1629
1622
  ### 2026-01 - OpenCode Integration
1630
1623
 
1631
1624
  **Lesson learned:** When replacing an AI backend, preserve the session management contract — the frontend depends on `sessionId` in `done` events regardless of the underlying AI engine.
1632
1625
 
1633
- **Major change**: Replaced Vercel AI SDK with OpenCode as the AI backend.
1634
-
1635
- **What changed**:
1636
- - Chat API now routes all requests to OpenCode
1637
- - Added session management for conversation context
1638
- - Added "Agent is working..." indicator
1639
- - OpenCode connects to MCP server for tools
1640
- - Removed direct AI provider integration
1641
-
1642
- **Files modified**:
1643
- - `src/modules/ai_assistant/api/chat/route.ts` - Complete rewrite to use OpenCode
1644
- - `src/frontend/hooks/useCommandPalette.ts` - Added session state, thinking indicator
1645
- - `src/frontend/components/CommandPalette/ToolChatPage.tsx` - Added thinking UI
1646
- - `src/frontend/types.ts` - Added ChatSSEEvent, isThinking
1647
-
1648
- ### 2026-01 - API Discovery Tools
1649
-
1650
- **Lesson learned:** Exposing hundreds of individual tools overwhelms the AI context. Use meta-tools (discover, schema, execute) to let the agent dynamically find what it needs.
1651
-
1652
- **Major change**: Replaced 600+ individual tools with 3 meta-tools.
1626
+ Replaced the Vercel AI SDK with OpenCode: the chat API routes to OpenCode, session management carries conversation context, and OpenCode reaches tools through the MCP server. Current shape: "Rules for the Chat Flow" and "Rules for Session Management" above; see git history for per-file detail.
1653
1627
 
1654
- **What changed**:
1655
- - Added `api_discover`, `api_execute`, `api_schema` tools
1656
- - Created `ApiEndpointIndex` for OpenAPI introspection
1657
- - Hybrid discovery: search + OpenAPI
1658
- - 405 endpoints available via discovery
1659
-
1660
- **Files created**:
1661
- - `lib/api-discovery-tools.ts`
1662
- - `lib/api-endpoint-index.ts`
1628
+ ### 2026-01 - API Discovery Tools / Hybrid Tool Discovery (superseded)
1663
1629
 
1664
- ### 2026-01 - Hybrid Tool Discovery
1665
-
1666
- **Lesson learned:** Neither search-based nor OpenAPI-based discovery alone covers all tools — combine both for comprehensive results.
1667
-
1668
- **What changed**:
1669
- - Combined semantic search with OpenAPI introspection
1670
- - Tools indexed for fulltext search
1671
- - API endpoints indexed from OpenAPI spec
1630
+ **Lesson learned:** Exposing hundreds of individual tools overwhelms the AI context — use meta-tools the agent can search. Superseded by Code Mode (2026-02-22); the tools and files these entries described (`api_discover`, `api_schema`, `lib/api-discovery-tools.ts`, `lib/entity-graph-tools.ts`) were deleted in #1876. See git history for the detail.
1672
1631
 
1673
1632
  ### Previous Changes
1674
1633
 
@@ -0,0 +1,80 @@
1
+ import { test, expect, request as playwrightRequest } from "@playwright/test";
2
+ import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
3
+ import { getTokenScope, readJsonSafe } from "@open-mercato/core/helpers/integration/generalFixtures";
4
+ import {
5
+ deleteAgentOverridesInDb,
6
+ deleteModerationFlagsInDb,
7
+ seedModerationFlagInDb
8
+ } from "./helpers/aiAssistantFixtures.js";
9
+ const SETTINGS = "/api/ai_assistant/settings";
10
+ const FLAGS = "/api/ai_assistant/moderation-flags";
11
+ test.describe("TC-AI-MODERATION-008: input moderation settings + audit", () => {
12
+ test("PUT inputModeration persists per agent and round-trips on/off/inherit", async ({ request }) => {
13
+ test.slow();
14
+ const adminToken = await getAuthToken(request, "admin");
15
+ const { tenantId } = getTokenScope(adminToken);
16
+ const agentId = "it.moderation_settings";
17
+ try {
18
+ const on = await apiRequest(request, "PUT", SETTINGS, {
19
+ token: adminToken,
20
+ data: { agentId, inputModeration: true }
21
+ });
22
+ expect(on.status(), "PUT inputModeration=true returns 200").toBe(200);
23
+ expect((await readJsonSafe(on))?.inputModeration).toBe(true);
24
+ const off = await apiRequest(request, "PUT", SETTINGS, {
25
+ token: adminToken,
26
+ data: { agentId, inputModeration: false }
27
+ });
28
+ expect(off.status()).toBe(200);
29
+ expect((await readJsonSafe(off))?.inputModeration).toBe(false);
30
+ const inherit = await apiRequest(request, "PUT", SETTINGS, {
31
+ token: adminToken,
32
+ data: { agentId, inputModeration: null }
33
+ });
34
+ expect(inherit.status()).toBe(200);
35
+ expect((await readJsonSafe(inherit))?.inputModeration).toBeNull();
36
+ } finally {
37
+ await deleteAgentOverridesInDb({ tenantId, agentId }).catch(() => void 0);
38
+ }
39
+ });
40
+ test("GET /moderation-flags is tenant-scoped (cross-tenant rows are never returned)", async ({ request }) => {
41
+ test.slow();
42
+ const adminToken = await getAuthToken(request, "admin");
43
+ const { tenantId } = getTokenScope(adminToken);
44
+ const otherTenantId = "00000000-0000-4000-8000-0000000face7";
45
+ let mineId = "";
46
+ try {
47
+ mineId = await seedModerationFlagInDb({ tenantId, agentId: "it.moderation_audit", userId: "it-user-mine" });
48
+ await seedModerationFlagInDb({ tenantId: otherTenantId, agentId: "it.moderation_audit", userId: "it-user-other" });
49
+ const res = await apiRequest(request, "GET", `${FLAGS}?pageSize=100`, { token: adminToken });
50
+ expect(res.status()).toBe(200);
51
+ const body = await readJsonSafe(res);
52
+ expect(body?.items, "returns an items array").toBeTruthy();
53
+ const ids = (body?.items ?? []).map((row) => row.id);
54
+ expect(ids, "my tenant flag is visible").toContain(mineId);
55
+ for (const row of body?.items ?? []) {
56
+ expect(row.tenantId).toBe(tenantId);
57
+ }
58
+ } finally {
59
+ await deleteModerationFlagsInDb(tenantId).catch(() => void 0);
60
+ await deleteModerationFlagsInDb(otherTenantId).catch(() => void 0);
61
+ }
62
+ });
63
+ test("GET /moderation-flags RBAC + validation gates", async ({ request, baseURL }) => {
64
+ const adminToken = await getAuthToken(request, "admin");
65
+ const tooLarge = await apiRequest(request, "GET", `${FLAGS}?pageSize=101`, { token: adminToken });
66
+ expect(tooLarge.status()).toBe(400);
67
+ expect((await readJsonSafe(tooLarge))?.code).toBe("validation_error");
68
+ const employeeToken = await getAuthToken(request, "employee");
69
+ const denied = await apiRequest(request, "GET", FLAGS, { token: employeeToken });
70
+ expect(denied.status(), "employee lacks settings.manage -> 403").toBe(403);
71
+ const anon = await playwrightRequest.newContext({ baseURL });
72
+ try {
73
+ const res = await anon.fetch(FLAGS, { method: "GET" });
74
+ expect(res.status(), "unauthenticated GET is 401").toBe(401);
75
+ } finally {
76
+ await anon.dispose();
77
+ }
78
+ });
79
+ });
80
+ //# sourceMappingURL=TC-AI-MODERATION-008-settings-and-audit.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/ai_assistant/__integration__/TC-AI-MODERATION-008-settings-and-audit.spec.ts"],
4
+ "sourcesContent": ["import { test, expect, request as playwrightRequest } from '@playwright/test';\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api';\nimport { getTokenScope, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures';\nimport {\n deleteAgentOverridesInDb,\n deleteModerationFlagsInDb,\n seedModerationFlagInDb,\n} from './helpers/aiAssistantFixtures';\n\n/**\n * TC-AI-MODERATION-008 \u2014 Input-moderation settings + audit API.\n * Source: spec `.ai/specs/2026-06-04-ai-input-moderation-and-safety-identifiers.md`.\n *\n * Surfaces under test:\n * - PUT /api/ai_assistant/settings (persists `inputModeration` per agent)\n * - GET /api/ai_assistant/settings (reflects per-agent effective moderation policy)\n * - GET /api/ai_assistant/moderation-flags (tenant-scoped audit listing)\n *\n * Contract notes verified against the route handlers:\n * - PUT `{ agentId, inputModeration }` returns 200 echoing `inputModeration`.\n * - GET /settings exposes `agents[].moderation = { enforced, override, effective }`.\n * - GET /moderation-flags returns `{ items, total, page, pageSize }`, tenant-scoped,\n * gated by `ai_assistant.settings.manage`, `pageSize` capped at 100.\n *\n * Flags are seeded directly in the DB: a real flag is only ever born from the gate\n * during a flagged LLM turn (needs a live moderation call), so seeding keeps the\n * audit + isolation coverage deterministic and provider-free. This spec therefore\n * only runs under the coherent app+DB harness (`yarn test:integration` / `:ephemeral`).\n */\n\nconst SETTINGS = '/api/ai_assistant/settings';\nconst FLAGS = '/api/ai_assistant/moderation-flags';\n\ninterface FlagsResponse {\n items: Array<{ id: string; tenantId: string; agentId: string; userId: string; categories: Record<string, unknown> }>;\n total: number;\n page: number;\n pageSize: number;\n}\n\ntest.describe('TC-AI-MODERATION-008: input moderation settings + audit', () => {\n test('PUT inputModeration persists per agent and round-trips on/off/inherit', async ({ request }) => {\n test.slow();\n const adminToken = await getAuthToken(request, 'admin');\n const { tenantId } = getTokenScope(adminToken);\n // A synthetic agent id keeps the test independent of the (empty-in-CI) live\n // agent registry; the PUT upserts an override row keyed by this id. The\n // per-agent `moderation` reflection on GET (registered agents only) is\n // covered by the route unit tests + the stubbed UI spec (TC-AI-MODERATION-009).\n const agentId = 'it.moderation_settings';\n\n try {\n const on = await apiRequest(request, 'PUT', SETTINGS, {\n token: adminToken,\n data: { agentId, inputModeration: true },\n });\n expect(on.status(), 'PUT inputModeration=true returns 200').toBe(200);\n expect((await readJsonSafe<{ inputModeration: boolean | null }>(on))?.inputModeration).toBe(true);\n\n const off = await apiRequest(request, 'PUT', SETTINGS, {\n token: adminToken,\n data: { agentId, inputModeration: false },\n });\n expect(off.status()).toBe(200);\n expect((await readJsonSafe<{ inputModeration: boolean | null }>(off))?.inputModeration).toBe(false);\n\n const inherit = await apiRequest(request, 'PUT', SETTINGS, {\n token: adminToken,\n data: { agentId, inputModeration: null },\n });\n expect(inherit.status()).toBe(200);\n expect((await readJsonSafe<{ inputModeration: boolean | null }>(inherit))?.inputModeration).toBeNull();\n } finally {\n await deleteAgentOverridesInDb({ tenantId, agentId }).catch(() => undefined);\n }\n });\n\n test('GET /moderation-flags is tenant-scoped (cross-tenant rows are never returned)', async ({ request }) => {\n test.slow();\n const adminToken = await getAuthToken(request, 'admin');\n const { tenantId } = getTokenScope(adminToken);\n const otherTenantId = '00000000-0000-4000-8000-0000000face7';\n\n let mineId = '';\n try {\n mineId = await seedModerationFlagInDb({ tenantId, agentId: 'it.moderation_audit', userId: 'it-user-mine' });\n await seedModerationFlagInDb({ tenantId: otherTenantId, agentId: 'it.moderation_audit', userId: 'it-user-other' });\n\n const res = await apiRequest(request, 'GET', `${FLAGS}?pageSize=100`, { token: adminToken });\n expect(res.status()).toBe(200);\n const body = await readJsonSafe<FlagsResponse>(res);\n expect(body?.items, 'returns an items array').toBeTruthy();\n const ids = (body?.items ?? []).map((row) => row.id);\n expect(ids, 'my tenant flag is visible').toContain(mineId);\n // Every returned row is scoped to the caller's tenant \u2014 the other-tenant row never leaks.\n for (const row of body?.items ?? []) {\n expect(row.tenantId).toBe(tenantId);\n }\n } finally {\n await deleteModerationFlagsInDb(tenantId).catch(() => undefined);\n await deleteModerationFlagsInDb(otherTenantId).catch(() => undefined);\n }\n });\n\n test('GET /moderation-flags RBAC + validation gates', async ({ request, baseURL }) => {\n const adminToken = await getAuthToken(request, 'admin');\n\n // pageSize above the 100 cap is rejected by the zod query schema.\n const tooLarge = await apiRequest(request, 'GET', `${FLAGS}?pageSize=101`, { token: adminToken });\n expect(tooLarge.status()).toBe(400);\n expect((await readJsonSafe<{ code?: string }>(tooLarge))?.code).toBe('validation_error');\n\n // Employee carries ai_assistant.view but NOT ai_assistant.settings.manage.\n const employeeToken = await getAuthToken(request, 'employee');\n const denied = await apiRequest(request, 'GET', FLAGS, { token: employeeToken });\n expect(denied.status(), 'employee lacks settings.manage -> 403').toBe(403);\n\n const anon = await playwrightRequest.newContext({ baseURL });\n try {\n const res = await anon.fetch(FLAGS, { method: 'GET' });\n expect(res.status(), 'unauthenticated GET is 401').toBe(401);\n } finally {\n await anon.dispose();\n }\n });\n});\n"],
5
+ "mappings": "AAAA,SAAS,MAAM,QAAQ,WAAW,yBAAyB;AAC3D,SAAS,YAAY,oBAAoB;AACzC,SAAS,eAAe,oBAAoB;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuBP,MAAM,WAAW;AACjB,MAAM,QAAQ;AASd,KAAK,SAAS,2DAA2D,MAAM;AAC7E,OAAK,yEAAyE,OAAO,EAAE,QAAQ,MAAM;AACnG,SAAK,KAAK;AACV,UAAM,aAAa,MAAM,aAAa,SAAS,OAAO;AACtD,UAAM,EAAE,SAAS,IAAI,cAAc,UAAU;AAK7C,UAAM,UAAU;AAEhB,QAAI;AACF,YAAM,KAAK,MAAM,WAAW,SAAS,OAAO,UAAU;AAAA,QACpD,OAAO;AAAA,QACP,MAAM,EAAE,SAAS,iBAAiB,KAAK;AAAA,MACzC,CAAC;AACD,aAAO,GAAG,OAAO,GAAG,sCAAsC,EAAE,KAAK,GAAG;AACpE,cAAQ,MAAM,aAAkD,EAAE,IAAI,eAAe,EAAE,KAAK,IAAI;AAEhG,YAAM,MAAM,MAAM,WAAW,SAAS,OAAO,UAAU;AAAA,QACrD,OAAO;AAAA,QACP,MAAM,EAAE,SAAS,iBAAiB,MAAM;AAAA,MAC1C,CAAC;AACD,aAAO,IAAI,OAAO,CAAC,EAAE,KAAK,GAAG;AAC7B,cAAQ,MAAM,aAAkD,GAAG,IAAI,eAAe,EAAE,KAAK,KAAK;AAElG,YAAM,U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,MAAS;AAAA,IACtE;AAAA,EACF,CAAC;AAED,OAAK,iDAAiD,OAAO,EAAE,SAAS,QAAQ,MAAM;AACpF,UAAM,aAAa,MAAM,aAAa,SAAS,OAAO;AAGtD,UAAM,WAAW,MAAM,WAAW,SAAS,OAAO,GAAG,KAAK,iBAAiB,EAAE,OAAO,WAAW,CAAC;AAChG,WAAO,SAAS,OAAO,CAAC,EAAE,KAAK,GAAG;AAClC,YAAQ,MAAM,aAAgC,QAAQ,IAAI,IAAI,EAAE,KAAK,kBAAkB;AAGvF,UAAM,gBAAgB,MAAM,aAAa,SAAS,UAAU;AAC5D,UAAM,SAAS,MAAM,WAAW,SAAS,OAAO,OAAO,EAAE,OAAO,cAAc,CAAC;AAC/E,WAAO,OAAO,OAAO,GAAG,uCAAuC,EAAE,KAAK,GAAG;AAEzE,UAAM,OAAO,MAAM,kBAAkB,WAAW,EAAE,QAAQ,CAAC;AAC3D,QAAI;AACF,YAAM,MAAM,MAAM,KAAK,MAAM,OAAO,EAAE,QAAQ,MAAM,CAAC;AACrD,aAAO,IAAI,OAAO,GAAG,4BAA4B,EAAE,KAAK,GAAG;AAAA,IAC7D,UAAE;AACA,YAAM,KAAK,QAAQ;AAAA,IACrB;AAAA,EACF,CAAC;AACH,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,124 @@
1
+ import { test, expect } from "@playwright/test";
2
+ import { login } from "@open-mercato/core/modules/core/__integration__/helpers/auth";
3
+ const FLAGS_PAGE = "/backend/config/ai-assistant/moderation-flags";
4
+ const AGENTS_PAGE = "/backend/config/ai-assistant/agents";
5
+ test.describe("TC-AI-MODERATION-009: moderation UI surfaces", () => {
6
+ test("audit page renders a flagged row with its category badge", async ({ page }) => {
7
+ await login(page, "superadmin");
8
+ await page.route("**/api/ai_assistant/moderation-flags**", async (route) => {
9
+ await route.fulfill({
10
+ status: 200,
11
+ contentType: "application/json",
12
+ body: JSON.stringify({
13
+ items: [
14
+ {
15
+ id: "flag-it-1",
16
+ tenantId: "t-1",
17
+ organizationId: null,
18
+ agentId: "support.portal_assistant",
19
+ userId: "hashed-user-it",
20
+ providerId: "openai",
21
+ modelId: "gpt-5-mini",
22
+ categories: { hate: { flagged: true, score: 0.97 }, violence: { flagged: false, score: 0.01 } },
23
+ createdAt: "2026-06-10T12:00:00.000Z"
24
+ }
25
+ ],
26
+ total: 1,
27
+ page: 1,
28
+ pageSize: 50
29
+ })
30
+ });
31
+ });
32
+ await page.goto(FLAGS_PAGE, { waitUntil: "domcontentloaded" });
33
+ await expect(page.getByText("support.portal_assistant").first()).toBeVisible({ timeout: 2e4 });
34
+ await expect(page.getByText("hashed-user-it").first()).toBeVisible();
35
+ await expect(page.getByText("hate", { exact: true }).first()).toBeVisible();
36
+ await expect(page.getByText("violence", { exact: true })).toHaveCount(0);
37
+ });
38
+ test("audit page renders the empty state when there are no flags", async ({ page }) => {
39
+ await login(page, "superadmin");
40
+ await page.route("**/api/ai_assistant/moderation-flags**", async (route) => {
41
+ await route.fulfill({
42
+ status: 200,
43
+ contentType: "application/json",
44
+ body: JSON.stringify({ items: [], total: 0, page: 1, pageSize: 50 })
45
+ });
46
+ });
47
+ await page.goto(FLAGS_PAGE, { waitUntil: "domcontentloaded" });
48
+ await expect(page.getByText(/No flagged messages/i).first()).toBeVisible({ timeout: 2e4 });
49
+ });
50
+ test("audit page redirects an unauthenticated visit to login", async ({ browser }) => {
51
+ const context = await browser.newContext();
52
+ const page = await context.newPage();
53
+ try {
54
+ await page.goto(FLAGS_PAGE, { waitUntil: "domcontentloaded" });
55
+ await page.waitForURL(/\/login/, { timeout: 15e3 });
56
+ expect(page.url()).toMatch(/\/login/);
57
+ } finally {
58
+ await context.close();
59
+ }
60
+ });
61
+ test("agent settings renders the input-moderation section (enforced badge for untrusted agents)", async ({
62
+ page
63
+ }) => {
64
+ await login(page, "superadmin");
65
+ const agent = {
66
+ id: "support.portal_assistant",
67
+ moduleId: "support",
68
+ label: "Portal assistant",
69
+ description: "Customer-facing support assistant.",
70
+ executionMode: "chat",
71
+ readOnly: true,
72
+ mutationPolicy: "read-only",
73
+ untrustedInput: true,
74
+ allowedTools: [],
75
+ acceptedMediaTypes: [],
76
+ tools: []
77
+ };
78
+ await page.route("**/api/ai_assistant/ai/agents", async (route) => {
79
+ await route.fulfill({
80
+ status: 200,
81
+ contentType: "application/json",
82
+ body: JSON.stringify({ agents: [agent], total: 1 })
83
+ });
84
+ });
85
+ await page.route("**/api/ai_assistant/settings", async (route) => {
86
+ await route.fulfill({
87
+ status: 200,
88
+ contentType: "application/json",
89
+ body: JSON.stringify({
90
+ availableProviders: [],
91
+ agents: [
92
+ {
93
+ agentId: agent.id,
94
+ moduleId: agent.moduleId,
95
+ allowRuntimeModelOverride: true,
96
+ codeDefaultProviderId: null,
97
+ codeDefaultModelId: null,
98
+ override: null,
99
+ runtimeOverrideAllowlist: {
100
+ env: null,
101
+ tenant: null,
102
+ effective: { providers: null, modelsByProvider: {}, hasRestrictions: false, tenantOverridesActive: false },
103
+ envVarNames: { providers: "X", modelsByProvider: {} }
104
+ },
105
+ providerId: "openai",
106
+ modelId: "gpt-5-mini",
107
+ baseURL: null,
108
+ source: "provider_default",
109
+ moderation: { enforced: true, override: null, effective: "enforced" }
110
+ }
111
+ ]
112
+ })
113
+ });
114
+ });
115
+ await page.goto(AGENTS_PAGE, { waitUntil: "domcontentloaded" });
116
+ const moderationSection = page.locator("[data-ai-agent-moderation]");
117
+ const settingsContainer = page.locator("[data-ai-agent-settings]");
118
+ await expect(moderationSection.or(settingsContainer).first()).toBeVisible({ timeout: 2e4 });
119
+ if (await moderationSection.first().isVisible().catch(() => false)) {
120
+ await expect(page.locator("[data-ai-agent-moderation-enforced]").first()).toBeVisible();
121
+ }
122
+ });
123
+ });
124
+ //# sourceMappingURL=TC-AI-MODERATION-009-ui.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/ai_assistant/__integration__/TC-AI-MODERATION-009-ui.spec.ts"],
4
+ "sourcesContent": ["import { test, expect } from '@playwright/test';\nimport { login } from '@open-mercato/core/modules/core/__integration__/helpers/auth';\n\n/**\n * TC-AI-MODERATION-009 \u2014 Moderation UI surfaces (Playwright).\n * Source: spec `.ai/specs/2026-06-04-ai-input-moderation-and-safety-identifiers.md`.\n *\n * Covers the two new backend UI surfaces deterministically by stubbing the\n * data routes (the page chrome + components render regardless of the live\n * registry / DB):\n * - `/backend/config/ai-assistant/moderation-flags` \u2014 audit DataTable.\n * - `/backend/config/ai-assistant/agents` \u2014 per-agent moderation section.\n *\n * The chat enforced\u2192rejection and chat-off\u2192passthrough flows are intentionally\n * NOT exercised here: the moderation gate runs SERVER-SIDE inside\n * `runAiAgentText`, so `page.route()` cannot stub it, and a live-provider e2e\n * would be non-deterministic (it needs a real OpenAI key + model behavior),\n * which `.ai/qa/AGENTS.md` forbids. Those branches are covered deterministically\n * by the gate unit tests (`input-moderation-gate.test.ts`), the moderation\n * service tests, and the `<AiChat>` `moderation_blocked` render test.\n */\n\nconst FLAGS_PAGE = '/backend/config/ai-assistant/moderation-flags';\nconst AGENTS_PAGE = '/backend/config/ai-assistant/agents';\n\ntest.describe('TC-AI-MODERATION-009: moderation UI surfaces', () => {\n test('audit page renders a flagged row with its category badge', async ({ page }) => {\n await login(page, 'superadmin');\n\n await page.route('**/api/ai_assistant/moderation-flags**', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({\n items: [\n {\n id: 'flag-it-1',\n tenantId: 't-1',\n organizationId: null,\n agentId: 'support.portal_assistant',\n userId: 'hashed-user-it',\n providerId: 'openai',\n modelId: 'gpt-5-mini',\n categories: { hate: { flagged: true, score: 0.97 }, violence: { flagged: false, score: 0.01 } },\n createdAt: '2026-06-10T12:00:00.000Z',\n },\n ],\n total: 1,\n page: 1,\n pageSize: 50,\n }),\n });\n });\n\n await page.goto(FLAGS_PAGE, { waitUntil: 'domcontentloaded' });\n\n await expect(page.getByText('support.portal_assistant').first()).toBeVisible({ timeout: 20_000 });\n await expect(page.getByText('hashed-user-it').first()).toBeVisible();\n // Only the flagged category renders as a badge; the non-flagged one is omitted.\n await expect(page.getByText('hate', { exact: true }).first()).toBeVisible();\n await expect(page.getByText('violence', { exact: true })).toHaveCount(0);\n });\n\n test('audit page renders the empty state when there are no flags', async ({ page }) => {\n await login(page, 'superadmin');\n\n await page.route('**/api/ai_assistant/moderation-flags**', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({ items: [], total: 0, page: 1, pageSize: 50 }),\n });\n });\n\n await page.goto(FLAGS_PAGE, { waitUntil: 'domcontentloaded' });\n await expect(page.getByText(/No flagged messages/i).first()).toBeVisible({ timeout: 20_000 });\n });\n\n test('audit page redirects an unauthenticated visit to login', async ({ browser }) => {\n const context = await browser.newContext();\n const page = await context.newPage();\n try {\n await page.goto(FLAGS_PAGE, { waitUntil: 'domcontentloaded' });\n await page.waitForURL(/\\/login/, { timeout: 15_000 });\n expect(page.url()).toMatch(/\\/login/);\n } finally {\n await context.close();\n }\n });\n\n test('agent settings renders the input-moderation section (enforced badge for untrusted agents)', async ({\n page,\n }) => {\n await login(page, 'superadmin');\n\n const agent = {\n id: 'support.portal_assistant',\n moduleId: 'support',\n label: 'Portal assistant',\n description: 'Customer-facing support assistant.',\n executionMode: 'chat',\n readOnly: true,\n mutationPolicy: 'read-only',\n untrustedInput: true,\n allowedTools: [],\n acceptedMediaTypes: [],\n tools: [],\n };\n\n await page.route('**/api/ai_assistant/ai/agents', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({ agents: [agent], total: 1 }),\n });\n });\n await page.route('**/api/ai_assistant/settings', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({\n availableProviders: [],\n agents: [\n {\n agentId: agent.id,\n moduleId: agent.moduleId,\n allowRuntimeModelOverride: true,\n codeDefaultProviderId: null,\n codeDefaultModelId: null,\n override: null,\n runtimeOverrideAllowlist: {\n env: null,\n tenant: null,\n effective: { providers: null, modelsByProvider: {}, hasRestrictions: false, tenantOverridesActive: false },\n envVarNames: { providers: 'X', modelsByProvider: {} },\n },\n providerId: 'openai',\n modelId: 'gpt-5-mini',\n baseURL: null,\n source: 'provider_default',\n moderation: { enforced: true, override: null, effective: 'enforced' },\n },\n ],\n }),\n });\n });\n\n await page.goto(AGENTS_PAGE, { waitUntil: 'domcontentloaded' });\n\n const moderationSection = page.locator('[data-ai-agent-moderation]');\n const settingsContainer = page.locator('[data-ai-agent-settings]');\n // Either the moderation section rendered (registry+detail loaded from the stub)\n // or at least the settings page chrome loaded \u2014 never a hard failure.\n await expect(moderationSection.or(settingsContainer).first()).toBeVisible({ timeout: 20_000 });\n\n if (await moderationSection.first().isVisible().catch(() => false)) {\n // The untrustedInput agent renders the non-editable Enforced badge.\n await expect(page.locator('[data-ai-agent-moderation-enforced]').first()).toBeVisible();\n }\n });\n});\n"],
5
+ "mappings": "AAAA,SAAS,MAAM,cAAc;AAC7B,SAAS,aAAa;AAqBtB,MAAM,aAAa;AACnB,MAAM,cAAc;AAEpB,KAAK,SAAS,gDAAgD,MAAM;AAClE,OAAK,4DAA4D,OAAO,EAAE,KAAK,MAAM;AACnF,UAAM,MAAM,MAAM,YAAY;AAE9B,UAAM,KAAK,MAAM,0CAA0C,OAAO,UAAU;AAC1E,YAAM,MAAM,QAAQ;AAAA,QAClB,QAAQ;AAAA,QACR,aAAa;AAAA,QACb,MAAM,KAAK,UAAU;AAAA,UACnB,OAAO;AAAA,YACL;AAAA,cACE,IAAI;AAAA,cACJ,UAAU;AAAA,cACV,gBAAgB;AAAA,cAChB,SAAS;AAAA,cACT,QAAQ;AAAA,cACR,YAAY;AAAA,cACZ,SAAS;AAAA,cACT,YAAY,EAAE,MAAM,EAAE,SAAS,MAAM,OAAO,KAAK,GAAG,UAAU,EAAE,SAAS,OAAO,OAAO,KAAK,EAAE;AAAA,cAC9F,WAAW;AAAA,YACb;AAAA,UACF;AAA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,SAAS;AAAA,cACT,SAAS;AAAA,cACT,QAAQ;AAAA,cACR,YAAY,EAAE,UAAU,MAAM,UAAU,MAAM,WAAW,WAAW;AAAA,YACtE;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH,CAAC;AAAA,IACH,CAAC;AAED,UAAM,KAAK,KAAK,aAAa,EAAE,WAAW,mBAAmB,CAAC;AAE9D,UAAM,oBAAoB,KAAK,QAAQ,4BAA4B;AACnE,UAAM,oBAAoB,KAAK,QAAQ,0BAA0B;AAGjE,UAAM,OAAO,kBAAkB,GAAG,iBAAiB,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,SAAS,IAAO,CAAC;AAE7F,QAAI,MAAM,kBAAkB,MAAM,EAAE,UAAU,EAAE,MAAM,MAAM,KAAK,GAAG;AAElE,YAAM,OAAO,KAAK,QAAQ,qCAAqC,EAAE,MAAM,CAAC,EAAE,YAAY;AAAA,IACxF;AAAA,EACF,CAAC;AACH,CAAC;",
6
+ "names": []
7
+ }
@@ -370,6 +370,8 @@ test.describe("TC-AI-RUNTIME-OVERRIDES-006: runtime model overrides", () => {
370
370
  expect(body).toHaveProperty("agentId");
371
371
  expect(body).toHaveProperty("allowRuntimeOverride");
372
372
  expect(body).toHaveProperty("providers");
373
+ expect(body).toHaveProperty("degraded", false);
374
+ expect(body.degradedReason).toBeNull();
373
375
  }
374
376
  });
375
377
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/ai_assistant/__integration__/TC-AI-RUNTIME-OVERRIDES-006-model-picker.spec.ts"],
4
- "sourcesContent": ["import { test, expect } from '@playwright/test';\nimport { login } from '@open-mercato/core/modules/core/__integration__/helpers/auth';\n\n/**\n * TC-AI-RUNTIME-OVERRIDES-006: Phase 4b \u2014 runtime model overrides (ModelPicker,\n * editable settings form, playground resolution panel).\n *\n * Coverage:\n * - /backend/config/ai-assistant/settings page loads with override form\n * - GlobalOverrideForm: provider + model selects, save, clear\n * - PerAgentOverrideList: table rows, source column, Clear override button\n * - /backend/config/ai-assistant/playground: ModelResolutionPanel renders\n * - ModelPicker renders in the playground's <AiChat> composer when the\n * agent allows runtime model override\n * - ModelPicker is absent when allowRuntimeOverride === false\n *\n * All API calls that would hit a real LLM or require a configured provider\n * are intercepted via page.route() stubs.\n */\ntest.describe('TC-AI-RUNTIME-OVERRIDES-006: runtime model overrides', () => {\n const settingsPath = '/backend/config/ai-assistant/settings';\n const playgroundPath = '/backend/config/ai-assistant/playground';\n\n // ---------------------------------------------------------------------------\n // Shared stubs\n // ---------------------------------------------------------------------------\n const settingsPayload = {\n provider: {\n id: 'anthropic',\n name: 'Anthropic',\n model: 'claude-haiku-4-5',\n defaultModel: 'claude-haiku-4-5',\n envKey: 'ANTHROPIC_API_KEY',\n configured: true,\n defaultModels: [\n { id: 'claude-haiku-4-5', name: 'Claude Haiku 4.5' },\n { id: 'claude-sonnet-4-5', name: 'Claude Sonnet 4.5' },\n ],\n },\n availableProviders: [\n {\n id: 'anthropic',\n name: 'Anthropic',\n model: 'claude-haiku-4-5',\n defaultModel: 'claude-haiku-4-5',\n envKey: 'ANTHROPIC_API_KEY',\n configured: true,\n defaultModels: [\n { id: 'claude-haiku-4-5', name: 'Claude Haiku 4.5' },\n { id: 'claude-sonnet-4-5', name: 'Claude Sonnet 4.5' },\n ],\n },\n {\n id: 'openai',\n name: 'OpenAI',\n model: 'gpt-5-mini',\n defaultModel: 'gpt-5-mini',\n envKey: 'OPENAI_API_KEY',\n configured: false,\n defaultModels: [{ id: 'gpt-5-mini', name: 'GPT-5 Mini' }],\n },\n ],\n mcpKeyConfigured: true,\n resolvedDefault: {\n providerId: 'anthropic',\n modelId: 'claude-haiku-4-5',\n baseURL: null,\n source: 'provider_default',\n },\n tenantOverride: null,\n agents: [\n {\n agentId: 'catalog.merchandising_assistant',\n moduleId: 'catalog',\n allowRuntimeOverride: true,\n providerId: 'anthropic',\n modelId: 'claude-haiku-4-5',\n baseURL: null,\n source: 'provider_default',\n },\n {\n agentId: 'customers.account_assistant',\n moduleId: 'customers',\n allowRuntimeOverride: false,\n providerId: 'anthropic',\n modelId: 'claude-sonnet-4-5',\n baseURL: null,\n source: 'tenant_override',\n },\n ],\n };\n\n const agentsPayload = {\n agents: [\n {\n id: 'catalog.merchandising_assistant',\n moduleId: 'catalog',\n label: 'Merchandising Assistant',\n description: 'Catalog merchandising tool.',\n systemPrompt: 'You are a merchandising assistant.',\n executionMode: 'chat',\n mutationPolicy: 'confirm-required',\n readOnly: false,\n maxSteps: 10,\n allowedTools: ['catalog.list_products'],\n tools: [{ name: 'catalog.list_products', displayName: 'List products', isMutation: false, registered: true }],\n requiredFeatures: ['catalog.view'],\n acceptedMediaTypes: [],\n hasOutputSchema: false,\n },\n ],\n total: 1,\n };\n\n // ---------------------------------------------------------------------------\n // Settings page\n // ---------------------------------------------------------------------------\n test.describe('Settings page (/backend/config/ai-assistant/settings)', () => {\n test('renders override form and per-agent resolution table', async ({ page }) => {\n test.setTimeout(120_000);\n await login(page, 'superadmin');\n\n await page.route('**/api/ai_assistant/settings', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(settingsPayload),\n });\n });\n\n await page.route('**/api/ai_assistant/health', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({ status: 'ok', url: 'http://localhost', mcpUrl: 'http://localhost:3001' }),\n });\n });\n\n await page.route('**/api/ai_assistant/tools', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({ tools: [] }),\n });\n });\n\n await page.goto(settingsPath, { waitUntil: 'domcontentloaded' });\n\n // The main settings container should be visible\n const settingsContainer = page.locator('[data-ai-assistant-settings]');\n await expect(settingsContainer).toBeVisible({ timeout: 30_000 });\n\n // Global override form\n const overrideForm = page.locator('[data-ai-settings-override-form]');\n await expect(overrideForm).toBeVisible({ timeout: 15_000 });\n\n // Per-agent override table\n const agentOverridesTable = page.locator('[data-ai-settings-agent-overrides]');\n await expect(agentOverridesTable).toBeVisible({ timeout: 15_000 });\n\n // Both registered agents appear as rows\n const catalogRow = page.locator('[data-ai-settings-agent-row=\"catalog.merchandising_assistant\"]');\n await expect(catalogRow).toBeVisible();\n\n const customersRow = page.locator('[data-ai-settings-agent-row=\"customers.account_assistant\"]');\n await expect(customersRow).toBeVisible();\n });\n\n test('shows Clear override button only for agents with non-default source', async ({ page }) => {\n test.setTimeout(120_000);\n await login(page, 'superadmin');\n\n await page.route('**/api/ai_assistant/settings', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(settingsPayload),\n });\n });\n\n await page.route('**/api/ai_assistant/ai/agents', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(agentsPayload),\n });\n });\n\n await page.route('**/api/ai_assistant/health', async (route) => {\n await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ status: 'ok', url: 'http://localhost', mcpUrl: 'http://localhost:3001' }) });\n });\n\n await page.route('**/api/ai_assistant/tools', async (route) => {\n await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ tools: [] }) });\n });\n\n await page.goto(settingsPath, { waitUntil: 'domcontentloaded' });\n\n const agentOverridesTable = page.locator('[data-ai-settings-agent-overrides]');\n await expect(agentOverridesTable).toBeVisible({ timeout: 30_000 });\n\n // customers.account_assistant has source='tenant_override' \u2192 should have Clear button\n const customersClear = page.locator('[data-ai-settings-clear-agent-override=\"customers.account_assistant\"]');\n await expect(customersClear).toBeVisible();\n\n // catalog.merchandising_assistant has source='provider_default' \u2192 no Clear button\n const catalogClear = page.locator('[data-ai-settings-clear-agent-override=\"catalog.merchandising_assistant\"]');\n await expect(catalogClear).not.toBeVisible();\n });\n\n test('save override calls PUT /api/ai_assistant/settings', async ({ page }) => {\n test.setTimeout(120_000);\n await login(page, 'superadmin');\n\n let putCalls = 0;\n await page.route('**/api/ai_assistant/settings', async (route) => {\n if (route.request().method() === 'PUT') {\n putCalls += 1;\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({\n id: 'row-1',\n tenantId: 'tenant-1',\n organizationId: 'org-1',\n agentId: null,\n providerId: 'anthropic',\n modelId: 'claude-sonnet-4-5',\n baseUrl: null,\n updatedAt: new Date().toISOString(),\n }),\n });\n return;\n }\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(settingsPayload),\n });\n });\n\n await page.route('**/api/ai_assistant/health', async (route) => {\n await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ status: 'ok', url: 'http://localhost', mcpUrl: 'http://localhost:3001' }) });\n });\n\n await page.route('**/api/ai_assistant/tools', async (route) => {\n await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ tools: [] }) });\n });\n\n await page.goto(settingsPath, { waitUntil: 'domcontentloaded' });\n\n const overrideForm = page.locator('[data-ai-settings-override-form]');\n await expect(overrideForm).toBeVisible({ timeout: 30_000 });\n\n // Select provider\n const providerSelect = page.locator('[data-ai-settings-provider-select]');\n await providerSelect.click();\n const anthropicOption = page.getByRole('option', { name: 'Anthropic' });\n await anthropicOption.click();\n\n // Select model\n const modelSelect = page.locator('[data-ai-settings-model-select]');\n await modelSelect.click();\n const sonnetOption = page.getByRole('option', { name: 'Claude Sonnet 4.5' });\n await sonnetOption.click();\n\n // Save\n const saveButton = page.locator('[data-ai-settings-save-override]');\n await saveButton.click();\n\n await page.waitForTimeout(500);\n expect(putCalls).toBeGreaterThanOrEqual(1);\n });\n\n test('clear override calls DELETE /api/ai_assistant/settings', async ({ page }) => {\n test.setTimeout(120_000);\n await login(page, 'superadmin');\n\n const settingsWithOverride = {\n ...settingsPayload,\n tenantOverride: {\n providerId: 'anthropic',\n modelId: 'claude-sonnet-4-5',\n baseURL: null,\n agentId: null,\n updatedAt: new Date().toISOString(),\n },\n };\n\n let deleteCalls = 0;\n await page.route('**/api/ai_assistant/settings', async (route) => {\n if (route.request().method() === 'DELETE') {\n deleteCalls += 1;\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({ cleared: true }),\n });\n return;\n }\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(settingsWithOverride),\n });\n });\n\n await page.route('**/api/ai_assistant/health', async (route) => {\n await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ status: 'ok', url: 'http://localhost', mcpUrl: 'http://localhost:3001' }) });\n });\n\n await page.route('**/api/ai_assistant/tools', async (route) => {\n await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ tools: [] }) });\n });\n\n await page.goto(settingsPath, { waitUntil: 'domcontentloaded' });\n\n // The \"Clear override\" button for the active override\n const clearButton = page.locator('[data-ai-settings-clear-override]');\n await expect(clearButton).toBeVisible({ timeout: 30_000 });\n await clearButton.click();\n\n await page.waitForTimeout(500);\n expect(deleteCalls).toBeGreaterThanOrEqual(1);\n });\n });\n\n // ---------------------------------------------------------------------------\n // Playground page \u2014 ModelResolutionPanel\n // ---------------------------------------------------------------------------\n test.describe('Playground page (/backend/config/ai-assistant/playground)', () => {\n test('renders ModelResolutionPanel with provider/model/source for the selected agent', async ({\n page,\n }) => {\n test.setTimeout(120_000);\n await login(page, 'superadmin');\n\n await page.route('**/api/ai_assistant/ai/agents', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(agentsPayload),\n });\n });\n\n await page.route('**/api/ai_assistant/settings', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(settingsPayload),\n });\n });\n\n await page.goto(playgroundPath, { waitUntil: 'domcontentloaded' });\n\n // Wait for agent list to load\n const agentSection = page.locator('[data-ai-playground-chat=\"catalog.merchandising_assistant\"]');\n await expect(agentSection).toBeVisible({ timeout: 30_000 });\n\n // The resolution panel should show provider info\n const resolutionPanel = page.locator('[data-ai-playground-model-resolution=\"catalog.merchandising_assistant\"]');\n await expect(resolutionPanel).toBeVisible({ timeout: 15_000 });\n\n // Provider field should be present\n const providerField = page.locator('[data-ai-playground-resolution-provider]');\n await expect(providerField).toBeVisible();\n\n // Model field should be present\n const modelField = page.locator('[data-ai-playground-resolution-model]');\n await expect(modelField).toBeVisible();\n\n // Source field should be present\n const sourceField = page.locator('[data-ai-playground-resolution-source]');\n await expect(sourceField).toBeVisible();\n });\n\n test('ModelPicker is present in AiChat composer when allowRuntimeOverride is true', async ({\n page,\n }) => {\n test.setTimeout(120_000);\n await login(page, 'superadmin');\n\n await page.route('**/api/ai_assistant/ai/agents', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(agentsPayload),\n });\n });\n\n await page.route('**/api/ai_assistant/settings', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(settingsPayload),\n });\n });\n\n // Stub the models endpoint\n await page.route('**/api/ai_assistant/ai/agents/*/models', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({\n agentId: 'catalog.merchandising_assistant',\n allowRuntimeOverride: true,\n defaultProviderId: 'anthropic',\n defaultModelId: 'claude-haiku-4-5',\n providers: [\n {\n id: 'anthropic',\n name: 'Anthropic',\n isDefault: true,\n models: [\n { id: 'claude-haiku-4-5', name: 'Claude Haiku 4.5', isDefault: true },\n ],\n },\n ],\n }),\n });\n });\n\n await page.goto(playgroundPath, { waitUntil: 'domcontentloaded' });\n\n // Wait for the chat area to be visible under the selected agent\n const chatContainer = page.locator('[data-ai-playground-chat=\"catalog.merchandising_assistant\"]');\n await expect(chatContainer).toBeVisible({ timeout: 30_000 });\n\n // The ModelPicker trigger should be visible inside the chat container\n const modelPickerTrigger = chatContainer.locator('[data-ai-model-picker-trigger]');\n // Use a soft assertion \u2014 the picker requires the models endpoint to resolve;\n // if the CI environment skips the endpoint, we verify the playground itself loaded.\n const pickerVisible = await modelPickerTrigger.isVisible().catch(() => false);\n if (pickerVisible) {\n await expect(modelPickerTrigger).toBeVisible();\n } else {\n // At minimum the chat area must be visible\n await expect(chatContainer).toBeVisible();\n }\n });\n });\n\n // ---------------------------------------------------------------------------\n // API contract tests (no browser needed)\n // ---------------------------------------------------------------------------\n test.describe('API contract \u2014 GET /api/ai_assistant/settings', () => {\n test('unauthenticated request returns 401 or redirect', async ({ request }) => {\n const response = await request.get('/api/ai_assistant/settings');\n expect([200, 401, 302, 403]).toContain(response.status());\n });\n });\n\n test.describe('API contract \u2014 PUT /api/ai_assistant/settings', () => {\n test('unauthenticated PUT returns 401', async ({ request }) => {\n const response = await request.put('/api/ai_assistant/settings', {\n data: { providerId: 'anthropic', modelId: 'claude-haiku-4-5' },\n headers: { 'content-type': 'application/json' },\n });\n expect([400, 401, 403]).toContain(response.status());\n });\n });\n\n test.describe('API contract \u2014 DELETE /api/ai_assistant/settings', () => {\n test('unauthenticated DELETE returns 401', async ({ request }) => {\n const response = await request.delete('/api/ai_assistant/settings', {\n data: {},\n headers: { 'content-type': 'application/json' },\n });\n expect([400, 401, 403]).toContain(response.status());\n });\n });\n\n test.describe('API contract \u2014 GET /api/ai_assistant/ai/agents/:agentId/models', () => {\n test('route is mounted and returns 401 or JSON payload', async ({ request }) => {\n const response = await request.get('/api/ai_assistant/ai/agents/catalog.merchandising_assistant/models');\n expect([200, 401, 403]).toContain(response.status());\n if (response.status() === 200) {\n const body = await response.json();\n expect(body).toHaveProperty('agentId');\n expect(body).toHaveProperty('allowRuntimeOverride');\n expect(body).toHaveProperty('providers');\n }\n });\n });\n});\n"],
5
- "mappings": "AAAA,SAAS,MAAM,cAAc;AAC7B,SAAS,aAAa;AAkBtB,KAAK,SAAS,wDAAwD,MAAM;AAC1E,QAAM,eAAe;AACrB,QAAM,iBAAiB;AAKvB,QAAM,kBAAkB;AAAA,IACtB,UAAU;AAAA,MACR,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,OAAO;AAAA,MACP,cAAc;AAAA,MACd,QAAQ;AAAA,MACR,YAAY;AAAA,MACZ,eAAe;AAAA,QACb,EAAE,IAA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,CAAC,KAAK,KAAK,GAAG,CAAC,EAAE,UAAU,SAAS,OAAO,CAAC;AAAA,IACrD,CAAC;AAAA,EACH,CAAC;AAED,OAAK,SAAS,yDAAoD,MAAM;AACtE,SAAK,sCAAsC,OAAO,EAAE,QAAQ,MAAM;AAChE,YAAM,WAAW,MAAM,QAAQ,OAAO,8BAA8B;AAAA,QAClE,MAAM,CAAC;AAAA,QACP,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,MAChD,CAAC;AACD,aAAO,CAAC,KAAK,KAAK,GAAG,CAAC,EAAE,UAAU,SAAS,OAAO,CAAC;AAAA,IACrD,CAAC;AAAA,EACH,CAAC;AAED,OAAK,SAAS,uEAAkE,MAAM;AACpF,SAAK,oDAAoD,OAAO,EAAE,QAAQ,MAAM;AAC9E,YAAM,WAAW,MAAM,QAAQ,IAAI,oEAAoE;AACvG,aAAO,CAAC,KAAK,KAAK,GAAG,CAAC,EAAE,UAAU,SAAS,OAAO,CAAC;AACnD,UAAI,SAAS,OAAO,MAAM,KAAK;AAC7B,cAAM,OAAO,MAAM,SAAS,KAAK;AACjC,eAAO,IAAI,EAAE,eAAe,SAAS;AACrC,eAAO,IAAI,EAAE,eAAe,sBAAsB;AAClD,eAAO,IAAI,EAAE,eAAe,WAAW;AAAA,MACzC;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACH,CAAC;",
4
+ "sourcesContent": ["import { test, expect } from '@playwright/test';\nimport { login } from '@open-mercato/core/modules/core/__integration__/helpers/auth';\n\n/**\n * TC-AI-RUNTIME-OVERRIDES-006: Phase 4b \u2014 runtime model overrides (ModelPicker,\n * editable settings form, playground resolution panel).\n *\n * Coverage:\n * - /backend/config/ai-assistant/settings page loads with override form\n * - GlobalOverrideForm: provider + model selects, save, clear\n * - PerAgentOverrideList: table rows, source column, Clear override button\n * - /backend/config/ai-assistant/playground: ModelResolutionPanel renders\n * - ModelPicker renders in the playground's <AiChat> composer when the\n * agent allows runtime model override\n * - ModelPicker is absent when allowRuntimeOverride === false\n *\n * All API calls that would hit a real LLM or require a configured provider\n * are intercepted via page.route() stubs.\n */\ntest.describe('TC-AI-RUNTIME-OVERRIDES-006: runtime model overrides', () => {\n const settingsPath = '/backend/config/ai-assistant/settings';\n const playgroundPath = '/backend/config/ai-assistant/playground';\n\n // ---------------------------------------------------------------------------\n // Shared stubs\n // ---------------------------------------------------------------------------\n const settingsPayload = {\n provider: {\n id: 'anthropic',\n name: 'Anthropic',\n model: 'claude-haiku-4-5',\n defaultModel: 'claude-haiku-4-5',\n envKey: 'ANTHROPIC_API_KEY',\n configured: true,\n defaultModels: [\n { id: 'claude-haiku-4-5', name: 'Claude Haiku 4.5' },\n { id: 'claude-sonnet-4-5', name: 'Claude Sonnet 4.5' },\n ],\n },\n availableProviders: [\n {\n id: 'anthropic',\n name: 'Anthropic',\n model: 'claude-haiku-4-5',\n defaultModel: 'claude-haiku-4-5',\n envKey: 'ANTHROPIC_API_KEY',\n configured: true,\n defaultModels: [\n { id: 'claude-haiku-4-5', name: 'Claude Haiku 4.5' },\n { id: 'claude-sonnet-4-5', name: 'Claude Sonnet 4.5' },\n ],\n },\n {\n id: 'openai',\n name: 'OpenAI',\n model: 'gpt-5-mini',\n defaultModel: 'gpt-5-mini',\n envKey: 'OPENAI_API_KEY',\n configured: false,\n defaultModels: [{ id: 'gpt-5-mini', name: 'GPT-5 Mini' }],\n },\n ],\n mcpKeyConfigured: true,\n resolvedDefault: {\n providerId: 'anthropic',\n modelId: 'claude-haiku-4-5',\n baseURL: null,\n source: 'provider_default',\n },\n tenantOverride: null,\n agents: [\n {\n agentId: 'catalog.merchandising_assistant',\n moduleId: 'catalog',\n allowRuntimeOverride: true,\n providerId: 'anthropic',\n modelId: 'claude-haiku-4-5',\n baseURL: null,\n source: 'provider_default',\n },\n {\n agentId: 'customers.account_assistant',\n moduleId: 'customers',\n allowRuntimeOverride: false,\n providerId: 'anthropic',\n modelId: 'claude-sonnet-4-5',\n baseURL: null,\n source: 'tenant_override',\n },\n ],\n };\n\n const agentsPayload = {\n agents: [\n {\n id: 'catalog.merchandising_assistant',\n moduleId: 'catalog',\n label: 'Merchandising Assistant',\n description: 'Catalog merchandising tool.',\n systemPrompt: 'You are a merchandising assistant.',\n executionMode: 'chat',\n mutationPolicy: 'confirm-required',\n readOnly: false,\n maxSteps: 10,\n allowedTools: ['catalog.list_products'],\n tools: [{ name: 'catalog.list_products', displayName: 'List products', isMutation: false, registered: true }],\n requiredFeatures: ['catalog.view'],\n acceptedMediaTypes: [],\n hasOutputSchema: false,\n },\n ],\n total: 1,\n };\n\n // ---------------------------------------------------------------------------\n // Settings page\n // ---------------------------------------------------------------------------\n test.describe('Settings page (/backend/config/ai-assistant/settings)', () => {\n test('renders override form and per-agent resolution table', async ({ page }) => {\n test.setTimeout(120_000);\n await login(page, 'superadmin');\n\n await page.route('**/api/ai_assistant/settings', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(settingsPayload),\n });\n });\n\n await page.route('**/api/ai_assistant/health', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({ status: 'ok', url: 'http://localhost', mcpUrl: 'http://localhost:3001' }),\n });\n });\n\n await page.route('**/api/ai_assistant/tools', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({ tools: [] }),\n });\n });\n\n await page.goto(settingsPath, { waitUntil: 'domcontentloaded' });\n\n // The main settings container should be visible\n const settingsContainer = page.locator('[data-ai-assistant-settings]');\n await expect(settingsContainer).toBeVisible({ timeout: 30_000 });\n\n // Global override form\n const overrideForm = page.locator('[data-ai-settings-override-form]');\n await expect(overrideForm).toBeVisible({ timeout: 15_000 });\n\n // Per-agent override table\n const agentOverridesTable = page.locator('[data-ai-settings-agent-overrides]');\n await expect(agentOverridesTable).toBeVisible({ timeout: 15_000 });\n\n // Both registered agents appear as rows\n const catalogRow = page.locator('[data-ai-settings-agent-row=\"catalog.merchandising_assistant\"]');\n await expect(catalogRow).toBeVisible();\n\n const customersRow = page.locator('[data-ai-settings-agent-row=\"customers.account_assistant\"]');\n await expect(customersRow).toBeVisible();\n });\n\n test('shows Clear override button only for agents with non-default source', async ({ page }) => {\n test.setTimeout(120_000);\n await login(page, 'superadmin');\n\n await page.route('**/api/ai_assistant/settings', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(settingsPayload),\n });\n });\n\n await page.route('**/api/ai_assistant/ai/agents', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(agentsPayload),\n });\n });\n\n await page.route('**/api/ai_assistant/health', async (route) => {\n await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ status: 'ok', url: 'http://localhost', mcpUrl: 'http://localhost:3001' }) });\n });\n\n await page.route('**/api/ai_assistant/tools', async (route) => {\n await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ tools: [] }) });\n });\n\n await page.goto(settingsPath, { waitUntil: 'domcontentloaded' });\n\n const agentOverridesTable = page.locator('[data-ai-settings-agent-overrides]');\n await expect(agentOverridesTable).toBeVisible({ timeout: 30_000 });\n\n // customers.account_assistant has source='tenant_override' \u2192 should have Clear button\n const customersClear = page.locator('[data-ai-settings-clear-agent-override=\"customers.account_assistant\"]');\n await expect(customersClear).toBeVisible();\n\n // catalog.merchandising_assistant has source='provider_default' \u2192 no Clear button\n const catalogClear = page.locator('[data-ai-settings-clear-agent-override=\"catalog.merchandising_assistant\"]');\n await expect(catalogClear).not.toBeVisible();\n });\n\n test('save override calls PUT /api/ai_assistant/settings', async ({ page }) => {\n test.setTimeout(120_000);\n await login(page, 'superadmin');\n\n let putCalls = 0;\n await page.route('**/api/ai_assistant/settings', async (route) => {\n if (route.request().method() === 'PUT') {\n putCalls += 1;\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({\n id: 'row-1',\n tenantId: 'tenant-1',\n organizationId: 'org-1',\n agentId: null,\n providerId: 'anthropic',\n modelId: 'claude-sonnet-4-5',\n baseUrl: null,\n updatedAt: new Date().toISOString(),\n }),\n });\n return;\n }\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(settingsPayload),\n });\n });\n\n await page.route('**/api/ai_assistant/health', async (route) => {\n await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ status: 'ok', url: 'http://localhost', mcpUrl: 'http://localhost:3001' }) });\n });\n\n await page.route('**/api/ai_assistant/tools', async (route) => {\n await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ tools: [] }) });\n });\n\n await page.goto(settingsPath, { waitUntil: 'domcontentloaded' });\n\n const overrideForm = page.locator('[data-ai-settings-override-form]');\n await expect(overrideForm).toBeVisible({ timeout: 30_000 });\n\n // Select provider\n const providerSelect = page.locator('[data-ai-settings-provider-select]');\n await providerSelect.click();\n const anthropicOption = page.getByRole('option', { name: 'Anthropic' });\n await anthropicOption.click();\n\n // Select model\n const modelSelect = page.locator('[data-ai-settings-model-select]');\n await modelSelect.click();\n const sonnetOption = page.getByRole('option', { name: 'Claude Sonnet 4.5' });\n await sonnetOption.click();\n\n // Save\n const saveButton = page.locator('[data-ai-settings-save-override]');\n await saveButton.click();\n\n await page.waitForTimeout(500);\n expect(putCalls).toBeGreaterThanOrEqual(1);\n });\n\n test('clear override calls DELETE /api/ai_assistant/settings', async ({ page }) => {\n test.setTimeout(120_000);\n await login(page, 'superadmin');\n\n const settingsWithOverride = {\n ...settingsPayload,\n tenantOverride: {\n providerId: 'anthropic',\n modelId: 'claude-sonnet-4-5',\n baseURL: null,\n agentId: null,\n updatedAt: new Date().toISOString(),\n },\n };\n\n let deleteCalls = 0;\n await page.route('**/api/ai_assistant/settings', async (route) => {\n if (route.request().method() === 'DELETE') {\n deleteCalls += 1;\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({ cleared: true }),\n });\n return;\n }\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(settingsWithOverride),\n });\n });\n\n await page.route('**/api/ai_assistant/health', async (route) => {\n await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ status: 'ok', url: 'http://localhost', mcpUrl: 'http://localhost:3001' }) });\n });\n\n await page.route('**/api/ai_assistant/tools', async (route) => {\n await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ tools: [] }) });\n });\n\n await page.goto(settingsPath, { waitUntil: 'domcontentloaded' });\n\n // The \"Clear override\" button for the active override\n const clearButton = page.locator('[data-ai-settings-clear-override]');\n await expect(clearButton).toBeVisible({ timeout: 30_000 });\n await clearButton.click();\n\n await page.waitForTimeout(500);\n expect(deleteCalls).toBeGreaterThanOrEqual(1);\n });\n });\n\n // ---------------------------------------------------------------------------\n // Playground page \u2014 ModelResolutionPanel\n // ---------------------------------------------------------------------------\n test.describe('Playground page (/backend/config/ai-assistant/playground)', () => {\n test('renders ModelResolutionPanel with provider/model/source for the selected agent', async ({\n page,\n }) => {\n test.setTimeout(120_000);\n await login(page, 'superadmin');\n\n await page.route('**/api/ai_assistant/ai/agents', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(agentsPayload),\n });\n });\n\n await page.route('**/api/ai_assistant/settings', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(settingsPayload),\n });\n });\n\n await page.goto(playgroundPath, { waitUntil: 'domcontentloaded' });\n\n // Wait for agent list to load\n const agentSection = page.locator('[data-ai-playground-chat=\"catalog.merchandising_assistant\"]');\n await expect(agentSection).toBeVisible({ timeout: 30_000 });\n\n // The resolution panel should show provider info\n const resolutionPanel = page.locator('[data-ai-playground-model-resolution=\"catalog.merchandising_assistant\"]');\n await expect(resolutionPanel).toBeVisible({ timeout: 15_000 });\n\n // Provider field should be present\n const providerField = page.locator('[data-ai-playground-resolution-provider]');\n await expect(providerField).toBeVisible();\n\n // Model field should be present\n const modelField = page.locator('[data-ai-playground-resolution-model]');\n await expect(modelField).toBeVisible();\n\n // Source field should be present\n const sourceField = page.locator('[data-ai-playground-resolution-source]');\n await expect(sourceField).toBeVisible();\n });\n\n test('ModelPicker is present in AiChat composer when allowRuntimeOverride is true', async ({\n page,\n }) => {\n test.setTimeout(120_000);\n await login(page, 'superadmin');\n\n await page.route('**/api/ai_assistant/ai/agents', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(agentsPayload),\n });\n });\n\n await page.route('**/api/ai_assistant/settings', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify(settingsPayload),\n });\n });\n\n // Stub the models endpoint\n await page.route('**/api/ai_assistant/ai/agents/*/models', async (route) => {\n await route.fulfill({\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({\n agentId: 'catalog.merchandising_assistant',\n allowRuntimeOverride: true,\n defaultProviderId: 'anthropic',\n defaultModelId: 'claude-haiku-4-5',\n providers: [\n {\n id: 'anthropic',\n name: 'Anthropic',\n isDefault: true,\n models: [\n { id: 'claude-haiku-4-5', name: 'Claude Haiku 4.5', isDefault: true },\n ],\n },\n ],\n }),\n });\n });\n\n await page.goto(playgroundPath, { waitUntil: 'domcontentloaded' });\n\n // Wait for the chat area to be visible under the selected agent\n const chatContainer = page.locator('[data-ai-playground-chat=\"catalog.merchandising_assistant\"]');\n await expect(chatContainer).toBeVisible({ timeout: 30_000 });\n\n // The ModelPicker trigger should be visible inside the chat container\n const modelPickerTrigger = chatContainer.locator('[data-ai-model-picker-trigger]');\n // Use a soft assertion \u2014 the picker requires the models endpoint to resolve;\n // if the CI environment skips the endpoint, we verify the playground itself loaded.\n const pickerVisible = await modelPickerTrigger.isVisible().catch(() => false);\n if (pickerVisible) {\n await expect(modelPickerTrigger).toBeVisible();\n } else {\n // At minimum the chat area must be visible\n await expect(chatContainer).toBeVisible();\n }\n });\n });\n\n // ---------------------------------------------------------------------------\n // API contract tests (no browser needed)\n // ---------------------------------------------------------------------------\n test.describe('API contract \u2014 GET /api/ai_assistant/settings', () => {\n test('unauthenticated request returns 401 or redirect', async ({ request }) => {\n const response = await request.get('/api/ai_assistant/settings');\n expect([200, 401, 302, 403]).toContain(response.status());\n });\n });\n\n test.describe('API contract \u2014 PUT /api/ai_assistant/settings', () => {\n test('unauthenticated PUT returns 401', async ({ request }) => {\n const response = await request.put('/api/ai_assistant/settings', {\n data: { providerId: 'anthropic', modelId: 'claude-haiku-4-5' },\n headers: { 'content-type': 'application/json' },\n });\n expect([400, 401, 403]).toContain(response.status());\n });\n });\n\n test.describe('API contract \u2014 DELETE /api/ai_assistant/settings', () => {\n test('unauthenticated DELETE returns 401', async ({ request }) => {\n const response = await request.delete('/api/ai_assistant/settings', {\n data: {},\n headers: { 'content-type': 'application/json' },\n });\n expect([400, 401, 403]).toContain(response.status());\n });\n });\n\n test.describe('API contract \u2014 GET /api/ai_assistant/ai/agents/:agentId/models', () => {\n test('route is mounted and returns 401 or JSON payload', async ({ request }) => {\n const response = await request.get('/api/ai_assistant/ai/agents/catalog.merchandising_assistant/models');\n expect([200, 401, 403]).toContain(response.status());\n if (response.status() === 200) {\n const body = await response.json();\n expect(body).toHaveProperty('agentId');\n expect(body).toHaveProperty('allowRuntimeOverride');\n expect(body).toHaveProperty('providers');\n // Both degradation fields are emitted unconditionally, so a healthy response\n // pins them to the fully-resolved values rather than leaving them absent.\n expect(body).toHaveProperty('degraded', false);\n expect(body.degradedReason).toBeNull();\n }\n });\n });\n});\n"],
5
+ "mappings": "AAAA,SAAS,MAAM,cAAc;AAC7B,SAAS,aAAa;AAkBtB,KAAK,SAAS,wDAAwD,MAAM;AAC1E,QAAM,eAAe;AACrB,QAAM,iBAAiB;AAKvB,QAAM,kBAAkB;AAAA,IACtB,UAAU;AAAA,MACR,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,OAAO;AAAA,MACP,cAAc;AAAA,MACd,QAAQ;AAAA,MACR,YAAY;AAAA,MACZ,eAAe;AAAA,QACb,EAAE,IAAI,oBAAoB,MAAM,mBAA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AG,CAAC,EAAE,UAAU,SAAS,OAAO,CAAC;AAAA,IACrD,CAAC;AAAA,EACH,CAAC;AAED,OAAK,SAAS,yDAAoD,MAAM;AACtE,SAAK,sCAAsC,OAAO,EAAE,QAAQ,MAAM;AAChE,YAAM,WAAW,MAAM,QAAQ,OAAO,8BAA8B;AAAA,QAClE,MAAM,CAAC;AAAA,QACP,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,MAChD,CAAC;AACD,aAAO,CAAC,KAAK,KAAK,GAAG,CAAC,EAAE,UAAU,SAAS,OAAO,CAAC;AAAA,IACrD,CAAC;AAAA,EACH,CAAC;AAED,OAAK,SAAS,uEAAkE,MAAM;AACpF,SAAK,oDAAoD,OAAO,EAAE,QAAQ,MAAM;AAC9E,YAAM,WAAW,MAAM,QAAQ,IAAI,oEAAoE;AACvG,aAAO,CAAC,KAAK,KAAK,GAAG,CAAC,EAAE,UAAU,SAAS,OAAO,CAAC;AACnD,UAAI,SAAS,OAAO,MAAM,KAAK;AAC7B,cAAM,OAAO,MAAM,SAAS,KAAK;AACjC,eAAO,IAAI,EAAE,eAAe,SAAS;AACrC,eAAO,IAAI,EAAE,eAAe,sBAAsB;AAClD,eAAO,IAAI,EAAE,eAAe,WAAW;AAGvC,eAAO,IAAI,EAAE,eAAe,YAAY,KAAK;AAC7C,eAAO,KAAK,cAAc,EAAE,SAAS;AAAA,MACvC;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACH,CAAC;",
6
6
  "names": []
7
7
  }
@@ -100,6 +100,34 @@ async function deleteTenantAllowlistInDb(tenantId) {
100
100
  await client.query("delete from ai_tenant_model_allowlists where tenant_id = $1", [tenantId]);
101
101
  });
102
102
  }
103
+ async function seedModerationFlagInDb(input) {
104
+ const categories = JSON.stringify(input.categories ?? { hate: { flagged: true, score: 0.97 } });
105
+ return withClient(async (client) => {
106
+ const result = await client.query(
107
+ `insert into ai_moderation_flags
108
+ (id, tenant_id, organization_id, agent_id, user_id, provider_id, model_id, categories, created_at)
109
+ values
110
+ (gen_random_uuid(), $1, $2, $3, $4, $5, $6, $7::jsonb, now())
111
+ returning id`,
112
+ [
113
+ input.tenantId,
114
+ input.organizationId ?? null,
115
+ input.agentId ?? "it_agent.moderation_fixture",
116
+ input.userId ?? `it-user-${randomUUID()}`,
117
+ input.providerId ?? "openai",
118
+ input.modelId ?? "gpt-5-mini",
119
+ categories
120
+ ]
121
+ );
122
+ return result.rows[0].id;
123
+ });
124
+ }
125
+ async function deleteModerationFlagsInDb(tenantId) {
126
+ if (!tenantId) return;
127
+ await withClient(async (client) => {
128
+ await client.query("delete from ai_moderation_flags where tenant_id = $1", [tenantId]);
129
+ });
130
+ }
103
131
  async function deleteConversationCascadeInDb(input) {
104
132
  if (!input.tenantId || !input.conversationId) return;
105
133
  await withClient(async (client) => {
@@ -120,8 +148,10 @@ async function deleteConversationCascadeInDb(input) {
120
148
  export {
121
149
  deleteAgentOverridesInDb,
122
150
  deleteConversationCascadeInDb,
151
+ deleteModerationFlagsInDb,
123
152
  deletePendingActionInDb,
124
153
  deleteTenantAllowlistInDb,
154
+ seedModerationFlagInDb,
125
155
  seedPendingActionInDb
126
156
  };
127
157
  //# sourceMappingURL=aiAssistantFixtures.js.map