@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,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { randomUUID } from 'node:crypto'
2
3
  import { createContainer } from 'awilix'
3
4
  import type { AwilixContainer } from 'awilix'
@@ -68,6 +69,8 @@ import { TASK_PLAN_RUNTIME_PROMPT_SECTION } from './task-plan-labels'
68
69
  // what `./ai-sdk.ts` consumers already rely on.
69
70
  import './llm-bootstrap'
70
71
 
72
+ const logger = createLogger('ai_assistant').child({ component: 'agent-runtime' })
73
+
71
74
  export interface AgentRequestPageContext {
72
75
  pageId?: string | null
73
76
  entityType?: string | null
@@ -565,11 +568,12 @@ export class BudgetEnforcer {
565
568
  private abort(reason: LoopBudgetAbortReason): void {
566
569
  if (this.abortReason !== null) return
567
570
  this.abortReason = reason
568
- console.info(
569
- `[AI Agents] Budget exceeded — aborting turn. Reason: ${reason}. ` +
570
- `toolCalls=${this.toolCallsUsed}, tokens=${this.tokensUsed}, ` +
571
- `elapsedMs=${Date.now() - this.turnStartMs}.`,
572
- )
571
+ logger.info('Budget exceeded — aborting turn', {
572
+ reason,
573
+ toolCalls: this.toolCallsUsed,
574
+ tokens: this.tokensUsed,
575
+ elapsedMs: Date.now() - this.turnStartMs,
576
+ })
573
577
  this.abortController.abort(reason)
574
578
  }
575
579
 
@@ -587,7 +591,7 @@ export class BudgetEnforcer {
587
591
  try {
588
592
  await userOnStepFinish(event)
589
593
  } catch (err) {
590
- console.error('[AI Agents] User onStepFinish threw; ignoring:', err)
594
+ logger.error('User onStepFinish threw; ignoring', { err })
591
595
  }
592
596
  }
593
597
  }
@@ -677,7 +681,7 @@ export function buildLoopTraceCollector(
677
681
  try {
678
682
  await userOnStepFinish(event)
679
683
  } catch (err) {
680
- console.error('[AI Agents] User onStepFinish in LoopTrace collector threw; ignoring:', err)
684
+ logger.error('User onStepFinish in LoopTrace collector threw; ignoring', { err })
681
685
  }
682
686
  }
683
687
  }
@@ -809,9 +813,7 @@ export function mergeStepOverrides(
809
813
  const normalized = normalizeAllowedToolNameForAgent(name, agent)
810
814
  const allowed = normalized !== null
811
815
  if (!allowed) {
812
- console.warn(
813
- `[AI Agents] loop:active_tools_filtered — tool "${name}" is not in agent "${agent.id}" allowedTools; dropping from activeTools.`,
814
- )
816
+ logger.warn('loop:active_tools_filtered — tool not in agent allowedTools; dropping from activeTools', { toolName: name, agentId: agent.id })
815
817
  }
816
818
  return normalized ? [normalized] : []
817
819
  })
