@open-mercato/ai-assistant 0.6.6-develop.6465.1.019f0fb26f → 0.6.6-develop.6471.1.9ab5bdd79a

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 (199) hide show
  1. package/dist/frontend/hooks/useCommandPalette.js +16 -14
  2. package/dist/frontend/hooks/useCommandPalette.js.map +2 -2
  3. package/dist/modules/ai_assistant/api/ai/actions/[id]/cancel/route.js +3 -1
  4. package/dist/modules/ai_assistant/api/ai/actions/[id]/cancel/route.js.map +2 -2
  5. package/dist/modules/ai_assistant/api/ai/actions/[id]/confirm/route.js +3 -1
  6. package/dist/modules/ai_assistant/api/ai/actions/[id]/confirm/route.js.map +2 -2
  7. package/dist/modules/ai_assistant/api/ai/actions/[id]/route.js +3 -1
  8. package/dist/modules/ai_assistant/api/ai/actions/[id]/route.js.map +2 -2
  9. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/loop-override/route.js +5 -3
  10. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/loop-override/route.js.map +2 -2
  11. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/models/route.js +4 -2
  12. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/models/route.js.map +2 -2
  13. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/mutation-policy/route.js +5 -3
  14. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/mutation-policy/route.js.map +2 -2
  15. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/prompt-override/route.js +4 -2
  16. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/prompt-override/route.js.map +2 -2
  17. package/dist/modules/ai_assistant/api/ai/agents/route.js +3 -1
  18. package/dist/modules/ai_assistant/api/ai/agents/route.js.map +2 -2
  19. package/dist/modules/ai_assistant/api/ai/chat/route.js +6 -7
  20. package/dist/modules/ai_assistant/api/ai/chat/route.js.map +2 -2
  21. package/dist/modules/ai_assistant/api/ai/conversations/[conversationId]/route.js +5 -3
  22. package/dist/modules/ai_assistant/api/ai/conversations/[conversationId]/route.js.map +2 -2
  23. package/dist/modules/ai_assistant/api/ai/conversations/import/route.js +3 -1
  24. package/dist/modules/ai_assistant/api/ai/conversations/import/route.js.map +2 -2
  25. package/dist/modules/ai_assistant/api/ai/conversations/route.js +4 -2
  26. package/dist/modules/ai_assistant/api/ai/conversations/route.js.map +2 -2
  27. package/dist/modules/ai_assistant/api/ai/run-object/route.js +3 -1
  28. package/dist/modules/ai_assistant/api/ai/run-object/route.js.map +2 -2
  29. package/dist/modules/ai_assistant/api/chat/route.js +23 -14
  30. package/dist/modules/ai_assistant/api/chat/route.js.map +2 -2
  31. package/dist/modules/ai_assistant/api/health/route.js +3 -1
  32. package/dist/modules/ai_assistant/api/health/route.js.map +2 -2
  33. package/dist/modules/ai_assistant/api/mcp-key/route.js +3 -1
  34. package/dist/modules/ai_assistant/api/mcp-key/route.js.map +2 -2
  35. package/dist/modules/ai_assistant/api/route/route.js +11 -9
  36. package/dist/modules/ai_assistant/api/route/route.js.map +2 -2
  37. package/dist/modules/ai_assistant/api/session-key/route.js +3 -1
  38. package/dist/modules/ai_assistant/api/session-key/route.js.map +2 -2
  39. package/dist/modules/ai_assistant/api/settings/allowlist/route.js +4 -2
  40. package/dist/modules/ai_assistant/api/settings/allowlist/route.js.map +2 -2
  41. package/dist/modules/ai_assistant/api/settings/route.js +6 -4
  42. package/dist/modules/ai_assistant/api/settings/route.js.map +2 -2
  43. package/dist/modules/ai_assistant/api/tools/execute/route.js +3 -1
  44. package/dist/modules/ai_assistant/api/tools/execute/route.js.map +2 -2
  45. package/dist/modules/ai_assistant/api/tools/route.js +3 -1
  46. package/dist/modules/ai_assistant/api/tools/route.js.map +2 -2
  47. package/dist/modules/ai_assistant/api/usage/daily/route.js +3 -1
  48. package/dist/modules/ai_assistant/api/usage/daily/route.js.map +2 -2
  49. package/dist/modules/ai_assistant/api/usage/sessions/[sessionId]/route.js +3 -1
  50. package/dist/modules/ai_assistant/api/usage/sessions/[sessionId]/route.js.map +2 -2
  51. package/dist/modules/ai_assistant/api/usage/sessions/route.js +3 -1
  52. package/dist/modules/ai_assistant/api/usage/sessions/route.js.map +2 -2
  53. package/dist/modules/ai_assistant/cli.js +3 -0
  54. package/dist/modules/ai_assistant/cli.js.map +2 -2
  55. package/dist/modules/ai_assistant/lib/agent-policy.js +7 -5
  56. package/dist/modules/ai_assistant/lib/agent-policy.js.map +2 -2
  57. package/dist/modules/ai_assistant/lib/agent-registry.js +11 -13
  58. package/dist/modules/ai_assistant/lib/agent-registry.js.map +2 -2
  59. package/dist/modules/ai_assistant/lib/agent-runtime.js +21 -44
  60. package/dist/modules/ai_assistant/lib/agent-runtime.js.map +2 -2
  61. package/dist/modules/ai_assistant/lib/agent-tools.js +5 -10
  62. package/dist/modules/ai_assistant/lib/agent-tools.js.map +2 -2
  63. package/dist/modules/ai_assistant/lib/ai-overrides.js +5 -9
  64. package/dist/modules/ai_assistant/lib/ai-overrides.js.map +2 -2
  65. package/dist/modules/ai_assistant/lib/api-endpoint-index.js +22 -22
  66. package/dist/modules/ai_assistant/lib/api-endpoint-index.js.map +2 -2
  67. package/dist/modules/ai_assistant/lib/attachment-parts.js +10 -26
  68. package/dist/modules/ai_assistant/lib/attachment-parts.js.map +2 -2
  69. package/dist/modules/ai_assistant/lib/auth.js +3 -1
  70. package/dist/modules/ai_assistant/lib/auth.js.map +2 -2
  71. package/dist/modules/ai_assistant/lib/codemode-tools.js +15 -17
  72. package/dist/modules/ai_assistant/lib/codemode-tools.js.map +2 -2
  73. package/dist/modules/ai_assistant/lib/entity-index.js +7 -5
  74. package/dist/modules/ai_assistant/lib/entity-index.js.map +2 -2
  75. package/dist/modules/ai_assistant/lib/generated-registry-loader.js +3 -4
  76. package/dist/modules/ai_assistant/lib/generated-registry-loader.js.map +2 -2
  77. package/dist/modules/ai_assistant/lib/http-server.js +45 -48
  78. package/dist/modules/ai_assistant/lib/http-server.js.map +2 -2
  79. package/dist/modules/ai_assistant/lib/llm-bootstrap.js +5 -12
  80. package/dist/modules/ai_assistant/lib/llm-bootstrap.js.map +2 -2
  81. package/dist/modules/ai_assistant/lib/mcp-client.js +3 -1
  82. package/dist/modules/ai_assistant/lib/mcp-client.js.map +2 -2
  83. package/dist/modules/ai_assistant/lib/mcp-dev-key-resolution.js +3 -1
  84. package/dist/modules/ai_assistant/lib/mcp-dev-key-resolution.js.map +2 -2
  85. package/dist/modules/ai_assistant/lib/mcp-dev-server.js +3 -1
  86. package/dist/modules/ai_assistant/lib/mcp-dev-server.js.map +2 -2
  87. package/dist/modules/ai_assistant/lib/mcp-server.js +24 -19
  88. package/dist/modules/ai_assistant/lib/mcp-server.js.map +2 -2
  89. package/dist/modules/ai_assistant/lib/mcp-tool-adapter.js +3 -1
  90. package/dist/modules/ai_assistant/lib/mcp-tool-adapter.js.map +2 -2
  91. package/dist/modules/ai_assistant/lib/model-factory.js +4 -2
  92. package/dist/modules/ai_assistant/lib/model-factory.js.map +2 -2
  93. package/dist/modules/ai_assistant/lib/opencode-client.js +5 -3
  94. package/dist/modules/ai_assistant/lib/opencode-client.js.map +2 -2
  95. package/dist/modules/ai_assistant/lib/opencode-handlers.js +30 -12
  96. package/dist/modules/ai_assistant/lib/opencode-handlers.js.map +2 -2
  97. package/dist/modules/ai_assistant/lib/pending-action-cancel.js +3 -1
  98. package/dist/modules/ai_assistant/lib/pending-action-cancel.js.map +2 -2
  99. package/dist/modules/ai_assistant/lib/pending-action-executor.js +3 -1
  100. package/dist/modules/ai_assistant/lib/pending-action-executor.js.map +2 -2
  101. package/dist/modules/ai_assistant/lib/prepare-mutation.js +4 -6
  102. package/dist/modules/ai_assistant/lib/prepare-mutation.js.map +2 -2
  103. package/dist/modules/ai_assistant/lib/schema-utils.js +3 -1
  104. package/dist/modules/ai_assistant/lib/schema-utils.js.map +2 -2
  105. package/dist/modules/ai_assistant/lib/token-usage-recorder.js +4 -8
  106. package/dist/modules/ai_assistant/lib/token-usage-recorder.js.map +2 -2
  107. package/dist/modules/ai_assistant/lib/tool-executor.js +3 -1
  108. package/dist/modules/ai_assistant/lib/tool-executor.js.map +2 -2
  109. package/dist/modules/ai_assistant/lib/tool-loader.js +18 -25
  110. package/dist/modules/ai_assistant/lib/tool-loader.js.map +2 -2
  111. package/dist/modules/ai_assistant/lib/tool-registry.js +3 -1
  112. package/dist/modules/ai_assistant/lib/tool-registry.js.map +2 -2
  113. package/dist/modules/ai_assistant/lib/tool-test-runner.js +3 -1
  114. package/dist/modules/ai_assistant/lib/tool-test-runner.js.map +2 -2
  115. package/dist/modules/ai_assistant/setup.js +4 -8
  116. package/dist/modules/ai_assistant/setup.js.map +2 -2
  117. package/dist/modules/ai_assistant/subscribers/conversation-shared-notify.js +3 -1
  118. package/dist/modules/ai_assistant/subscribers/conversation-shared-notify.js.map +2 -2
  119. package/dist/modules/ai_assistant/workers/ai-pending-action-cleanup.js +7 -19
  120. package/dist/modules/ai_assistant/workers/ai-pending-action-cleanup.js.map +2 -2
  121. package/dist/modules/ai_assistant/workers/ai-token-usage-prune.js +5 -11
  122. package/dist/modules/ai_assistant/workers/ai-token-usage-prune.js.map +2 -2
  123. package/package.json +6 -6
  124. package/src/frontend/hooks/useCommandPalette.ts +17 -16
  125. package/src/modules/ai_assistant/__tests__/events.test.ts +23 -5
  126. package/src/modules/ai_assistant/__tests__/integration/ws-c-attachment-bridge.test.ts +21 -3
  127. package/src/modules/ai_assistant/__tests__/integration/ws-c-policy-and-tools.test.ts +22 -3
  128. package/src/modules/ai_assistant/__tests__/token-usage-recorder.test.ts +26 -5
  129. package/src/modules/ai_assistant/api/ai/actions/[id]/cancel/route.ts +4 -1
  130. package/src/modules/ai_assistant/api/ai/actions/[id]/confirm/route.ts +4 -1
  131. package/src/modules/ai_assistant/api/ai/actions/[id]/route.ts +4 -1
  132. package/src/modules/ai_assistant/api/ai/agents/[agentId]/loop-override/route.ts +6 -3
  133. package/src/modules/ai_assistant/api/ai/agents/[agentId]/models/route.ts +5 -2
  134. package/src/modules/ai_assistant/api/ai/agents/[agentId]/mutation-policy/route.ts +6 -3
  135. package/src/modules/ai_assistant/api/ai/agents/[agentId]/prompt-override/route.ts +5 -2
  136. package/src/modules/ai_assistant/api/ai/agents/route.ts +4 -1
  137. package/src/modules/ai_assistant/api/ai/chat/route.ts +7 -7
  138. package/src/modules/ai_assistant/api/ai/conversations/[conversationId]/route.ts +6 -3
  139. package/src/modules/ai_assistant/api/ai/conversations/import/route.ts +4 -1
  140. package/src/modules/ai_assistant/api/ai/conversations/route.ts +5 -2
  141. package/src/modules/ai_assistant/api/ai/run-object/route.ts +4 -1
  142. package/src/modules/ai_assistant/api/chat/route.ts +24 -15
  143. package/src/modules/ai_assistant/api/health/route.ts +4 -1
  144. package/src/modules/ai_assistant/api/mcp-key/route.ts +4 -1
  145. package/src/modules/ai_assistant/api/route/route.ts +12 -9
  146. package/src/modules/ai_assistant/api/session-key/route.ts +4 -1
  147. package/src/modules/ai_assistant/api/settings/allowlist/route.ts +5 -2
  148. package/src/modules/ai_assistant/api/settings/route.ts +7 -4
  149. package/src/modules/ai_assistant/api/tools/execute/route.ts +4 -1
  150. package/src/modules/ai_assistant/api/tools/route.ts +4 -1
  151. package/src/modules/ai_assistant/api/usage/daily/route.ts +4 -1
  152. package/src/modules/ai_assistant/api/usage/sessions/[sessionId]/route.ts +4 -1
  153. package/src/modules/ai_assistant/api/usage/sessions/route.ts +4 -1
  154. package/src/modules/ai_assistant/cli.ts +5 -0
  155. package/src/modules/ai_assistant/lib/__tests__/agent-policy.mutation-override.test.ts +20 -2
  156. package/src/modules/ai_assistant/lib/__tests__/agent-registry.test.ts +25 -5
  157. package/src/modules/ai_assistant/lib/__tests__/agent-runtime-loop-phase0.test.ts +21 -2
  158. package/src/modules/ai_assistant/lib/__tests__/agent-runtime-parity.test.ts +23 -3
  159. package/src/modules/ai_assistant/lib/__tests__/agent-runtime-phase4a.test.ts +20 -2
  160. package/src/modules/ai_assistant/lib/__tests__/agent-tools.test.ts +22 -3
  161. package/src/modules/ai_assistant/lib/__tests__/ai-overrides.test.ts +23 -3
  162. package/src/modules/ai_assistant/lib/__tests__/attachment-parts.test.ts +25 -7
  163. package/src/modules/ai_assistant/lib/__tests__/model-factory.test.ts +25 -5
  164. package/src/modules/ai_assistant/lib/__tests__/pending-action-cancel.test.ts +19 -1
  165. package/src/modules/ai_assistant/lib/__tests__/prepare-mutation.test.ts +22 -3
  166. package/src/modules/ai_assistant/lib/agent-policy.ts +8 -5
  167. package/src/modules/ai_assistant/lib/agent-registry.ts +12 -15
  168. package/src/modules/ai_assistant/lib/agent-runtime.ts +23 -46
  169. package/src/modules/ai_assistant/lib/agent-tools.ts +7 -11
  170. package/src/modules/ai_assistant/lib/ai-overrides.ts +6 -9
  171. package/src/modules/ai_assistant/lib/api-endpoint-index.ts +23 -22
  172. package/src/modules/ai_assistant/lib/attachment-parts.ts +14 -29
  173. package/src/modules/ai_assistant/lib/auth.ts +4 -1
  174. package/src/modules/ai_assistant/lib/codemode-tools.ts +17 -17
  175. package/src/modules/ai_assistant/lib/entity-index.ts +8 -5
  176. package/src/modules/ai_assistant/lib/generated-registry-loader.ts +4 -4
  177. package/src/modules/ai_assistant/lib/http-server.ts +46 -48
  178. package/src/modules/ai_assistant/lib/llm-bootstrap.ts +7 -13
  179. package/src/modules/ai_assistant/lib/mcp-client.ts +4 -1
  180. package/src/modules/ai_assistant/lib/mcp-dev-key-resolution.ts +4 -1
  181. package/src/modules/ai_assistant/lib/mcp-dev-server.ts +4 -1
  182. package/src/modules/ai_assistant/lib/mcp-server.ts +27 -19
  183. package/src/modules/ai_assistant/lib/mcp-tool-adapter.ts +4 -1
  184. package/src/modules/ai_assistant/lib/model-factory.ts +6 -3
  185. package/src/modules/ai_assistant/lib/opencode-client.ts +6 -3
  186. package/src/modules/ai_assistant/lib/opencode-handlers.ts +32 -12
  187. package/src/modules/ai_assistant/lib/pending-action-cancel.ts +4 -1
  188. package/src/modules/ai_assistant/lib/pending-action-executor.ts +4 -1
  189. package/src/modules/ai_assistant/lib/prepare-mutation.ts +5 -6
  190. package/src/modules/ai_assistant/lib/schema-utils.ts +4 -1
  191. package/src/modules/ai_assistant/lib/token-usage-recorder.ts +5 -8
  192. package/src/modules/ai_assistant/lib/tool-executor.ts +4 -1
  193. package/src/modules/ai_assistant/lib/tool-loader.ts +19 -25
  194. package/src/modules/ai_assistant/lib/tool-registry.ts +4 -1
  195. package/src/modules/ai_assistant/lib/tool-test-runner.ts +4 -1
  196. package/src/modules/ai_assistant/setup.ts +5 -8
  197. package/src/modules/ai_assistant/subscribers/conversation-shared-notify.ts +4 -1
  198. package/src/modules/ai_assistant/workers/ai-pending-action-cleanup.ts +8 -19
  199. package/src/modules/ai_assistant/workers/ai-token-usage-prune.ts +6 -11
