@open-mercato/ai-assistant 0.5.1-develop.3036.f02c281f23 → 0.5.1-develop.3045.b4b3320cc2

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 (273) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/AGENTS.md +361 -0
  3. package/README.md +5 -0
  4. package/dist/index.js +154 -0
  5. package/dist/index.js.map +2 -2
  6. package/dist/modules/ai_assistant/__integration__/TC-AI-002-agent-policy.spec.js +73 -0
  7. package/dist/modules/ai_assistant/__integration__/TC-AI-002-agent-policy.spec.js.map +7 -0
  8. package/dist/modules/ai_assistant/__integration__/TC-AI-AGENT-SETTINGS-005-settings-page.spec.js +484 -0
  9. package/dist/modules/ai_assistant/__integration__/TC-AI-AGENT-SETTINGS-005-settings-page.spec.js.map +7 -0
  10. package/dist/modules/ai_assistant/__integration__/TC-AI-PLAYGROUND-004-playground.spec.js +251 -0
  11. package/dist/modules/ai_assistant/__integration__/TC-AI-PLAYGROUND-004-playground.spec.js.map +7 -0
  12. package/dist/modules/ai_assistant/__integration__/TC-INT-AI-TOOLS.spec.js +91 -0
  13. package/dist/modules/ai_assistant/__integration__/TC-INT-AI-TOOLS.spec.js.map +7 -0
  14. package/dist/modules/ai_assistant/ai-tools/attachments-pack.js +202 -0
  15. package/dist/modules/ai_assistant/ai-tools/attachments-pack.js.map +7 -0
  16. package/dist/modules/ai_assistant/ai-tools/meta-pack.js +121 -0
  17. package/dist/modules/ai_assistant/ai-tools/meta-pack.js.map +7 -0
  18. package/dist/modules/ai_assistant/ai-tools/search-pack.js +94 -0
  19. package/dist/modules/ai_assistant/ai-tools/search-pack.js.map +7 -0
  20. package/dist/modules/ai_assistant/ai-tools.js +14 -0
  21. package/dist/modules/ai_assistant/ai-tools.js.map +7 -0
  22. package/dist/modules/ai_assistant/api/ai/actions/[id]/cancel/route.js +175 -0
  23. package/dist/modules/ai_assistant/api/ai/actions/[id]/cancel/route.js.map +7 -0
  24. package/dist/modules/ai_assistant/api/ai/actions/[id]/confirm/route.js +174 -0
  25. package/dist/modules/ai_assistant/api/ai/actions/[id]/confirm/route.js.map +7 -0
  26. package/dist/modules/ai_assistant/api/ai/actions/[id]/route.js +101 -0
  27. package/dist/modules/ai_assistant/api/ai/actions/[id]/route.js.map +7 -0
  28. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/mutation-policy/route.js +311 -0
  29. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/mutation-policy/route.js.map +7 -0
  30. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/prompt-override/route.js +246 -0
  31. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/prompt-override/route.js.map +7 -0
  32. package/dist/modules/ai_assistant/api/ai/agents/route.js +94 -0
  33. package/dist/modules/ai_assistant/api/ai/agents/route.js.map +7 -0
  34. package/dist/modules/ai_assistant/api/ai/chat/route.js +173 -0
  35. package/dist/modules/ai_assistant/api/ai/chat/route.js.map +7 -0
  36. package/dist/modules/ai_assistant/api/ai/run-object/route.js +167 -0
  37. package/dist/modules/ai_assistant/api/ai/run-object/route.js.map +7 -0
  38. package/dist/modules/ai_assistant/backend/config/ai-assistant/agents/AiAgentSettingsPageClient.js +1111 -0
  39. package/dist/modules/ai_assistant/backend/config/ai-assistant/agents/AiAgentSettingsPageClient.js.map +7 -0
  40. package/dist/modules/ai_assistant/backend/config/ai-assistant/agents/page.js +10 -0
  41. package/dist/modules/ai_assistant/backend/config/ai-assistant/agents/page.js.map +7 -0
  42. package/dist/modules/ai_assistant/backend/config/ai-assistant/agents/page.meta.js +28 -0
  43. package/dist/modules/ai_assistant/backend/config/ai-assistant/agents/page.meta.js.map +7 -0
  44. package/dist/modules/ai_assistant/backend/config/ai-assistant/legacy/page.js +10 -0
  45. package/dist/modules/ai_assistant/backend/config/ai-assistant/legacy/page.js.map +7 -0
  46. package/dist/modules/ai_assistant/backend/config/ai-assistant/legacy/page.meta.js +30 -0
  47. package/dist/modules/ai_assistant/backend/config/ai-assistant/legacy/page.meta.js.map +7 -0
  48. package/dist/modules/ai_assistant/backend/config/ai-assistant/page.js +4 -6
  49. package/dist/modules/ai_assistant/backend/config/ai-assistant/page.js.map +2 -2
  50. package/dist/modules/ai_assistant/backend/config/ai-assistant/page.meta.js +1 -21
  51. package/dist/modules/ai_assistant/backend/config/ai-assistant/page.meta.js.map +2 -2
  52. package/dist/modules/ai_assistant/backend/config/ai-assistant/playground/AiPlaygroundPageClient.js +462 -0
  53. package/dist/modules/ai_assistant/backend/config/ai-assistant/playground/AiPlaygroundPageClient.js.map +7 -0
  54. package/dist/modules/ai_assistant/backend/config/ai-assistant/playground/page.js +10 -0
  55. package/dist/modules/ai_assistant/backend/config/ai-assistant/playground/page.js.map +7 -0
  56. package/dist/modules/ai_assistant/backend/config/ai-assistant/playground/page.meta.js +28 -0
  57. package/dist/modules/ai_assistant/backend/config/ai-assistant/playground/page.meta.js.map +7 -0
  58. package/dist/modules/ai_assistant/cli.js +78 -12
  59. package/dist/modules/ai_assistant/cli.js.map +2 -2
  60. package/dist/modules/ai_assistant/data/entities/AiAgentMutationPolicyOverride.js +5 -0
  61. package/dist/modules/ai_assistant/data/entities/AiAgentMutationPolicyOverride.js.map +7 -0
  62. package/dist/modules/ai_assistant/data/entities/AiAgentPromptOverride.js +5 -0
  63. package/dist/modules/ai_assistant/data/entities/AiAgentPromptOverride.js.map +7 -0
  64. package/dist/modules/ai_assistant/data/entities/AiPendingAction.js +5 -0
  65. package/dist/modules/ai_assistant/data/entities/AiPendingAction.js.map +7 -0
  66. package/dist/modules/ai_assistant/data/entities.js +228 -0
  67. package/dist/modules/ai_assistant/data/entities.js.map +7 -0
  68. package/dist/modules/ai_assistant/data/repositories/AiAgentMutationPolicyOverrideRepository.js +95 -0
  69. package/dist/modules/ai_assistant/data/repositories/AiAgentMutationPolicyOverrideRepository.js.map +7 -0
  70. package/dist/modules/ai_assistant/data/repositories/AiAgentPromptOverrideRepository.js +95 -0
  71. package/dist/modules/ai_assistant/data/repositories/AiAgentPromptOverrideRepository.js.map +7 -0
  72. package/dist/modules/ai_assistant/data/repositories/AiPendingActionRepository.js +223 -0
  73. package/dist/modules/ai_assistant/data/repositories/AiPendingActionRepository.js.map +7 -0
  74. package/dist/modules/ai_assistant/events.js +33 -0
  75. package/dist/modules/ai_assistant/events.js.map +7 -0
  76. package/dist/modules/ai_assistant/i18n/de.json +252 -0
  77. package/dist/modules/ai_assistant/i18n/en.json +252 -0
  78. package/dist/modules/ai_assistant/i18n/es.json +252 -0
  79. package/dist/modules/ai_assistant/i18n/pl.json +252 -0
  80. package/dist/modules/ai_assistant/lib/agent-policy.js +168 -0
  81. package/dist/modules/ai_assistant/lib/agent-policy.js.map +7 -0
  82. package/dist/modules/ai_assistant/lib/agent-registry.js +195 -0
  83. package/dist/modules/ai_assistant/lib/agent-registry.js.map +7 -0
  84. package/dist/modules/ai_assistant/lib/agent-runtime.js +451 -0
  85. package/dist/modules/ai_assistant/lib/agent-runtime.js.map +7 -0
  86. package/dist/modules/ai_assistant/lib/agent-tools.js +223 -0
  87. package/dist/modules/ai_assistant/lib/agent-tools.js.map +7 -0
  88. package/dist/modules/ai_assistant/lib/agent-transport.js +25 -0
  89. package/dist/modules/ai_assistant/lib/agent-transport.js.map +7 -0
  90. package/dist/modules/ai_assistant/lib/ai-agent-definition.js +11 -0
  91. package/dist/modules/ai_assistant/lib/ai-agent-definition.js.map +7 -0
  92. package/dist/modules/ai_assistant/lib/ai-agents-generated.d.js +1 -0
  93. package/dist/modules/ai_assistant/lib/ai-agents-generated.d.js.map +7 -0
  94. package/dist/modules/ai_assistant/lib/ai-api-operation-runner.js +239 -0
  95. package/dist/modules/ai_assistant/lib/ai-api-operation-runner.js.map +7 -0
  96. package/dist/modules/ai_assistant/lib/ai-overrides.js +189 -0
  97. package/dist/modules/ai_assistant/lib/ai-overrides.js.map +7 -0
  98. package/dist/modules/ai_assistant/lib/ai-tool-definition.js +7 -0
  99. package/dist/modules/ai_assistant/lib/ai-tool-definition.js.map +7 -0
  100. package/dist/modules/ai_assistant/lib/ai-tools-generated.d.js +1 -0
  101. package/dist/modules/ai_assistant/lib/ai-tools-generated.d.js.map +7 -0
  102. package/dist/modules/ai_assistant/lib/api-backed-tool.js +48 -0
  103. package/dist/modules/ai_assistant/lib/api-backed-tool.js.map +7 -0
  104. package/dist/modules/ai_assistant/lib/attachment-bridge-types.js +1 -0
  105. package/dist/modules/ai_assistant/lib/attachment-bridge-types.js.map +7 -0
  106. package/dist/modules/ai_assistant/lib/attachment-parts.js +276 -0
  107. package/dist/modules/ai_assistant/lib/attachment-parts.js.map +7 -0
  108. package/dist/modules/ai_assistant/lib/model-factory.js +68 -0
  109. package/dist/modules/ai_assistant/lib/model-factory.js.map +7 -0
  110. package/dist/modules/ai_assistant/lib/pending-action-cancel.js +86 -0
  111. package/dist/modules/ai_assistant/lib/pending-action-cancel.js.map +7 -0
  112. package/dist/modules/ai_assistant/lib/pending-action-client.js +35 -0
  113. package/dist/modules/ai_assistant/lib/pending-action-client.js.map +7 -0
  114. package/dist/modules/ai_assistant/lib/pending-action-executor.js +243 -0
  115. package/dist/modules/ai_assistant/lib/pending-action-executor.js.map +7 -0
  116. package/dist/modules/ai_assistant/lib/pending-action-recheck.js +246 -0
  117. package/dist/modules/ai_assistant/lib/pending-action-recheck.js.map +7 -0
  118. package/dist/modules/ai_assistant/lib/pending-action-types.js +70 -0
  119. package/dist/modules/ai_assistant/lib/pending-action-types.js.map +7 -0
  120. package/dist/modules/ai_assistant/lib/prepare-mutation.js +315 -0
  121. package/dist/modules/ai_assistant/lib/prepare-mutation.js.map +7 -0
  122. package/dist/modules/ai_assistant/lib/prompt-composition-types.js +7 -0
  123. package/dist/modules/ai_assistant/lib/prompt-composition-types.js.map +7 -0
  124. package/dist/modules/ai_assistant/lib/prompt-override-merge.js +175 -0
  125. package/dist/modules/ai_assistant/lib/prompt-override-merge.js.map +7 -0
  126. package/dist/modules/ai_assistant/lib/schema-utils.js +5 -1
  127. package/dist/modules/ai_assistant/lib/schema-utils.js.map +2 -2
  128. package/dist/modules/ai_assistant/lib/tool-executor.js +13 -2
  129. package/dist/modules/ai_assistant/lib/tool-executor.js.map +2 -2
  130. package/dist/modules/ai_assistant/lib/tool-loader.js +86 -11
  131. package/dist/modules/ai_assistant/lib/tool-loader.js.map +2 -2
  132. package/dist/modules/ai_assistant/lib/tool-test-fixtures.js +120 -0
  133. package/dist/modules/ai_assistant/lib/tool-test-fixtures.js.map +7 -0
  134. package/dist/modules/ai_assistant/lib/tool-test-runner.js +418 -0
  135. package/dist/modules/ai_assistant/lib/tool-test-runner.js.map +7 -0
  136. package/dist/modules/ai_assistant/migrations/Migration20260419100521.js +17 -0
  137. package/dist/modules/ai_assistant/migrations/Migration20260419100521.js.map +7 -0
  138. package/dist/modules/ai_assistant/migrations/Migration20260419132948.js +16 -0
  139. package/dist/modules/ai_assistant/migrations/Migration20260419132948.js.map +7 -0
  140. package/dist/modules/ai_assistant/migrations/Migration20260419134235.js +17 -0
  141. package/dist/modules/ai_assistant/migrations/Migration20260419134235.js.map +7 -0
  142. package/dist/modules/ai_assistant/setup.js +36 -0
  143. package/dist/modules/ai_assistant/setup.js.map +2 -2
  144. package/dist/modules/ai_assistant/workers/ai-pending-action-cleanup.js +161 -0
  145. package/dist/modules/ai_assistant/workers/ai-pending-action-cleanup.js.map +7 -0
  146. package/generated/entities/ai_agent_mutation_policy_override/index.ts +9 -0
  147. package/generated/entities/ai_agent_prompt_override/index.ts +10 -0
  148. package/generated/entities/ai_pending_action/index.ts +24 -0
  149. package/generated/entities.ids.generated.ts +13 -0
  150. package/generated/entity-fields-registry.ts +57 -0
  151. package/jest.config.cjs +7 -0
  152. package/package.json +4 -4
  153. package/src/index.ts +215 -0
  154. package/src/modules/ai_assistant/__integration__/README.md +5 -0
  155. package/src/modules/ai_assistant/__integration__/TC-AI-002-agent-policy.spec.ts +115 -0
  156. package/src/modules/ai_assistant/__integration__/TC-AI-AGENT-SETTINGS-005-settings-page.spec.ts +574 -0
  157. package/src/modules/ai_assistant/__integration__/TC-AI-PLAYGROUND-004-playground.spec.ts +333 -0
  158. package/src/modules/ai_assistant/__integration__/TC-INT-AI-TOOLS.spec.ts +135 -0
  159. package/src/modules/ai_assistant/__tests__/events.test.ts +145 -0
  160. package/src/modules/ai_assistant/__tests__/integration/pending-action-contract.test.ts +1015 -0
  161. package/src/modules/ai_assistant/__tests__/integration/ws-c-attachment-bridge.test.ts +235 -0
  162. package/src/modules/ai_assistant/__tests__/integration/ws-c-policy-and-tools.test.ts +330 -0
  163. package/src/modules/ai_assistant/__tests__/integration/ws-c-tool-pack-coverage.test.ts +285 -0
  164. package/src/modules/ai_assistant/ai-tools/__tests__/attachments-pack.test.ts +322 -0
  165. package/src/modules/ai_assistant/ai-tools/__tests__/meta-pack.test.ts +218 -0
  166. package/src/modules/ai_assistant/ai-tools/__tests__/search-pack.test.ts +192 -0
  167. package/src/modules/ai_assistant/ai-tools/attachments-pack.ts +269 -0
  168. package/src/modules/ai_assistant/ai-tools/meta-pack.ts +140 -0
  169. package/src/modules/ai_assistant/ai-tools/search-pack.ts +122 -0
  170. package/src/modules/ai_assistant/ai-tools.ts +21 -0
  171. package/src/modules/ai_assistant/api/ai/actions/[id]/__tests__/route.test.ts +222 -0
  172. package/src/modules/ai_assistant/api/ai/actions/[id]/cancel/__tests__/route.test.ts +286 -0
  173. package/src/modules/ai_assistant/api/ai/actions/[id]/cancel/route.ts +237 -0
  174. package/src/modules/ai_assistant/api/ai/actions/[id]/confirm/__tests__/route.test.ts +339 -0
  175. package/src/modules/ai_assistant/api/ai/actions/[id]/confirm/route.ts +229 -0
  176. package/src/modules/ai_assistant/api/ai/actions/[id]/route.ts +142 -0
  177. package/src/modules/ai_assistant/api/ai/agents/[agentId]/mutation-policy/__tests__/route.test.ts +367 -0
  178. package/src/modules/ai_assistant/api/ai/agents/[agentId]/mutation-policy/route.ts +380 -0
  179. package/src/modules/ai_assistant/api/ai/agents/[agentId]/prompt-override/__tests__/route.test.ts +333 -0
  180. package/src/modules/ai_assistant/api/ai/agents/[agentId]/prompt-override/route.ts +307 -0
  181. package/src/modules/ai_assistant/api/ai/agents/route.ts +107 -0
  182. package/src/modules/ai_assistant/api/ai/chat/__tests__/route.test.ts +282 -0
  183. package/src/modules/ai_assistant/api/ai/chat/route.ts +207 -0
  184. package/src/modules/ai_assistant/api/ai/run-object/__tests__/route.test.ts +282 -0
  185. package/src/modules/ai_assistant/api/ai/run-object/route.ts +204 -0
  186. package/src/modules/ai_assistant/backend/config/ai-assistant/agents/AiAgentSettingsPageClient.tsx +1419 -0
  187. package/src/modules/ai_assistant/backend/config/ai-assistant/agents/page.meta.ts +26 -0
  188. package/src/modules/ai_assistant/backend/config/ai-assistant/agents/page.tsx +12 -0
  189. package/src/modules/ai_assistant/backend/config/ai-assistant/legacy/page.meta.ts +28 -0
  190. package/src/modules/ai_assistant/backend/config/ai-assistant/legacy/page.tsx +12 -0
  191. package/src/modules/ai_assistant/backend/config/ai-assistant/page.meta.ts +8 -23
  192. package/src/modules/ai_assistant/backend/config/ai-assistant/page.tsx +15 -10
  193. package/src/modules/ai_assistant/backend/config/ai-assistant/playground/AiPlaygroundPageClient.tsx +604 -0
  194. package/src/modules/ai_assistant/backend/config/ai-assistant/playground/page.meta.ts +26 -0
  195. package/src/modules/ai_assistant/backend/config/ai-assistant/playground/page.tsx +12 -0
  196. package/src/modules/ai_assistant/cli.ts +99 -24
  197. package/src/modules/ai_assistant/data/__tests__/schema-unique-indexes.test.ts +69 -0
  198. package/src/modules/ai_assistant/data/entities/AiAgentMutationPolicyOverride.ts +7 -0
  199. package/src/modules/ai_assistant/data/entities/AiAgentPromptOverride.ts +7 -0
  200. package/src/modules/ai_assistant/data/entities/AiPendingAction.ts +7 -0
  201. package/src/modules/ai_assistant/data/entities.ts +270 -0
  202. package/src/modules/ai_assistant/data/repositories/AiAgentMutationPolicyOverrideRepository.ts +129 -0
  203. package/src/modules/ai_assistant/data/repositories/AiAgentPromptOverrideRepository.ts +132 -0
  204. package/src/modules/ai_assistant/data/repositories/AiPendingActionRepository.ts +334 -0
  205. package/src/modules/ai_assistant/data/repositories/__tests__/AiAgentMutationPolicyOverrideRepository.test.ts +195 -0
  206. package/src/modules/ai_assistant/data/repositories/__tests__/AiAgentPromptOverrideRepository.test.ts +197 -0
  207. package/src/modules/ai_assistant/data/repositories/__tests__/AiPendingActionRepository.test.ts +357 -0
  208. package/src/modules/ai_assistant/events.ts +112 -0
  209. package/src/modules/ai_assistant/i18n/de.json +252 -0
  210. package/src/modules/ai_assistant/i18n/en.json +252 -0
  211. package/src/modules/ai_assistant/i18n/es.json +252 -0
  212. package/src/modules/ai_assistant/i18n/pl.json +252 -0
  213. package/src/modules/ai_assistant/lib/__tests__/agent-policy.mutation-override.test.ts +203 -0
  214. package/src/modules/ai_assistant/lib/__tests__/agent-policy.test.ts +385 -0
  215. package/src/modules/ai_assistant/lib/__tests__/agent-registry.test.ts +217 -0
  216. package/src/modules/ai_assistant/lib/__tests__/agent-runtime-object.test.ts +329 -0
  217. package/src/modules/ai_assistant/lib/__tests__/agent-runtime-parity.test.ts +573 -0
  218. package/src/modules/ai_assistant/lib/__tests__/agent-runtime.test.ts +291 -0
  219. package/src/modules/ai_assistant/lib/__tests__/agent-tools.test.ts +172 -0
  220. package/src/modules/ai_assistant/lib/__tests__/agent-transport.test.ts +41 -0
  221. package/src/modules/ai_assistant/lib/__tests__/ai-agent-definition.test.ts +183 -0
  222. package/src/modules/ai_assistant/lib/__tests__/ai-api-operation-runner.test.ts +432 -0
  223. package/src/modules/ai_assistant/lib/__tests__/ai-overrides.test.ts +308 -0
  224. package/src/modules/ai_assistant/lib/__tests__/api-backed-tool.test.ts +302 -0
  225. package/src/modules/ai_assistant/lib/__tests__/attachment-bridge-and-prompt-types.test.ts +188 -0
  226. package/src/modules/ai_assistant/lib/__tests__/attachment-parts.test.ts +531 -0
  227. package/src/modules/ai_assistant/lib/__tests__/max-steps-budget.integration.test.ts +263 -0
  228. package/src/modules/ai_assistant/lib/__tests__/model-factory.integration.test.ts +183 -0
  229. package/src/modules/ai_assistant/lib/__tests__/model-factory.test.ts +168 -0
  230. package/src/modules/ai_assistant/lib/__tests__/pending-action-cancel.test.ts +235 -0
  231. package/src/modules/ai_assistant/lib/__tests__/pending-action-client.test.ts +148 -0
  232. package/src/modules/ai_assistant/lib/__tests__/pending-action-executor.test.ts +348 -0
  233. package/src/modules/ai_assistant/lib/__tests__/pending-action-recheck.test.ts +378 -0
  234. package/src/modules/ai_assistant/lib/__tests__/phase-0-additive-contract.test.ts +299 -0
  235. package/src/modules/ai_assistant/lib/__tests__/prepare-mutation.test.ts +610 -0
  236. package/src/modules/ai_assistant/lib/__tests__/prompt-override-merge.test.ts +136 -0
  237. package/src/modules/ai_assistant/lib/__tests__/tool-loader.test.ts +125 -0
  238. package/src/modules/ai_assistant/lib/agent-policy.ts +270 -0
  239. package/src/modules/ai_assistant/lib/agent-registry.ts +277 -0
  240. package/src/modules/ai_assistant/lib/agent-runtime.ts +751 -0
  241. package/src/modules/ai_assistant/lib/agent-tools.ts +396 -0
  242. package/src/modules/ai_assistant/lib/agent-transport.ts +51 -0
  243. package/src/modules/ai_assistant/lib/ai-agent-definition.ts +86 -0
  244. package/src/modules/ai_assistant/lib/ai-agents-generated.d.ts +18 -0
  245. package/src/modules/ai_assistant/lib/ai-api-operation-runner.ts +333 -0
  246. package/src/modules/ai_assistant/lib/ai-overrides.ts +389 -0
  247. package/src/modules/ai_assistant/lib/ai-tool-definition.ts +7 -0
  248. package/src/modules/ai_assistant/lib/ai-tools-generated.d.ts +7 -0
  249. package/src/modules/ai_assistant/lib/api-backed-tool.ts +85 -0
  250. package/src/modules/ai_assistant/lib/attachment-bridge-types.ts +24 -0
  251. package/src/modules/ai_assistant/lib/attachment-parts.ts +433 -0
  252. package/src/modules/ai_assistant/lib/model-factory.ts +212 -0
  253. package/src/modules/ai_assistant/lib/pending-action-cancel.ts +179 -0
  254. package/src/modules/ai_assistant/lib/pending-action-client.ts +126 -0
  255. package/src/modules/ai_assistant/lib/pending-action-executor.ts +424 -0
  256. package/src/modules/ai_assistant/lib/pending-action-recheck.ts +410 -0
  257. package/src/modules/ai_assistant/lib/pending-action-types.ts +194 -0
  258. package/src/modules/ai_assistant/lib/prepare-mutation.ts +448 -0
  259. package/src/modules/ai_assistant/lib/prompt-composition-types.ts +24 -0
  260. package/src/modules/ai_assistant/lib/prompt-override-merge.ts +253 -0
  261. package/src/modules/ai_assistant/lib/schema-utils.ts +14 -2
  262. package/src/modules/ai_assistant/lib/tool-executor.ts +25 -3
  263. package/src/modules/ai_assistant/lib/tool-loader.ts +159 -13
  264. package/src/modules/ai_assistant/lib/tool-test-fixtures.ts +160 -0
  265. package/src/modules/ai_assistant/lib/tool-test-runner.ts +596 -0
  266. package/src/modules/ai_assistant/lib/types.ts +105 -2
  267. package/src/modules/ai_assistant/migrations/.snapshot-open-mercato.json +871 -0
  268. package/src/modules/ai_assistant/migrations/Migration20260419100521.ts +17 -0
  269. package/src/modules/ai_assistant/migrations/Migration20260419132948.ts +16 -0
  270. package/src/modules/ai_assistant/migrations/Migration20260419134235.ts +17 -0
  271. package/src/modules/ai_assistant/setup.ts +53 -0
  272. package/src/modules/ai_assistant/workers/__tests__/ai-pending-action-cleanup.test.ts +333 -0
  273. package/src/modules/ai_assistant/workers/ai-pending-action-cleanup.ts +269 -0
