@indexnetwork/protocol 0.1.0

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 (365) hide show
  1. package/dist/agents/chat.agent.d.ts +218 -0
  2. package/dist/agents/chat.agent.d.ts.map +1 -0
  3. package/dist/agents/chat.agent.js +884 -0
  4. package/dist/agents/chat.agent.js.map +1 -0
  5. package/dist/agents/chat.prompt.d.ts +18 -0
  6. package/dist/agents/chat.prompt.d.ts.map +1 -0
  7. package/dist/agents/chat.prompt.js +372 -0
  8. package/dist/agents/chat.prompt.js.map +1 -0
  9. package/dist/agents/chat.prompt.modules.d.ts +61 -0
  10. package/dist/agents/chat.prompt.modules.d.ts.map +1 -0
  11. package/dist/agents/chat.prompt.modules.js +366 -0
  12. package/dist/agents/chat.prompt.modules.js.map +1 -0
  13. package/dist/agents/chat.title.generator.d.ts +20 -0
  14. package/dist/agents/chat.title.generator.d.ts.map +1 -0
  15. package/dist/agents/chat.title.generator.js +66 -0
  16. package/dist/agents/chat.title.generator.js.map +1 -0
  17. package/dist/agents/home.categorizer.d.ts +28 -0
  18. package/dist/agents/home.categorizer.d.ts.map +1 -0
  19. package/dist/agents/home.categorizer.js +170 -0
  20. package/dist/agents/home.categorizer.js.map +1 -0
  21. package/dist/agents/hyde.generator.d.ts +27 -0
  22. package/dist/agents/hyde.generator.d.ts.map +1 -0
  23. package/dist/agents/hyde.generator.js +75 -0
  24. package/dist/agents/hyde.generator.js.map +1 -0
  25. package/dist/agents/hyde.strategies.d.ts +17 -0
  26. package/dist/agents/hyde.strategies.d.ts.map +1 -0
  27. package/dist/agents/hyde.strategies.js +29 -0
  28. package/dist/agents/hyde.strategies.js.map +1 -0
  29. package/dist/agents/intent.clarifier.d.ts +29 -0
  30. package/dist/agents/intent.clarifier.d.ts.map +1 -0
  31. package/dist/agents/intent.clarifier.js +186 -0
  32. package/dist/agents/intent.clarifier.js.map +1 -0
  33. package/dist/agents/intent.indexer.d.ts +77 -0
  34. package/dist/agents/intent.indexer.d.ts.map +1 -0
  35. package/dist/agents/intent.indexer.js +164 -0
  36. package/dist/agents/intent.indexer.js.map +1 -0
  37. package/dist/agents/intent.inferrer.d.ts +95 -0
  38. package/dist/agents/intent.inferrer.d.ts.map +1 -0
  39. package/dist/agents/intent.inferrer.js +238 -0
  40. package/dist/agents/intent.inferrer.js.map +1 -0
  41. package/dist/agents/intent.reconciler.d.ts +106 -0
  42. package/dist/agents/intent.reconciler.d.ts.map +1 -0
  43. package/dist/agents/intent.reconciler.js +184 -0
  44. package/dist/agents/intent.reconciler.js.map +1 -0
  45. package/dist/agents/intent.verifier.d.ts +97 -0
  46. package/dist/agents/intent.verifier.d.ts.map +1 -0
  47. package/dist/agents/intent.verifier.js +234 -0
  48. package/dist/agents/intent.verifier.js.map +1 -0
  49. package/dist/agents/invite.generator.d.ts +47 -0
  50. package/dist/agents/invite.generator.d.ts.map +1 -0
  51. package/dist/agents/invite.generator.js +56 -0
  52. package/dist/agents/invite.generator.js.map +1 -0
  53. package/dist/agents/lens.inferrer.d.ts +37 -0
  54. package/dist/agents/lens.inferrer.d.ts.map +1 -0
  55. package/dist/agents/lens.inferrer.js +98 -0
  56. package/dist/agents/lens.inferrer.js.map +1 -0
  57. package/dist/agents/model.config.d.ts +120 -0
  58. package/dist/agents/model.config.d.ts.map +1 -0
  59. package/dist/agents/model.config.js +76 -0
  60. package/dist/agents/model.config.js.map +1 -0
  61. package/dist/agents/negotiation.insights.generator.d.ts +32 -0
  62. package/dist/agents/negotiation.insights.generator.d.ts.map +1 -0
  63. package/dist/agents/negotiation.insights.generator.js +105 -0
  64. package/dist/agents/negotiation.insights.generator.js.map +1 -0
  65. package/dist/agents/negotiation.proposer.d.ts +26 -0
  66. package/dist/agents/negotiation.proposer.d.ts.map +1 -0
  67. package/dist/agents/negotiation.proposer.js +67 -0
  68. package/dist/agents/negotiation.proposer.js.map +1 -0
  69. package/dist/agents/negotiation.responder.d.ts +26 -0
  70. package/dist/agents/negotiation.responder.d.ts.map +1 -0
  71. package/dist/agents/negotiation.responder.js +71 -0
  72. package/dist/agents/negotiation.responder.js.map +1 -0
  73. package/dist/agents/opportunity.evaluator.d.ts +253 -0
  74. package/dist/agents/opportunity.evaluator.d.ts.map +1 -0
  75. package/dist/agents/opportunity.evaluator.js +413 -0
  76. package/dist/agents/opportunity.evaluator.js.map +1 -0
  77. package/dist/agents/opportunity.presenter.d.ts +115 -0
  78. package/dist/agents/opportunity.presenter.d.ts.map +1 -0
  79. package/dist/agents/opportunity.presenter.js +524 -0
  80. package/dist/agents/opportunity.presenter.js.map +1 -0
  81. package/dist/agents/profile.generator.d.ts +67 -0
  82. package/dist/agents/profile.generator.d.ts.map +1 -0
  83. package/dist/agents/profile.generator.js +97 -0
  84. package/dist/agents/profile.generator.js.map +1 -0
  85. package/dist/agents/profile.hyde.generator.d.ts +43 -0
  86. package/dist/agents/profile.hyde.generator.d.ts.map +1 -0
  87. package/dist/agents/profile.hyde.generator.js +113 -0
  88. package/dist/agents/profile.hyde.generator.js.map +1 -0
  89. package/dist/agents/suggestion.generator.d.ts +24 -0
  90. package/dist/agents/suggestion.generator.d.ts.map +1 -0
  91. package/dist/agents/suggestion.generator.js +96 -0
  92. package/dist/agents/suggestion.generator.js.map +1 -0
  93. package/dist/graphs/chat.graph.d.ts +312 -0
  94. package/dist/graphs/chat.graph.d.ts.map +1 -0
  95. package/dist/graphs/chat.graph.js +267 -0
  96. package/dist/graphs/chat.graph.js.map +1 -0
  97. package/dist/graphs/home.graph.d.ts +180 -0
  98. package/dist/graphs/home.graph.d.ts.map +1 -0
  99. package/dist/graphs/home.graph.js +598 -0
  100. package/dist/graphs/home.graph.js.map +1 -0
  101. package/dist/graphs/hyde.graph.d.ts +110 -0
  102. package/dist/graphs/hyde.graph.d.ts.map +1 -0
  103. package/dist/graphs/hyde.graph.js +235 -0
  104. package/dist/graphs/hyde.graph.js.map +1 -0
  105. package/dist/graphs/index.graph.d.ts +620 -0
  106. package/dist/graphs/index.graph.d.ts.map +1 -0
  107. package/dist/graphs/index.graph.js +226 -0
  108. package/dist/graphs/index.graph.js.map +1 -0
  109. package/dist/graphs/index_membership.graph.d.ts +250 -0
  110. package/dist/graphs/index_membership.graph.d.ts.map +1 -0
  111. package/dist/graphs/index_membership.graph.js +204 -0
  112. package/dist/graphs/index_membership.graph.js.map +1 -0
  113. package/dist/graphs/intent.graph.d.ts +490 -0
  114. package/dist/graphs/intent.graph.d.ts.map +1 -0
  115. package/dist/graphs/intent.graph.js +787 -0
  116. package/dist/graphs/intent.graph.js.map +1 -0
  117. package/dist/graphs/intent_index.graph.d.ts +396 -0
  118. package/dist/graphs/intent_index.graph.d.ts.map +1 -0
  119. package/dist/graphs/intent_index.graph.js +331 -0
  120. package/dist/graphs/intent_index.graph.js.map +1 -0
  121. package/dist/graphs/maintenance.graph.d.ts +177 -0
  122. package/dist/graphs/maintenance.graph.d.ts.map +1 -0
  123. package/dist/graphs/maintenance.graph.js +173 -0
  124. package/dist/graphs/maintenance.graph.js.map +1 -0
  125. package/dist/graphs/negotiation.graph.d.ts +819 -0
  126. package/dist/graphs/negotiation.graph.d.ts.map +1 -0
  127. package/dist/graphs/negotiation.graph.js +255 -0
  128. package/dist/graphs/negotiation.graph.js.map +1 -0
  129. package/dist/graphs/opportunity.graph.d.ts +1082 -0
  130. package/dist/graphs/opportunity.graph.d.ts.map +1 -0
  131. package/dist/graphs/opportunity.graph.js +2534 -0
  132. package/dist/graphs/opportunity.graph.js.map +1 -0
  133. package/dist/graphs/profile.graph.d.ts +617 -0
  134. package/dist/graphs/profile.graph.d.ts.map +1 -0
  135. package/dist/graphs/profile.graph.js +839 -0
  136. package/dist/graphs/profile.graph.js.map +1 -0
  137. package/dist/graphs/tests/chat.graph.mocks.d.ts +104 -0
  138. package/dist/graphs/tests/chat.graph.mocks.d.ts.map +1 -0
  139. package/dist/graphs/tests/chat.graph.mocks.js +225 -0
  140. package/dist/graphs/tests/chat.graph.mocks.js.map +1 -0
  141. package/dist/index.d.ts +62 -0
  142. package/dist/index.d.ts.map +1 -0
  143. package/dist/index.js +44 -0
  144. package/dist/index.js.map +1 -0
  145. package/dist/interfaces/auth.interface.d.ts +15 -0
  146. package/dist/interfaces/auth.interface.d.ts.map +1 -0
  147. package/dist/interfaces/auth.interface.js +2 -0
  148. package/dist/interfaces/auth.interface.js.map +1 -0
  149. package/dist/interfaces/cache.interface.d.ts +43 -0
  150. package/dist/interfaces/cache.interface.d.ts.map +1 -0
  151. package/dist/interfaces/cache.interface.js +6 -0
  152. package/dist/interfaces/cache.interface.js.map +1 -0
  153. package/dist/interfaces/chat-session.interface.d.ts +11 -0
  154. package/dist/interfaces/chat-session.interface.d.ts.map +1 -0
  155. package/dist/interfaces/chat-session.interface.js +2 -0
  156. package/dist/interfaces/chat-session.interface.js.map +1 -0
  157. package/dist/interfaces/contact.interface.d.ts +48 -0
  158. package/dist/interfaces/contact.interface.d.ts.map +1 -0
  159. package/dist/interfaces/contact.interface.js +2 -0
  160. package/dist/interfaces/contact.interface.js.map +1 -0
  161. package/dist/interfaces/database.interface.d.ts +1495 -0
  162. package/dist/interfaces/database.interface.d.ts.map +1 -0
  163. package/dist/interfaces/database.interface.js +2 -0
  164. package/dist/interfaces/database.interface.js.map +1 -0
  165. package/dist/interfaces/embedder.interface.d.ts +85 -0
  166. package/dist/interfaces/embedder.interface.d.ts.map +1 -0
  167. package/dist/interfaces/embedder.interface.js +5 -0
  168. package/dist/interfaces/embedder.interface.js.map +1 -0
  169. package/dist/interfaces/enrichment.interface.d.ts +40 -0
  170. package/dist/interfaces/enrichment.interface.d.ts.map +1 -0
  171. package/dist/interfaces/enrichment.interface.js +2 -0
  172. package/dist/interfaces/enrichment.interface.js.map +1 -0
  173. package/dist/interfaces/integration.interface.d.ts +91 -0
  174. package/dist/interfaces/integration.interface.d.ts.map +1 -0
  175. package/dist/interfaces/integration.interface.js +2 -0
  176. package/dist/interfaces/integration.interface.js.map +1 -0
  177. package/dist/interfaces/queue.interface.d.ts +17 -0
  178. package/dist/interfaces/queue.interface.d.ts.map +1 -0
  179. package/dist/interfaces/queue.interface.js +5 -0
  180. package/dist/interfaces/queue.interface.js.map +1 -0
  181. package/dist/interfaces/scraper.interface.d.ts +31 -0
  182. package/dist/interfaces/scraper.interface.d.ts.map +1 -0
  183. package/dist/interfaces/scraper.interface.js +2 -0
  184. package/dist/interfaces/scraper.interface.js.map +1 -0
  185. package/dist/interfaces/storage.interface.d.ts +46 -0
  186. package/dist/interfaces/storage.interface.d.ts.map +1 -0
  187. package/dist/interfaces/storage.interface.js +6 -0
  188. package/dist/interfaces/storage.interface.js.map +1 -0
  189. package/dist/mcp/mcp.server.d.ts +29 -0
  190. package/dist/mcp/mcp.server.d.ts.map +1 -0
  191. package/dist/mcp/mcp.server.js +171 -0
  192. package/dist/mcp/mcp.server.js.map +1 -0
  193. package/dist/states/chat.state.d.ts +126 -0
  194. package/dist/states/chat.state.d.ts.map +1 -0
  195. package/dist/states/chat.state.js +112 -0
  196. package/dist/states/chat.state.js.map +1 -0
  197. package/dist/states/home.state.d.ts +100 -0
  198. package/dist/states/home.state.d.ts.map +1 -0
  199. package/dist/states/home.state.js +74 -0
  200. package/dist/states/home.state.js.map +1 -0
  201. package/dist/states/hyde.state.d.ts +54 -0
  202. package/dist/states/hyde.state.d.ts.map +1 -0
  203. package/dist/states/hyde.state.js +66 -0
  204. package/dist/states/hyde.state.js.map +1 -0
  205. package/dist/states/index.state.d.ts +179 -0
  206. package/dist/states/index.state.d.ts.map +1 -0
  207. package/dist/states/index.state.js +56 -0
  208. package/dist/states/index.state.js.map +1 -0
  209. package/dist/states/index_membership.state.d.ts +77 -0
  210. package/dist/states/index_membership.state.d.ts.map +1 -0
  211. package/dist/states/index_membership.state.js +43 -0
  212. package/dist/states/index_membership.state.js.map +1 -0
  213. package/dist/states/intent.state.d.ts +203 -0
  214. package/dist/states/intent.state.d.ts.map +1 -0
  215. package/dist/states/intent.state.js +153 -0
  216. package/dist/states/intent.state.js.map +1 -0
  217. package/dist/states/intent_index.state.d.ts +148 -0
  218. package/dist/states/intent_index.state.d.ts.map +1 -0
  219. package/dist/states/intent_index.state.js +100 -0
  220. package/dist/states/intent_index.state.js.map +1 -0
  221. package/dist/states/maintenance.state.d.ts +36 -0
  222. package/dist/states/maintenance.state.d.ts.map +1 -0
  223. package/dist/states/maintenance.state.js +56 -0
  224. package/dist/states/maintenance.state.js.map +1 -0
  225. package/dist/states/negotiation.state.d.ts +230 -0
  226. package/dist/states/negotiation.state.d.ts.map +1 -0
  227. package/dist/states/negotiation.state.js +82 -0
  228. package/dist/states/negotiation.state.js.map +1 -0
  229. package/dist/states/opportunity.state.d.ts +300 -0
  230. package/dist/states/opportunity.state.d.ts.map +1 -0
  231. package/dist/states/opportunity.state.js +207 -0
  232. package/dist/states/opportunity.state.js.map +1 -0
  233. package/dist/states/profile.state.d.ts +172 -0
  234. package/dist/states/profile.state.d.ts.map +1 -0
  235. package/dist/states/profile.state.js +133 -0
  236. package/dist/states/profile.state.js.map +1 -0
  237. package/dist/streamers/chat.streamer.d.ts +55 -0
  238. package/dist/streamers/chat.streamer.d.ts.map +1 -0
  239. package/dist/streamers/chat.streamer.js +186 -0
  240. package/dist/streamers/chat.streamer.js.map +1 -0
  241. package/dist/streamers/index.d.ts +3 -0
  242. package/dist/streamers/index.d.ts.map +1 -0
  243. package/dist/streamers/index.js +3 -0
  244. package/dist/streamers/index.js.map +1 -0
  245. package/dist/streamers/response.streamer.d.ts +36 -0
  246. package/dist/streamers/response.streamer.d.ts.map +1 -0
  247. package/dist/streamers/response.streamer.js +46 -0
  248. package/dist/streamers/response.streamer.js.map +1 -0
  249. package/dist/support/chat.utils.d.ts +42 -0
  250. package/dist/support/chat.utils.d.ts.map +1 -0
  251. package/dist/support/chat.utils.js +89 -0
  252. package/dist/support/chat.utils.js.map +1 -0
  253. package/dist/support/debug-meta.sanitizer.d.ts +18 -0
  254. package/dist/support/debug-meta.sanitizer.d.ts.map +1 -0
  255. package/dist/support/debug-meta.sanitizer.js +82 -0
  256. package/dist/support/debug-meta.sanitizer.js.map +1 -0
  257. package/dist/support/feed.health.d.ts +32 -0
  258. package/dist/support/feed.health.d.ts.map +1 -0
  259. package/dist/support/feed.health.js +76 -0
  260. package/dist/support/feed.health.js.map +1 -0
  261. package/dist/support/introducer.discovery.d.ts +78 -0
  262. package/dist/support/introducer.discovery.d.ts.map +1 -0
  263. package/dist/support/introducer.discovery.js +101 -0
  264. package/dist/support/introducer.discovery.js.map +1 -0
  265. package/dist/support/log.d.ts +65 -0
  266. package/dist/support/log.d.ts.map +1 -0
  267. package/dist/support/log.js +76 -0
  268. package/dist/support/log.js.map +1 -0
  269. package/dist/support/lucide.icon-catalog.d.ts +22 -0
  270. package/dist/support/lucide.icon-catalog.d.ts.map +1 -0
  271. package/dist/support/lucide.icon-catalog.js +101 -0
  272. package/dist/support/lucide.icon-catalog.js.map +1 -0
  273. package/dist/support/opportunity.card-text.d.ts +39 -0
  274. package/dist/support/opportunity.card-text.d.ts.map +1 -0
  275. package/dist/support/opportunity.card-text.js +333 -0
  276. package/dist/support/opportunity.card-text.js.map +1 -0
  277. package/dist/support/opportunity.constants.d.ts +9 -0
  278. package/dist/support/opportunity.constants.d.ts.map +1 -0
  279. package/dist/support/opportunity.constants.js +11 -0
  280. package/dist/support/opportunity.constants.js.map +1 -0
  281. package/dist/support/opportunity.discover.d.ts +144 -0
  282. package/dist/support/opportunity.discover.d.ts.map +1 -0
  283. package/dist/support/opportunity.discover.js +610 -0
  284. package/dist/support/opportunity.discover.js.map +1 -0
  285. package/dist/support/opportunity.enricher.d.ts +44 -0
  286. package/dist/support/opportunity.enricher.d.ts.map +1 -0
  287. package/dist/support/opportunity.enricher.js +245 -0
  288. package/dist/support/opportunity.enricher.js.map +1 -0
  289. package/dist/support/opportunity.persist.d.ts +39 -0
  290. package/dist/support/opportunity.persist.d.ts.map +1 -0
  291. package/dist/support/opportunity.persist.js +63 -0
  292. package/dist/support/opportunity.persist.js.map +1 -0
  293. package/dist/support/opportunity.presentation.d.ts +21 -0
  294. package/dist/support/opportunity.presentation.d.ts.map +1 -0
  295. package/dist/support/opportunity.presentation.js +75 -0
  296. package/dist/support/opportunity.presentation.js.map +1 -0
  297. package/dist/support/opportunity.sanitize.d.ts +18 -0
  298. package/dist/support/opportunity.sanitize.d.ts.map +1 -0
  299. package/dist/support/opportunity.sanitize.js +89 -0
  300. package/dist/support/opportunity.sanitize.js.map +1 -0
  301. package/dist/support/opportunity.utils.d.ts +99 -0
  302. package/dist/support/opportunity.utils.d.ts.map +1 -0
  303. package/dist/support/opportunity.utils.js +184 -0
  304. package/dist/support/opportunity.utils.js.map +1 -0
  305. package/dist/support/performance.d.ts +19 -0
  306. package/dist/support/performance.d.ts.map +1 -0
  307. package/dist/support/performance.js +43 -0
  308. package/dist/support/performance.js.map +1 -0
  309. package/dist/support/profile.enrichment-display-name.d.ts +16 -0
  310. package/dist/support/profile.enrichment-display-name.d.ts.map +1 -0
  311. package/dist/support/profile.enrichment-display-name.js +22 -0
  312. package/dist/support/profile.enrichment-display-name.js.map +1 -0
  313. package/dist/support/protocol.logger.d.ts +22 -0
  314. package/dist/support/protocol.logger.d.ts.map +1 -0
  315. package/dist/support/protocol.logger.js +44 -0
  316. package/dist/support/protocol.logger.js.map +1 -0
  317. package/dist/support/request-context.d.ts +19 -0
  318. package/dist/support/request-context.d.ts.map +1 -0
  319. package/dist/support/request-context.js +7 -0
  320. package/dist/support/request-context.js.map +1 -0
  321. package/dist/tools/contact.tools.d.ts +7 -0
  322. package/dist/tools/contact.tools.d.ts.map +1 -0
  323. package/dist/tools/contact.tools.js +115 -0
  324. package/dist/tools/contact.tools.js.map +1 -0
  325. package/dist/tools/index.d.ts +17 -0
  326. package/dist/tools/index.d.ts.map +1 -0
  327. package/dist/tools/index.js +140 -0
  328. package/dist/tools/index.js.map +1 -0
  329. package/dist/tools/index.tools.d.ts +3 -0
  330. package/dist/tools/index.tools.d.ts.map +1 -0
  331. package/dist/tools/index.tools.js +423 -0
  332. package/dist/tools/index.tools.js.map +1 -0
  333. package/dist/tools/integration.tools.d.ts +13 -0
  334. package/dist/tools/integration.tools.d.ts.map +1 -0
  335. package/dist/tools/integration.tools.js +77 -0
  336. package/dist/tools/integration.tools.js.map +1 -0
  337. package/dist/tools/intent.tools.d.ts +3 -0
  338. package/dist/tools/intent.tools.d.ts.map +1 -0
  339. package/dist/tools/intent.tools.js +458 -0
  340. package/dist/tools/intent.tools.js.map +1 -0
  341. package/dist/tools/opportunity.tools.d.ts +44 -0
  342. package/dist/tools/opportunity.tools.d.ts.map +1 -0
  343. package/dist/tools/opportunity.tools.js +814 -0
  344. package/dist/tools/opportunity.tools.js.map +1 -0
  345. package/dist/tools/profile.tools.d.ts +3 -0
  346. package/dist/tools/profile.tools.d.ts.map +1 -0
  347. package/dist/tools/profile.tools.js +513 -0
  348. package/dist/tools/profile.tools.js.map +1 -0
  349. package/dist/tools/tool.helpers.d.ts +225 -0
  350. package/dist/tools/tool.helpers.d.ts.map +1 -0
  351. package/dist/tools/tool.helpers.js +172 -0
  352. package/dist/tools/tool.helpers.js.map +1 -0
  353. package/dist/tools/tool.registry.d.ts +12 -0
  354. package/dist/tools/tool.registry.d.ts.map +1 -0
  355. package/dist/tools/tool.registry.js +62 -0
  356. package/dist/tools/tool.registry.js.map +1 -0
  357. package/dist/tools/utility.tools.d.ts +3 -0
  358. package/dist/tools/utility.tools.d.ts.map +1 -0
  359. package/dist/tools/utility.tools.js +107 -0
  360. package/dist/tools/utility.tools.js.map +1 -0
  361. package/dist/types/chat-streaming.types.d.ts +472 -0
  362. package/dist/types/chat-streaming.types.d.ts.map +1 -0
  363. package/dist/types/chat-streaming.types.js +260 -0
  364. package/dist/types/chat-streaming.types.js.map +1 -0
  365. package/package.json +32 -0