@@ -825,9 +827,7 @@ export function mergeStepOverrides(
825
827
  for (const [toolKey, userHandler] of Object.entries(userTools)) {
826
828
  const wrappedHandler = wrappedToolRegistry[toolKey]
827
829
  if (!wrappedHandler) {
828
- console.warn(
829
- `[AI Agents] mergeStepOverrides — tool "${toolKey}" from user prepareStep is not in the wrapper tool registry; dropping.`,
830
- )
830
+ logger.warn('mergeStepOverrides — tool from user prepareStep is not in the wrapper tool registry; dropping', { toolName: toolKey })
831
831
  continue
832
832
  }
833
833
  if (userHandler !== wrappedHandler) {
@@ -908,9 +908,7 @@ export function buildWrapperPrepareStep(
908
908
  const normalized = normalizeAllowedToolNameForAgent(name, agent)
909
909
  const allowed = normalized !== null
910
910
  if (!allowed) {
911
- console.warn(
912
- `[AI Agents] loop:active_tools_filtered — tool "${name}" is not in agent "${agent.id}" allowedTools; dropping from activeTools.`,
913
- )
911
+ logger.warn('loop:active_tools_filtered — tool not in agent allowedTools; dropping from activeTools', { toolName: name, agentId: agent.id })
914
912
  }
915
913
  return normalized ? [normalized] : []
916
914
  })
@@ -921,10 +919,7 @@ export function buildWrapperPrepareStep(
921
919
  try {
922
920
  userOverride = await effectiveLoop.prepareStep(state)
923
921
  } catch (error) {
924
- console.error(
925
- `[AI Agents] User prepareStep threw for agent "${agent.id}"; ignoring user override:`,
926
- error,
927
- )
922
+ logger.error('User prepareStep threw; ignoring user override', { agentId: agent.id, err: error })
928
923
  return mapPrepareStepResultForModel(wrapperOverride, wrappedTools)
929
924
  }
930
925
  return mapPrepareStepResultForModel(
@@ -1026,10 +1021,7 @@ async function resolveTenantAllowlistSnapshot(
1026
1021
  organizationId: organizationId ?? null,
1027
1022
  })
1028
1023
  } catch (error) {
1029
- console.warn(
1030
- '[AI Agents] Tenant allowlist lookup failed; falling back to env-only enforcement.',
1031
- error,
1032
- )
1024
+ logger.warn('Tenant allowlist lookup failed; falling back to env-only enforcement', { err: error })
1033
1025
  return null
1034
1026
  }
1035
1027
  }
@@ -1062,9 +1054,7 @@ export async function composeSystemPrompt(
1062
1054
  if (typeof entityType !== 'string' || entityType.length === 0) return baseFromOverride
1063
1055
  if (typeof recordId !== 'string' || recordId.length === 0) return baseFromOverride
1064
1056
  if (!container) {
1065
- console.warn(
1066
- `[AI Agents] Agent "${agent.id}" declares resolvePageContext but no container was passed to runAiAgentText; skipping hydration.`,
1067
- )
1057
+ logger.warn('Agent declares resolvePageContext but no container was passed to runAiAgentText; skipping hydration', { agentId: agent.id })
1068
1058
  return baseFromOverride
1069
1059
  }
1070
1060
  const hydrationInput: AiAgentPageContextInput = {
@@ -1080,10 +1070,7 @@ export async function composeSystemPrompt(
1080
1070
  return `${baseFromOverride}\n\n${hydrated}`
1081
1071
  }
1082
1072
  } catch (error) {
1083
- console.error(
1084
- `[AI Agents] resolvePageContext for agent "${agent.id}" failed; continuing without hydration:`,
1085
- error,
1086
- )
1073
+ logger.error('resolvePageContext failed; continuing without hydration', { agentId: agent.id, err: error })
1087
1074
  }
1088
1075
  return baseFromOverride
1089
1076
  }
@@ -1124,10 +1111,7 @@ async function resolveBaseSystemPromptWithOverride(
1124
1111
  }
1125
1112
  return composeSystemPromptWithOverride(base, { sections: latest.sections })
1126
1113
  } catch (error) {
1127
- console.warn(
1128
- `[AI Agents] Prompt-override lookup failed for agent "${agent.id}"; falling back to built-in prompt.`,
1129
- error,
1130
- )
1114
+ logger.warn('Prompt-override lookup failed; falling back to built-in prompt', { agentId: agent.id, err: error })
1131
1115
  return base
1132
1116
  }
1133
1117
  }
@@ -1159,17 +1143,13 @@ async function resolveMutationPolicyOverride(
1159
1143
  if (!row) return null
1160
1144
  const raw = row.mutationPolicy
1161
1145
  if (!isKnownMutationPolicy(raw)) {
1162
- console.warn(
1163
- `[AI Agents] Ignoring corrupt mutationPolicy override row for agent "${agentId}": "${raw}". Falling back to code-declared policy.`,
1164
- )
1146
+ logger.warn('Ignoring corrupt mutationPolicy override row; falling back to code-declared policy', { agentId, policy: raw })
1165
1147
  return null
1166
1148
  }
1167
1149
  return raw
1168
1150
  } catch (error) {
1169
- console.warn(
1170
- `[AI Agents] mutationPolicy override lookup failed for agent "${agentId}"; falling back to code-declared policy.`,
1171
- error,
1172
- )
1151
+ logger.warn('mutationPolicy override lookup failed; falling back to code-declared policy', { agentId, err: error })
1152
+
1173
1153
  return null
1174
1154
  }
