@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,291 @@
1
+ import type { AiAgentDefinition, AiAgentPageContextInput } from '../ai-agent-definition'
2
+ import type { AiToolDefinition } from '../types'
3
+
4
+ const streamTextMock = jest.fn()
5
+ const stepCountIsMock = jest.fn((count: number) => ({ __stopWhen: 'stepCount', count }))
6
+ const convertToModelMessagesMock = jest.fn((messages: unknown) => messages)
7
+
8
+ jest.mock('ai', () => {
9
+ const actual = jest.requireActual('ai')
10
+ return {
11
+ ...actual,
12
+ streamText: (...args: unknown[]) => streamTextMock(...args),
13
+ stepCountIs: (...args: unknown[]) => stepCountIsMock(...(args as [number])),
14
+ convertToModelMessages: (...args: unknown[]) => convertToModelMessagesMock(...args),
15
+ }
16
+ })
17
+
18
+ const createModelMock = jest.fn(
19
+ (options: { modelId: string; apiKey: string }) => ({ id: options.modelId, apiKey: options.apiKey }),
20
+ )
21
+ const resolveApiKeyMock = jest.fn(() => 'test-api-key')
22
+
23
+ jest.mock('@open-mercato/shared/lib/ai/llm-provider-registry', () => ({
24
+ llmProviderRegistry: {
25
+ resolveFirstConfigured: () => ({
26
+ id: 'test-provider',
27
+ defaultModel: 'provider-default-model',
28
+ resolveApiKey: resolveApiKeyMock,
29
+ createModel: createModelMock,
30
+ }),
31
+ },
32
+ }))
33
+
34
+ import { z } from 'zod'
35
+ import {
36
+ resetAgentRegistryForTests,
37
+ seedAgentRegistryForTests,
38
+ } from '../agent-registry'
39
+ import { toolRegistry, registerMcpTool } from '../tool-registry'
40
+ import { runAiAgentText, composeSystemPrompt } from '../agent-runtime'
41
+
42
+ function makeAgent(
43
+ overrides: Partial<AiAgentDefinition> & Pick<AiAgentDefinition, 'id' | 'moduleId'>,
44
+ ): AiAgentDefinition {
45
+ return {
46
+ label: `${overrides.id} label`,
47
+ description: `${overrides.id} description`,
48
+ systemPrompt: 'System prompt base.',
49
+ allowedTools: [],
50
+ ...overrides,
51
+ }
52
+ }
53
+
54
+ function makeTool(
55
+ overrides: Partial<AiToolDefinition> & Pick<AiToolDefinition, 'name'>,
56
+ ): AiToolDefinition {
57
+ return {
58
+ description: `${overrides.name} description`,
59
+ inputSchema: z.object({}),
60
+ handler: async () => ({ ok: true }),
61
+ ...overrides,
62
+ }
63
+ }
64
+
65
+ const baseAuth = {
66
+ tenantId: 'tenant-1',
67
+ organizationId: 'org-1',
68
+ userId: 'user-1',
69
+ features: ['*'],
70
+ isSuperAdmin: true,
71
+ }
72
+
73
+ const baseMessages = [{ role: 'user' as const, id: 'm1', parts: [{ type: 'text' as const, text: 'hi' }] }]
74
+
75
+ function fakeStreamResult(): {
76
+ toTextStreamResponse: jest.Mock
77
+ toUIMessageStreamResponse: jest.Mock
78
+ } {
79
+ const toTextStreamResponse = jest.fn(
80
+ () =>
81
+ new Response('streamed', {
82
+ status: 200,
83
+ headers: { 'Content-Type': 'text/event-stream' },
84
+ }),
85
+ )
86
+ const toUIMessageStreamResponse = jest.fn(
87
+ () =>
88
+ new Response('streamed', {
89
+ status: 200,
90
+ headers: { 'Content-Type': 'text/event-stream' },
91
+ }),
92
+ )
93
+ return { toTextStreamResponse, toUIMessageStreamResponse }
94
+ }
95
+
96
+ describe('runAiAgentText', () => {
97
+ beforeEach(() => {
98
+ jest.clearAllMocks()
99
+ resetAgentRegistryForTests()
100
+ toolRegistry.clear()
101
+ streamTextMock.mockImplementation(() => fakeStreamResult())
102
+ })
103
+
104
+ afterAll(() => {
105
+ resetAgentRegistryForTests()
106
+ toolRegistry.clear()
107
+ })
108
+
109
+ it('invokes streamText with the composed system prompt and tools map', async () => {
110
+ registerMcpTool(makeTool({ name: 'customers.list_people' }), { moduleId: 'customers' })
111
+ seedAgentRegistryForTests([
112
+ makeAgent({
113
+ id: 'customers.assistant',
114
+ moduleId: 'customers',
115
+ allowedTools: ['customers.list_people'],
116
+ }),
117
+ ])
118
+
119
+ const response = await runAiAgentText({
120
+ agentId: 'customers.assistant',
121
+ messages: baseMessages as never,
122
+ authContext: baseAuth,
123
+ })
124
+
125
+ expect(response).toBeInstanceOf(Response)
126
+ expect(streamTextMock).toHaveBeenCalledTimes(1)
127
+ const callArg = streamTextMock.mock.calls[0][0] as {
128
+ system: string
129
+ tools: Record<string, unknown>
130
+ messages: unknown
131
+ model: { id: string }
132
+ stopWhen?: unknown
133
+ }
134
+ expect(callArg.system).toBe('System prompt base.')
135
+ expect(Object.keys(callArg.tools)).toEqual(['customers__list_people'])
136
+ // PR #1593 applies a default stopWhen of stepCountIs(10) when maxSteps
137
+ // is undefined so tool-calls actually execute (agent-runtime.ts).
138
+ expect(callArg.stopWhen).toBeDefined()
139
+ expect(callArg.model.id).toBe('provider-default-model')
140
+ expect(convertToModelMessagesMock).toHaveBeenCalledWith(baseMessages)
141
+ })
142
+
143
+ it('propagates maxSteps as stopWhen: stepCountIs(n)', async () => {
144
+ seedAgentRegistryForTests([
145
+ makeAgent({
146
+ id: 'customers.assistant',
147
+ moduleId: 'customers',
148
+ maxSteps: 5,
149
+ }),
150
+ ])
151
+
152
+ await runAiAgentText({
153
+ agentId: 'customers.assistant',
154
+ messages: baseMessages as never,
155
+ authContext: baseAuth,
156
+ })
157
+
158
+ expect(stepCountIsMock).toHaveBeenCalledWith(5)
159
+ const callArg = streamTextMock.mock.calls[0][0] as { stopWhen: unknown }
160
+ expect(callArg.stopWhen).toEqual({ __stopWhen: 'stepCount', count: 5 })
161
+ })
162
+
163
+ it('lets modelOverride win over agent.defaultModel', async () => {
164
+ seedAgentRegistryForTests([
165
+ makeAgent({
166
+ id: 'customers.assistant',
167
+ moduleId: 'customers',
168
+ defaultModel: 'agent-default',
169
+ }),
170
+ ])
171
+
172
+ await runAiAgentText({
173
+ agentId: 'customers.assistant',
174
+ messages: baseMessages as never,
175
+ authContext: baseAuth,
176
+ modelOverride: 'override-model',
177
+ })
178
+
179
+ expect(createModelMock).toHaveBeenCalledWith(
180
+ expect.objectContaining({ modelId: 'override-model' }),
181
+ )
182
+ })
183
+
184
+ it('falls back to agent.defaultModel when no override is given', async () => {
185
+ seedAgentRegistryForTests([
186
+ makeAgent({
187
+ id: 'customers.assistant',
188
+ moduleId: 'customers',
189
+ defaultModel: 'agent-default',
190
+ }),
191
+ ])
192
+
193
+ await runAiAgentText({
194
+ agentId: 'customers.assistant',
195
+ messages: baseMessages as never,
196
+ authContext: baseAuth,
197
+ })
198
+
199
+ expect(createModelMock).toHaveBeenCalledWith(
200
+ expect.objectContaining({ modelId: 'agent-default' }),
201
+ )
202
+ })
203
+
204
+ it('appends resolvePageContext output to the system prompt when entityType+recordId are present', async () => {
205
+ const resolvePageContext = jest.fn(async (_input: AiAgentPageContextInput) => 'Hydrated record context.')
206
+ seedAgentRegistryForTests([
207
+ makeAgent({
208
+ id: 'customers.assistant',
209
+ moduleId: 'customers',
210
+ resolvePageContext,
211
+ }),
212
+ ])
213
+
214
+ await runAiAgentText({
215
+ agentId: 'customers.assistant',
216
+ messages: baseMessages as never,
217
+ authContext: baseAuth,
218
+ pageContext: { entityType: 'customers:person', recordId: 'abc' },
219
+ container: {} as never,
220
+ })
221
+
222
+ expect(resolvePageContext).toHaveBeenCalledTimes(1)
223
+ const callArg = streamTextMock.mock.calls[0][0] as { system: string }
224
+ expect(callArg.system).toBe('System prompt base.\n\nHydrated record context.')
225
+ })
226
+
227
+ it('skips resolvePageContext silently when entityType or recordId are missing', async () => {
228
+ const resolvePageContext = jest.fn(async () => 'should-not-append')
229
+ seedAgentRegistryForTests([
230
+ makeAgent({
231
+ id: 'customers.assistant',
232
+ moduleId: 'customers',
233
+ resolvePageContext,
234
+ }),
235
+ ])
236
+
237
+ await runAiAgentText({
238
+ agentId: 'customers.assistant',
239
+ messages: baseMessages as never,
240
+ authContext: baseAuth,
241
+ pageContext: { pageId: 'customers.people' },
242
+ container: {} as never,
243
+ })
244
+
245
+ expect(resolvePageContext).not.toHaveBeenCalled()
246
+ const callArg = streamTextMock.mock.calls[0][0] as { system: string }
247
+ expect(callArg.system).toBe('System prompt base.')
248
+ })
249
+
250
+ it('does not fail the request if resolvePageContext throws', async () => {
251
+ const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
252
+ const resolvePageContext = jest.fn(async () => {
253
+ throw new Error('boom')
254
+ })
255
+ seedAgentRegistryForTests([
256
+ makeAgent({
257
+ id: 'customers.assistant',
258
+ moduleId: 'customers',
259
+ resolvePageContext,
260
+ }),
261
+ ])
262
+
263
+ const response = await runAiAgentText({
264
+ agentId: 'customers.assistant',
265
+ messages: baseMessages as never,
266
+ authContext: baseAuth,
267
+ pageContext: { entityType: 'customers:person', recordId: 'abc' },
268
+ container: {} as never,
269
+ })
270
+
271
+ expect(response).toBeInstanceOf(Response)
272
+ const callArg = streamTextMock.mock.calls[0][0] as { system: string }
273
+ expect(callArg.system).toBe('System prompt base.')
274
+ errorSpy.mockRestore()
275
+ })
276
+ })
277
+
278
+ describe('composeSystemPrompt', () => {
279
+ it('returns base prompt when resolvePageContext is not declared', async () => {
280
+ const agent: AiAgentDefinition = {
281
+ id: 'x.y',
282
+ moduleId: 'x',
283
+ label: 'x',
284
+ description: 'x',
285
+ systemPrompt: 'base',
286
+ allowedTools: [],
287
+ }
288
+ const result = await composeSystemPrompt(agent, undefined, undefined, null, null)
289
+ expect(result).toBe('base')
290
+ })
291
+ })
@@ -0,0 +1,172 @@
1
+ import { z } from 'zod'
2
+ import type { AiAgentDefinition } from '../ai-agent-definition'
3
+ import type { AiToolDefinition } from '../types'
4
+ import { resolveAiAgentTools, AgentPolicyError } from '../agent-tools'
5
+ import {
6
+ resetAgentRegistryForTests,
7
+ seedAgentRegistryForTests,
8
+ } from '../agent-registry'
9
+ import { toolRegistry, registerMcpTool } from '../tool-registry'
10
+
11
+ function makeAgent(
12
+ overrides: Partial<AiAgentDefinition> & Pick<AiAgentDefinition, 'id' | 'moduleId'>,
13
+ ): AiAgentDefinition {
14
+ return {
15
+ label: `${overrides.id} label`,
16
+ description: `${overrides.id} description`,
17
+ systemPrompt: 'You are a test agent.',
18
+ allowedTools: [],
19
+ ...overrides,
20
+ }
21
+ }
22
+
23
+ function makeTool(
24
+ overrides: Partial<AiToolDefinition> & Pick<AiToolDefinition, 'name'>,
25
+ ): AiToolDefinition {
26
+ return {
27
+ description: `${overrides.name} description`,
28
+ inputSchema: z.object({ query: z.string().optional() }),
29
+ handler: async () => ({ ok: true }),
30
+ ...overrides,
31
+ }
32
+ }
33
+
34
+ const baseAuth = {
35
+ tenantId: 'tenant-1',
36
+ organizationId: 'org-1',
37
+ userId: 'user-1',
38
+ features: ['*'],
39
+ isSuperAdmin: true,
40
+ }
41
+
42
+ describe('resolveAiAgentTools', () => {
43
+ let warnSpy: jest.SpyInstance
44
+
45
+ beforeEach(() => {
46
+ resetAgentRegistryForTests()
47
+ toolRegistry.clear()
48
+ warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {})
49
+ })
50
+
51
+ afterEach(() => {
52
+ warnSpy.mockRestore()
53
+ })
54
+
55
+ afterAll(() => {
56
+ resetAgentRegistryForTests()
57
+ toolRegistry.clear()
58
+ })
59
+
60
+ it('throws AgentPolicyError with structured deny code when the agent is unknown', async () => {
61
+ await expect(
62
+ resolveAiAgentTools({
63
+ agentId: 'missing.agent',
64
+ authContext: baseAuth,
65
+ }),
66
+ ).rejects.toMatchObject({
67
+ name: 'AgentPolicyError',
68
+ code: 'agent_unknown',
69
+ })
70
+ })
71
+
72
+ it('throws AgentPolicyError when the agent requires features the caller lacks', async () => {
73
+ seedAgentRegistryForTests([
74
+ makeAgent({
75
+ id: 'customers.assistant',
76
+ moduleId: 'customers',
77
+ requiredFeatures: ['customers.assistant.use'],
78
+ }),
79
+ ])
80
+
81
+ await expect(
82
+ resolveAiAgentTools({
83
+ agentId: 'customers.assistant',
84
+ authContext: { ...baseAuth, features: [], isSuperAdmin: false },
85
+ }),
86
+ ).rejects.toBeInstanceOf(AgentPolicyError)
87
+ })
88
+
89
+ it('returns whitelisted tools adapted to the AI SDK shape', async () => {
90
+ registerMcpTool(makeTool({ name: 'customers.list_people' }), { moduleId: 'customers' })
91
+ registerMcpTool(makeTool({ name: 'customers.get_person' }), { moduleId: 'customers' })
92
+ seedAgentRegistryForTests([
93
+ makeAgent({
94
+ id: 'customers.assistant',
95
+ moduleId: 'customers',
96
+ allowedTools: ['customers.list_people', 'customers.get_person'],
97
+ }),
98
+ ])
99
+
100
+ const result = await resolveAiAgentTools({
101
+ agentId: 'customers.assistant',
102
+ authContext: baseAuth,
103
+ })
104
+
105
+ expect(result.agent.id).toBe('customers.assistant')
106
+ expect(Object.keys(result.tools).sort()).toEqual([
107
+ 'customers__get_person',
108
+ 'customers__list_people',
109
+ ])
110
+ for (const [, tool] of Object.entries(result.tools)) {
111
+ expect(tool).toBeDefined()
112
+ expect(typeof (tool as { execute?: unknown }).execute).toBe('function')
113
+ }
114
+ })
115
+
116
+ it('skips tools the caller lacks features for and still returns the rest', async () => {
117
+ registerMcpTool(
118
+ makeTool({
119
+ name: 'customers.list_people',
120
+ requiredFeatures: ['customers.people.view'],
121
+ }),
122
+ { moduleId: 'customers' },
123
+ )
124
+ registerMcpTool(
125
+ makeTool({
126
+ name: 'catalog.list_products',
127
+ requiredFeatures: ['catalog.products.view'],
128
+ }),
129
+ { moduleId: 'catalog' },
130
+ )
131
+ seedAgentRegistryForTests([
132
+ makeAgent({
133
+ id: 'customers.assistant',
134
+ moduleId: 'customers',
135
+ allowedTools: ['customers.list_people', 'catalog.list_products'],
136
+ }),
137
+ ])
138
+
139
+ const result = await resolveAiAgentTools({
140
+ agentId: 'customers.assistant',
141
+ authContext: {
142
+ ...baseAuth,
143
+ features: ['customers.people.view'],
144
+ isSuperAdmin: false,
145
+ },
146
+ })
147
+
148
+ expect(Object.keys(result.tools)).toEqual(['customers__list_people'])
149
+ expect(warnSpy).toHaveBeenCalledWith(
150
+ expect.stringContaining('catalog.list_products'),
151
+ )
152
+ })
153
+
154
+ it('skips a whitelisted tool that vanished from the registry between checks', async () => {
155
+ seedAgentRegistryForTests([
156
+ makeAgent({
157
+ id: 'customers.assistant',
158
+ moduleId: 'customers',
159
+ allowedTools: ['customers.list_people'],
160
+ }),
161
+ ])
162
+
163
+ const result = await resolveAiAgentTools({
164
+ agentId: 'customers.assistant',
165
+ authContext: baseAuth,
166
+ })
167
+
168
+ // Tool never registered -> policy gate returns tool_unknown -> warn + skip.
169
+ expect(result.tools).toEqual({})
170
+ expect(warnSpy).toHaveBeenCalled()
171
+ })
172
+ })
@@ -0,0 +1,41 @@
1
+ import { createAiAgentTransport } from '../agent-transport'
2
+
3
+ describe('createAiAgentTransport', () => {
4
+ it('points at the default ai_assistant dispatcher with the agent query param', () => {
5
+ const transport = createAiAgentTransport({ agentId: 'customers.assistant' })
6
+ // ChatTransport keeps the api URL as a protected field — access it for test assertions.
7
+ const apiUrl = (transport as unknown as { api: string }).api
8
+ expect(apiUrl).toBe('/api/ai_assistant/ai/chat?agent=customers.assistant')
9
+ })
10
+
11
+ it('honors a custom endpoint override', () => {
12
+ const transport = createAiAgentTransport({
13
+ agentId: 'catalog.merchandising_assistant',
14
+ endpoint: '/custom/chat',
15
+ })
16
+ const apiUrl = (transport as unknown as { api: string }).api
17
+ expect(apiUrl).toBe('/custom/chat?agent=catalog.merchandising_assistant')
18
+ })
19
+
20
+ it('merges extra body fields and surfaces the debug flag when provided', () => {
21
+ const transport = createAiAgentTransport({
22
+ agentId: 'customers.assistant',
23
+ body: { pageContext: { pageId: 'customers.people' } },
24
+ debug: true,
25
+ })
26
+ const body = (transport as unknown as { body: Record<string, unknown> }).body
27
+ expect(body).toEqual({
28
+ pageContext: { pageId: 'customers.people' },
29
+ debug: true,
30
+ })
31
+ })
32
+
33
+ it('preserves the agent query when the endpoint already contains a query string', () => {
34
+ const transport = createAiAgentTransport({
35
+ agentId: 'customers.assistant',
36
+ endpoint: '/api/ai/chat?trace=1',
37
+ })
38
+ const apiUrl = (transport as unknown as { api: string }).api
39
+ expect(apiUrl).toBe('/api/ai/chat?trace=1&agent=customers.assistant')
40
+ })
41
+ })
@@ -0,0 +1,183 @@
1
+ import { z } from 'zod'
2
+ import {
3
+ defineAiAgent,
4
+ defineAiAgentExtension,
5
+ type AiAgentDefinition,
6
+ } from '../ai-agent-definition'
7
+ import { defineAiTool } from '../ai-tool-definition'
8
+ import type { AiToolDefinition, McpToolDefinition } from '../types'
9
+
10
+ describe('defineAiTool', () => {
11
+ it('returns the tool definition unchanged (identity builder)', () => {
12
+ const tool = defineAiTool({
13
+ name: 'catalog.search_products',
14
+ description: 'Search the product catalog',
15
+ inputSchema: z.object({ query: z.string() }),
16
+ handler: async (input) => ({ matches: [input.query] }),
17
+ })
18
+ expect(tool.name).toBe('catalog.search_products')
19
+ expect(tool.description).toBe('Search the product catalog')
20
+ expect(typeof tool.handler).toBe('function')
21
+ })
22
+
23
+ it('preserves additive focused-agent metadata on AiToolDefinition', () => {
24
+ const tool = defineAiTool({
25
+ name: 'catalog.update_product',
26
+ description: 'Update a product',
27
+ inputSchema: z.object({ id: z.string() }),
28
+ requiredFeatures: ['catalog.products.update'],
29
+ handler: async (input) => ({ ok: true, id: input.id }),
30
+ displayName: 'Update product',
31
+ tags: ['write', 'catalog'],
32
+ isMutation: true,
33
+ maxCallsPerTurn: 1,
34
+ supportsAttachments: true,
35
+ })
36
+ expect(tool.displayName).toBe('Update product')
37
+ expect(tool.tags).toEqual(['write', 'catalog'])
38
+ expect(tool.isMutation).toBe(true)
39
+ expect(tool.maxCallsPerTurn).toBe(1)
40
+ expect(tool.supportsAttachments).toBe(true)
41
+ })
42
+
43
+ it('returns an object assignable to AiToolDefinition and McpToolDefinition (BC)', () => {
44
+ const built = defineAiTool({
45
+ name: 'meta.ping',
46
+ description: 'Ping',
47
+ inputSchema: z.object({}),
48
+ handler: async () => ({ pong: true }),
49
+ })
50
+ const asAi: AiToolDefinition = built
51
+ const asMcp: McpToolDefinition = built
52
+ expect(asAi.name).toBe('meta.ping')
53
+ expect(asMcp.name).toBe('meta.ping')
54
+ })
55
+
56
+ it('plain-object AiToolDefinition authored without defineAiTool() still type-checks', () => {
57
+ const plain: AiToolDefinition<{ id: string }, { ok: boolean }> = {
58
+ name: 'customers.get',
59
+ description: 'Fetch a customer',
60
+ inputSchema: z.object({ id: z.string() }),
61
+ handler: async () => ({ ok: true }),
62
+ }
63
+ expect(plain.name).toBe('customers.get')
64
+ })
65
+ })
66
+
67
+ describe('defineAiAgentExtension', () => {
68
+ it('returns the extension definition unchanged (identity builder)', () => {
69
+ const extension = defineAiAgentExtension({
70
+ targetAgentId: 'catalog.catalog_assistant',
71
+ replaceAllowedTools: ['catalog.list_products'],
72
+ deleteAllowedTools: ['catalog.old_tool'],
73
+ appendAllowedTools: ['example.catalog_stats'],
74
+ replaceSystemPrompt: 'Replacement prompt.',
75
+ appendSystemPrompt: 'Use example.catalog_stats for app-level catalog metrics.',
76
+ replaceSuggestions: [
77
+ { label: 'Start fresh', prompt: 'Start fresh' },
78
+ ],
79
+ deleteSuggestions: ['Old prompt'],
80
+ appendSuggestions: [
81
+ { label: 'Show catalog stats', prompt: 'Show catalog stats' },
82
+ ],
83
+ })
84
+
85
+ expect(extension.targetAgentId).toBe('catalog.catalog_assistant')
86
+ expect(extension.replaceAllowedTools).toEqual(['catalog.list_products'])
87
+ expect(extension.deleteAllowedTools).toEqual(['catalog.old_tool'])
88
+ expect(extension.appendAllowedTools).toEqual(['example.catalog_stats'])
89
+ expect(extension.replaceSystemPrompt).toBe('Replacement prompt.')
90
+ expect(extension.deleteSuggestions).toEqual(['Old prompt'])
91
+ expect(extension.appendSuggestions).toEqual([
92
+ { label: 'Show catalog stats', prompt: 'Show catalog stats' },
93
+ ])
94
+ })
95
+ })
96
+
97
+ describe('defineAiAgent', () => {
98
+ it('returns the agent definition unchanged (identity builder)', () => {
99
+ const agent = defineAiAgent({
100
+ id: 'catalog.merchandising_assistant',
101
+ moduleId: 'catalog',
102
+ label: 'Merchandising assistant',
103
+ description: 'Draft product descriptions and extract attributes',
104
+ systemPrompt: 'You are a merchandising assistant.',
105
+ allowedTools: ['catalog.search_products', 'catalog.get_product'],
106
+ })
107
+ expect(agent.id).toBe('catalog.merchandising_assistant')
108
+ expect(agent.moduleId).toBe('catalog')
109
+ expect(agent.allowedTools).toHaveLength(2)
110
+ })
111
+
112
+ it('accepts every optional spec field', () => {
113
+ const resolvePageContext = jest.fn<
114
+ Promise<string | null>,
115
+ [
116
+ Parameters<NonNullable<AiAgentDefinition['resolvePageContext']>>[0],
117
+ ]
118
+ >(async () => 'context string')
119
+
120
+ const agent = defineAiAgent({
121
+ id: 'catalog.demo',
122
+ moduleId: 'catalog',
123
+ label: 'Demo',
124
+ description: 'Demo agent with all optional fields set',
125
+ systemPrompt: 'prompt',
126
+ allowedTools: ['catalog.search_products'],
127
+ executionMode: 'chat',
128
+ defaultModel: 'gpt-4o',
129
+ acceptedMediaTypes: ['image', 'pdf', 'file'],
130
+ requiredFeatures: ['catalog.products.view'],
131
+ uiParts: ['mutation-preview-card'],
132
+ readOnly: true,
133
+ mutationPolicy: 'read-only',
134
+ maxSteps: 12,
135
+ output: {
136
+ schemaName: 'ProductBrief',
137
+ schema: z.object({ name: z.string() }),
138
+ mode: 'generate',
139
+ },
140
+ resolvePageContext,
141
+ keywords: ['catalog', 'merchandising'],
142
+ suggestions: [
143
+ { label: 'Show catalog stats', prompt: 'Show catalog stats' },
144
+ ],
145
+ domain: 'catalog',
146
+ dataCapabilities: {
147
+ entities: ['catalog.product'],
148
+ operations: ['read', 'search'],
149
+ searchableFields: ['name', 'sku'],
150
+ },
151
+ })
152
+
153
+ expect(agent.executionMode).toBe('chat')
154
+ expect(agent.mutationPolicy).toBe('read-only')
155
+ expect(agent.maxSteps).toBe(12)
156
+ expect(agent.output?.schemaName).toBe('ProductBrief')
157
+ expect(agent.output?.mode).toBe('generate')
158
+ expect(agent.dataCapabilities?.operations).toEqual(['read', 'search'])
159
+ expect(agent.keywords).toEqual(['catalog', 'merchandising'])
160
+ expect(agent.suggestions).toEqual([
161
+ { label: 'Show catalog stats', prompt: 'Show catalog stats' },
162
+ ])
163
+ expect(agent.domain).toBe('catalog')
164
+ expect(agent.acceptedMediaTypes).toEqual(['image', 'pdf', 'file'])
165
+ expect(agent.requiredFeatures).toEqual(['catalog.products.view'])
166
+ expect(agent.uiParts).toEqual(['mutation-preview-card'])
167
+ expect(agent.readOnly).toBe(true)
168
+ expect(agent.defaultModel).toBe('gpt-4o')
169
+ expect(resolvePageContext).not.toHaveBeenCalled()
170
+ })
171
+
172
+ it('enforces the structural shape at the type level (compile-time contract)', () => {
173
+ const minimal: AiAgentDefinition = {
174
+ id: 'mod.agent',
175
+ moduleId: 'mod',
176
+ label: 'l',
177
+ description: 'd',
178
+ systemPrompt: 'p',
179
+ allowedTools: [],
180
+ }
181
+ expect(minimal.allowedTools).toEqual([])
182
+ })
183
+ })