@@ -0,0 +1,308 @@
1
+ /**
2
+ * Coverage for the AI override pipeline. The pipeline is the only public
3
+ * way for downstream modules (or app-level code) to replace or disable
4
+ * an AI agent / AI tool registered by another module — see spec
5
+ * `.ai/specs/2026-04-30-ai-overrides-and-module-disable.md`.
6
+ *
7
+ * The pipeline has three tiers (highest precedence first):
8
+ * 1. programmatic — `applyAiAgentOverrides` / `applyAiToolOverrides`
9
+ * 2. modules.ts — `applyAiOverridesFromEnabledModules`
10
+ * 3. file-based — `aiAgentOverrides` / `aiToolOverrides` exports from
11
+ * `<module>/ai-agents.ts` / `<module>/ai-tools.ts`
12
+ */
13
+ import {
14
+ applyAgentOverrideMap,
15
+ applyAiAgentOverrides,
16
+ applyAiToolOverrides,
17
+ applyAiOverridesFromEnabledModules,
18
+ composeAgentOverrideMap,
19
+ composeToolOverrideMap,
20
+ applyToolOverrideMap,
21
+ resetProgrammaticOverridesForTests,
22
+ snapshotProgrammaticOverrides,
23
+ type AiAgentOverrideConfigEntry,
24
+ type AiToolOverrideConfigEntry,
25
+ } from '../ai-overrides'
26
+ import {
27
+ applyAgentOverrideEntriesForTests,
28
+ listAgents,
29
+ resetAgentRegistryForTests,
30
+ seedAgentRegistryForTests,
31
+ } from '../agent-registry'
32
+ import type { AiAgentDefinition } from '../ai-agent-definition'
33
+ import type { AiToolDefinition } from '../types'
34
+ import { z } from 'zod'
35
+
36
+ function makeAgent(id: string, overrides: Partial<AiAgentDefinition> = {}): AiAgentDefinition {
37
+ return {
38
+ id,
39
+ moduleId: id.split('.')[0] ?? 'mod',
40
+ label: id,
41
+ description: id,
42
+ systemPrompt: 'system',
43
+ allowedTools: [],
44
+ ...overrides,
45
+ } as AiAgentDefinition
46
+ }
47
+
48
+ function makeTool(name: string, overrides: Partial<AiToolDefinition> = {}): AiToolDefinition {
49
+ return {
50
+ name,
51
+ description: name,
52
+ inputSchema: z.object({}),
53
+ requiredFeatures: [],
54
+ handler: async () => ({ ok: true }),
55
+ ...overrides,
56
+ } as AiToolDefinition
57
+ }
58
+
59
+ beforeEach(() => {
60
+ resetAgentRegistryForTests()
61
+ resetProgrammaticOverridesForTests()
62
+ })
63
+
64
+ describe('composeAgentOverrideMap', () => {
65
+ it('merges file-based entries in order, last wins', () => {
66
+ const baseAgent = makeAgent('catalog.merchandising_assistant')
67
+ const replacement = makeAgent('catalog.merchandising_assistant', { label: 'Replacement' })
68
+ const entries: AiAgentOverrideConfigEntry[] = [
69
+ { moduleId: 'app', overrides: { 'catalog.merchandising_assistant': baseAgent } },
70
+ { moduleId: 'app2', overrides: { 'catalog.merchandising_assistant': replacement } },
71
+ ]
72
+ const map = composeAgentOverrideMap(entries)
73
+ expect(map['catalog.merchandising_assistant']).toBe(replacement)
74
+ })
75
+
76
+ it('modules.ts overrides supersede file-based entries', () => {
77
+ const fileAgent = makeAgent('catalog.merchandising_assistant', { label: 'File' })
78
+ const modulesAgent = makeAgent('catalog.merchandising_assistant', { label: 'Modules.ts' })
79
+ applyAiOverridesFromEnabledModules([
80
+ { id: 'app', overrides: { ai: { agents: { 'catalog.merchandising_assistant': modulesAgent } } } },
81
+ ])
82
+ const entries: AiAgentOverrideConfigEntry[] = [
83
+ { moduleId: 'app', overrides: { 'catalog.merchandising_assistant': fileAgent } },
84
+ ]
85
+ const map = composeAgentOverrideMap(entries)
86
+ expect(map['catalog.merchandising_assistant']).toBe(modulesAgent)
87
+ })
88
+
89
+ it('programmatic overrides supersede modules.ts and file-based', () => {
90
+ const fileAgent = makeAgent('catalog.merchandising_assistant', { label: 'File' })
91
+ const modulesAgent = makeAgent('catalog.merchandising_assistant', { label: 'Modules.ts' })
92
+ const programmaticAgent = makeAgent('catalog.merchandising_assistant', { label: 'Programmatic' })
93
+ applyAiOverridesFromEnabledModules([
94
+ { id: 'app', overrides: { ai: { agents: { 'catalog.merchandising_assistant': modulesAgent } } } },
95
+ ])
96
+ applyAiAgentOverrides({ 'catalog.merchandising_assistant': programmaticAgent })
97
+ const entries: AiAgentOverrideConfigEntry[] = [
98
+ { moduleId: 'app', overrides: { 'catalog.merchandising_assistant': fileAgent } },
99
+ ]
100
+ const map = composeAgentOverrideMap(entries)
101
+ expect(map['catalog.merchandising_assistant']).toBe(programmaticAgent)
102
+ })
103
+
104
+ it('null override propagates through every layer', () => {
105
+ applyAiAgentOverrides({ 'catalog.catalog_assistant': null })
106
+ const map = composeAgentOverrideMap([])
107
+ expect(map['catalog.catalog_assistant']).toBeNull()
108
+ })
109
+ })
110
+
111
+ describe('applyAgentOverrideMap', () => {
112
+ it('replaces an existing agent in place', () => {
113
+ const original = makeAgent('catalog.merchandising_assistant', { label: 'Original' })
114
+ const replacement = makeAgent('catalog.merchandising_assistant', { label: 'Replacement' })
115
+ const out = applyAgentOverrideMap([original], {
116
+ 'catalog.merchandising_assistant': replacement,
117
+ })
118
+ expect(out).toHaveLength(1)
119
+ expect(out[0]).toBe(replacement)
120
+ })
121
+
122
+ it('disables an agent when the override is null', () => {
123
+ const a = makeAgent('catalog.catalog_assistant')
124
+ const b = makeAgent('catalog.merchandising_assistant')
125
+ const out = applyAgentOverrideMap([a, b], { 'catalog.catalog_assistant': null })
126
+ expect(out).toHaveLength(1)
127
+ expect(out[0].id).toBe('catalog.merchandising_assistant')
128
+ })
129
+
130
+ it('warns and skips a malformed override (id mismatch)', () => {
131
+ const a = makeAgent('catalog.catalog_assistant')
132
+ const malformed = makeAgent('catalog.merchandising_assistant')
133
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {})
134
+ const out = applyAgentOverrideMap([a], {
135
+ // The map key says one id but the value carries another.
136
+ 'catalog.catalog_assistant': malformed,
137
+ })
138
+ expect(warnSpy).toHaveBeenCalled()
139
+ expect(out).toHaveLength(1)
140
+ expect(out[0]).toBe(a)
141
+ warnSpy.mockRestore()
142
+ })
143
+
144
+ it('warns when an override targets an id with no base entry but does not throw', () => {
145
+ const replacement = makeAgent('catalog.unknown')
146
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {})
147
+ const out = applyAgentOverrideMap([], { 'catalog.unknown': replacement })
148
+ expect(warnSpy).toHaveBeenCalled()
149
+ // Override that registers a brand-new agent IS supported (synthetic agents)
150
+ expect(out).toHaveLength(1)
151
+ expect(out[0]).toBe(replacement)
152
+ warnSpy.mockRestore()
153
+ })
154
+
155
+ it('returns a copy when the override map is empty', () => {
156
+ const a = makeAgent('m.a')
157
+ const out = applyAgentOverrideMap([a], {})
158
+ expect(out).not.toBe([a])
159
+ expect(out).toEqual([a])
160
+ })
161
+ })
162
+
163
+ describe('agent-registry override pipeline', () => {
164
+ it('disables an agent registered by another module via a null override', () => {
165
+ seedAgentRegistryForTests([
166
+ makeAgent('catalog.catalog_assistant'),
167
+ makeAgent('catalog.merchandising_assistant'),
168
+ ])
169
+ expect(listAgents().map((a) => a.id)).toEqual([
170
+ 'catalog.catalog_assistant',
171
+ 'catalog.merchandising_assistant',
172
+ ])
173
+ applyAgentOverrideEntriesForTests([
174
+ { moduleId: 'app', overrides: { 'catalog.catalog_assistant': null } },
175
+ ])
176
+ expect(listAgents().map((a) => a.id)).toEqual(['catalog.merchandising_assistant'])
177
+ })
178
+
179
+ it('replaces an agent registered by another module', () => {
180
+ seedAgentRegistryForTests([
181
+ makeAgent('catalog.merchandising_assistant', { label: 'Default' }),
182
+ ])
183
+ const replacement = makeAgent('catalog.merchandising_assistant', { label: 'App-level Replacement' })
184
+ applyAgentOverrideEntriesForTests([
185
+ { moduleId: 'app', overrides: { 'catalog.merchandising_assistant': replacement } },
186
+ ])
187
+ const list = listAgents()
188
+ expect(list).toHaveLength(1)
189
+ expect(list[0].label).toBe('App-level Replacement')
190
+ })
191
+
192
+ it('module load order — last file entry wins', () => {
193
+ seedAgentRegistryForTests([makeAgent('m.x', { label: 'Original' })])
194
+ const first = makeAgent('m.x', { label: 'First override' })
195
+ const second = makeAgent('m.x', { label: 'Second override' })
196
+ applyAgentOverrideEntriesForTests([
197
+ { moduleId: 'overrider1', overrides: { 'm.x': first } },
198
+ { moduleId: 'overrider2', overrides: { 'm.x': second } },
199
+ ])
200
+ expect(listAgents()[0].label).toBe('Second override')
201
+ })
202
+
203
+ it('modules.ts override beats file-based override', () => {
204
+ seedAgentRegistryForTests([makeAgent('m.x', { label: 'Original' })])
205
+ const fileAgent = makeAgent('m.x', { label: 'File' })
206
+ const modulesAgent = makeAgent('m.x', { label: 'Modules.ts' })
207
+ applyAiOverridesFromEnabledModules([
208
+ { id: 'app', overrides: { ai: { agents: { 'm.x': modulesAgent } } } },
209
+ ])
210
+ applyAgentOverrideEntriesForTests([
211
+ { moduleId: 'overrider', overrides: { 'm.x': fileAgent } },
212
+ ])
213
+ expect(listAgents()[0].label).toBe('Modules.ts')
214
+ })
215
+
216
+ it('programmatic override beats both modules.ts and file-based override', () => {
217
+ seedAgentRegistryForTests([makeAgent('m.x', { label: 'Original' })])
218
+ const fileAgent = makeAgent('m.x', { label: 'File' })
219
+ const modulesAgent = makeAgent('m.x', { label: 'Modules.ts' })
220
+ const programmatic = makeAgent('m.x', { label: 'Programmatic' })
221
+ applyAiOverridesFromEnabledModules([
222
+ { id: 'app', overrides: { ai: { agents: { 'm.x': modulesAgent } } } },
223
+ ])
224
+ applyAiAgentOverrides({ 'm.x': programmatic })
225
+ applyAgentOverrideEntriesForTests([
226
+ { moduleId: 'overrider', overrides: { 'm.x': fileAgent } },
227
+ ])
228
+ expect(listAgents()[0].label).toBe('Programmatic')
229
+ })
230
+
231
+ it('snapshotProgrammaticOverrides reflects the current state', () => {
232
+ expect(snapshotProgrammaticOverrides().agents).toEqual({})
233
+ expect(snapshotProgrammaticOverrides().modulesConfigAgents).toEqual({})
234
+ const replacement = makeAgent('m.x', { label: 'X' })
235
+ applyAiAgentOverrides({ 'm.x': replacement, 'm.y': null })
236
+ applyAiOverridesFromEnabledModules([
237
+ { id: 'app', overrides: { ai: { agents: { 'm.z': null } } } },
238
+ ])
239
+ const snapshot = snapshotProgrammaticOverrides()
240
+ expect(snapshot.agents).toEqual({ 'm.x': replacement, 'm.y': null })
241
+ expect(snapshot.modulesConfigAgents).toEqual({ 'm.z': null })
242
+ })
243
+ })
244
+
245
+ describe('tool override map', () => {
246
+ it('disables a tool when the override is null', () => {
247
+ const base = new Map<string, AiToolDefinition>([
248
+ ['customers.update_deal_stage', makeTool('customers.update_deal_stage')],
249
+ ['customers.list_people', makeTool('customers.list_people')],
250
+ ])
251
+ const out = applyToolOverrideMap(base, { 'customers.update_deal_stage': null })
252
+ expect(out.has('customers.update_deal_stage')).toBe(false)
253
+ expect(out.has('customers.list_people')).toBe(true)
254
+ })
255
+
256
+ it('replaces a tool when the override is a definition', () => {
257
+ const original = makeTool('customers.update_deal_stage', { description: 'Original' })
258
+ const replacement = makeTool('customers.update_deal_stage', { description: 'Replacement' })
259
+ const base = new Map<string, AiToolDefinition>([['customers.update_deal_stage', original]])
260
+ const out = applyToolOverrideMap(base, { 'customers.update_deal_stage': replacement })
261
+ expect(out.get('customers.update_deal_stage')).toBe(replacement)
262
+ })
263
+
264
+ it('skips and warns on malformed overrides (name mismatch)', () => {
265
+ const original = makeTool('customers.update_deal_stage')
266
+ const malformed = makeTool('customers.list_people')
267
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {})
268
+ const base = new Map<string, AiToolDefinition>([['customers.update_deal_stage', original]])
269
+ const out = applyToolOverrideMap(base, { 'customers.update_deal_stage': malformed })
270
+ expect(warnSpy).toHaveBeenCalled()
271
+ expect(out.get('customers.update_deal_stage')).toBe(original)
272
+ warnSpy.mockRestore()
273
+ })
274
+
275
+ it('composeToolOverrideMap: programmatic beats modules.ts and file-based', () => {
276
+ const fileTool = makeTool('m.x', { description: 'File' })
277
+ const modulesTool = makeTool('m.x', { description: 'Modules.ts' })
278
+ const progTool = makeTool('m.x', { description: 'Programmatic' })
279
+ applyAiOverridesFromEnabledModules([
280
+ { id: 'app', overrides: { ai: { tools: { 'm.x': modulesTool } } } },
281
+ ])
282
+ applyAiToolOverrides({ 'm.x': progTool })
283
+ const entries: AiToolOverrideConfigEntry[] = [
284
+ { moduleId: 'app', overrides: { 'm.x': fileTool } },
285
+ ]
286
+ const map = composeToolOverrideMap(entries)
287
+ expect(map['m.x']).toBe(progTool)
288
+ })
289
+
290
+ it('composeToolOverrideMap: modules.ts beats file-based', () => {
291
+ const fileTool = makeTool('m.x', { description: 'File' })
292
+ const modulesTool = makeTool('m.x', { description: 'Modules.ts' })
293
+ applyAiOverridesFromEnabledModules([
294
+ { id: 'app', overrides: { ai: { tools: { 'm.x': modulesTool } } } },
295
+ ])
296
+ const entries: AiToolOverrideConfigEntry[] = [
297
+ { moduleId: 'app', overrides: { 'm.x': fileTool } },
298
+ ]
299
+ const map = composeToolOverrideMap(entries)
300
+ expect(map['m.x']).toBe(modulesTool)
301
+ })
302
+
303
+ it('composeToolOverrideMap: null disables across every layer', () => {
304
+ applyAiToolOverrides({ 'm.x': null })
305
+ const map = composeToolOverrideMap([])
306
+ expect(map['m.x']).toBeNull()
307
+ })
308
+ })
@@ -0,0 +1,302 @@
1
+ import { z } from 'zod'
2
+ import { defineApiBackedAiTool } from '../api-backed-tool'
3
+ import {
4
+ createAiApiOperationRunner,
5
+ type AiApiOperationRequest,
6
+ type AiApiOperationResponse,
7
+ type AiToolExecutionContext,
8
+ } from '../ai-api-operation-runner'
9
+ import type { AiToolDefinition, McpToolContext } from '../types'
10
+
11
+ jest.mock('../ai-api-operation-runner', () => {
12
+ const actual = jest.requireActual('../ai-api-operation-runner')
13
+ return {
14
+ ...actual,
15
+ createAiApiOperationRunner: jest.fn(),
16
+ }
17
+ })
18
+
19
+ const mockedCreateRunner = jest.mocked(createAiApiOperationRunner)
20
+
21
+ function makeBaseCtx(): McpToolContext {
22
+ return {
23
+ tenantId: 'tenant-1',
24
+ organizationId: 'org-1',
25
+ userId: 'user-1',
26
+ container: {} as McpToolContext['container'],
27
+ userFeatures: ['*'],
28
+ isSuperAdmin: true,
29
+ }
30
+ }
31
+
32
+ function asExecutionCtx(tool: AiToolDefinition, base: McpToolContext = makeBaseCtx()): AiToolExecutionContext {
33
+ return { ...base, tool }
34
+ }
35
+
36
+ function mockRunnerWith(response: AiApiOperationResponse<unknown>): jest.Mock {
37
+ const run = jest.fn(async () => response)
38
+ mockedCreateRunner.mockReturnValue({ run } as unknown as ReturnType<typeof createAiApiOperationRunner>)
39
+ return run
40
+ }
41
+
42
+ describe('defineApiBackedAiTool', () => {
43
+ beforeEach(() => {
44
+ mockedCreateRunner.mockReset()
45
+ })
46
+
47
+ it('returns an AiToolDefinition forwarding name/description/inputSchema/requiredFeatures and isMutation defaults', () => {
48
+ const inputSchema = z.object({ id: z.string() })
49
+ const tool = defineApiBackedAiTool({
50
+ name: 'customers.list_people',
51
+ description: 'List people',
52
+ inputSchema,
53
+ requiredFeatures: ['customers.people.view'],
54
+ toOperation: () => ({ method: 'GET', path: '/customers/people' }),
55
+ mapResponse: (response) => response.data ?? null,
56
+ })
57
+
58
+ expect(tool.name).toBe('customers.list_people')
59
+ expect(tool.description).toBe('List people')
60
+ expect(tool.inputSchema).toBe(inputSchema)
61
+ expect(tool.requiredFeatures).toEqual(['customers.people.view'])
62
+ expect(tool.isMutation).toBeUndefined()
63
+ expect(tool.displayName).toBeUndefined()
64
+ expect(typeof tool.handler).toBe('function')
65
+ })
66
+
67
+ it('forwards displayName when provided', () => {
68
+ const tool = defineApiBackedAiTool({
69
+ name: 'customers.list_people',
70
+ displayName: 'List people',
71
+ description: 'desc',
72
+ inputSchema: z.object({}),
73
+ requiredFeatures: ['customers.people.view'],
74
+ toOperation: () => ({ method: 'GET', path: '/customers/people' }),
75
+ mapResponse: () => null,
76
+ })
77
+ expect(tool.displayName).toBe('List people')
78
+ })
79
+
80
+ it('preserves loadBeforeRecord and loadBeforeRecords pass-through', () => {
81
+ const loadBeforeRecord = jest.fn(async () => ({
82
+ recordId: 'r-1',
83
+ entityType: 'customers:person',
84
+ recordVersion: '1',
85
+ before: {},
86
+ }))
87
+ const loadBeforeRecords = jest.fn(async () => [
88
+ { recordId: 'r-1', entityType: 'catalog:product', label: 'Hat', recordVersion: '1', before: {} },
89
+ ])
90
+
91
+ const tool = defineApiBackedAiTool({
92
+ name: 'catalog.update_product',
93
+ description: 'desc',
94
+ inputSchema: z.object({}),
95
+ requiredFeatures: ['catalog.products.manage'],
96
+ isMutation: true,
97
+ loadBeforeRecord,
98
+ loadBeforeRecords,
99
+ toOperation: () => ({ method: 'PUT', path: '/catalog/products', body: {} }),
100
+ mapResponse: () => null,
101
+ })
102
+
103
+ expect(tool.isMutation).toBe(true)
104
+ expect(tool.loadBeforeRecord).toBe(loadBeforeRecord)
105
+ expect(tool.loadBeforeRecords).toBe(loadBeforeRecords)
106
+ })
107
+
108
+ it('invokes toOperation with the parsed input and the same ctx, passing the operation to runner.run', async () => {
109
+ const operation: AiApiOperationRequest = {
110
+ method: 'GET',
111
+ path: '/customers/people',
112
+ query: { search: 'taylor' },
113
+ }
114
+ const toOperation = jest.fn(() => operation)
115
+ const mapResponse = jest.fn((response: AiApiOperationResponse<{ items: unknown[] }>) => response.data?.items ?? [])
116
+ const run = mockRunnerWith({ success: true, statusCode: 200, data: { items: [{ id: 'p1' }] } })
117
+
118
+ const tool = defineApiBackedAiTool<{ search: string }, { items: unknown[] }, unknown[]>({
119
+ name: 'customers.list_people',
120
+ description: 'List people',
121
+ inputSchema: z.object({ search: z.string() }),
122
+ requiredFeatures: ['customers.people.view'],
123
+ toOperation,
124
+ mapResponse,
125
+ })
126
+
127
+ const baseCtx = makeBaseCtx()
128
+ const result = await tool.handler({ search: 'taylor' }, baseCtx)
129
+
130
+ expect(toOperation).toHaveBeenCalledTimes(1)
131
+ const [opInput, opCtx] = toOperation.mock.calls[0]
132
+ expect(opInput).toEqual({ search: 'taylor' })
133
+ expect(opCtx.tenantId).toBe(baseCtx.tenantId)
134
+ expect(opCtx.organizationId).toBe(baseCtx.organizationId)
135
+ expect(opCtx.userId).toBe(baseCtx.userId)
136
+ expect(opCtx.tool).toBe(tool)
137
+
138
+ expect(mockedCreateRunner).toHaveBeenCalledTimes(1)
139
+ expect(mockedCreateRunner.mock.calls[0][0].tool).toBe(tool)
140
+ expect(run).toHaveBeenCalledWith(operation)
141
+
142
+ expect(mapResponse).toHaveBeenCalledTimes(1)
143
+ const [mappedResponse, mappedInput, mappedCtx] = mapResponse.mock.calls[0]
144
+ expect(mappedResponse).toEqual({ success: true, statusCode: 200, data: { items: [{ id: 'p1' }] } })
145
+ expect(mappedInput).toEqual({ search: 'taylor' })
146
+ expect(mappedCtx.tool).toBe(tool)
147
+
148
+ expect(result).toEqual([{ id: 'p1' }])
149
+ })
150
+
151
+ it('returns mapResponse output on a successful runner response', async () => {
152
+ mockRunnerWith({ success: true, statusCode: 200, data: { count: 7 } })
153
+
154
+ const tool = defineApiBackedAiTool<{}, { count: number }, { total: number }>({
155
+ name: 'customers.count_people',
156
+ description: 'Count',
157
+ inputSchema: z.object({}),
158
+ requiredFeatures: ['customers.people.view'],
159
+ toOperation: () => ({ method: 'GET', path: '/customers/people' }),
160
+ mapResponse: (response) => ({ total: response.data?.count ?? 0 }),
161
+ })
162
+
163
+ const result = await tool.handler({}, makeBaseCtx())
164
+ expect(result).toEqual({ total: 7 })
165
+ })
166
+
167
+ it('throws an Error using response.error when the runner reports failure', async () => {
168
+ mockRunnerWith({ success: false, statusCode: 403, error: 'forbidden by route policy' })
169
+
170
+ const mapResponse = jest.fn()
171
+ const tool = defineApiBackedAiTool({
172
+ name: 'customers.list_people',
173
+ description: 'List',
174
+ inputSchema: z.object({}),
175
+ requiredFeatures: ['customers.people.view'],
176
+ toOperation: () => ({ method: 'GET', path: '/customers/people' }),
177
+ mapResponse,
178
+ })
179
+
180
+ await expect(tool.handler({}, makeBaseCtx())).rejects.toThrow('forbidden by route policy')
181
+ expect(mapResponse).not.toHaveBeenCalled()
182
+ })
183
+
184
+ it('throws a fallback Error message when the runner reports failure without an error string', async () => {
185
+ mockRunnerWith({ success: false, statusCode: 500 })
186
+
187
+ const tool = defineApiBackedAiTool({
188
+ name: 'customers.list_people',
189
+ description: 'List',
190
+ inputSchema: z.object({}),
191
+ requiredFeatures: ['customers.people.view'],
192
+ toOperation: () => ({ method: 'GET', path: '/customers/people' }),
193
+ mapResponse: () => null,
194
+ })
195
+
196
+ await expect(tool.handler({}, makeBaseCtx())).rejects.toThrow(/customers\.list_people/)
197
+ })
198
+
199
+ it('awaits async toOperation and async mapResponse', async () => {
200
+ const operation: AiApiOperationRequest = { method: 'GET', path: '/catalog/products' }
201
+ const toOperation = jest.fn(async () => {
202
+ await Promise.resolve()
203
+ return operation
204
+ })
205
+ const mapResponse = jest.fn(async (response: AiApiOperationResponse<{ value: number }>) => {
206
+ await Promise.resolve()
207
+ return (response.data?.value ?? 0) * 2
208
+ })
209
+ const run = mockRunnerWith({ success: true, statusCode: 200, data: { value: 21 } })
210
+
211
+ const tool = defineApiBackedAiTool<{}, { value: number }, number>({
212
+ name: 'catalog.compute',
213
+ description: 'Compute',
214
+ inputSchema: z.object({}),
215
+ requiredFeatures: ['catalog.products.view'],
216
+ toOperation,
217
+ mapResponse,
218
+ })
219
+
220
+ const result = await tool.handler({}, makeBaseCtx())
221
+ expect(result).toBe(42)
222
+ expect(toOperation).toHaveBeenCalledTimes(1)
223
+ expect(run).toHaveBeenCalledWith(operation)
224
+ expect(mapResponse).toHaveBeenCalledTimes(1)
225
+ })
226
+
227
+ it('round-trips read-tool metadata (no isMutation)', () => {
228
+ const tool = defineApiBackedAiTool({
229
+ name: 'customers.list_people',
230
+ description: 'List',
231
+ inputSchema: z.object({}),
232
+ requiredFeatures: ['customers.people.view'],
233
+ toOperation: () => ({ method: 'GET', path: '/customers/people' }),
234
+ mapResponse: () => null,
235
+ })
236
+
237
+ expect(tool.isMutation).toBeUndefined()
238
+ expect(tool.loadBeforeRecord).toBeUndefined()
239
+ expect(tool.loadBeforeRecords).toBeUndefined()
240
+ })
241
+
242
+ it('round-trips mutation-tool metadata with isMutation: true', () => {
243
+ const tool = defineApiBackedAiTool({
244
+ name: 'customers.update_deal_stage',
245
+ description: 'Update deal stage',
246
+ inputSchema: z.object({ dealId: z.string(), toPipelineStageId: z.string() }),
247
+ requiredFeatures: ['customers.deals.manage'],
248
+ isMutation: true,
249
+ toOperation: (input) => ({
250
+ method: 'PUT',
251
+ path: '/customers/deals',
252
+ body: { id: input.dealId, pipelineStageId: input.toPipelineStageId },
253
+ }),
254
+ mapResponse: (response) => response.data,
255
+ })
256
+
257
+ expect(tool.isMutation).toBe(true)
258
+ expect(tool.requiredFeatures).toEqual(['customers.deals.manage'])
259
+ })
260
+
261
+ it('does not invoke the runner if toOperation throws', async () => {
262
+ const run = jest.fn()
263
+ mockedCreateRunner.mockReturnValue({ run } as unknown as ReturnType<typeof createAiApiOperationRunner>)
264
+
265
+ const tool = defineApiBackedAiTool({
266
+ name: 'customers.broken',
267
+ description: 'Broken',
268
+ inputSchema: z.object({}),
269
+ requiredFeatures: ['customers.people.view'],
270
+ toOperation: () => {
271
+ throw new Error('cannot build operation')
272
+ },
273
+ mapResponse: () => null,
274
+ })
275
+
276
+ await expect(tool.handler({}, makeBaseCtx())).rejects.toThrow('cannot build operation')
277
+ expect(run).not.toHaveBeenCalled()
278
+ })
279
+
280
+ it('passes the synthesized AiToolExecutionContext (with tool reference) to the runner factory', async () => {
281
+ mockRunnerWith({ success: true, statusCode: 200, data: null })
282
+
283
+ const tool = defineApiBackedAiTool({
284
+ name: 'customers.ctx_check',
285
+ description: 'desc',
286
+ inputSchema: z.object({}),
287
+ requiredFeatures: ['customers.people.view'],
288
+ toOperation: () => ({ method: 'GET', path: '/customers/people' }),
289
+ mapResponse: () => null,
290
+ })
291
+
292
+ const baseCtx = makeBaseCtx()
293
+ await tool.handler({}, baseCtx)
294
+
295
+ const factoryCtx = mockedCreateRunner.mock.calls[0][0]
296
+ const expected = asExecutionCtx(tool, baseCtx)
297
+ expect(factoryCtx.tenantId).toBe(expected.tenantId)
298
+ expect(factoryCtx.organizationId).toBe(expected.organizationId)
299
+ expect(factoryCtx.userId).toBe(expected.userId)
300
+ expect(factoryCtx.tool).toBe(tool)
301
+ })
302
+ })