1175
1155
  }
@@ -1213,10 +1193,7 @@ async function resolveRuntimeModelOverride(
1213
1193
  baseURL: row.baseUrl ?? null,
1214
1194
  }
1215
1195
  } catch (error) {
1216
- console.warn(
1217
- `[AI Agents] Runtime model override lookup failed for agent "${agentId}"; falling back to lower-priority sources.`,
1218
- error,
1219
- )
1196
+ logger.warn('Runtime model override lookup failed; falling back to lower-priority sources', { agentId, err: error })
1220
1197
  return null
1221
1198
  }
1222
1199
  }
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { dynamicTool, type Tool } from 'ai'
2
3
  import type { AwilixContainer } from 'awilix'
3
4
  import type { ZodType } from 'zod'
@@ -15,6 +16,8 @@ import { toolRegistry } from './tool-registry'
15
16
  import { toSafeZodSchema } from './schema-utils'
16
17
  import { prepareMutation } from './prepare-mutation'
17
18
 
19
+ const logger = createLogger('ai_assistant')
20
+
18
21
  /**
19
22
  * Error thrown by `resolveAiAgentTools` (and downstream `runAiAgentText`) when
20
23
  * the agent-level policy check denies a request. Carries the structured deny
@@ -297,7 +300,7 @@ function adaptToolToAiSdk(
297
300
  /**
298
301
  * Resolves the agent's whitelisted tools into an AI SDK `tools` map, enforcing
299
302
  * the same policy gate as the HTTP dispatcher. Throws {@link AgentPolicyError}
300
- * on agent-level deny; tool-level denies are skipped with a `console.warn`
303
+ * on agent-level deny; tool-level denies are skipped with a logger warning
301
304
  * because the agent author whitelisted a tool the caller is not currently
302
305
  * permitted to execute (deterministic non-failure — the remaining tools still
303
306
  * reach the model).
@@ -338,9 +341,7 @@ export async function resolveAiAgentTools(
338
341
  mutationPolicyOverride,
339
342
  })
340
343
  if (!toolDecision.ok) {
341
- console.warn(
342
- `[AI Agents] Skipping tool "${toolName}" for agent "${agent.id}": ${toolDecision.message}`,
343
- )
344
+ logger.warn('Skipping tool for agent', { toolName, agentId: agent.id, reason: toolDecision.message })
344
345
  continue
345
346
  }
346
347
 
@@ -348,9 +349,7 @@ export async function resolveAiAgentTools(
348
349
  | AiToolDefinition
349
350
  | undefined
350
351
  if (!record) {
351
- console.warn(
352
- `[AI Agents] Tool "${toolName}" vanished from registry between policy checks; skipping.`,
353
- )
352
+ logger.warn('Tool vanished from registry between policy checks; skipping', { toolName })
354
353
  continue
355
354
  }
356
355
 
@@ -389,10 +388,7 @@ export async function resolveAiAgentTools(
389
388
  effectiveMutationPolicy,
390
389
  )
391
390
  } catch (error) {
392
- console.error(
393
- `[AI Agents] Failed to adapt tool "${toolName}" for agent "${agent.id}":`,
394
- error,
395
- )
391
+ logger.error('Failed to adapt tool for agent', { toolName, agentId: agent.id, err: error })
396
392
  }
397
393
  }
398
394
 
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import {
2
3
  registerModuleOverrideApplier,
3
4
  type ModuleOverrideEntry,
@@ -33,6 +34,8 @@ import {
33
34
  import type { AiAgentDefinition, AiAgentExtension } from './ai-agent-definition'
34
35
  import type { AiToolDefinition } from './types'
35
36
 
37
+ const logger = createLogger('ai_assistant')
38
+
36
39
  /** Override for a single agent: replace with a definition or remove with `null`. */
37
40
  export type AiAgentOverride = AiAgentDefinition | null
38
41
 
@@ -319,18 +322,14 @@ export function applyAgentOverrideMap(
319
322
  // — useful for app-level "synthetic" agents without authoring a
320
323
  // module file. Warn at the structured logger so the operator
321
324
  // notices a stale id slipping through.
322
- console.warn(
323
- `[AI Overrides] Override registers a new agent "${id}" — no base entry to replace.`,
324
- )
325
+ logger.warn('Override registers a new agent — no base entry to replace', { agentId: id })
325
326
  }