@@ -1,5 +1,6 @@
1
1
  'use client'
2
2
 
3
+ import { createLogger } from '@open-mercato/shared/lib/logger'
3
4
  import { useState, useCallback, useEffect, useMemo, useRef } from 'react'
4
5
  import type {
5
6
  AgentStatus,
@@ -28,6 +29,8 @@ import { useRecentActions } from './useRecentActions'
28
29
  import { useRecentTools } from './useRecentTools'
29
30
  import { useAiAssistantVisibility } from './useAiAssistantVisibility'
30
31
 
32
+ const logger = createLogger('ai_assistant').child({ component: 'command-palette' })
33
+
31
34
  interface UseCommandPaletteOptions {
32
35
  pageContext: PageContext | null
33
36
  selectedEntities?: SelectedEntity[]
@@ -198,11 +201,11 @@ export function useCommandPalette(options: UseCommandPaletteOptions) {
198
201
  if (state.isOpen && tools.length > 0) {
199
202
  // Fetch auth context if not already loaded
200
203
  if (!initialContext) {
201
- console.log('[CommandPalette] Fetching initial context via context_whoami...')
204
+ logger.debug('Fetching initial context via context_whoami')
202
205
  executeToolApi('context_whoami', {})
203
206
  .then((result) => {
204
207
  if (result.success && result.result) {
205
- console.log('[CommandPalette] Got initial context:', result.result)
208
+ logger.debug('Got initial context')
206
209
  const ctx = result.result as {
207
210
  tenantId: string | null
208
211
  organizationId: string | null
@@ -214,25 +217,25 @@ export function useCommandPalette(options: UseCommandPaletteOptions) {
214
217
  }
215
218
  })
216
219
  .catch((err) => {
217
- console.error('[CommandPalette] Failed to fetch initial context:', err)
220
+ logger.error('Failed to fetch initial context', { err })
218
221
  })
219
222
  }
220
223
 
221
224
  // Fetch available entity types if not already loaded
222
225
  if (!availableEntities) {
223
- console.log('[CommandPalette] Fetching available entities via search_schema...')
226
+ logger.debug('Fetching available entities via search_schema')
224
227
  executeToolApi('search_schema', {})
225
228
  .then((result) => {
226
229
  if (result.success && result.result) {
227
230
  const schemaResult = result.result as { entities?: Array<{ entityId: string; enabled: boolean }> }
228
- console.log('[CommandPalette] Got entity schema:', schemaResult.entities?.length, 'entities')
231
+ logger.debug('Got entity schema', { entities: schemaResult.entities?.length })
229
232
  if (schemaResult.entities) {
230
233
  setAvailableEntities(schemaResult.entities.filter(e => e.enabled))
231
234
  }
232
235
  }
233
236
  })
234
237
  .catch((err) => {
235
- console.error('[CommandPalette] Failed to fetch entity schema:', err)
238
+ logger.error('Failed to fetch entity schema', { err })
236
239
  })
237
240
  }
238
241
  }
@@ -568,7 +571,7 @@ export function useCommandPalette(options: UseCommandPaletteOptions) {
568
571
 
569
572
  if (!response.ok) {
570
573
  const errorText = await response.text()
571
- console.error('[startAgenticChat] Error response body:', errorText)
574
+ logger.error('Chat request returned error response', { status: response.status })
572
575
  throw new Error(`Chat request failed: ${response.status} - ${errorText}`)
573
576
  }
574
577
 
@@ -602,7 +605,6 @@ export function useCommandPalette(options: UseCommandPaletteOptions) {
602
605
  try {
603
606
  const event = JSON.parse(data)
604
607
 
605
-
606
608
  // Track all events for debug panel (except question - handled separately with enriched data)
607
609
  if (event.type !== 'question') {
608
610
  addDebugEvent(event.type as DebugEventType, event)
@@ -676,7 +678,7 @@ export function useCommandPalette(options: UseCommandPaletteOptions) {
676
678
  setAgentStatus({ type: 'thinking' })
677
679
  }
678
680
  } else if (event.type === 'error') {
679
- console.error('[startAgenticChat] Error event:', event.error)
681
+ logger.error('Chat stream error event', { err: event.error })
680
682
  setAgentStatus({ type: 'idle' })
681
683
  } else if (event.type === 'done') {
682
684
  setIsThinking(false)
@@ -717,7 +719,7 @@ export function useCommandPalette(options: UseCommandPaletteOptions) {
717
719
  setIsSessionAuthorized(true)
718
720
  }
719
721
  } catch (parseError) {
720
- console.warn('[startAgenticChat] Failed to parse event:', data, parseError)
722
+ logger.warn('Failed to parse chat stream event', { err: parseError })
721
723
  }
722
724
  }
723
725
  }
@@ -730,7 +732,7 @@ export function useCommandPalette(options: UseCommandPaletteOptions) {
730
732
  if (error instanceof Error && error.name === 'AbortError') {
731
733
  return
732
734
  }
733
- console.error('[startAgenticChat] Error:', error)
735
+ logger.error('Agentic chat failed', { err: error })
734
736
  setAgentStatus({ type: 'idle' })
735
737
  setMessages((prev) => [
736
738
  ...prev,
@@ -824,7 +826,7 @@ export function useCommandPalette(options: UseCommandPaletteOptions) {
824
826
 
825
827
  setMessages((prev) => prev.map((m) => (m.id === 'streaming' ? { ...m, id: generateId() } : m)))
826
828
  } catch (error) {
827
- console.error('General chat error:', error)
829
+ logger.error('General chat failed', { err: error })
828
830
  setMessages((prev) => [
829
831
  ...prev,
830
832
  {
@@ -1029,7 +1031,6 @@ export function useCommandPalette(options: UseCommandPaletteOptions) {
1029
1031
  try {
1030
1032
  const event = JSON.parse(data)
1031
1033
 
1032
-
1033
1034
  // Track all events for debug panel (except question - handled separately with enriched data)
1034
1035
  if (event.type !== 'question') {
1035
1036
  addDebugEvent(event.type as DebugEventType, event)
@@ -1207,7 +1208,7 @@ export function useCommandPalette(options: UseCommandPaletteOptions) {
1207
1208
  if (error instanceof Error && error.name === 'AbortError') {
1208
1209
  return
1209
1210
  }
1210
- console.error('Tool chat error:', error)
1211
+ logger.error('Tool chat failed', { err: error })
1211
1212
  setAgentStatus({ type: 'idle' })
1212
1213
  setMessages((prev) => [
1213
1214
  ...prev,
@@ -1296,7 +1297,7 @@ export function useCommandPalette(options: UseCommandPaletteOptions) {
1296
1297
  // Answer sent successfully - the original stream will handle the response
1297
1298
  // Note: isThinking stays true until the original stream sends 'done' or more 'text'
1298
1299
  } catch (error) {
1299
- console.error('[answerQuestion] Error:', error)
1300
+ logger.error('Answer question failed', { err: error })
1300
1301
  setIsThinking(false)
1301
1302
  setAgentStatus({ type: 'idle' })
1302
1303
  setMessages((prev) => [
@@ -1388,7 +1389,7 @@ export function useCommandPalette(options: UseCommandPaletteOptions) {
1388
1389
  // Finalize the assistant message
1389
1390
  setMessages((prev) => prev.map((m) => (m.id === 'streaming' ? { ...m, id: generateId() } : m)))
1390
1391
  } catch (error) {
1391
- console.error('Chat error:', error)
1392
+ logger.error('Chat failed', { err: error })
1392
1393
  // Add error message
1393
1394
  setMessages((prev) => [
1394
1395
  ...prev,
@@ -20,6 +20,23 @@ import {
20
20
  } from '../events'
21
21
  import { setGlobalEventBus } from '@open-mercato/shared/modules/events'
22
22
 
23
+ jest.mock('@open-mercato/shared/lib/logger', () => {
24
+ const mocked = {
25
+ debug: jest.fn(),
26
+ info: jest.fn(),
27
+ warn: jest.fn(),
28
+ error: jest.fn(),
29
+ child: jest.fn(),
30
+ }
31
+ mocked.child.mockImplementation(() => mocked)
32
+ return { createLogger: jest.fn(() => mocked) }
33
+ })
34
+
35
+ const testLogger = jest
36
+ .requireMock('@open-mercato/shared/lib/logger')
37
+ .createLogger('test') as Record<'debug' | 'info' | 'warn' | 'error', jest.Mock>
38
+
39
+
23
40
  const FROZEN_EVENT_IDS: ReadonlyArray<AiAssistantEventId> = [
24
41
  'ai.action.confirmed',
25
42
  'ai.action.cancelled',
@@ -46,12 +63,13 @@ describe('ai_assistant events module', () => {
46
63
 
47
64
  describe('emitAiAssistantEvent', () => {
48
65
  const emitSpy = jest.fn().mockResolvedValue(undefined)
49
- let consoleErrorSpy: jest.SpyInstance
66
+ let consoleErrorSpy: jest.Mock
50
67
 
51
68
  beforeEach(() => {
52
69
  emitSpy.mockClear()
53
70
  setGlobalEventBus({ emit: (id, payload, opts) => emitSpy(id, payload, opts) })
54
- consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
71
+ consoleErrorSpy = testLogger.error
72
+ consoleErrorSpy.mockClear()
55
73
  })
56
74
 
57
75
  afterEach(() => {
@@ -138,9 +156,9 @@ describe('ai_assistant events module', () => {
138
156
  { pendingActionId: 'pa_1' },
139
157
  )
140
158
  expect(consoleErrorSpy).toHaveBeenCalledTimes(1)
141
- const [message] = consoleErrorSpy.mock.calls[0]
142
- expect(message).toContain('ai_assistant')
143
- expect(message).toContain('ai.action.nope')
159
+ const [message, fields] = consoleErrorSpy.mock.calls[0]
160
+ expect(message).toContain('undeclared event')
161
+ expect(fields).toMatchObject({ moduleId: 'ai_assistant', eventId: 'ai.action.nope' })
144
162
  })
145
163
  })
146
164
  })
@@ -55,6 +55,23 @@ jest.mock('fs', () => {
55
55
 
56
56
  import { resolveAttachmentParts } from '../../lib/attachment-parts'
57
57
 
58
+ jest.mock('@open-mercato/shared/lib/logger', () => {
59
+ const mocked = {
60
+ debug: jest.fn(),
61
+ info: jest.fn(),
62
+ warn: jest.fn(),
63
+ error: jest.fn(),
64
+ child: jest.fn(),
65
+ }
66
+ mocked.child.mockImplementation(() => mocked)
67
+ return { createLogger: jest.fn(() => mocked) }
68
+ })
69
+
70
+ const testLogger = jest
71
+ .requireMock('@open-mercato/shared/lib/logger')
72
+ .createLogger('test') as Record<'debug' | 'info' | 'warn' | 'error', jest.Mock>
73
+
74
+
58
75
  type AttachmentRowOverrides = {
59
76
  id?: string
60
77
  fileName?: string
@@ -116,11 +133,12 @@ function makeAuth(overrides: Partial<AiChatRequestContext> = {}): AiChatRequestC
116
133
  }
117
134
 
118
135
  describe('WS-C integration — attachment bridge', () => {
119
- let warnSpy: jest.SpyInstance
136
+ let warnSpy: jest.Mock
120
137
 
121
138
  beforeEach(() => {
122
139
  jest.clearAllMocks()
123
- warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {})
140
+ warnSpy = testLogger.warn
141
+ warnSpy.mockClear()
124
142
  })
125
143
 
126
144
  afterEach(() => {
@@ -165,7 +183,7 @@ describe('WS-C integration — attachment bridge', () => {
165
183
  expect(ids).not.toContain('not-found')
166
184
 
167
185
  // The warn for the foreign attachment MUST NOT reveal tenant-b or org-b.
168
- const warnCalls = warnSpy.mock.calls.map((call) => call.join(' '))
186
+ const warnCalls = warnSpy.mock.calls.map((call) => call.map((arg: unknown) => (typeof arg === 'string' ? arg : JSON.stringify(arg))).join(' '))
169
187
  const foreignWarn = warnCalls.find((message) => message.includes('foreign-attachment'))
170
188
  expect(foreignWarn).toBeDefined()
171
189
  expect(foreignWarn).not.toMatch(/tenant-b/)
@@ -60,6 +60,23 @@ import { resolveAiAgentTools, AgentPolicyError } from '../../lib/agent-tools'
60
60
  import { checkAgentPolicy } from '../../lib/agent-policy'
61
61
  import { runAiAgentText } from '../../lib/agent-runtime'
62
62
 
63
+ jest.mock('@open-mercato/shared/lib/logger', () => {
64
+ const mocked = {
65
+ debug: jest.fn(),
66
+ info: jest.fn(),
67
+ warn: jest.fn(),
68
+ error: jest.fn(),
69
+ child: jest.fn(),
70
+ }
71
+ mocked.child.mockImplementation(() => mocked)
72
+ return { createLogger: jest.fn(() => mocked) }
73
+ })
74
+
75
+ const testLogger = jest
76
+ .requireMock('@open-mercato/shared/lib/logger')
77
+ .createLogger('test') as Record<'debug' | 'info' | 'warn' | 'error', jest.Mock>
78
+
79
+
63
80
  function makeAgent(
64
81
  overrides: Partial<AiAgentDefinition> & Pick<AiAgentDefinition, 'id' | 'moduleId'>,
65
82
  ): AiAgentDefinition {
@@ -114,13 +131,14 @@ function fakeStreamTextResult() {
114
131
  }
115
132
 
116
133
  describe('WS-C integration — agent policy gate + tool resolution', () => {
117
- let warnSpy: jest.SpyInstance
134
+ let warnSpy: jest.Mock
118
135
 
119
136
  beforeEach(() => {
120
137
  jest.clearAllMocks()
121
138
  resetAgentRegistryForTests()
122
139
  toolRegistry.clear()
123
- warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {})
140
+ warnSpy = testLogger.warn
141
+ warnSpy.mockClear()
124
142
  streamTextMock.mockImplementation(() => fakeStreamTextResult())
125
143
  })
126
144
 
@@ -245,7 +263,8 @@ describe('WS-C integration — agent policy gate + tool resolution', () => {
245
263
  })
246
264
  expect(Object.keys(resolved.tools)).toEqual(['catalog__list_products'])
247
265
  expect(warnSpy).toHaveBeenCalledWith(
248
- expect.stringContaining('catalog.get_product'),
266
+ expect.any(String),
267
+ expect.objectContaining({ toolName: 'catalog.get_product' }),
249
268
  )
250
269
  })
251
270
 
@@ -10,6 +10,23 @@
10
10
  import { recordTokenUsage, type RecordTokenUsageInput } from '../lib/token-usage-recorder'
11
11
  import type { AwilixContainer } from 'awilix'
12
12
 
13
+ jest.mock('@open-mercato/shared/lib/logger', () => {
14
+ const mocked = {
15
+ debug: jest.fn(),
16
+ info: jest.fn(),
17
+ warn: jest.fn(),
18
+ error: jest.fn(),
19
+ child: jest.fn(),
20
+ }
21
+ mocked.child.mockImplementation(() => mocked)
22
+ return { createLogger: jest.fn(() => mocked) }
23
+ })
24
+
25
+ const testLogger = jest
26
+ .requireMock('@open-mercato/shared/lib/logger')
27
+ .createLogger('test') as Record<'debug' | 'info' | 'warn' | 'error', jest.Mock>
28
+
29
+
13
30
  function makeInput(overrides: Partial<RecordTokenUsageInput> = {}): RecordTokenUsageInput {
14
31
  return {
15
32
  authContext: {
@@ -71,7 +88,8 @@ describe('recordTokenUsage — R12 compliance', () => {
71
88
  })
72
89
 
73
90
  it('never throws when createEvent throws', async () => {
74
- const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {})
91
+ const warnSpy = testLogger.warn
92
+ warnSpy.mockClear()
75
93
  const input = makeInput()
76
94
  const container = makeContainer({ createEventThrows: true })
77
95
  await expect(recordTokenUsage(input, container)).resolves.toBeUndefined()
@@ -79,7 +97,8 @@ describe('recordTokenUsage — R12 compliance', () => {
79
97
  })
80
98
 
81
99
  it('never throws when upsertDaily throws', async () => {
82
- const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {})
100
+ const warnSpy = testLogger.warn
101
+ warnSpy.mockClear()
83
102
  const input = makeInput()
84
103
  const container = makeContainer({ upsertDailyThrows: true })
85
104
  await expect(recordTokenUsage(input, container)).resolves.toBeUndefined()
@@ -87,19 +106,21 @@ describe('recordTokenUsage — R12 compliance', () => {
87
106
  })
88
107
 
89
108
  it('logs a warn when DB write fails', async () => {
90
- const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {})
109
+ const warnSpy = testLogger.warn
110
+ warnSpy.mockClear()
91
111
  const input = makeInput()
92
112
  const container = makeContainer({ createEventThrows: true })
93
113
  await recordTokenUsage(input, container)
94
114
  expect(warnSpy).toHaveBeenCalledWith(
95
- expect.stringContaining('[AI token-usage]'),
115
+ expect.stringContaining('recordTokenUsage failed'),
96
116
  expect.anything(),
97
117
  )
98
118
  warnSpy.mockRestore()
99
119
  })
100
120
 
101
121
  it('returns immediately without writing when tenantId is falsy', async () => {
102
- const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {})
122
+ const warnSpy = testLogger.warn
123
+ warnSpy.mockClear()
103
124
  const input = makeInput({ authContext: { tenantId: null, organizationId: null, userId: 'user-1' } })
104
125
  const container = makeContainer({})
105
126
  await expect(recordTokenUsage(input, container)).resolves.toBeUndefined()
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { NextResponse, type NextRequest } from 'next/server'
2
3
  import { z } from 'zod'
3
4
  import type { EntityManager } from '@mikro-orm/postgresql'
@@ -11,6 +12,8 @@ import { serializePendingActionForClient } from '../../../../../lib/pending-acti
11
12
  import { checkStatusAndExpiry } from '../../../../../lib/pending-action-recheck'
12
13
  import { executePendingActionCancel } from '../../../../../lib/pending-action-cancel'
13
14
 
15
+ const logger = createLogger('ai_assistant')
16
+
14
17
  /**
15
18
  * POST `/api/ai/actions/:id/cancel` — mutation approval gate cancel
16
19
  * endpoint (spec §9.4, Step 5.9).
@@ -227,7 +230,7 @@ export async function POST(req: NextRequest, context: RouteContext): Promise<Res
227
230
  pendingAction: serializePendingActionForClient(cancelResult.row),
228
231
  })
229
232
  } catch (error) {
230
- console.error('[AI Pending Action CANCEL] Failure:', error)
233
+ logger.error('AI Pending Action CANCEL — Failure', { err: error })
231
234
  return jsonError(
232
235
  500,
233
236
  error instanceof Error ? error.message : 'Failed to cancel pending action.',
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { NextResponse, type NextRequest } from 'next/server'
2
3
  import { z } from 'zod'
3
4
  import type { EntityManager } from '@mikro-orm/postgresql'
@@ -24,6 +25,8 @@ import { AiAgentMutationPolicyOverrideRepository } from '../../../../../data/rep
24
25
  import type { AiAgentMutationPolicy } from '../../../../../lib/ai-agent-definition'
25
26
  import { isKnownMutationPolicy } from '../../../../../lib/agent-policy'
26
27
 
28
+ const logger = createLogger('ai_assistant')
29
+
27
30
  /**
28
31
  * POST `/api/ai/actions/:id/confirm` — mutation approval gate confirm
29
32
  * endpoint (spec §9.4, Step 5.8).
@@ -219,7 +222,7 @@ export async function POST(req: NextRequest, context: RouteContext): Promise<Res
219
222
  mutationResult: executed.executionResult,
220
223
  })
221
224
  } catch (error) {
222
- console.error('[AI Pending Action CONFIRM] Failure:', error)
225
+ logger.error('AI Pending Action CONFIRM — Failure', { err: error })
223
226
  return jsonError(
224
227
  500,
225
228
  error instanceof Error ? error.message : 'Failed to confirm pending action.',
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { NextResponse, type NextRequest } from 'next/server'
2
3
  import { z } from 'zod'
3
4
  import type { EntityManager } from '@mikro-orm/postgresql'
@@ -9,6 +10,8 @@ import { AiPendingActionRepository } from '../../../../data/repositories/AiPendi
9
10
  import { hasRequiredFeatures } from '../../../../lib/auth'
10
11
  import { serializePendingActionForClient } from '../../../../lib/pending-action-client'
11
12
 
13
+ const logger = createLogger('ai_assistant')
14
+
12
15
  /**
13
16
  * GET `/api/ai/actions/:id` — reconnect/polling endpoint for the Phase 3 WS-C
14
17
  * mutation approval gate (spec §9, Step 5.7).
@@ -132,7 +135,7 @@ export async function GET(req: NextRequest, context: RouteContext): Promise<Resp
132
135
 
133
136
  return NextResponse.json(serializePendingActionForClient(row))
134
137
  } catch (error) {
135
- console.error('[AI Pending Action GET] Failure:', error)
138
+ logger.error('AI Pending Action GET — Failure', { err: error })
136
139
  return jsonError(
137
140
  500,
138
141
  error instanceof Error ? error.message : 'Failed to load pending action.',
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { NextResponse, type NextRequest } from 'next/server'
2
3
  import { z } from 'zod'
3
4
  import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
@@ -13,6 +14,8 @@ import {
13
14
  } from '../../../../../data/repositories/AiAgentRuntimeOverrideRepository'
14
15
  import type { AiAgentRuntimeOverride } from '../../../../../data/entities'
15
16
 
17
+ const logger = createLogger('ai_assistant')
18
+
16
19
  const agentIdPattern = /^[a-z0-9_]+\.[a-z0-9_]+$/
17
20
 
18
21
  const agentIdParamSchema = z.object({
@@ -233,7 +236,7 @@ export async function GET(req: NextRequest, context: RouteContext): Promise<Resp
233
236
  override: hasLoopData ? serializeLoopOverride(row!) : null,
234
237
  })
235
238
  } catch (error) {
236
- console.error('[AI Loop Override GET] Failure:', error)
239
+ logger.error('AI Loop Override GET — Failure', { err: error })
237
240
  return jsonError(
238
241
  500,
239
242
  error instanceof Error ? error.message : 'Failed to load loop override.',
@@ -313,7 +316,7 @@ export async function PUT(req: NextRequest, context: RouteContext): Promise<Resp
313
316
  if (error instanceof AiAgentRuntimeOverrideValidationError) {
314
317
  return jsonError(400, error.message, error.code)
315
318
  }
316
- console.error('[AI Loop Override PUT] Failure:', error)
319
+ logger.error('AI Loop Override PUT — Failure', { err: error })
317
320
  return jsonError(
318
321
  500,
319
322
  error instanceof Error ? error.message : 'Failed to save loop override.',
@@ -378,7 +381,7 @@ export async function DELETE(req: NextRequest, context: RouteContext): Promise<R
378
381
 
379
382
  return NextResponse.json({ ok: true, agentId: agent.id, cleared: true })
380
383
  } catch (error) {
381
- console.error('[AI Loop Override DELETE] Failure:', error)
384
+ logger.error('AI Loop Override DELETE — Failure', { err: error })
382
385
  return jsonError(
383
386
  500,
384
387
  error instanceof Error ? error.message : 'Failed to clear loop override.',
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { NextResponse, type NextRequest } from 'next/server'
2
3
  import { z } from 'zod'
3
4
  import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
@@ -21,6 +22,8 @@ import {
21
22
  import { AiTenantModelAllowlistRepository } from '../../../../../data/repositories/AiTenantModelAllowlistRepository'
22
23
  import { AiAgentRuntimeOverrideRepository } from '../../../../../data/repositories/AiAgentRuntimeOverrideRepository'
23
24
 
25
+ const logger = createLogger('ai_assistant')
26
+
24
27
  function modelsForPicker(
25
28
  provider: ReturnType<typeof llmProviderRegistry.list>[number],
26
29
  allowedModelIds: string[] | undefined,
@@ -170,7 +173,7 @@ export async function GET(
170
173
  // Picker still renders against env-only so the UI does not break, but log at
171
174
  // error level so an outage is operationally visible. The chat dispatcher
172
175
  // refuses to dispatch when this lookup fails, so writes stay safe.
173
- console.error('[AI Agents Models] Failed to load tenant allowlist:', snapshotError)
176
+ logger.error('AI Agents Models — Failed to load tenant allowlist', { err: snapshotError })
174
177
  }
175
178
  }
176
179
 
@@ -246,7 +249,7 @@ export async function GET(
246
249
  providers,
247
250
  })
248
251
  } catch (error) {
249
- console.error('[AI Agents Models] GET error:', error)
252
+ logger.error('AI Agents Models — GET error', { err: error })
250
253
  return NextResponse.json({ error: 'Failed to resolve agent models.' }, { status: 500 })
251
254
  }
252
255
  }
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { NextResponse, type NextRequest } from 'next/server'
2
3
  import { z } from 'zod'
3
4
  import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
@@ -18,6 +19,8 @@ import type {
18
19
  AiAgentMutationPolicy,
19
20
  } from '../../../../../lib/ai-agent-definition'
20
21
 
22
+ const logger = createLogger('ai_assistant')
23
+
21
24
  const agentIdPattern = /^[a-z0-9_]+\.[a-z0-9_]+$/
22
25
 
23
26
  const agentIdParamSchema = z.object({
@@ -232,7 +235,7 @@ export async function GET(req: NextRequest, context: RouteContext): Promise<Resp
232
235
  override: current ? serializeOverride(current) : null,
233
236
  })
234
237
  } catch (error) {
235
- console.error('[AI Mutation Policy GET] Failure:', error)
238
+ logger.error('AI Mutation Policy GET — Failure', { err: error })
236
239
  return jsonError(
237
240
  500,
238
241
  error instanceof Error ? error.message : 'Failed to load mutationPolicy override.',
@@ -316,7 +319,7 @@ export async function POST(req: NextRequest, context: RouteContext): Promise<Res
316
319
  override: serializeOverride(saved),
317
320
  })
318
321
  } catch (error) {
319
- console.error('[AI Mutation Policy POST] Failure:', error)
322
+ logger.error('AI Mutation Policy POST — Failure', { err: error })
320
323
  return jsonError(
321
324
  500,
322
325
  error instanceof Error ? error.message : 'Failed to save mutationPolicy override.',
@@ -370,7 +373,7 @@ export async function DELETE(req: NextRequest, context: RouteContext): Promise<R
370
373
  cleared,
371
374
  })
372
375
  } catch (error) {
373
- console.error('[AI Mutation Policy DELETE] Failure:', error)
376
+ logger.error('AI Mutation Policy DELETE — Failure', { err: error })
374
377
  return jsonError(
375
378
  500,
376
379
  error instanceof Error ? error.message : 'Failed to clear mutationPolicy override.',
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { NextResponse, type NextRequest } from 'next/server'
2
3
  import { z } from 'zod'
3
4
  import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
@@ -11,6 +12,8 @@ import { AiAgentPromptOverrideRepository } from '../../../../../data/repositorie
11
12
  import type { AiAgentPromptOverride } from '../../../../../data/entities'
12
13
  import { findReservedKeys } from '../../../../../lib/prompt-override-merge'
13
14
 
15
+ const logger = createLogger('ai_assistant')
16
+
14
17
  const agentIdPattern = /^[a-z0-9_]+\.[a-z0-9_]+$/
15
18
 
16
19
  const agentIdParamSchema = z.object({
@@ -214,7 +217,7 @@ export async function GET(req: NextRequest, context: RouteContext): Promise<Resp
214
217
  versions: versions.map(serializeOverride),
215
218
  })
216
219
  } catch (error) {
217
- console.error('[AI Prompt Override GET] Failure:', error)
220
+ logger.error('AI Prompt Override GET — Failure', { err: error })
218
221
  return jsonError(
219
222
  500,
220
223
  error instanceof Error ? error.message : 'Failed to load prompt override.',
@@ -297,7 +300,7 @@ export async function POST(req: NextRequest, context: RouteContext): Promise<Res
297
300
  updatedAt: saved.updatedAt?.toISOString?.() ?? new Date().toISOString(),
298
301
  })
299
302
  } catch (error) {
300
- console.error('[AI Prompt Override POST] Failure:', error)
303
+ logger.error('AI Prompt Override POST — Failure', { err: error })
301
304
  return jsonError(
302
305
  500,
303
306
  error instanceof Error ? error.message : 'Failed to save prompt override.',
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { NextResponse, type NextRequest } from 'next/server'
2
3
  import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
3
4
  import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
@@ -9,6 +10,8 @@ import { hasRequiredFeatures } from '../../../lib/auth'
9
10
  import { toolRegistry } from '../../../lib/tool-registry'
10
11
  import type { AiToolDefinition } from '../../../lib/types'
11
12
 
13
+ const logger = createLogger('ai_assistant')
14
+
12
15
  export const openApi: OpenApiRouteDoc = {
13
16
  tag: 'AI Assistant',
14
17
  summary: 'List AI agents the caller can invoke',
@@ -103,7 +106,7 @@ export async function GET(req: NextRequest) {
103
106
 
104
107
  return NextResponse.json({ agents, total: agents.length, aiConfigured })
105
108
  } catch (error) {
106
- console.error('[AI Agents] Failed to list agents:', error)
109
+ logger.error('AI Agents — Failed to list agents', { err: error })
107
110
  return NextResponse.json(
108
111
  { error: 'Failed to list agents', code: 'internal_error' },
109
112
  { status: 500 },
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { NextResponse, type NextRequest } from 'next/server'
2
3
  import type { UIMessage } from 'ai'
3
4
  import { z } from 'zod'
@@ -32,6 +33,8 @@ import { createConversationStorage } from '../../../lib/conversation-storage'
32
33
  import { checkAiChatRateLimit } from '../../../lib/rate-limit'
33
34
  import type { EntityManager } from '@mikro-orm/postgresql'
34
35
 
36
+ const logger = createLogger('ai_assistant')
37
+
35
38
  const MAX_MESSAGES = 100
36
39
 
37
40
  const agentIdPattern = /^[a-z0-9_]+\.[a-z0-9_]+$/
@@ -389,7 +392,7 @@ function persistAssistantOnStreamCompletion(input: {
389
392
  )
390
393
  }
391
394
  } catch (error) {
392
- console.error('[AI Chat Agent] Conversation persistence failure:', error)
395
+ logger.error('AI Chat Agent — Conversation persistence failure', { err: error })
393
396
  } finally {
394
397
  reader.releaseLock()
395
398
  await writer.close().catch(() => undefined)
@@ -534,10 +537,7 @@ export async function POST(req: NextRequest): Promise<Response> {
534
537
  // Fail closed: refuse to dispatch if we cannot confirm the tenant allowlist.
535
538
  // Silently falling back to env-only would widen the effective allowlist when
536
539
  // the DB is unavailable, which is the opposite of what an admin intends.
537
- console.error(
538
- '[AI Chat Agent] Tenant allowlist lookup failed; refusing to dispatch:',
539
- snapshotError,
540
- )
540
+ logger.error('Tenant allowlist lookup failed; refusing to dispatch', { err: snapshotError })
541
541
  return jsonError(
542
542
  503,
543
543
  'Tenant allowlist is temporarily unavailable. Try again shortly.',
@@ -663,7 +663,7 @@ export async function POST(req: NextRequest): Promise<Response> {
663
663
  if (error instanceof Error && error.name === 'AiChatConversationOrgNotFoundError') {
664
664
  return jsonError(400, error.message, 'organization_not_found')
665
665
  }
666
- console.error('[AI Chat Agent] Failed to persist user message:', error)
666
+ logger.error('AI Chat Agent — Failed to persist user message', { err: error })
667
667
  }
668
668
 
669
669
  const response = await runAiAgentText({
@@ -700,7 +700,7 @@ export async function POST(req: NextRequest): Promise<Response> {
700
700
  if (error instanceof AgentPolicyError) {
701
701
  return jsonError(statusForDenyCode(error.code), error.message, error.code)
702
702
  }
703
- console.error('[AI Chat Agent] Dispatch failure:', error)
703
+ logger.error('AI Chat Agent — Dispatch failure', { err: error })
704
704
  return jsonError(
705
705
  500,
706
706
  error instanceof Error ? error.message : 'Agent dispatch failed.',