@@ -0,0 +1,225 @@
1
+ import { z } from "zod";
2
+ import type { ModelConfig } from "../agents/model.config.js";
3
+ import type { ProfileDocument } from "../agents/profile.generator.js";
4
+ import type { ChatGraphCompositeDatabase, IndexMembership, UserRecord, UserDatabase, SystemDatabase, NegotiationDatabase } from "../interfaces/database.interface.js";
5
+ import type { Scraper } from "../interfaces/scraper.interface.js";
6
+ import type { Cache, HydeCache } from "../interfaces/cache.interface.js";
7
+ import type { CompiledOpportunityGraph } from "../support/opportunity.discover.js";
8
+ import type { IntegrationAdapter } from "../interfaces/integration.interface.js";
9
+ import type { ContactServiceAdapter } from "../interfaces/contact.interface.js";
10
+ import type { ProfileEnricher } from "../interfaces/enrichment.interface.js";
11
+ import type { IntentGraphQueue } from "../interfaces/queue.interface.js";
12
+ import type { ChatSessionReader } from "../interfaces/chat-session.interface.js";
13
+ import type { Embedder } from "../interfaces/embedder.interface.js";
14
+ /** Profile without embedding — used in resolved context to avoid bloating prompts and memory. */
15
+ export type ProfileContext = Omit<ProfileDocument, "embedding"> | null;
16
+ /** Minimal interface for an invokable compiled LangGraph. */
17
+ export type CompiledGraph = {
18
+ invoke: (input: any) => Promise<any>;
19
+ };
20
+ /**
21
+ * Resolved context available to every tool handler.
22
+ * Contains the current user and optional index identity, resolved from DB at init.
23
+ * The LLM can see this context (via system prompt) but cannot change it.
24
+ */
25
+ export interface ResolvedToolContext {
26
+ userId: string;
27
+ userName: string;
28
+ userEmail: string;
29
+ indexId?: string;
30
+ indexName?: string;
31
+ /** True when chat is index-scoped and the user owns the index. */
32
+ isOwner?: boolean;
33
+ user: UserRecord;
34
+ userProfile: ProfileContext;
35
+ userIndexes: IndexMembership[];
36
+ scopedIndex?: {
37
+ id: string;
38
+ title: string;
39
+ prompt: string | null;
40
+ };
41
+ scopedMembershipRole?: "owner" | "member";
42
+ /** True when user has not completed onboarding (onboarding.completedAt is null). */
43
+ isOnboarding: boolean;
44
+ /** True when the user has a non-empty name. */
45
+ hasName: boolean;
46
+ /** Chat session ID when tools are used in a chat; used for draft opportunities (context.conversationId). */
47
+ sessionId?: string;
48
+ }
49
+ /**
50
+ * Dependencies passed when creating tools for a user session.
51
+ * Includes DB adapters, embedder, and scraper.
52
+ *
53
+ * Note: userDb and systemDb are optional inputs - if not provided, createChatTools
54
+ * will create them internally from the chatDatabaseAdapter singleton.
55
+ */
56
+ export interface ToolContext {
57
+ userId: string;
58
+ /** @deprecated Use userDb or systemDb instead. Kept for backwards compatibility. */
59
+ database: ChatGraphCompositeDatabase;
60
+ /** Context-bound database for accessing the authenticated user's own resources. Created internally if not provided. */
61
+ userDb?: UserDatabase;
62
+ /** Context-bound database for LLM/system operations on cross-user resources within shared indexes. Created internally if not provided. */
63
+ systemDb?: SystemDatabase;
64
+ embedder: Embedder;
65
+ scraper: Scraper;
66
+ /** When set, chat is scoped to this index; tools use it as default for read_intents and create_intent. */
67
+ indexId?: string;
68
+ /** Chat session ID when creating tools for a chat; enables draft opportunities with context.conversationId. */
69
+ sessionId?: string;
70
+ /** General-purpose cache (e.g. for tool results). */
71
+ cache: Cache;
72
+ /** Dedicated cache for HyDE graph (may be same instance as cache). */
73
+ hydeCache: HydeCache;
74
+ /** External integration platform adapter (OAuth, tool actions). */
75
+ integration: IntegrationAdapter;
76
+ /** Queue for enqueuing follow-up intent processing (HyDE generation/deletion). */
77
+ intentQueue: IntentGraphQueue;
78
+ /** Contact management operations. */
79
+ contactService: ContactServiceAdapter;
80
+ /** Chat session reader for loading conversation history. */
81
+ chatSession: ChatSessionReader;
82
+ /** Profile enrichment from external data sources. */
83
+ enricher: ProfileEnricher;
84
+ /** Database adapter for negotiation/conversation operations. */
85
+ negotiationDatabase: NegotiationDatabase;
86
+ /** Integration importer for bulk contact import from toolkits. */
87
+ integrationImporter: {
88
+ importContacts(userId: string, toolkit: string): Promise<{
89
+ imported: number;
90
+ skipped: number;
91
+ newContacts: number;
92
+ existingContacts: number;
93
+ }>;
94
+ };
95
+ /** Factory for user-scoped database access. */
96
+ createUserDatabase: (db: ChatGraphCompositeDatabase, userId: string) => UserDatabase;
97
+ /** Factory for system-scoped database access. */
98
+ createSystemDatabase: (db: ChatGraphCompositeDatabase, userId: string, indexScope: string[], embedder?: Embedder) => SystemDatabase;
99
+ /** Optional runtime LLM config. Pass to override env vars for API key, model, etc. */
100
+ modelConfig?: ModelConfig;
101
+ }
102
+ /**
103
+ * All external dependencies needed to initialize the protocol tool engine.
104
+ * The host application (composition root) must provide concrete implementations.
105
+ * This is the subset of ToolContext that is NOT per-request (no userId, indexId, sessionId).
106
+ */
107
+ export type ProtocolDeps = Omit<ToolContext, 'userId' | 'indexId' | 'sessionId' | 'userDb' | 'systemDb'>;
108
+ /**
109
+ * Thrown when a requested chat scope is invalid for the authenticated user.
110
+ * Controllers can map this to an HTTP status code.
111
+ */
112
+ export declare class ChatContextAccessError extends Error {
113
+ readonly statusCode: number;
114
+ readonly code: "USER_NOT_FOUND" | "INDEX_NOT_FOUND" | "INDEX_MEMBERSHIP_REQUIRED";
115
+ constructor(message: string, statusCode: number, code: "USER_NOT_FOUND" | "INDEX_NOT_FOUND" | "INDEX_MEMBERSHIP_REQUIRED");
116
+ }
117
+ /**
118
+ * Resolve the canonical context used by chat tools and system prompt.
119
+ * This preloads user identity, profile, index memberships, and scoped index role.
120
+ */
121
+ export declare function resolveChatContext(params: {
122
+ database: Pick<ChatGraphCompositeDatabase, "getUser" | "getProfile" | "getIndexMemberships" | "getIndexMembership" | "getIndex" | "isIndexOwner" | "isIndexMember">;
123
+ userId: string;
124
+ indexId?: string;
125
+ /** Chat session ID for draft opportunities (stored as context.conversationId). */
126
+ sessionId?: string;
127
+ }): Promise<ResolvedToolContext>;
128
+ /**
129
+ * Type for the `defineTool` closure created in `createChatTools`.
130
+ * Auto-injects resolved context and provides uniform logging / error handling.
131
+ */
132
+ export type DefineTool = <T extends z.ZodType>(opts: {
133
+ name: string;
134
+ description: string;
135
+ querySchema: T;
136
+ handler: (input: {
137
+ context: ResolvedToolContext;
138
+ query: z.infer<T>;
139
+ }) => Promise<string>;
140
+ }) => any;
141
+ /**
142
+ * A raw tool definition before LangChain wrapping.
143
+ * Used by the tool registry for direct HTTP invocation.
144
+ */
145
+ export interface RawToolDefinition {
146
+ name: string;
147
+ description: string;
148
+ schema: z.ZodType;
149
+ handler: (input: {
150
+ context: ResolvedToolContext;
151
+ query: unknown;
152
+ }) => Promise<string>;
153
+ }
154
+ /**
155
+ * Registry mapping tool names to their raw definitions.
156
+ */
157
+ export type ToolRegistry = Map<string, RawToolDefinition>;
158
+ /**
159
+ * Shared dependencies available to all tool domain factories.
160
+ * Passed by `createChatTools` after compiling all subgraphs.
161
+ */
162
+ export interface ToolDeps {
163
+ /** @deprecated Use userDb or systemDb instead. Kept for backwards compatibility. */
164
+ database: ChatGraphCompositeDatabase;
165
+ /** Context-bound database for accessing the authenticated user's own resources. */
166
+ userDb: UserDatabase;
167
+ /** Context-bound database for LLM/system operations on cross-user resources within shared indexes. */
168
+ systemDb: SystemDatabase;
169
+ scraper: Scraper;
170
+ embedder: import('../interfaces/embedder.interface.js').Embedder;
171
+ cache: Cache;
172
+ integration: IntegrationAdapter;
173
+ contactService: ContactServiceAdapter;
174
+ integrationImporter: {
175
+ importContacts(userId: string, toolkit: string): Promise<{
176
+ imported: number;
177
+ skipped: number;
178
+ newContacts: number;
179
+ existingContacts: number;
180
+ }>;
181
+ };
182
+ enricher: ProfileEnricher;
183
+ graphs: {
184
+ profile: CompiledGraph;
185
+ intent: CompiledGraph;
186
+ index: CompiledGraph;
187
+ indexMembership: CompiledGraph;
188
+ intentIndex: CompiledGraph;
189
+ opportunity: CompiledOpportunityGraph;
190
+ };
191
+ }
192
+ export declare function success<T>(data: T): string;
193
+ export declare function error(message: string, debugSteps?: Array<{
194
+ step: string;
195
+ detail?: string;
196
+ data?: Record<string, unknown>;
197
+ }>): string;
198
+ /** Return needsClarification for missing required fields. */
199
+ export declare function needsClarification(params: {
200
+ missingFields: string[];
201
+ message: string;
202
+ }): string;
203
+ /** UUID v4 format: 8-4-4-4-12 hex chars (e.g. c2505011-2e45-426e-81dd-b9abb9b72023) */
204
+ export declare const UUID_REGEX: RegExp;
205
+ /**
206
+ * Resolves an array of index IDs to their display titles.
207
+ * Skips any IDs that don't resolve (deleted or invalid indexes).
208
+ */
209
+ export declare function resolveIndexNames(database: {
210
+ getIndex(id: string): Promise<{
211
+ id: string;
212
+ title: string;
213
+ } | null>;
214
+ }, indexIds: string[]): Promise<string[]>;
215
+ /**
216
+ * Normalize a URL string: if it lacks a protocol, prepend "https://".
217
+ * Returns the normalized URL or null if the result is not a valid URL.
218
+ */
219
+ export declare function normalizeUrl(raw: string): string | null;
220
+ /**
221
+ * Extract unique, valid URLs from a string (e.g. user message or details).
222
+ * Handles both full URLs (https://...) and bare domains (github.com/...).
223
+ */
224
+ export declare function extractUrls(text: string): string[];
225
+ //# sourceMappingURL=tool.helpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool.helpers.d.ts","sourceRoot":"","sources":["../../src/tools/tool.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,KAAK,EACV,0BAA0B,EAC1B,eAAe,EACf,UAAU,EACV,YAAY,EACZ,cAAc,EACd,mBAAmB,EACpB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,oCAAoC,CAAC;AAClE,OAAO,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kCAAkC,CAAC;AACzE,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AACnF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oCAAoC,CAAC;AAChF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAC7E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AACzE,OAAO,KAAK,EAA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,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAAE,CAAC,GACpF,MAAM,CAMR;AAED,6DAA6D;AAC7D,wBAAgB,kBAAkB,CAAC,MAAM,EAAE;IACzC,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,OAAO,EAAE,MAAM,CAAC;CACjB,GAAG,MAAM,CAMT;AAgBD,uFAAuF;AACvF,eAAO,MAAM,UAAU,QAAoE,CAAC;AAE5F;;;GAGG;AACH,wBAAsB,iBAAiB,CACrC,QAAQ,EAAE;IAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC,CAAA;CAAE,EACjF,QAAQ,EAAE,MAAM,EAAE,GACjB,OAAO,CAAC,MAAM,EAAE,CAAC,CAMnB;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAWvD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CA2BlD"}
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Thrown when a requested chat scope is invalid for the authenticated user.
3
+ * Controllers can map this to an HTTP status code.
4
+ */
5
+ export class ChatContextAccessError extends Error {
6
+ constructor(message, statusCode, code) {
7
+ super(message);
8
+ this.statusCode = statusCode;
9
+ this.code = code;
10
+ this.name = "ChatContextAccessError";
11
+ }
12
+ }
13
+ /**
14
+ * Resolve the canonical context used by chat tools and system prompt.
15
+ * This preloads user identity, profile, index memberships, and scoped index role.
16
+ */
17
+ export async function resolveChatContext(params) {
18
+ const { database, userId, indexId, sessionId } = params;
19
+ const [user, rawProfile, userIndexes] = await Promise.all([
20
+ database.getUser(userId),
21
+ database.getProfile(userId),
22
+ database.getIndexMemberships(userId),
23
+ ]);
24
+ // Omit embedding from profile so resolved context stays lean (embedding is for search only).
25
+ let userProfile = null;
26
+ if (rawProfile) {
27
+ const { embedding: _omit, ...rest } = rawProfile;
28
+ userProfile = rest;
29
+ }
30
+ if (!user) {
31
+ throw new ChatContextAccessError("User not found", 404, "USER_NOT_FOUND");
32
+ }
33
+ let scopedIndex = undefined;
34
+ let scopedMembershipRole = undefined;
35
+ let isOwner = false;
36
+ let indexName;
37
+ if (indexId) {
38
+ const [index, isMember, owner] = await Promise.all([
39
+ database.getIndex(indexId),
40
+ database.isIndexMember(indexId, userId),
41
+ database.isIndexOwner(indexId, userId),
42
+ ]);
43
+ if (!index) {
44
+ throw new ChatContextAccessError("Index not found", 404, "INDEX_NOT_FOUND");
45
+ }
46
+ if (!isMember) {
47
+ throw new ChatContextAccessError("You are not a member of this index", 403, "INDEX_MEMBERSHIP_REQUIRED");
48
+ }
49
+ let membership = userIndexes.find((m) => m.indexId === index.id);
50
+ if (membership === undefined) {
51
+ membership = (await database.getIndexMembership(index.id, userId)) ?? undefined;
52
+ }
53
+ scopedIndex = {
54
+ id: index.id,
55
+ title: index.title,
56
+ prompt: membership?.indexPrompt ?? null,
57
+ };
58
+ isOwner = owner;
59
+ indexName = index.title;
60
+ scopedMembershipRole = owner ? "owner" : "member";
61
+ }
62
+ const userName = user.name ?? "Unknown";
63
+ const userEmail = user.email ?? "";
64
+ const hasName = !!user.name?.trim();
65
+ return {
66
+ userId,
67
+ userName,
68
+ userEmail,
69
+ indexId,
70
+ indexName,
71
+ isOwner,
72
+ user,
73
+ userProfile,
74
+ userIndexes,
75
+ scopedIndex,
76
+ scopedMembershipRole,
77
+ isOnboarding: !(user.onboarding?.completedAt),
78
+ hasName,
79
+ ...(sessionId !== undefined ? { sessionId } : {}),
80
+ };
81
+ }
82
+ // ═══════════════════════════════════════════════════════════════════════════════
83
+ // TOOL RESULT HELPERS
84
+ // ═══════════════════════════════════════════════════════════════════════════════
85
+ export function success(data) {
86
+ return JSON.stringify({ success: true, data });
87
+ }
88
+ export function error(message, debugSteps) {
89
+ return JSON.stringify({
90
+ success: false,
91
+ error: message,
92
+ ...(debugSteps?.length ? { debugSteps } : {}),
93
+ });
94
+ }
95
+ /** Return needsClarification for missing required fields. */
96
+ export function needsClarification(params) {
97
+ return JSON.stringify({
98
+ success: false,
99
+ needsClarification: true,
100
+ ...params,
101
+ });
102
+ }
103
+ // ═══════════════════════════════════════════════════════════════════════════════
104
+ // CONSTANTS & UTILITIES
105
+ // ═══════════════════════════════════════════════════════════════════════════════
106
+ /** Matches http/https URLs in text; captures full URL. */
107
+ const URL_IN_TEXT_REGEX = /https?:\/\/[^\s"'<>)\]]+/gi;
108
+ /**
109
+ * Matches bare domain URLs without protocol (e.g. github.com/foo, www.example.com).
110
+ * Requires at least a SLD.TLD pattern followed by optional path.
111
+ * Negative lookbehind ensures we don't double-match URLs already caught by URL_IN_TEXT_REGEX.
112
+ */
113
+ const BARE_URL_REGEX = /(?<!\w:\/\/)(?<![/\w])(?:www\.)?[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.(?:com|org|net|io|dev|co|ai|app|xyz|me|info|gg|so|sh|cc|ly|fm|tv|to|tech|design|network|world|edu|gov|mil|int|us|uk|eu|de|fr|ca|au|jp|cn|in|br|nl|se|no|fi|dk|ch|at|be|it|es|pt|pl|cz|ru|kr|tw|hk|sg|nz|za|mx|ar|cl|id|ph|th|vn|my|ie)(?:\/[^\s"'<>)\]]*)?/gi;
114
+ /** UUID v4 format: 8-4-4-4-12 hex chars (e.g. c2505011-2e45-426e-81dd-b9abb9b72023) */
115
+ export const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
116
+ /**
117
+ * Resolves an array of index IDs to their display titles.
118
+ * Skips any IDs that don't resolve (deleted or invalid indexes).
119
+ */
120
+ export async function resolveIndexNames(database, indexIds) {
121
+ if (indexIds.length === 0)
122
+ return [];
123
+ const results = await Promise.all(indexIds.map(id => database.getIndex(id)));
124
+ return results.filter(Boolean).map(idx => idx.title);
125
+ }
126
+ /**
127
+ * Normalize a URL string: if it lacks a protocol, prepend "https://".
128
+ * Returns the normalized URL or null if the result is not a valid URL.
129
+ */
130
+ export function normalizeUrl(raw) {
131
+ let url = raw.replace(/[.,;:!?)]+$/, "").trim();
132
+ if (!/^https?:\/\//i.test(url)) {
133
+ url = `https://${url}`;
134
+ }
135
+ try {
136
+ new URL(url);
137
+ return url;
138
+ }
139
+ catch {
140
+ return null;
141
+ }
142
+ }
143
+ /**
144
+ * Extract unique, valid URLs from a string (e.g. user message or details).
145
+ * Handles both full URLs (https://...) and bare domains (github.com/...).
146
+ */
147
+ export function extractUrls(text) {
148
+ if (!text || typeof text !== "string")
149
+ return [];
150
+ const seen = new Set();
151
+ const out = [];
152
+ // Pass 1: full protocol URLs
153
+ const fullMatches = text.match(URL_IN_TEXT_REGEX) ?? [];
154
+ for (const raw of fullMatches) {
155
+ const url = normalizeUrl(raw);
156
+ if (url && !seen.has(url)) {
157
+ seen.add(url);
158
+ out.push(url);
159
+ }
160
+ }
161
+ // Pass 2: bare domain URLs (e.g. github.com/foo)
162
+ const bareMatches = text.match(BARE_URL_REGEX) ?? [];
163
+ for (const raw of bareMatches) {
164
+ const url = normalizeUrl(raw);
165
+ if (url && !seen.has(url)) {
166
+ seen.add(url);
167
+ out.push(url);
168
+ }
169
+ }
170
+ return out;
171
+ }
172
+ //# sourceMappingURL=tool.helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool.helpers.js","sourceRoot":"","sources":["../../src/tools/tool.helpers.ts"],"names":[],"mappings":"AAoIA;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,KAAK;IAC/C,YACE,OAAe,EACC,UAAkB,EAClB,IAAwE;QAExF,KAAK,CAAC,OAAO,CAAC,CAAC;QAHC,eAAU,GAAV,UAAU,CAAQ;QAClB,SAAI,GAAJ,IAAI,CAAoE;QAGxF,IAAI,CA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;IAED,iDAAiD;IACjD,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC;IACrD,KAAK,MAAM,GAAG,IAAI,WAAW,EAAE,CAAC;QAC9B,MAAM,GAAG,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC;QAC9B,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YAC1B,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACd,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAChB,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -0,0 +1,12 @@
1
+ import type { ToolDeps, ToolRegistry } from './tool.helpers.js';
2
+ /**
3
+ * Creates a tool registry containing all tool handlers indexed by name.
4
+ * Handlers are raw async functions (not LangChain tool() wrappers) that
5
+ * accept { context, query } and return a JSON string.
6
+ *
7
+ * @param deps - Shared tool dependencies (graphs, database, embedder, etc.)
8
+ * @param context - Resolved user context for this request.
9
+ * @returns Map of tool name to raw tool definition.
10
+ */
11
+ export declare function createToolRegistry(deps: ToolDeps): ToolRegistry;
12
+ //# sourceMappingURL=tool.registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool.registry.d.ts","sourceRoot":"","sources":["../../src/tools/tool.registry.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAmC,QAAQ,EAAqB,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAapH;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,QAAQ,GAAG,YAAY,CAkD/D"}
@@ -0,0 +1,62 @@
1
+ import { createProfileTools } from './profile.tools.js';
2
+ import { createIntentTools } from './intent.tools.js';
3
+ import { createIndexTools } from './index.tools.js';
4
+ import { createOpportunityTools } from './opportunity.tools.js';
5
+ import { createUtilityTools } from './utility.tools.js';
6
+ import { createIntegrationTools } from './integration.tools.js';
7
+ import { createContactTools } from './contact.tools.js';
8
+ import { protocolLogger } from '../support/protocol.logger.js';
9
+ import { error } from './tool.helpers.js';
10
+ const logger = protocolLogger('ToolRegistry');
11
+ /**
12
+ * Creates a tool registry containing all tool handlers indexed by name.
13
+ * Handlers are raw async functions (not LangChain tool() wrappers) that
14
+ * accept { context, query } and return a JSON string.
15
+ *
16
+ * @param deps - Shared tool dependencies (graphs, database, embedder, etc.)
17
+ * @param context - Resolved user context for this request.
18
+ * @returns Map of tool name to raw tool definition.
19
+ */
20
+ export function createToolRegistry(deps) {
21
+ const registry = new Map();
22
+ // defineTool that captures raw handlers into the registry
23
+ function defineTool(opts) {
24
+ const entry = {
25
+ name: opts.name,
26
+ description: opts.description,
27
+ schema: opts.querySchema,
28
+ handler: async (input) => {
29
+ logger.verbose(`Tool: ${opts.name}`, {
30
+ context: { userId: input.context.userId, indexId: input.context.indexId },
31
+ query: input.query,
32
+ });
33
+ try {
34
+ return await opts.handler({ context: input.context, query: input.query });
35
+ }
36
+ catch (err) {
37
+ logger.error(`${opts.name} failed`, {
38
+ error: err instanceof Error ? err.message : String(err),
39
+ });
40
+ return error(`Failed to execute ${opts.name}: ${err instanceof Error ? err.message : String(err)}`);
41
+ }
42
+ },
43
+ };
44
+ registry.set(opts.name, entry);
45
+ // Return a dummy — create*Tools functions collect return values into arrays,
46
+ // but for the registry path we only need the side-effect on the Map.
47
+ return null;
48
+ }
49
+ // Create all tool domains -- each one calls defineTool() which populates the registry.
50
+ // The local defineTool is compatible with DefineTool (which returns any).
51
+ const dt = defineTool;
52
+ createProfileTools(dt, deps);
53
+ createIntentTools(dt, deps);
54
+ createIndexTools(dt, deps);
55
+ createOpportunityTools(dt, deps);
56
+ createUtilityTools(dt, deps);
57
+ createIntegrationTools(dt, deps);
58
+ createContactTools(dt, deps);
59
+ logger.verbose(`Tool registry created with ${registry.size} tools`);
60
+ return registry;
61
+ }
62
+ //# sourceMappingURL=tool.registry.js.map
@@ -0,0 +1 @@
1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AAClB,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { DefineTool, ToolDeps } from "./tool.helpers.js";
2
+ export declare function createUtilityTools(defineTool: DefineTool, deps: ToolDeps): readonly [any, any];
3
+ //# sourceMappingURL=utility.tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utility.tools.d.ts","sourceRoot":"","sources":["../../src/tools/utility.tools.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAG9D,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,uBAuHxE"}
@@ -0,0 +1,107 @@
1
+ import { z } from "zod";
2
+ import { success, error, normalizeUrl } from "./tool.helpers.js";
3
+ export function createUtilityTools(defineTool, deps) {
4
+ const { scraper } = deps;
5
+ const scrapeUrl = defineTool({
6
+ name: "scrape_url",
7
+ description: "Extracts text content from a URL (articles, profiles, documentation, etc.). Use this to read web pages, LinkedIn/GitHub profiles, or any public web content. The URL does not need http:// or https:// — bare domains like github.com/user/repo work fine. Pass 'objective' when you know the downstream use: e.g. 'User wants to create an intent from this link (project/repo).' or 'User wants to update their profile from this page.' — this returns content better suited for that use.",
8
+ querySchema: z.object({
9
+ url: z.string().describe("The URL to scrape (protocol optional — e.g. 'github.com/user/repo' is fine)"),
10
+ objective: z.string().optional().describe("Optional: why we're scraping. E.g. 'User wants to create an intent from this link' or 'User wants to update their profile from this page'. Omit for generic extraction."),
11
+ }),
12
+ handler: async ({ context: _context, query }) => {
13
+ const normalizedUrl = normalizeUrl(query.url);
14
+ if (!normalizedUrl) {
15
+ return error("Invalid URL format. Please provide a valid URL (e.g. 'github.com/user/repo' or 'https://example.com').");
16
+ }
17
+ const content = await scraper.extractUrlContent(normalizedUrl, {
18
+ objective: query.objective?.trim() || undefined,
19
+ });
20
+ if (!content) {
21
+ return error("Couldn't extract content from that URL. It may be blocked, require login, or have no extractable text.");
22
+ }
23
+ const truncatedContent = content.length > 10000
24
+ ? content.substring(0, 10000) + "\n\n[Content truncated...]"
25
+ : content;
26
+ return success({
27
+ url: normalizedUrl,
28
+ contentLength: content.length,
29
+ content: truncatedContent,
30
+ });
31
+ },
32
+ });
33
+ const readDocs = defineTool({
34
+ name: "read_docs",
35
+ description: "Returns the protocol's business logic documentation: entity model, intent lifecycle, opportunity lifecycle, discovery mechanics, and key workflows. Call this when you need to understand how the system works or explain it to the user.",
36
+ querySchema: z.object({
37
+ topic: z.string().optional().describe("Optional: narrow to a specific topic (e.g. 'opportunities', 'intents', 'indexes', 'profiles', 'discovery')."),
38
+ }),
39
+ handler: async ({ context: _context, query }) => {
40
+ const topic = query.topic?.trim().toLowerCase();
41
+ const sections = {
42
+ entities: `## Entity Model
43
+
44
+ - **Users**: People on the platform. Authenticated via session (Better Auth).
45
+ - **Profiles**: A user's identity — bio, skills, interests, location, social links. Generated from account data or social URLs. Has a vector embedding for semantic matching.
46
+ - **Indexes**: Communities or groups. Each has a title, optional prompt (purpose description), and a join policy (anyone or invite_only). Users join indexes as members; the creator is the owner.
47
+ - **Index Members**: Junction between Users and Indexes. Tracks permissions, join date, auto-assign setting, and optional member prompt.
48
+ - **Intents**: What a user is looking for — wants, needs, and priorities. Each has a description (payload), summary, confidence score, and vector embedding. Intents belong to a user but are linked to indexes via IntentIndexes (many-to-many).
49
+ - **IntentIndexes**: Junction between Intents and Indexes. An intent can be in multiple indexes. When an intent is created, it is evaluated against index prompts and linked to relevant ones.
50
+ - **Opportunities**: Discovered connections between users based on intent overlap. Have roles (introducer, patient, agent, peer), status lifecycle, reasoning, and presentation data.
51
+ - **HyDE Documents**: Hypothetical Document Embeddings — generated synthetic documents used for semantic retrieval of intents and profiles`,
52
+ intents: `## Intent Lifecycle
53
+
54
+ 1. **Creation**: User describes what they're looking for. The IntentClarifier checks if it's specific enough — vague intents get a refinement suggestion before persisting.
55
+ 2. **Inference**: The intent graph extracts structured intents from free text. It can infer multiple intents from a single input and reconcile with existing ones (update if similar, create if new).
56
+ 3. **Semantic Governance**: Each intent gets a confidence score, semantic entropy measure, speech act type (commissive, directive, assertive), referential anchor, and felicity conditions (sincerity, authority).
57
+ 4. **Index Assignment**: After creation, the intent is evaluated against all indexes the user belongs to (using the index prompt as criteria). It's automatically linked to matching indexes via IntentIndexes.
58
+ 5. **Discovery**: Creating an intent triggers background opportunity detection — the system looks for other users in shared indexes whose intents complement this one.
59
+ 6. **Update/Archive**: Intents can be updated (re-processed through the graph) or archived (soft delete).`,
60
+ opportunities: `## Opportunity Lifecycle
61
+
62
+ 1. **Detection**: The opportunity graph finds users whose intents semantically complement each other within shared indexes. Uses HyDE embeddings for retrieval and an evaluator agent for scoring.
63
+ 2. **Roles**: Each opportunity assigns roles — introducer (who triggered it), patient (seeker), agent (helper), or peer (mutual). The current user's role determines what they see.
64
+ 3. **Status Flow**: latent (draft) → pending (sent) → accepted/rejected/expired. Users see "draft", "sent", "connected" in natural language.
65
+ 4. **Visibility**: Role-based. The introducer sees the draft first. After sending, the next person in the reveal chain sees it. Not all parties see all details at every stage.
66
+ 5. **Presentation**: Each opportunity gets a personalized summary, suggested action, and reasoning — generated by an LLM presenter agent.
67
+ 6. **Two Modes**:
68
+ - **Discovery**: System finds matches for the user's intents in an index (or all indexes). Triggered by create_intent or create_opportunities with searchQuery.
69
+ - **Introduction**: A user introduces two specific people. The system gathers both profiles and intents from shared indexes and creates the opportunity.`,
70
+ indexes: `## Index Mechanics
71
+
72
+ - Indexes are communities where members share what they're looking for.
73
+ - Each index has a **prompt** that describes its purpose (e.g. "AI/ML co-founders in Berlin"). This prompt is used by the intent indexer agent to evaluate whether an intent belongs.
74
+ - **Join policy**: "anyone" (open) or "invite_only" (owner adds members).
75
+ - Members can see all intents in the index (not just their own).
76
+ - The **auto-assign** setting on a membership means new intents by that user are automatically evaluated against the index.
77
+ - Index owners can update settings, add/remove members, and delete the index (if sole member).`,
78
+ profiles: `## Profile System
79
+
80
+ - Profiles are auto-generated from user account data (name, email, social links).
81
+ - Can be enriched by scraping LinkedIn, GitHub, Twitter, or personal websites.
82
+ - The profile graph generates a structured identity (bio, skills, interests, location), narrative context, and attributes.
83
+ - Profiles have vector embeddings used for semantic matching in opportunity detection.
84
+ - HyDE (Hypothetical Document Embedding) generates synthetic documents from profiles for better retrieval: Mirror (self-description), Reciprocal (what they'd look for), and Neighborhood (related community context).`,
85
+ discovery: `## Discovery Mechanics
86
+
87
+ - Discovery runs when an intent is created (automatic) or when create_opportunities is called explicitly.
88
+ - The opportunity graph pipeline: Preparation (gather context) → Scope (determine indexes) → Discovery (semantic matching of intents) → Evaluation (LLM scores relevance) → Ranking → Persist.
89
+ - Semantic matching uses HyDE embeddings to find candidate intents that complement the source intent.
90
+ - The evaluator agent scores each match on relevance, complementarity, and actionability.
91
+ - Results are persisted as opportunities with appropriate roles and presentation.
92
+ - Background processing: after intent creation, a queue job continues looking for matches asynchronously.`,
93
+ };
94
+ if (topic) {
95
+ const matched = Object.entries(sections).find(([key]) => key.includes(topic) || topic.includes(key));
96
+ if (matched) {
97
+ return success({ topic: matched[0], content: matched[1] });
98
+ }
99
+ // If topic not found, return all
100
+ }
101
+ const fullDoc = Object.values(sections).join("\n\n");
102
+ return success({ content: fullDoc });
103
+ },
104
+ });
105
+ return [scrapeUrl, readDocs];
106
+ }
107
+ //# sourceMappingURL=utility.tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utility.tools.js","sourceRoot":"","sources":["../../src/tools/utility.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjE,MAAM,UAAU,kBAAkB,CAAC,UAAsB,EAAE,IAAc;IACvE,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAEzB,MAAM,SAAS,GAAG,UAAU,CAAC;QAC3B,IAAI,EAAE,YAAY;QAClB,WAAW,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