326
327
  if (value === null) {
327
328
  byId.delete(id)
328
329
  continue
329
330
  }
330
331
  if (!value || typeof value.id !== 'string' || value.id !== id) {
331
- console.warn(
332
- `[AI Overrides] Skipping malformed agent override for id "${id}" — id mismatch or missing fields.`,
333
- )
332
+ logger.warn('Skipping malformed agent override — id mismatch or missing fields', { agentId: id })
334
333
  continue
335
334
  }
336
335
  byId.set(id, value)
@@ -355,9 +354,7 @@ export function applyToolOverrideMap<TTool extends { name: string }>(
355
354
  }
356
355
  if (value === undefined) continue
357
356
  if (!value || typeof (value as TTool).name !== 'string' || (value as TTool).name !== name) {
358
- console.warn(
359
- `[AI Overrides] Skipping malformed tool override for name "${name}" — name mismatch or missing fields.`,
360
- )
357
+ logger.warn('Skipping malformed tool override — name mismatch or missing fields', { toolName: name })
361
358
  continue
362
359
  }
363
360
  out.set(name, value as TTool)
@@ -8,11 +8,14 @@
8
8
  * fan-out have been removed.
9
9
  */
10
10
 
11
+ import { createLogger } from '@open-mercato/shared/lib/logger'
11
12
  import type { OpenApiDocument } from '@open-mercato/shared/lib/openapi'
12
13
  import { buildOpenApiDocument } from '@open-mercato/shared/lib/openapi'
13
14
  import type { Module } from '@open-mercato/shared/modules/registry'
14
15
  import { fetchWithTimeout, resolveTimeoutMs } from '@open-mercato/shared/lib/http/fetchWithTimeout'
15
16
 
17
+ const logger = createLogger('ai_assistant').child({ component: 'api-index' })
18
+
16
19
  const DEFAULT_OPENAPI_FETCH_TIMEOUT_MS = 10_000
17
20
 
18
21
  function resolveOpenapiFetchTimeoutMs(): number {
@@ -128,7 +131,7 @@ export async function loadRichOpenApiSpec(): Promise<OpenApiDocument | null> {
128
131
  if (!doc.paths || Object.keys(doc.paths).length === 0) {
129
132
  return null
130
133
  }
131
- console.error(`[API Index] Rich OpenAPI spec built from ${modulesWithApis.length} modules (Tier 2)`)
134
+ logger.debug('Rich OpenAPI spec built from module registry', { modules: modulesWithApis.length, tier: 2 })
132
135
  rawSpecCache = doc
133
136
  return doc
134
137
  }
@@ -171,12 +174,12 @@ async function loadRawOpenApiSpec(): Promise<OpenApiDocument | null> {
171
174
  const jsonPath = path.join(appRoot.generatedDir, 'openapi.generated.json')
172
175
  if (fs.existsSync(jsonPath)) {
173
176
  const doc = JSON.parse(fs.readFileSync(jsonPath, 'utf-8')) as OpenApiDocument
174
- console.error(`[API Index] Raw OpenAPI spec loaded from ${jsonPath}`)
177
+ logger.debug('Raw OpenAPI spec loaded from generated JSON', { jsonPath })
175
178
  return doc
176
179
  }
177
180
  }
178
181
  } catch (error) {
179
- console.error('[API Index] Raw spec from JSON failed:', error instanceof Error ? error.message : error)
182
+ logger.warn('Raw spec from generated JSON failed', { err: error })
180
183
  }
181
184
 
182
185
  // Tier 2: Module registry
@@ -191,7 +194,7 @@ async function loadRawOpenApiSpec(): Promise<OpenApiDocument | null> {
191
194
  version: '1.0.0',
192
195
  servers: [{ url: process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000' }],
193
196
  })
194
- console.error(`[API Index] Raw OpenAPI spec built from ${modulesWithApis.length} modules`)
197
+ logger.debug('Raw OpenAPI spec built from module registry', { modules: modulesWithApis.length })
195
198
  return doc
196
199
  }
197
200
  } catch {
@@ -211,11 +214,11 @@ async function loadRawOpenApiSpec(): Promise<OpenApiDocument | null> {
211
214
  })
212
215
  if (response.ok) {
213
216
  const doc = (await response.json()) as OpenApiDocument
214
- console.error('[API Index] Raw OpenAPI spec fetched via HTTP')
217
+ logger.debug('Raw OpenAPI spec fetched via HTTP')
215
218
  return doc
216
219
  }
217
220
  } catch (error) {
218
- console.error('[API Index] Raw spec HTTP fetch failed:', error instanceof Error ? error.message : error)
221
+ logger.warn('Raw spec HTTP fetch failed', { err: error })
219
222
  }
220
223
 
221
224
  return null
@@ -251,21 +254,21 @@ async function parseApiEndpointsFromGeneratedJson(): Promise<ApiEndpoint[]> {
251
254
  }
252
255
 
253
256
  if (!appRoot) {
254
- console.error('[API Index] Could not find app root')
257
+ logger.warn('Could not find app root')
255
258
  return []
256
259
  }
257
260
 
258
261
  const jsonPath = path.join(appRoot.generatedDir, 'openapi.generated.json')
259
262
  if (!fs.existsSync(jsonPath)) {
260
- console.error('[API Index] openapi.generated.json not found - run yarn generate')
263
+ logger.warn('openapi.generated.json not found - run yarn generate')
261
264
  return []
262
265
  }
263
266
 
264
267
  const doc = JSON.parse(fs.readFileSync(jsonPath, 'utf-8')) as OpenApiDocument
265
- console.error(`[API Index] Loaded OpenAPI from ${jsonPath}`)
268
+ logger.debug('Loaded OpenAPI from generated JSON', { jsonPath })
266
269
  return extractEndpoints(doc)
267
270
  } catch (error) {
268
- console.error('[API Index] Error reading generated JSON:', error instanceof Error ? error.message : error)
271
+ logger.error('Error reading generated OpenAPI JSON', { err: error })
269
272
  return []
270
273
  }
271
274
  }
@@ -282,9 +285,7 @@ async function parseApiEndpointsFromModules(): Promise<ApiEndpoint[]> {
282
285
  const modulesWithApis = modules.filter((m) => m.apis && m.apis.length > 0)
283
286
 
284
287
  if (modulesWithApis.length > 0) {
285
- console.error(
286
- `[API Index] Found ${modules.length} modules, ${modulesWithApis.length} with APIs`
287
- )
288
+ logger.debug('Modules discovered for OpenAPI generation', { modules: modules.length, withApis: modulesWithApis.length })
288
289
 
289
290
  // Generate OpenAPI spec from modules
290
291
  const doc = buildOpenApiDocument(modules, {
@@ -319,22 +320,22 @@ async function parseApiEndpointsFromHttp(): Promise<ApiEndpoint[]> {
319
320
  const openApiUrl = `${baseUrl}/api/docs/openapi`
320
321
 
321
322
  try {
322
- console.error(`[API Index] Fetching OpenAPI spec from ${openApiUrl}...`)
323
+ logger.debug('Fetching OpenAPI spec', { openApiUrl })
323
324
  const response = await fetchWithTimeout(openApiUrl, {
324
325
  timeoutMs: resolveOpenapiFetchTimeoutMs(),
325
326
  })
326
327
 
327
328
  if (!response.ok) {
328
- console.error(`[API Index] Failed to fetch OpenAPI spec: ${response.status} ${response.statusText}`)
329
+ logger.warn('Failed to fetch OpenAPI spec', { status: response.status, statusText: response.statusText })
329
330
  return []
330
331
  }
331
332
 
332
333
  const doc = (await response.json()) as OpenApiDocument
333
- console.error(`[API Index] Successfully fetched OpenAPI spec`)
334
+ logger.debug('Successfully fetched OpenAPI spec')
334
335
  return extractEndpoints(doc)
335
336
  } catch (error) {
336
- console.error('[API Index] Could not fetch OpenAPI spec:', error instanceof Error ? error.message : error)
337
- console.error('[API Index] Make sure the app is running at', baseUrl)
337
+ logger.warn('Could not fetch OpenAPI spec', { err: error })
338
+ logger.warn('OpenAPI fetch fallback requires the app to be running', { baseUrl })
338
339
  return []
339
340
  }
340
341
  }
@@ -346,19 +347,19 @@ async function parseApiEndpoints(): Promise<ApiEndpoint[]> {
346
347
  // Try generated JSON first (works in CLI context without Next.js)
347
348
  const fromJson = await parseApiEndpointsFromGeneratedJson()
348
349
  if (fromJson.length > 0) {
349
- console.error(`[API Index] Loaded ${fromJson.length} endpoints from generated JSON`)
350
+ logger.debug('Loaded endpoints from generated JSON', { count: fromJson.length })
350
351
  return fromJson
351
352
  }
352
353
 
353
354
  // Try loading from module registry (works in Next.js context)
354
355
  const fromModules = await parseApiEndpointsFromModules()
355
356
  if (fromModules.length > 0) {
356
- console.error(`[API Index] Loaded ${fromModules.length} endpoints from modules registry`)
357
+ logger.debug('Loaded endpoints from modules registry', { count: fromModules.length })
357
358
  return fromModules
358
359
  }
359
360
 
360
361
  // Fall back to HTTP fetch (requires running Next.js app)
361
- console.error('[API Index] Generated JSON and modules not available, falling back to HTTP fetch...')
362
+ logger.debug('Generated JSON and modules not available, falling back to HTTP fetch')
362
363
  return parseApiEndpointsFromHttp()
363
364
  }
364
365
 
@@ -403,7 +404,7 @@ function extractEndpoints(doc: OpenApiDocument): ApiEndpoint[] {
403
404
  }
404
405
  }
405
406
 
406
- console.error(`[API Index] Parsed ${endpoints.length} endpoints from OpenAPI spec`)
407
+ logger.debug('Parsed endpoints from OpenAPI spec', { count: endpoints.length })
407
408
  return endpoints
408
409
  }
409
410
 
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import { promises as fs } from 'fs'
2
3
  import type { AwilixContainer } from 'awilix'
3
4
  import type { EntityManager } from '@mikro-orm/postgresql'
@@ -11,6 +12,8 @@ import type {
11
12
  AiResolvedAttachmentPart,
12
13
  } from './attachment-bridge-types'
13
14
 
15
+ const logger = createLogger('ai_assistant')
16
+
14
17
  // Provider-native inline byte limit. Most AI providers accept inline image/PDF
15
18
  // payloads comfortably under 4 MB; anything larger SHOULD travel as a short-lived
16
19
  // signed URL (see AttachmentSigner below). Above this ceiling and with no signer
@@ -198,10 +201,7 @@ async function readAttachmentBytes(row: AttachmentRow): Promise<Uint8Array | nul
198
201
  const buffer = await fs.readFile(absolutePath)
199
202
  return new Uint8Array(buffer)
200
203
  } catch (error) {
201
- console.warn(
202
- `[AI Agents] Failed to read attachment ${row.id} from storage; falling back to metadata-only:`,
203
- error,
204
- )
204
+ logger.warn('Failed to read attachment from storage; falling back to metadata-only', { attachmentId: row.id, err: error })
205
205
  return null
206
206
  }
207
207
  }
@@ -259,10 +259,7 @@ async function classifyAndBuildPart(
259
259
  }
260
260
  }
261
261
  } catch (error) {
262
- console.warn(
263
- `[AI Agents] attachmentSigner failed for ${row.id}; falling back to metadata-only:`,
264
- error,
265
- )
262
+ logger.warn('attachmentSigner failed; falling back to metadata-only', { attachmentId: row.id, err: error })
266
263
  }
267
264
  }
268
265
  return { ...base, source: 'metadata-only' }
@@ -279,12 +276,12 @@ async function classifyAndBuildPart(
279
276
  * Contract:
280
277
  *
281
278
  * - Tenant/org scope is enforced: records that don't belong to the caller are
282
- * dropped with a `console.warn`. Super-admin callers bypass the scope check.
279
+ * dropped with a logger warning. Super-admin callers bypass the scope check.
283
280
  * - When the agent declares `acceptedMediaTypes`, parts whose classified media
284
- * type is not in the whitelist are dropped with a `console.warn`.
281
+ * type is not in the whitelist are dropped with a logger warning.
285
282
  * `acceptedMediaTypes: undefined` means "no filter".
286
283
  * - When the DI container is missing or the attachments service is
287
- * unavailable, the helper returns `[]` with a single `console.warn` and
284
+ * unavailable, the helper returns `[]` with a single logger warning and
288
285
  * does NOT throw — the caller's `attachmentIds` pass-through to
289
286
  * {@link resolveAiAgentTools} remains the Step 3.6 parity behavior.
290
287
  * - The returned parts are ordered to match `attachmentIds`. Any id that
@@ -299,9 +296,7 @@ export async function resolveAttachmentParts(
299
296
 
300
297
  const em = resolveEm(input.container)
301
298
  if (!em) {
302
- console.warn(
303
- '[AI Agents] resolveAttachmentParts called without a DI container exposing `em`; skipping attachment resolution.',
304
- )
299
+ logger.warn('resolveAttachmentParts called without a DI container exposing `em`; skipping attachment resolution')
305
300
  return []
306
301
  }
307
302
 
@@ -319,27 +314,20 @@ export async function resolveAttachmentParts(
319
314
  try {
320
315
  row = await loadAttachmentRow(em, id, input.authContext)
321
316
  } catch (error) {
322
- console.warn(
323
- `[AI Agents] Failed to load attachment ${id}; skipping:`,
324
- error,
325
- )
317
+ logger.warn('Failed to load attachment; skipping', { attachmentId: id, err: error })
326
318
  continue
327
319
  }
328
320
  if (!row) {
329
- console.warn(`[AI Agents] Attachment ${id} not found; skipping.`)
321
+ logger.warn('Attachment not found; skipping', { attachmentId: id })
330
322
  continue
331
323
  }
332
324
  if (!rowBelongsToCaller(row, input.authContext)) {
333
- console.warn(
334
- `[AI Agents] Attachment ${id} is out of scope for caller (tenant=${input.authContext.tenantId}, org=${input.authContext.organizationId}); skipping.`,
335
- )
325
+ logger.warn('Attachment is out of scope for caller; skipping', { attachmentId: id, tenantId: input.authContext.tenantId, organizationId: input.authContext.organizationId })
336
326
  continue
337
327
  }
338
328
  const mediaClass = classifyMediaType(row.mimeType)
339
329
  if (acceptedSet && !acceptedSet.has(mediaClass)) {
340
- console.warn(
341
- `[AI Agents] Attachment ${id} (${row.mimeType}) is not in agent acceptedMediaTypes=${[...acceptedSet].join(',')}; skipping.`,
342
- )
330
+ logger.warn('Attachment is not in agent acceptedMediaTypes; skipping', { attachmentId: id, mimeType: row.mimeType, acceptedMediaTypes: [...acceptedSet].join(',') })
343
331
  continue
344
332
  }
345
333
  try {
@@ -353,10 +341,7 @@ export async function resolveAttachmentParts(
353
341
  )
354
342
  parts.push(part)
355
343
  } catch (error) {
356
- console.warn(
357
- `[AI Agents] Failed to build attachment part for ${id}; skipping:`,
358
- error,
359
- )
344
+ logger.warn('Failed to build attachment part; skipping', { attachmentId: id, err: error })
360
345
  }
361
346
  }
362
347
 
@@ -1,8 +1,11 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
1
2
  import type { AwilixContainer } from 'awilix'
2
3
  import type { EntityManager } from '@mikro-orm/postgresql'
3
4
  import type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'
4
5
  import { hasAllFeatures } from '@open-mercato/shared/lib/auth/featureMatch'
5
6
 
7
+ const logger = createLogger('ai_assistant')
8
+
6
9
  /**
7
10
  * Successful authentication result.
8
11
  */
@@ -107,7 +110,7 @@ export async function authenticateMcpRequest(
107
110
  }
108
111
  } catch (error) {
109
112
  const message = error instanceof Error ? error.message : String(error)
110
- console.error('[MCP Auth] Authentication failed:', message)
113
+ logger.error('MCP authentication failed', { err: error })
111
114
  return { success: false, error: 'Authentication failed' }
112
115
  }
113
116
  }