@indexnetwork/protocol 6.12.0-rc.403.1 → 6.13.22-rc.405.1

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 (1180) hide show
  1. package/CHANGELOG.md +241 -0
  2. package/IMPLEMENTATION.md +20 -0
  3. package/STABILITY.md +4 -0
  4. package/dist/agent/agent.tools.d.ts +11 -3
  5. package/dist/agent/agent.tools.js +11 -301
  6. package/dist/capabilities/communities.facade.d.ts +13 -0
  7. package/dist/capabilities/communities.facade.js +12 -0
  8. package/dist/capabilities/communities.tools.port.d.ts +5 -0
  9. package/dist/capabilities/communities.tools.port.js +1 -0
  10. package/dist/capabilities/contacts.facade.d.ts +9 -0
  11. package/dist/capabilities/contacts.facade.js +8 -0
  12. package/dist/capabilities/contacts.tools.port.d.ts +9 -0
  13. package/dist/capabilities/contacts.tools.port.js +1 -0
  14. package/dist/capabilities/integrations.facade.d.ts +8 -0
  15. package/dist/capabilities/integrations.facade.js +7 -0
  16. package/dist/capabilities/integrations.tools.port.d.ts +9 -0
  17. package/dist/capabilities/integrations.tools.port.js +1 -0
  18. package/dist/capabilities/interaction-composition.facade.d.ts +10 -0
  19. package/dist/capabilities/interaction-composition.facade.js +9 -0
  20. package/dist/capabilities/negotiation.discovery.facade.d.ts +9 -0
  21. package/dist/capabilities/negotiation.discovery.facade.js +7 -0
  22. package/dist/capabilities/negotiation.facade.d.ts +23 -0
  23. package/dist/capabilities/negotiation.facade.js +17 -0
  24. package/dist/capabilities/negotiation.memory.facade.d.ts +6 -0
  25. package/dist/capabilities/negotiation.memory.facade.js +5 -0
  26. package/dist/capabilities/negotiation.questions.facade.d.ts +6 -0
  27. package/dist/capabilities/negotiation.questions.facade.js +5 -0
  28. package/dist/capabilities/negotiation.state.facade.d.ts +5 -0
  29. package/dist/capabilities/negotiation.state.facade.js +1 -0
  30. package/dist/capabilities/negotiation.summary.facade.d.ts +5 -0
  31. package/dist/capabilities/negotiation.summary.facade.js +5 -0
  32. package/dist/capabilities/negotiation.tools.port.d.ts +5 -0
  33. package/dist/capabilities/negotiation.tools.port.js +1 -0
  34. package/dist/capabilities/opportunities.facade.d.ts +50 -0
  35. package/dist/capabilities/opportunities.facade.js +50 -0
  36. package/dist/capabilities/opportunities.safety.facade.d.ts +2 -0
  37. package/dist/capabilities/opportunities.safety.facade.js +2 -0
  38. package/dist/capabilities/opportunities.tools.port.d.ts +5 -0
  39. package/dist/capabilities/opportunities.tools.port.js +1 -0
  40. package/dist/capabilities/participant-agents.debug.facade.d.ts +2 -0
  41. package/dist/capabilities/participant-agents.debug.facade.js +1 -0
  42. package/dist/capabilities/participant-agents.facade.d.ts +35 -0
  43. package/dist/capabilities/participant-agents.facade.js +35 -0
  44. package/dist/capabilities/participant-agents.tools.facade.d.ts +8 -0
  45. package/dist/capabilities/participant-agents.tools.facade.js +8 -0
  46. package/dist/capabilities/participant-agents.tools.port.d.ts +9 -0
  47. package/dist/capabilities/participant-agents.tools.port.js +1 -0
  48. package/dist/capabilities/participant-context.facade.d.ts +13 -0
  49. package/dist/capabilities/participant-context.facade.js +14 -0
  50. package/dist/capabilities/participant-context.tools.port.d.ts +9 -0
  51. package/dist/capabilities/participant-context.tools.port.js +1 -0
  52. package/dist/capabilities/questions.enqueue.facade.d.ts +5 -0
  53. package/dist/capabilities/questions.enqueue.facade.js +1 -0
  54. package/dist/capabilities/questions.facade.d.ts +8 -0
  55. package/dist/capabilities/questions.facade.js +7 -0
  56. package/dist/capabilities/questions.runtime.facade.d.ts +5 -0
  57. package/dist/capabilities/questions.runtime.facade.js +5 -0
  58. package/dist/capabilities/questions.tools.port.d.ts +5 -0
  59. package/dist/capabilities/questions.tools.port.js +1 -0
  60. package/dist/capabilities/signals.facade.d.ts +16 -0
  61. package/dist/capabilities/signals.facade.js +14 -0
  62. package/dist/capabilities/signals.indexing.facade.d.ts +12 -0
  63. package/dist/capabilities/signals.indexing.facade.js +11 -0
  64. package/dist/capabilities/signals.tools.port.d.ts +5 -0
  65. package/dist/capabilities/signals.tools.port.js +1 -0
  66. package/dist/chat/chat-streaming.types.d.ts +0 -1
  67. package/dist/chat/chat-streaming.types.js +1 -2
  68. package/dist/chat/chat.agent.d.ts +0 -1
  69. package/dist/chat/chat.agent.js +0 -1
  70. package/dist/chat/chat.graph.d.ts +0 -1
  71. package/dist/chat/chat.graph.js +0 -1
  72. package/dist/chat/chat.interrupt.classifier.d.ts +0 -1
  73. package/dist/chat/chat.interrupt.classifier.js +0 -1
  74. package/dist/chat/chat.persona.d.ts +0 -1
  75. package/dist/chat/chat.persona.js +0 -1
  76. package/dist/chat/chat.prompt.d.ts +0 -1
  77. package/dist/chat/chat.prompt.js +0 -1
  78. package/dist/chat/chat.prompt.modules.d.ts +0 -1
  79. package/dist/chat/chat.prompt.modules.js +0 -1
  80. package/dist/chat/chat.question-dedup.d.ts +0 -1
  81. package/dist/chat/chat.question-dedup.js +0 -1
  82. package/dist/chat/chat.state.d.ts +0 -1
  83. package/dist/chat/chat.state.js +0 -1
  84. package/dist/chat/chat.streamer.d.ts +0 -1
  85. package/dist/chat/chat.streamer.js +0 -1
  86. package/dist/chat/chat.suggester.d.ts +0 -1
  87. package/dist/chat/chat.suggester.js +0 -1
  88. package/dist/chat/chat.summarizer.d.ts +0 -1
  89. package/dist/chat/chat.summarizer.js +0 -1
  90. package/dist/chat/chat.title.generator.d.ts +0 -1
  91. package/dist/chat/chat.title.generator.js +0 -1
  92. package/dist/chat/chat.tools.d.ts +0 -1
  93. package/dist/chat/chat.tools.js +0 -1
  94. package/dist/chat/chat.utils.d.ts +0 -1
  95. package/dist/chat/chat.utils.js +0 -1
  96. package/dist/chat/negotiator.persona.d.ts +0 -1
  97. package/dist/chat/negotiator.persona.js +0 -1
  98. package/dist/chat/negotiator.prompt.d.ts +1 -2
  99. package/dist/chat/negotiator.prompt.js +1 -2
  100. package/dist/chat/negotiator.tools.d.ts +0 -1
  101. package/dist/chat/negotiator.tools.js +0 -1
  102. package/dist/chat/onboarding.persona.d.ts +0 -1
  103. package/dist/chat/onboarding.persona.js +0 -1
  104. package/dist/chat/onboarding.prompt.d.ts +0 -1
  105. package/dist/chat/onboarding.prompt.js +0 -1
  106. package/dist/chat/reporter.action.contracts.d.ts +36 -0
  107. package/dist/chat/reporter.action.contracts.js +1 -0
  108. package/dist/chat/reporter.action.tools.d.ts +2 -37
  109. package/dist/chat/reporter.action.tools.js +0 -1
  110. package/dist/chat/reporter.persona.d.ts +0 -1
  111. package/dist/chat/reporter.persona.js +0 -1
  112. package/dist/chat/reporter.prompt.d.ts +0 -1
  113. package/dist/chat/reporter.prompt.js +0 -1
  114. package/dist/chat/signal.persona.d.ts +0 -1
  115. package/dist/chat/signal.persona.js +0 -1
  116. package/dist/chat/signal.prompt.d.ts +0 -1
  117. package/dist/chat/signal.prompt.js +0 -1
  118. package/dist/communities/application/index.d.ts +45 -0
  119. package/dist/communities/application/index.js +50 -0
  120. package/dist/communities/application/indexer.graph.d.ts +446 -0
  121. package/dist/communities/application/indexer.graph.js +420 -0
  122. package/dist/communities/application/indexer.state.d.ts +172 -0
  123. package/dist/communities/application/indexer.state.js +116 -0
  124. package/dist/communities/application/membership.graph.d.ts +270 -0
  125. package/dist/communities/application/membership.graph.js +229 -0
  126. package/dist/communities/application/network.graph.d.ts +648 -0
  127. package/dist/communities/application/network.graph.js +303 -0
  128. package/dist/communities/application/network.recommender.d.ts +44 -0
  129. package/dist/communities/application/network.recommender.js +113 -0
  130. package/dist/communities/application/network.tools.d.ts +35 -0
  131. package/dist/communities/application/network.tools.js +578 -0
  132. package/dist/communities/domain/index.d.ts +29 -0
  133. package/dist/communities/domain/index.js +31 -0
  134. package/dist/communities/domain/membership.state.d.ts +87 -0
  135. package/dist/communities/domain/membership.state.js +53 -0
  136. package/dist/communities/domain/network.state.d.ts +192 -0
  137. package/dist/communities/domain/network.state.js +66 -0
  138. package/dist/communities/index.d.ts +14 -0
  139. package/dist/communities/index.js +14 -0
  140. package/dist/communities/ports/index.d.ts +25 -0
  141. package/dist/communities/ports/index.js +27 -0
  142. package/dist/communities/public/index.d.ts +30 -0
  143. package/dist/communities/public/index.js +33 -0
  144. package/dist/contact/contact.inviter.d.ts +7 -44
  145. package/dist/contact/contact.inviter.js +6 -59
  146. package/dist/contact/contact.tools.d.ts +7 -5
  147. package/dist/contact/contact.tools.js +7 -177
  148. package/dist/contacts/application/contact.inviter.d.ts +49 -0
  149. package/dist/contacts/application/contact.inviter.js +64 -0
  150. package/dist/contacts/application/contact.tools.d.ts +20 -0
  151. package/dist/contacts/application/contact.tools.js +191 -0
  152. package/dist/contacts/application/index.d.ts +22 -0
  153. package/dist/contacts/application/index.js +21 -0
  154. package/dist/contacts/domain/contact.types.d.ts +51 -0
  155. package/dist/contacts/domain/contact.types.js +10 -0
  156. package/dist/contacts/domain/index.d.ts +18 -0
  157. package/dist/contacts/domain/index.js +1 -0
  158. package/dist/contacts/index.d.ts +24 -0
  159. package/dist/contacts/index.js +24 -0
  160. package/dist/contacts/ports/contact.repository.port.d.ts +28 -0
  161. package/dist/contacts/ports/contact.repository.port.js +14 -0
  162. package/dist/contacts/ports/contact.tools.port.d.ts +26 -0
  163. package/dist/contacts/ports/contact.tools.port.js +21 -0
  164. package/dist/contacts/ports/index.d.ts +22 -0
  165. package/dist/contacts/ports/index.js +21 -0
  166. package/dist/contacts/public/index.d.ts +36 -0
  167. package/dist/contacts/public/index.js +33 -0
  168. package/dist/context/context.generator.d.ts +0 -1
  169. package/dist/context/context.generator.js +0 -1
  170. package/dist/enrichment/enrichment.enricher.d.ts +0 -1
  171. package/dist/enrichment/enrichment.enricher.js +0 -1
  172. package/dist/enrichment/enrichment.generator.d.ts +0 -1
  173. package/dist/enrichment/enrichment.generator.js +0 -1
  174. package/dist/enrichment/enrichment.graph.d.ts +6 -7
  175. package/dist/enrichment/enrichment.graph.js +0 -1
  176. package/dist/enrichment/enrichment.state.d.ts +2 -3
  177. package/dist/enrichment/enrichment.state.js +0 -1
  178. package/dist/enrichment/enrichment.tools.d.ts +3 -3
  179. package/dist/enrichment/enrichment.tools.js +0 -1
  180. package/dist/index.d.ts +106 -91
  181. package/dist/index.js +79 -71
  182. package/dist/integration/integration.tools.d.ts +6 -10
  183. package/dist/integration/integration.tools.js +6 -82
  184. package/dist/integrations/application/index.d.ts +14 -0
  185. package/dist/integrations/application/index.js +14 -0
  186. package/dist/integrations/application/integration.tools.d.ts +27 -0
  187. package/dist/integrations/application/integration.tools.js +98 -0
  188. package/dist/integrations/domain/index.d.ts +18 -0
  189. package/dist/integrations/domain/index.js +1 -0
  190. package/dist/integrations/domain/integration.types.d.ts +53 -0
  191. package/dist/integrations/domain/integration.types.js +11 -0
  192. package/dist/integrations/index.d.ts +27 -0
  193. package/dist/integrations/index.js +27 -0
  194. package/dist/integrations/ports/index.d.ts +28 -0
  195. package/dist/integrations/ports/index.js +26 -0
  196. package/dist/integrations/ports/integration.adapter.port.d.ts +62 -0
  197. package/dist/integrations/ports/integration.adapter.port.js +15 -0
  198. package/dist/integrations/ports/integration.importer.port.d.ts +31 -0
  199. package/dist/integrations/ports/integration.importer.port.js +15 -0
  200. package/dist/integrations/ports/integration.tools.port.d.ts +28 -0
  201. package/dist/integrations/ports/integration.tools.port.js +21 -0
  202. package/dist/integrations/public/index.d.ts +37 -0
  203. package/dist/integrations/public/index.js +34 -0
  204. package/dist/intent/intent.clarifier.d.ts +3 -52
  205. package/dist/intent/intent.clarifier.js +2 -202
  206. package/dist/intent/intent.graph.d.ts +3 -551
  207. package/dist/intent/intent.graph.js +3 -937
  208. package/dist/intent/intent.indexer.d.ts +2 -83
  209. package/dist/intent/intent.indexer.js +2 -171
  210. package/dist/intent/intent.inferrer.d.ts +2 -95
  211. package/dist/intent/intent.inferrer.js +2 -234
  212. package/dist/intent/intent.reconciler.d.ts +2 -106
  213. package/dist/intent/intent.reconciler.js +2 -187
  214. package/dist/intent/intent.specificity.d.ts +2 -3
  215. package/dist/intent/intent.specificity.js +2 -3
  216. package/dist/intent/intent.state.d.ts +8 -229
  217. package/dist/intent/intent.state.js +8 -189
  218. package/dist/intent/intent.tools.d.ts +6 -24
  219. package/dist/intent/intent.tools.js +4 -788
  220. package/dist/intent/intent.verifier.d.ts +2 -116
  221. package/dist/intent/intent.verifier.js +2 -263
  222. package/dist/maintenance/maintenance.graph.d.ts +0 -1
  223. package/dist/maintenance/maintenance.graph.js +0 -1
  224. package/dist/maintenance/maintenance.state.d.ts +0 -1
  225. package/dist/maintenance/maintenance.state.js +0 -1
  226. package/dist/mcp/elicitation.builder.d.ts +0 -1
  227. package/dist/mcp/elicitation.builder.js +0 -1
  228. package/dist/mcp/elicitation.dispatcher.d.ts +0 -1
  229. package/dist/mcp/elicitation.dispatcher.js +0 -1
  230. package/dist/mcp/mcp.server.d.ts +0 -1
  231. package/dist/mcp/mcp.server.js +1 -2
  232. package/dist/negotiation/application/index.d.ts +48 -0
  233. package/dist/negotiation/application/index.js +49 -0
  234. package/dist/negotiation/application/insight.generator.d.ts +31 -0
  235. package/dist/negotiation/application/insight.generator.js +105 -0
  236. package/dist/negotiation/application/negotiation.agent.d.ts +110 -0
  237. package/dist/negotiation/application/negotiation.agent.js +244 -0
  238. package/dist/negotiation/application/negotiation.detail-reader.d.ts +94 -0
  239. package/dist/negotiation/application/negotiation.detail-reader.js +91 -0
  240. package/dist/negotiation/application/negotiation.graph.d.ts +664 -0
  241. package/dist/negotiation/application/negotiation.graph.js +1393 -0
  242. package/dist/negotiation/application/negotiation.reflect.d.ts +194 -0
  243. package/dist/negotiation/application/negotiation.reflect.js +145 -0
  244. package/dist/negotiation/application/negotiation.screen.d.ts +78 -0
  245. package/dist/negotiation/application/negotiation.screen.js +108 -0
  246. package/dist/negotiation/application/negotiation.summarizer.d.ts +25 -0
  247. package/dist/negotiation/application/negotiation.summarizer.js +101 -0
  248. package/dist/negotiation/application/negotiation.tools.d.ts +18 -0
  249. package/dist/negotiation/application/negotiation.tools.js +782 -0
  250. package/dist/negotiation/domain/index.d.ts +48 -0
  251. package/dist/negotiation/domain/index.js +50 -0
  252. package/dist/negotiation/domain/negotiation.consultation-policy.d.ts +39 -0
  253. package/dist/negotiation/domain/negotiation.consultation-policy.js +68 -0
  254. package/dist/negotiation/domain/negotiation.deadlock.contracts.d.ts +10 -0
  255. package/dist/negotiation/domain/negotiation.deadlock.contracts.js +1 -0
  256. package/dist/negotiation/domain/negotiation.deadlock.d.ts +81 -0
  257. package/dist/negotiation/domain/negotiation.deadlock.js +103 -0
  258. package/dist/negotiation/domain/negotiation.intent-snapshot-provenance.d.ts +21 -0
  259. package/dist/negotiation/domain/negotiation.intent-snapshot-provenance.js +28 -0
  260. package/dist/negotiation/domain/negotiation.lifecycle-narration.d.ts +18 -0
  261. package/dist/negotiation/domain/negotiation.lifecycle-narration.js +87 -0
  262. package/dist/negotiation/domain/negotiation.memory.d.ts +65 -0
  263. package/dist/negotiation/domain/negotiation.memory.js +83 -0
  264. package/dist/negotiation/domain/negotiation.protocol.d.ts +536 -0
  265. package/dist/negotiation/domain/negotiation.protocol.js +202 -0
  266. package/dist/negotiation/domain/negotiation.question-safety.d.ts +25 -0
  267. package/dist/negotiation/domain/negotiation.question-safety.js +55 -0
  268. package/dist/negotiation/domain/negotiation.screen.contracts.d.ts +88 -0
  269. package/dist/negotiation/domain/negotiation.screen.contracts.js +58 -0
  270. package/dist/negotiation/domain/negotiation.state.d.ts +497 -0
  271. package/dist/negotiation/domain/negotiation.state.js +288 -0
  272. package/dist/negotiation/domain/negotiation.task-lock-policy.d.ts +10 -0
  273. package/dist/negotiation/domain/negotiation.task-lock-policy.js +22 -0
  274. package/dist/negotiation/index.d.ts +49 -0
  275. package/dist/negotiation/index.js +49 -0
  276. package/dist/negotiation/insight.generator.d.ts +3 -30
  277. package/dist/negotiation/insight.generator.js +3 -104
  278. package/dist/negotiation/negotiation.agent.d.ts +3 -109
  279. package/dist/negotiation/negotiation.agent.js +3 -248
  280. package/dist/negotiation/negotiation.attribution.d.ts +0 -1
  281. package/dist/negotiation/negotiation.attribution.js +0 -1
  282. package/dist/negotiation/negotiation.consultation-policy.d.ts +3 -38
  283. package/dist/negotiation/negotiation.consultation-policy.js +3 -67
  284. package/dist/negotiation/negotiation.deadlock.contracts.d.ts +5 -0
  285. package/dist/negotiation/negotiation.deadlock.contracts.js +5 -0
  286. package/dist/negotiation/negotiation.deadlock.d.ts +3 -94
  287. package/dist/negotiation/negotiation.deadlock.js +3 -101
  288. package/dist/negotiation/negotiation.detail-reader.d.ts +5 -0
  289. package/dist/negotiation/negotiation.detail-reader.js +5 -0
  290. package/dist/negotiation/negotiation.graph.d.ts +3 -663
  291. package/dist/negotiation/negotiation.graph.js +3 -1459
  292. package/dist/negotiation/negotiation.intent-snapshot-provenance.d.ts +5 -0
  293. package/dist/negotiation/negotiation.intent-snapshot-provenance.js +5 -0
  294. package/dist/negotiation/negotiation.lifecycle-narration.d.ts +5 -0
  295. package/dist/negotiation/negotiation.lifecycle-narration.js +5 -0
  296. package/dist/negotiation/negotiation.memory.d.ts +5 -56
  297. package/dist/negotiation/negotiation.memory.js +5 -69
  298. package/dist/negotiation/negotiation.protocol.d.ts +3 -535
  299. package/dist/negotiation/negotiation.protocol.js +3 -201
  300. package/dist/negotiation/negotiation.question-safety.d.ts +3 -24
  301. package/dist/negotiation/negotiation.question-safety.js +3 -54
  302. package/dist/negotiation/negotiation.reflect.d.ts +4 -197
  303. package/dist/negotiation/negotiation.reflect.js +4 -151
  304. package/dist/negotiation/negotiation.screen.d.ts +6 -159
  305. package/dist/negotiation/negotiation.screen.js +6 -152
  306. package/dist/negotiation/negotiation.state.d.ts +3 -495
  307. package/dist/negotiation/negotiation.state.js +3 -284
  308. package/dist/negotiation/negotiation.summarizer.d.ts +3 -24
  309. package/dist/negotiation/negotiation.summarizer.js +3 -100
  310. package/dist/negotiation/negotiation.task-lock-policy.d.ts +5 -0
  311. package/dist/negotiation/negotiation.task-lock-policy.js +5 -0
  312. package/dist/negotiation/negotiation.tools.d.ts +3 -15
  313. package/dist/negotiation/negotiation.tools.js +3 -946
  314. package/dist/negotiation/ports/index.d.ts +18 -0
  315. package/dist/negotiation/ports/index.js +18 -0
  316. package/dist/negotiation/ports/negotiation.tools.port.d.ts +18 -0
  317. package/dist/negotiation/ports/negotiation.tools.port.js +1 -0
  318. package/dist/negotiation/public/index.d.ts +58 -0
  319. package/dist/negotiation/public/index.js +60 -0
  320. package/dist/network/indexer/indexer.graph.d.ts +3 -413
  321. package/dist/network/indexer/indexer.graph.js +3 -375
  322. package/dist/network/indexer/indexer.state.d.ts +3 -149
  323. package/dist/network/indexer/indexer.state.js +3 -98
  324. package/dist/network/membership/membership.graph.d.ts +3 -248
  325. package/dist/network/membership/membership.graph.js +3 -202
  326. package/dist/network/membership/membership.state.d.ts +3 -75
  327. package/dist/network/membership/membership.state.js +3 -41
  328. package/dist/network/network.graph.d.ts +3 -629
  329. package/dist/network/network.graph.js +3 -267
  330. package/dist/network/network.recommender.d.ts +3 -40
  331. package/dist/network/network.recommender.js +3 -109
  332. package/dist/network/network.state.d.ts +3 -180
  333. package/dist/network/network.state.js +3 -54
  334. package/dist/network/network.tools.d.ts +5 -3
  335. package/dist/network/network.tools.js +5 -566
  336. package/dist/opportunity/application/delivery-card.cache.d.ts +25 -0
  337. package/dist/opportunity/application/delivery-card.cache.js +43 -0
  338. package/dist/opportunity/application/index.d.ts +63 -0
  339. package/dist/opportunity/application/index.js +68 -0
  340. package/dist/opportunity/application/negotiation-context.loader.d.ts +59 -0
  341. package/dist/opportunity/application/negotiation-context.loader.js +88 -0
  342. package/dist/opportunity/application/opportunity.card-presentation.d.ts +44 -0
  343. package/dist/opportunity/application/opportunity.card-presentation.js +104 -0
  344. package/dist/opportunity/application/opportunity.discover.d.ts +215 -0
  345. package/dist/opportunity/application/opportunity.discover.js +793 -0
  346. package/dist/opportunity/application/opportunity.discovery-continuation-finalization.d.ts +34 -0
  347. package/dist/opportunity/application/opportunity.discovery-continuation-finalization.js +74 -0
  348. package/dist/opportunity/application/opportunity.discovery-mcp-lifecycle-finalization.d.ts +44 -0
  349. package/dist/opportunity/application/opportunity.discovery-mcp-lifecycle-finalization.js +92 -0
  350. package/dist/opportunity/application/opportunity.discovery-negotiation-summary.d.ts +14 -0
  351. package/dist/opportunity/application/opportunity.discovery-negotiation-summary.js +46 -0
  352. package/dist/opportunity/application/opportunity.enricher.d.ts +71 -0
  353. package/dist/opportunity/application/opportunity.enricher.js +280 -0
  354. package/dist/opportunity/application/opportunity.evaluator.d.ts +275 -0
  355. package/dist/opportunity/application/opportunity.evaluator.js +459 -0
  356. package/dist/opportunity/application/opportunity.existing-negotiation.d.ts +77 -0
  357. package/dist/opportunity/application/opportunity.existing-negotiation.js +109 -0
  358. package/dist/opportunity/application/opportunity.feed-selection.d.ts +30 -0
  359. package/dist/opportunity/application/opportunity.feed-selection.js +96 -0
  360. package/dist/opportunity/application/opportunity.graph.d.ts +1427 -0
  361. package/dist/opportunity/application/opportunity.graph.js +3693 -0
  362. package/dist/opportunity/application/opportunity.introducer.d.ts +77 -0
  363. package/dist/opportunity/application/opportunity.introducer.js +99 -0
  364. package/dist/opportunity/application/opportunity.lifecycle.d.ts +63 -0
  365. package/dist/opportunity/application/opportunity.lifecycle.js +181 -0
  366. package/dist/opportunity/application/opportunity.newborn-stamping.d.ts +41 -0
  367. package/dist/opportunity/application/opportunity.newborn-stamping.js +81 -0
  368. package/dist/opportunity/application/opportunity.pending-questions.d.ts +33 -0
  369. package/dist/opportunity/application/opportunity.pending-questions.js +42 -0
  370. package/dist/opportunity/application/opportunity.persist.d.ts +58 -0
  371. package/dist/opportunity/application/opportunity.persist.js +145 -0
  372. package/dist/opportunity/application/opportunity.persistence-admission.d.ts +39 -0
  373. package/dist/opportunity/application/opportunity.persistence-admission.js +59 -0
  374. package/dist/opportunity/application/opportunity.presenter.d.ts +156 -0
  375. package/dist/opportunity/application/opportunity.presenter.js +736 -0
  376. package/dist/opportunity/application/opportunity.tools.d.ts +131 -0
  377. package/dist/opportunity/application/opportunity.tools.js +1834 -0
  378. package/dist/opportunity/application/opportunity.update-admission.d.ts +24 -0
  379. package/dist/opportunity/application/opportunity.update-admission.js +38 -0
  380. package/dist/opportunity/delivery-card.cache.d.ts +5 -26
  381. package/dist/opportunity/delivery-card.cache.js +5 -44
  382. package/dist/opportunity/discovery-question.helper.d.ts +3 -17
  383. package/dist/opportunity/discovery-question.helper.js +3 -14
  384. package/dist/opportunity/discriminator/discriminator.adjustments.d.ts +0 -1
  385. package/dist/opportunity/discriminator/discriminator.adjustments.js +0 -1
  386. package/dist/opportunity/discriminator/discriminator.assigner.d.ts +4 -5
  387. package/dist/opportunity/discriminator/discriminator.assigner.js +0 -1
  388. package/dist/opportunity/discriminator/discriminator.env.d.ts +0 -1
  389. package/dist/opportunity/discriminator/discriminator.env.js +0 -1
  390. package/dist/opportunity/discriminator/discriminator.miner.d.ts +0 -1
  391. package/dist/opportunity/discriminator/discriminator.miner.js +0 -1
  392. package/dist/opportunity/discriminator/discriminator.push.d.ts +0 -1
  393. package/dist/opportunity/discriminator/discriminator.push.js +0 -1
  394. package/dist/opportunity/discriminator/discriminator.question.d.ts +0 -1
  395. package/dist/opportunity/discriminator/discriminator.question.js +0 -1
  396. package/dist/opportunity/discriminator/discriminator.scorer.d.ts +0 -1
  397. package/dist/opportunity/discriminator/discriminator.scorer.js +0 -1
  398. package/dist/opportunity/discriminator/discriminator.shadow.d.ts +0 -1
  399. package/dist/opportunity/discriminator/discriminator.shadow.js +0 -1
  400. package/dist/opportunity/discriminator/discriminator.types.d.ts +0 -1
  401. package/dist/opportunity/discriminator/discriminator.types.js +0 -1
  402. package/dist/opportunity/domain/discovery-question.helper.d.ts +18 -0
  403. package/dist/opportunity/domain/discovery-question.helper.js +15 -0
  404. package/dist/opportunity/domain/index.d.ts +55 -0
  405. package/dist/opportunity/domain/index.js +52 -0
  406. package/dist/opportunity/domain/negotiation-summary.builder.d.ts +37 -0
  407. package/dist/opportunity/domain/negotiation-summary.builder.js +66 -0
  408. package/dist/opportunity/domain/opportunity.actor.d.ts +15 -0
  409. package/dist/opportunity/domain/opportunity.actor.js +39 -0
  410. package/dist/opportunity/domain/opportunity.claim-safety.d.ts +24 -0
  411. package/dist/opportunity/domain/opportunity.claim-safety.js +88 -0
  412. package/dist/opportunity/domain/opportunity.discovery-run-coalescing.d.ts +33 -0
  413. package/dist/opportunity/domain/opportunity.discovery-run-coalescing.js +33 -0
  414. package/dist/opportunity/domain/opportunity.discovery.contracts.d.ts +45 -0
  415. package/dist/opportunity/domain/opportunity.discovery.contracts.js +1 -0
  416. package/dist/opportunity/domain/opportunity.evidence.d.ts +21 -0
  417. package/dist/opportunity/domain/opportunity.evidence.js +78 -0
  418. package/dist/opportunity/domain/opportunity.labels.d.ts +8 -0
  419. package/dist/opportunity/domain/opportunity.labels.js +10 -0
  420. package/dist/opportunity/domain/opportunity.presentation-cache.d.ts +6 -0
  421. package/dist/opportunity/domain/opportunity.presentation-cache.js +14 -0
  422. package/dist/opportunity/domain/opportunity.presentation.d.ts +76 -0
  423. package/dist/opportunity/domain/opportunity.presentation.js +516 -0
  424. package/dist/opportunity/domain/opportunity.safe-presentation.d.ts +104 -0
  425. package/dist/opportunity/domain/opportunity.safe-presentation.js +102 -0
  426. package/dist/opportunity/domain/opportunity.state.d.ts +519 -0
  427. package/dist/opportunity/domain/opportunity.state.js +309 -0
  428. package/dist/opportunity/domain/opportunity.utils.d.ts +217 -0
  429. package/dist/opportunity/domain/opportunity.utils.js +395 -0
  430. package/dist/opportunity/feed/feed.categorizer.d.ts +0 -1
  431. package/dist/opportunity/feed/feed.categorizer.js +0 -1
  432. package/dist/opportunity/feed/feed.graph.d.ts +1 -2
  433. package/dist/opportunity/feed/feed.graph.js +0 -1
  434. package/dist/opportunity/feed/feed.health.d.ts +0 -1
  435. package/dist/opportunity/feed/feed.health.js +0 -1
  436. package/dist/opportunity/feed/feed.state.d.ts +1 -2
  437. package/dist/opportunity/feed/feed.state.js +0 -1
  438. package/dist/opportunity/index.d.ts +37 -0
  439. package/dist/opportunity/index.js +37 -0
  440. package/dist/opportunity/negotiation-context.loader.d.ts +3 -58
  441. package/dist/opportunity/negotiation-context.loader.js +3 -87
  442. package/dist/opportunity/negotiation-evidence/negotiation-evidence.env.d.ts +0 -1
  443. package/dist/opportunity/negotiation-evidence/negotiation-evidence.env.js +0 -1
  444. package/dist/opportunity/negotiation-evidence/negotiation-evidence.extractor.d.ts +0 -1
  445. package/dist/opportunity/negotiation-evidence/negotiation-evidence.extractor.js +0 -1
  446. package/dist/opportunity/negotiation-evidence/negotiation-evidence.miner.d.ts +0 -1
  447. package/dist/opportunity/negotiation-evidence/negotiation-evidence.miner.js +0 -1
  448. package/dist/opportunity/negotiation-evidence/negotiation-evidence.shadow.d.ts +0 -1
  449. package/dist/opportunity/negotiation-evidence/negotiation-evidence.shadow.js +0 -1
  450. package/dist/opportunity/negotiation-evidence/negotiation-evidence.types.d.ts +0 -1
  451. package/dist/opportunity/negotiation-evidence/negotiation-evidence.types.js +0 -1
  452. package/dist/opportunity/negotiation-evidence/negotiation-evidence.verifier.d.ts +0 -1
  453. package/dist/opportunity/negotiation-evidence/negotiation-evidence.verifier.js +0 -1
  454. package/dist/opportunity/negotiation-summary.builder.d.ts +3 -36
  455. package/dist/opportunity/negotiation-summary.builder.js +3 -65
  456. package/dist/opportunity/opportunity.actor.d.ts +3 -14
  457. package/dist/opportunity/opportunity.actor.js +3 -38
  458. package/dist/opportunity/opportunity.card-presentation.d.ts +5 -0
  459. package/dist/opportunity/opportunity.card-presentation.js +5 -0
  460. package/dist/opportunity/opportunity.claim-safety.d.ts +3 -23
  461. package/dist/opportunity/opportunity.claim-safety.js +3 -87
  462. package/dist/opportunity/opportunity.discover.d.ts +3 -218
  463. package/dist/opportunity/opportunity.discover.js +3 -917
  464. package/dist/opportunity/opportunity.discovery-continuation-finalization.d.ts +5 -0
  465. package/dist/opportunity/opportunity.discovery-continuation-finalization.js +5 -0
  466. package/dist/opportunity/opportunity.discovery-mcp-lifecycle-finalization.d.ts +5 -0
  467. package/dist/opportunity/opportunity.discovery-mcp-lifecycle-finalization.js +5 -0
  468. package/dist/opportunity/opportunity.discovery-negotiation-summary.d.ts +5 -0
  469. package/dist/opportunity/opportunity.discovery-negotiation-summary.js +5 -0
  470. package/dist/opportunity/opportunity.discovery-run-coalescing.d.ts +5 -0
  471. package/dist/opportunity/opportunity.discovery-run-coalescing.js +5 -0
  472. package/dist/opportunity/opportunity.discovery.contracts.d.ts +5 -0
  473. package/dist/opportunity/opportunity.discovery.contracts.js +5 -0
  474. package/dist/opportunity/opportunity.enricher.d.ts +3 -70
  475. package/dist/opportunity/opportunity.enricher.js +3 -279
  476. package/dist/opportunity/opportunity.evaluator.d.ts +5 -276
  477. package/dist/opportunity/opportunity.evaluator.js +5 -460
  478. package/dist/opportunity/opportunity.evidence.d.ts +5 -22
  479. package/dist/opportunity/opportunity.evidence.js +5 -79
  480. package/dist/opportunity/opportunity.existing-negotiation.d.ts +5 -0
  481. package/dist/opportunity/opportunity.existing-negotiation.js +5 -0
  482. package/dist/opportunity/opportunity.feed-selection.d.ts +5 -0
  483. package/dist/opportunity/opportunity.feed-selection.js +5 -0
  484. package/dist/opportunity/opportunity.graph.d.ts +3 -1489
  485. package/dist/opportunity/opportunity.graph.js +3 -4071
  486. package/dist/opportunity/opportunity.introducer.d.ts +3 -76
  487. package/dist/opportunity/opportunity.introducer.js +3 -98
  488. package/dist/opportunity/opportunity.labels.d.ts +5 -9
  489. package/dist/opportunity/opportunity.labels.js +5 -11
  490. package/dist/opportunity/opportunity.lifecycle.d.ts +5 -0
  491. package/dist/opportunity/opportunity.lifecycle.js +5 -0
  492. package/dist/opportunity/opportunity.newborn-stamping.d.ts +5 -0
  493. package/dist/opportunity/opportunity.newborn-stamping.js +5 -0
  494. package/dist/opportunity/opportunity.pending-questions.d.ts +3 -32
  495. package/dist/opportunity/opportunity.pending-questions.js +3 -41
  496. package/dist/opportunity/opportunity.persist.d.ts +3 -57
  497. package/dist/opportunity/opportunity.persist.js +3 -144
  498. package/dist/opportunity/opportunity.persistence-admission.d.ts +5 -0
  499. package/dist/opportunity/opportunity.persistence-admission.js +5 -0
  500. package/dist/opportunity/opportunity.presentation-cache.d.ts +5 -7
  501. package/dist/opportunity/opportunity.presentation-cache.js +5 -15
  502. package/dist/opportunity/opportunity.presentation.d.ts +3 -75
  503. package/dist/opportunity/opportunity.presentation.js +3 -515
  504. package/dist/opportunity/opportunity.presenter.d.ts +10 -155
  505. package/dist/opportunity/opportunity.presenter.js +10 -735
  506. package/dist/opportunity/opportunity.safe-presentation.d.ts +3 -103
  507. package/dist/opportunity/opportunity.safe-presentation.js +3 -101
  508. package/dist/opportunity/opportunity.state.d.ts +3 -518
  509. package/dist/opportunity/opportunity.state.js +3 -308
  510. package/dist/opportunity/opportunity.tools.d.ts +3 -157
  511. package/dist/opportunity/opportunity.tools.js +3 -2238
  512. package/dist/opportunity/opportunity.update-admission.d.ts +5 -0
  513. package/dist/opportunity/opportunity.update-admission.js +5 -0
  514. package/dist/opportunity/opportunity.utils.d.ts +3 -216
  515. package/dist/opportunity/opportunity.utils.js +3 -394
  516. package/dist/opportunity/outcome/outcome.env.d.ts +0 -1
  517. package/dist/opportunity/outcome/outcome.env.js +0 -1
  518. package/dist/opportunity/outcome/outcome.hypotheses.d.ts +0 -1
  519. package/dist/opportunity/outcome/outcome.hypotheses.js +0 -1
  520. package/dist/opportunity/outcome/outcome.shadow.d.ts +0 -1
  521. package/dist/opportunity/outcome/outcome.shadow.js +0 -1
  522. package/dist/opportunity/outcome/outcome.types.d.ts +0 -1
  523. package/dist/opportunity/outcome/outcome.types.js +0 -1
  524. package/dist/opportunity/ports/index.d.ts +5 -0
  525. package/dist/opportunity/ports/index.js +1 -0
  526. package/dist/opportunity/ports/opportunity.tools.port.d.ts +5 -0
  527. package/dist/opportunity/ports/opportunity.tools.port.js +1 -0
  528. package/dist/opportunity/public/index.d.ts +58 -0
  529. package/dist/opportunity/public/index.js +51 -0
  530. package/dist/participant-agents/application/agent.tools.d.ts +16 -0
  531. package/dist/participant-agents/application/agent.tools.js +313 -0
  532. package/dist/participant-agents/application/index.d.ts +21 -0
  533. package/dist/participant-agents/application/index.js +22 -0
  534. package/dist/participant-agents/domain/agent.types.d.ts +76 -0
  535. package/dist/participant-agents/domain/agent.types.js +22 -0
  536. package/dist/participant-agents/domain/index.d.ts +20 -0
  537. package/dist/participant-agents/domain/index.js +1 -0
  538. package/dist/participant-agents/index.d.ts +24 -0
  539. package/dist/participant-agents/index.js +24 -0
  540. package/dist/participant-agents/ports/agent.dispatcher.port.d.ts +25 -0
  541. package/dist/participant-agents/ports/agent.dispatcher.port.js +1 -0
  542. package/dist/participant-agents/ports/agent.repository.port.d.ts +118 -0
  543. package/dist/participant-agents/ports/agent.repository.port.js +10 -0
  544. package/dist/participant-agents/ports/agent.tools.port.d.ts +24 -0
  545. package/dist/participant-agents/ports/agent.tools.port.js +20 -0
  546. package/dist/participant-agents/ports/index.d.ts +29 -0
  547. package/dist/participant-agents/ports/index.js +27 -0
  548. package/dist/participant-agents/public/index.d.ts +39 -0
  549. package/dist/participant-agents/public/index.js +36 -0
  550. package/dist/participant-context/application/index.d.ts +73 -0
  551. package/dist/participant-context/application/index.js +83 -0
  552. package/dist/participant-context/domain/index.d.ts +67 -0
  553. package/dist/participant-context/domain/index.js +68 -0
  554. package/dist/participant-context/index.d.ts +16 -0
  555. package/dist/participant-context/index.js +16 -0
  556. package/dist/participant-context/ports/index.d.ts +37 -0
  557. package/dist/participant-context/ports/index.js +34 -0
  558. package/dist/participant-context/public/index.d.ts +48 -0
  559. package/dist/participant-context/public/index.js +55 -0
  560. package/dist/platform/index.d.ts +19 -0
  561. package/dist/platform/index.js +23 -0
  562. package/dist/premise/premise.analyzer.d.ts +0 -1
  563. package/dist/premise/premise.analyzer.js +0 -2
  564. package/dist/premise/premise.decomposer.d.ts +0 -1
  565. package/dist/premise/premise.decomposer.js +0 -2
  566. package/dist/premise/premise.graph.d.ts +1 -2
  567. package/dist/premise/premise.graph.js +0 -2
  568. package/dist/premise/premise.indexer.d.ts +0 -1
  569. package/dist/premise/premise.indexer.js +0 -2
  570. package/dist/premise/premise.state.d.ts +1 -2
  571. package/dist/premise/premise.state.js +0 -1
  572. package/dist/premise/premise.tools.d.ts +3 -3
  573. package/dist/premise/premise.tools.js +0 -2
  574. package/dist/public/index.d.ts +17 -0
  575. package/dist/public/index.js +17 -0
  576. package/dist/questioner/questioner.agent.d.ts +4 -27
  577. package/dist/questioner/questioner.agent.js +3 -133
  578. package/dist/questioner/questioner.ask.tool.d.ts +3 -12
  579. package/dist/questioner/questioner.ask.tool.js +3 -299
  580. package/dist/questioner/questioner.discovery.prompt.d.ts +3 -7
  581. package/dist/questioner/questioner.discovery.prompt.js +3 -180
  582. package/dist/questioner/questioner.env.d.ts +3 -57
  583. package/dist/questioner/questioner.env.js +3 -93
  584. package/dist/questioner/questioner.presets.d.ts +4 -19
  585. package/dist/questioner/questioner.presets.js +3 -465
  586. package/dist/questioner/questioner.qud.d.ts +3 -6
  587. package/dist/questioner/questioner.qud.js +3 -10
  588. package/dist/questioner/questioner.tools.d.ts +3 -15
  589. package/dist/questioner/questioner.tools.js +3 -186
  590. package/dist/questioner/questioner.types.d.ts +4 -218
  591. package/dist/questioner/questioner.types.js +5 -62
  592. package/dist/questions/application/index.d.ts +39 -0
  593. package/dist/questions/application/index.js +41 -0
  594. package/dist/questions/application/question.agent.d.ts +28 -0
  595. package/dist/questions/application/question.agent.js +139 -0
  596. package/dist/questions/application/question.ask.tool.d.ts +12 -0
  597. package/dist/questions/application/question.ask.tool.js +300 -0
  598. package/dist/questions/application/question.discovery.prompt.d.ts +8 -0
  599. package/dist/questions/application/question.discovery.prompt.js +181 -0
  600. package/dist/questions/application/question.env.d.ts +61 -0
  601. package/dist/questions/application/question.env.js +97 -0
  602. package/dist/questions/application/question.input.d.ts +237 -0
  603. package/dist/questions/application/question.input.js +61 -0
  604. package/dist/questions/application/question.presets.d.ts +24 -0
  605. package/dist/questions/application/question.presets.js +445 -0
  606. package/dist/questions/application/question.qud.d.ts +12 -0
  607. package/dist/questions/application/question.qud.js +16 -0
  608. package/dist/questions/application/question.tools.d.ts +15 -0
  609. package/dist/questions/application/question.tools.js +190 -0
  610. package/dist/questions/domain/index.d.ts +25 -0
  611. package/dist/questions/domain/index.js +25 -0
  612. package/dist/questions/domain/question.schema.d.ts +1537 -0
  613. package/dist/questions/domain/question.schema.js +422 -0
  614. package/dist/questions/index.d.ts +22 -0
  615. package/dist/questions/index.js +22 -0
  616. package/dist/questions/ports/index.d.ts +29 -0
  617. package/dist/questions/ports/index.js +27 -0
  618. package/dist/questions/ports/question.generator.port.d.ts +34 -0
  619. package/dist/questions/ports/question.generator.port.js +1 -0
  620. package/dist/questions/ports/question.persistence.port.d.ts +87 -0
  621. package/dist/questions/ports/question.persistence.port.js +1 -0
  622. package/dist/questions/ports/question.tools.port.d.ts +15 -0
  623. package/dist/questions/ports/question.tools.port.js +1 -0
  624. package/dist/questions/public/index.d.ts +47 -0
  625. package/dist/questions/public/index.js +49 -0
  626. package/dist/runtime/background/index.d.ts +14 -0
  627. package/dist/runtime/background/index.js +14 -0
  628. package/dist/runtime/foreground/composition/tool.factory.d.ts +16 -0
  629. package/dist/runtime/foreground/composition/tool.factory.js +224 -0
  630. package/dist/runtime/foreground/composition/tool.registry.d.ts +11 -0
  631. package/dist/runtime/foreground/composition/tool.registry.js +106 -0
  632. package/dist/runtime/foreground/index.d.ts +13 -0
  633. package/dist/runtime/foreground/index.js +13 -0
  634. package/dist/runtime/foreground/signals/intent.tools.d.ts +13 -0
  635. package/dist/runtime/foreground/signals/intent.tools.js +13 -0
  636. package/dist/shared/agent/model-signal.d.ts +0 -1
  637. package/dist/shared/agent/model-signal.js +0 -1
  638. package/dist/shared/agent/model.config.d.ts +0 -1
  639. package/dist/shared/agent/model.config.js +0 -1
  640. package/dist/shared/agent/tool.factory.d.ts +4 -15
  641. package/dist/shared/agent/tool.factory.js +4 -226
  642. package/dist/shared/agent/tool.helpers.d.ts +51 -12
  643. package/dist/shared/agent/tool.helpers.js +0 -1
  644. package/dist/shared/agent/tool.registry.d.ts +9 -9
  645. package/dist/shared/agent/tool.registry.js +9 -104
  646. package/dist/shared/agent/tool.runtime.d.ts +0 -1
  647. package/dist/shared/agent/tool.runtime.js +0 -1
  648. package/dist/shared/agent/tool.scope.d.ts +0 -1
  649. package/dist/shared/agent/tool.scope.js +0 -1
  650. package/dist/shared/agent/utility.tools.d.ts +5 -3
  651. package/dist/shared/agent/utility.tools.js +0 -1
  652. package/dist/shared/assignment/network-assignment.policy.d.ts +0 -1
  653. package/dist/shared/assignment/network-assignment.policy.js +0 -1
  654. package/dist/shared/hyde/hyde.documents.d.ts +0 -1
  655. package/dist/shared/hyde/hyde.documents.js +0 -1
  656. package/dist/shared/hyde/hyde.env.d.ts +0 -1
  657. package/dist/shared/hyde/hyde.env.js +0 -1
  658. package/dist/shared/hyde/hyde.frame.d.ts +4 -5
  659. package/dist/shared/hyde/hyde.frame.js +0 -1
  660. package/dist/shared/hyde/hyde.generator.d.ts +0 -1
  661. package/dist/shared/hyde/hyde.generator.js +0 -1
  662. package/dist/shared/hyde/hyde.graph.d.ts +0 -1
  663. package/dist/shared/hyde/hyde.graph.js +0 -1
  664. package/dist/shared/hyde/hyde.state.d.ts +0 -1
  665. package/dist/shared/hyde/hyde.state.js +0 -1
  666. package/dist/shared/hyde/hyde.strategies.d.ts +0 -1
  667. package/dist/shared/hyde/hyde.strategies.js +0 -1
  668. package/dist/shared/hyde/hyde.validator.d.ts +0 -1
  669. package/dist/shared/hyde/hyde.validator.js +0 -1
  670. package/dist/shared/hyde/lens.inferrer.d.ts +6 -7
  671. package/dist/shared/hyde/lens.inferrer.js +0 -1
  672. package/dist/shared/interfaces/agent-dispatcher.interface.d.ts +4 -1
  673. package/dist/shared/interfaces/agent-dispatcher.interface.js +4 -1
  674. package/dist/shared/interfaces/agent.interface.d.ts +13 -173
  675. package/dist/shared/interfaces/agent.interface.js +12 -12
  676. package/dist/shared/interfaces/auth.interface.d.ts +0 -1
  677. package/dist/shared/interfaces/auth.interface.js +0 -1
  678. package/dist/shared/interfaces/cache.interface.d.ts +0 -1
  679. package/dist/shared/interfaces/cache.interface.js +0 -1
  680. package/dist/shared/interfaces/chat-message-writer.interface.d.ts +0 -1
  681. package/dist/shared/interfaces/chat-message-writer.interface.js +0 -1
  682. package/dist/shared/interfaces/chat-session.interface.d.ts +0 -1
  683. package/dist/shared/interfaces/chat-session.interface.js +0 -1
  684. package/dist/shared/interfaces/chat-summary.interface.d.ts +0 -1
  685. package/dist/shared/interfaces/chat-summary.interface.js +0 -1
  686. package/dist/shared/interfaces/connect-link.interface.d.ts +0 -1
  687. package/dist/shared/interfaces/connect-link.interface.js +0 -1
  688. package/dist/shared/interfaces/contact.interface.d.ts +7 -55
  689. package/dist/shared/interfaces/contact.interface.js +7 -1
  690. package/dist/shared/interfaces/database.interface.d.ts +0 -1
  691. package/dist/shared/interfaces/database.interface.js +0 -1
  692. package/dist/shared/interfaces/delivery-ledger.interface.d.ts +0 -1
  693. package/dist/shared/interfaces/delivery-ledger.interface.js +0 -1
  694. package/dist/shared/interfaces/discovery-run.interface.d.ts +2 -3
  695. package/dist/shared/interfaces/discovery-run.interface.js +0 -1
  696. package/dist/shared/interfaces/embedder.interface.d.ts +0 -1
  697. package/dist/shared/interfaces/embedder.interface.js +0 -1
  698. package/dist/shared/interfaces/enrichment-run.interface.d.ts +2 -3
  699. package/dist/shared/interfaces/enrichment-run.interface.js +0 -1
  700. package/dist/shared/interfaces/enrichment.interface.d.ts +0 -1
  701. package/dist/shared/interfaces/enrichment.interface.js +0 -1
  702. package/dist/shared/interfaces/integration.interface.d.ts +6 -88
  703. package/dist/shared/interfaces/integration.interface.js +7 -1
  704. package/dist/shared/interfaces/negotiation-events.interface.d.ts +0 -1
  705. package/dist/shared/interfaces/negotiation-events.interface.js +0 -1
  706. package/dist/shared/interfaces/negotiation-summary.interface.d.ts +0 -1
  707. package/dist/shared/interfaces/negotiation-summary.interface.js +0 -1
  708. package/dist/shared/interfaces/negotiator-memory.interface.d.ts +0 -1
  709. package/dist/shared/interfaces/negotiator-memory.interface.js +0 -1
  710. package/dist/shared/interfaces/question-generator.interface.d.ts +3 -28
  711. package/dist/shared/interfaces/question-generator.interface.js +0 -1
  712. package/dist/shared/interfaces/questioner.interface.d.ts +3 -77
  713. package/dist/shared/interfaces/questioner.interface.js +0 -1
  714. package/dist/shared/interfaces/queue.interface.d.ts +0 -1
  715. package/dist/shared/interfaces/queue.interface.js +0 -1
  716. package/dist/shared/interfaces/scraper.interface.d.ts +0 -1
  717. package/dist/shared/interfaces/scraper.interface.js +0 -1
  718. package/dist/shared/interfaces/tool-request-context.interface.d.ts +12 -0
  719. package/dist/shared/interfaces/tool-request-context.interface.js +1 -0
  720. package/dist/shared/network/metadata.renderer.d.ts +0 -1
  721. package/dist/shared/network/metadata.renderer.js +0 -1
  722. package/dist/shared/observability/debug-meta.sanitizer.d.ts +0 -1
  723. package/dist/shared/observability/debug-meta.sanitizer.js +0 -1
  724. package/dist/shared/observability/log.d.ts +0 -1
  725. package/dist/shared/observability/log.js +0 -1
  726. package/dist/shared/observability/performance.d.ts +0 -1
  727. package/dist/shared/observability/performance.js +0 -1
  728. package/dist/shared/observability/protocol.logger.d.ts +0 -1
  729. package/dist/shared/observability/protocol.logger.js +0 -1
  730. package/dist/shared/observability/request-context.d.ts +0 -1
  731. package/dist/shared/observability/request-context.js +0 -1
  732. package/dist/shared/observability/trace.d.ts +0 -1
  733. package/dist/shared/observability/trace.js +0 -1
  734. package/dist/shared/schemas/chat-context.schema.d.ts +0 -1
  735. package/dist/shared/schemas/chat-context.schema.js +0 -1
  736. package/dist/shared/schemas/discovery-question.schema.d.ts +17 -18
  737. package/dist/shared/schemas/discovery-question.schema.js +0 -1
  738. package/dist/shared/schemas/identity.schema.d.ts +0 -1
  739. package/dist/shared/schemas/identity.schema.js +0 -1
  740. package/dist/shared/schemas/mcp-auth.schema.d.ts +0 -1
  741. package/dist/shared/schemas/mcp-auth.schema.js +0 -1
  742. package/dist/shared/schemas/negotiation-digest.schema.d.ts +5 -6
  743. package/dist/shared/schemas/negotiation-digest.schema.js +0 -1
  744. package/dist/shared/schemas/negotiation-state.schema.d.ts +4 -5
  745. package/dist/shared/schemas/negotiation-state.schema.js +0 -1
  746. package/dist/shared/schemas/network-assignment.schema.d.ts +0 -1
  747. package/dist/shared/schemas/network-assignment.schema.js +0 -1
  748. package/dist/shared/schemas/pending-question.schema.d.ts +0 -1
  749. package/dist/shared/schemas/pending-question.schema.js +0 -1
  750. package/dist/shared/schemas/question.schema.d.ts +3 -1505
  751. package/dist/shared/schemas/question.schema.js +3 -410
  752. package/dist/shared/ui/lucide.icon-catalog.d.ts +0 -1
  753. package/dist/shared/ui/lucide.icon-catalog.js +0 -1
  754. package/dist/shared/utils/social-label.d.ts +0 -1
  755. package/dist/shared/utils/social-label.js +0 -1
  756. package/dist/shared/utils/telegram-handle.d.ts +0 -1
  757. package/dist/shared/utils/telegram-handle.js +0 -1
  758. package/dist/signals/application/index.d.ts +19 -0
  759. package/dist/signals/application/index.js +22 -0
  760. package/dist/signals/application/intent.clarifier.d.ts +51 -0
  761. package/dist/signals/application/intent.clarifier.js +201 -0
  762. package/dist/signals/application/intent.graph.d.ts +552 -0
  763. package/dist/signals/application/intent.graph.js +938 -0
  764. package/dist/signals/application/intent.indexer.d.ts +82 -0
  765. package/dist/signals/application/intent.indexer.js +170 -0
  766. package/dist/signals/application/intent.inferrer.d.ts +94 -0
  767. package/dist/signals/application/intent.inferrer.js +233 -0
  768. package/dist/signals/application/intent.reconciler.d.ts +105 -0
  769. package/dist/signals/application/intent.reconciler.js +186 -0
  770. package/dist/signals/application/intent.tools.d.ts +24 -0
  771. package/dist/signals/application/intent.tools.js +789 -0
  772. package/dist/signals/application/intent.verifier.d.ts +115 -0
  773. package/dist/signals/application/intent.verifier.js +262 -0
  774. package/dist/signals/domain/index.d.ts +9 -0
  775. package/dist/signals/domain/index.js +11 -0
  776. package/dist/signals/domain/intent.state.d.ts +230 -0
  777. package/dist/signals/domain/intent.state.js +190 -0
  778. package/dist/signals/domain/signal.specificity.d.ts +2 -0
  779. package/dist/signals/domain/signal.specificity.js +2 -0
  780. package/dist/signals/index.d.ts +13 -0
  781. package/dist/signals/index.js +13 -0
  782. package/dist/signals/ports/index.d.ts +15 -0
  783. package/dist/signals/ports/index.js +13 -0
  784. package/dist/signals/public/index.d.ts +15 -0
  785. package/dist/signals/public/index.js +16 -0
  786. package/package.json +14 -3
  787. package/dist/agent/agent.tools.d.ts.map +0 -1
  788. package/dist/agent/agent.tools.js.map +0 -1
  789. package/dist/agent/tests/fakes.d.ts +0 -25
  790. package/dist/agent/tests/fakes.d.ts.map +0 -1
  791. package/dist/agent/tests/fakes.js +0 -178
  792. package/dist/agent/tests/fakes.js.map +0 -1
  793. package/dist/chat/chat-streaming.types.d.ts.map +0 -1
  794. package/dist/chat/chat-streaming.types.js.map +0 -1
  795. package/dist/chat/chat.agent.d.ts.map +0 -1
  796. package/dist/chat/chat.agent.js.map +0 -1
  797. package/dist/chat/chat.graph.d.ts.map +0 -1
  798. package/dist/chat/chat.graph.js.map +0 -1
  799. package/dist/chat/chat.interrupt.classifier.d.ts.map +0 -1
  800. package/dist/chat/chat.interrupt.classifier.js.map +0 -1
  801. package/dist/chat/chat.persona.d.ts.map +0 -1
  802. package/dist/chat/chat.persona.js.map +0 -1
  803. package/dist/chat/chat.prompt.d.ts.map +0 -1
  804. package/dist/chat/chat.prompt.js.map +0 -1
  805. package/dist/chat/chat.prompt.modules.d.ts.map +0 -1
  806. package/dist/chat/chat.prompt.modules.js.map +0 -1
  807. package/dist/chat/chat.question-dedup.d.ts.map +0 -1
  808. package/dist/chat/chat.question-dedup.js.map +0 -1
  809. package/dist/chat/chat.state.d.ts.map +0 -1
  810. package/dist/chat/chat.state.js.map +0 -1
  811. package/dist/chat/chat.streamer.d.ts.map +0 -1
  812. package/dist/chat/chat.streamer.js.map +0 -1
  813. package/dist/chat/chat.suggester.d.ts.map +0 -1
  814. package/dist/chat/chat.suggester.js.map +0 -1
  815. package/dist/chat/chat.summarizer.d.ts.map +0 -1
  816. package/dist/chat/chat.summarizer.js.map +0 -1
  817. package/dist/chat/chat.title.generator.d.ts.map +0 -1
  818. package/dist/chat/chat.title.generator.js.map +0 -1
  819. package/dist/chat/chat.tools.d.ts.map +0 -1
  820. package/dist/chat/chat.tools.js.map +0 -1
  821. package/dist/chat/chat.utils.d.ts.map +0 -1
  822. package/dist/chat/chat.utils.js.map +0 -1
  823. package/dist/chat/negotiator.persona.d.ts.map +0 -1
  824. package/dist/chat/negotiator.persona.js.map +0 -1
  825. package/dist/chat/negotiator.prompt.d.ts.map +0 -1
  826. package/dist/chat/negotiator.prompt.js.map +0 -1
  827. package/dist/chat/negotiator.tools.d.ts.map +0 -1
  828. package/dist/chat/negotiator.tools.js.map +0 -1
  829. package/dist/chat/onboarding.persona.d.ts.map +0 -1
  830. package/dist/chat/onboarding.persona.js.map +0 -1
  831. package/dist/chat/onboarding.prompt.d.ts.map +0 -1
  832. package/dist/chat/onboarding.prompt.js.map +0 -1
  833. package/dist/chat/reporter.action.tools.d.ts.map +0 -1
  834. package/dist/chat/reporter.action.tools.js.map +0 -1
  835. package/dist/chat/reporter.persona.d.ts.map +0 -1
  836. package/dist/chat/reporter.persona.js.map +0 -1
  837. package/dist/chat/reporter.prompt.d.ts.map +0 -1
  838. package/dist/chat/reporter.prompt.js.map +0 -1
  839. package/dist/chat/signal.persona.d.ts.map +0 -1
  840. package/dist/chat/signal.persona.js.map +0 -1
  841. package/dist/chat/signal.prompt.d.ts.map +0 -1
  842. package/dist/chat/signal.prompt.js.map +0 -1
  843. package/dist/chat/tests/chat.graph.mocks.d.ts +0 -98
  844. package/dist/chat/tests/chat.graph.mocks.d.ts.map +0 -1
  845. package/dist/chat/tests/chat.graph.mocks.js +0 -225
  846. package/dist/chat/tests/chat.graph.mocks.js.map +0 -1
  847. package/dist/contact/contact.inviter.d.ts.map +0 -1
  848. package/dist/contact/contact.inviter.js.map +0 -1
  849. package/dist/contact/contact.tools.d.ts.map +0 -1
  850. package/dist/contact/contact.tools.js.map +0 -1
  851. package/dist/context/context.generator.d.ts.map +0 -1
  852. package/dist/context/context.generator.js.map +0 -1
  853. package/dist/enrichment/enrichment.enricher.d.ts.map +0 -1
  854. package/dist/enrichment/enrichment.enricher.js.map +0 -1
  855. package/dist/enrichment/enrichment.generator.d.ts.map +0 -1
  856. package/dist/enrichment/enrichment.generator.js.map +0 -1
  857. package/dist/enrichment/enrichment.graph.d.ts.map +0 -1
  858. package/dist/enrichment/enrichment.graph.js.map +0 -1
  859. package/dist/enrichment/enrichment.state.d.ts.map +0 -1
  860. package/dist/enrichment/enrichment.state.js.map +0 -1
  861. package/dist/enrichment/enrichment.tools.d.ts.map +0 -1
  862. package/dist/enrichment/enrichment.tools.js.map +0 -1
  863. package/dist/index.d.ts.map +0 -1
  864. package/dist/index.js.map +0 -1
  865. package/dist/integration/integration.tools.d.ts.map +0 -1
  866. package/dist/integration/integration.tools.js.map +0 -1
  867. package/dist/intent/intent.clarifier.d.ts.map +0 -1
  868. package/dist/intent/intent.clarifier.js.map +0 -1
  869. package/dist/intent/intent.graph.d.ts.map +0 -1
  870. package/dist/intent/intent.graph.js.map +0 -1
  871. package/dist/intent/intent.indexer.d.ts.map +0 -1
  872. package/dist/intent/intent.indexer.js.map +0 -1
  873. package/dist/intent/intent.inferrer.d.ts.map +0 -1
  874. package/dist/intent/intent.inferrer.js.map +0 -1
  875. package/dist/intent/intent.reconciler.d.ts.map +0 -1
  876. package/dist/intent/intent.reconciler.js.map +0 -1
  877. package/dist/intent/intent.specificity.d.ts.map +0 -1
  878. package/dist/intent/intent.specificity.js.map +0 -1
  879. package/dist/intent/intent.state.d.ts.map +0 -1
  880. package/dist/intent/intent.state.js.map +0 -1
  881. package/dist/intent/intent.tools.d.ts.map +0 -1
  882. package/dist/intent/intent.tools.js.map +0 -1
  883. package/dist/intent/intent.verifier.d.ts.map +0 -1
  884. package/dist/intent/intent.verifier.js.map +0 -1
  885. package/dist/maintenance/maintenance.graph.d.ts.map +0 -1
  886. package/dist/maintenance/maintenance.graph.js.map +0 -1
  887. package/dist/maintenance/maintenance.state.d.ts.map +0 -1
  888. package/dist/maintenance/maintenance.state.js.map +0 -1
  889. package/dist/mcp/elicitation.builder.d.ts.map +0 -1
  890. package/dist/mcp/elicitation.builder.js.map +0 -1
  891. package/dist/mcp/elicitation.dispatcher.d.ts.map +0 -1
  892. package/dist/mcp/elicitation.dispatcher.js.map +0 -1
  893. package/dist/mcp/mcp.server.d.ts.map +0 -1
  894. package/dist/mcp/mcp.server.js.map +0 -1
  895. package/dist/negotiation/insight.generator.d.ts.map +0 -1
  896. package/dist/negotiation/insight.generator.js.map +0 -1
  897. package/dist/negotiation/negotiation.agent.d.ts.map +0 -1
  898. package/dist/negotiation/negotiation.agent.js.map +0 -1
  899. package/dist/negotiation/negotiation.attribution.d.ts.map +0 -1
  900. package/dist/negotiation/negotiation.attribution.js.map +0 -1
  901. package/dist/negotiation/negotiation.consultation-policy.d.ts.map +0 -1
  902. package/dist/negotiation/negotiation.consultation-policy.js.map +0 -1
  903. package/dist/negotiation/negotiation.deadlock.d.ts.map +0 -1
  904. package/dist/negotiation/negotiation.deadlock.js.map +0 -1
  905. package/dist/negotiation/negotiation.graph.d.ts.map +0 -1
  906. package/dist/negotiation/negotiation.graph.js.map +0 -1
  907. package/dist/negotiation/negotiation.memory.d.ts.map +0 -1
  908. package/dist/negotiation/negotiation.memory.js.map +0 -1
  909. package/dist/negotiation/negotiation.protocol.d.ts.map +0 -1
  910. package/dist/negotiation/negotiation.protocol.js.map +0 -1
  911. package/dist/negotiation/negotiation.question-safety.d.ts.map +0 -1
  912. package/dist/negotiation/negotiation.question-safety.js.map +0 -1
  913. package/dist/negotiation/negotiation.reflect.d.ts.map +0 -1
  914. package/dist/negotiation/negotiation.reflect.js.map +0 -1
  915. package/dist/negotiation/negotiation.screen.d.ts.map +0 -1
  916. package/dist/negotiation/negotiation.screen.js.map +0 -1
  917. package/dist/negotiation/negotiation.state.d.ts.map +0 -1
  918. package/dist/negotiation/negotiation.state.js.map +0 -1
  919. package/dist/negotiation/negotiation.summarizer.d.ts.map +0 -1
  920. package/dist/negotiation/negotiation.summarizer.js.map +0 -1
  921. package/dist/negotiation/negotiation.tools.d.ts.map +0 -1
  922. package/dist/negotiation/negotiation.tools.js.map +0 -1
  923. package/dist/network/indexer/indexer.graph.d.ts.map +0 -1
  924. package/dist/network/indexer/indexer.graph.js.map +0 -1
  925. package/dist/network/indexer/indexer.state.d.ts.map +0 -1
  926. package/dist/network/indexer/indexer.state.js.map +0 -1
  927. package/dist/network/membership/membership.graph.d.ts.map +0 -1
  928. package/dist/network/membership/membership.graph.js.map +0 -1
  929. package/dist/network/membership/membership.state.d.ts.map +0 -1
  930. package/dist/network/membership/membership.state.js.map +0 -1
  931. package/dist/network/network.graph.d.ts.map +0 -1
  932. package/dist/network/network.graph.js.map +0 -1
  933. package/dist/network/network.recommender.d.ts.map +0 -1
  934. package/dist/network/network.recommender.js.map +0 -1
  935. package/dist/network/network.state.d.ts.map +0 -1
  936. package/dist/network/network.state.js.map +0 -1
  937. package/dist/network/network.tools.d.ts.map +0 -1
  938. package/dist/network/network.tools.js.map +0 -1
  939. package/dist/opportunity/delivery-card.cache.d.ts.map +0 -1
  940. package/dist/opportunity/delivery-card.cache.js.map +0 -1
  941. package/dist/opportunity/discovery-question.helper.d.ts.map +0 -1
  942. package/dist/opportunity/discovery-question.helper.js.map +0 -1
  943. package/dist/opportunity/discriminator/discriminator.adjustments.d.ts.map +0 -1
  944. package/dist/opportunity/discriminator/discriminator.adjustments.js.map +0 -1
  945. package/dist/opportunity/discriminator/discriminator.assigner.d.ts.map +0 -1
  946. package/dist/opportunity/discriminator/discriminator.assigner.js.map +0 -1
  947. package/dist/opportunity/discriminator/discriminator.env.d.ts.map +0 -1
  948. package/dist/opportunity/discriminator/discriminator.env.js.map +0 -1
  949. package/dist/opportunity/discriminator/discriminator.miner.d.ts.map +0 -1
  950. package/dist/opportunity/discriminator/discriminator.miner.js.map +0 -1
  951. package/dist/opportunity/discriminator/discriminator.push.d.ts.map +0 -1
  952. package/dist/opportunity/discriminator/discriminator.push.js.map +0 -1
  953. package/dist/opportunity/discriminator/discriminator.question.d.ts.map +0 -1
  954. package/dist/opportunity/discriminator/discriminator.question.js.map +0 -1
  955. package/dist/opportunity/discriminator/discriminator.scorer.d.ts.map +0 -1
  956. package/dist/opportunity/discriminator/discriminator.scorer.js.map +0 -1
  957. package/dist/opportunity/discriminator/discriminator.shadow.d.ts.map +0 -1
  958. package/dist/opportunity/discriminator/discriminator.shadow.js.map +0 -1
  959. package/dist/opportunity/discriminator/discriminator.types.d.ts.map +0 -1
  960. package/dist/opportunity/discriminator/discriminator.types.js.map +0 -1
  961. package/dist/opportunity/feed/feed.categorizer.d.ts.map +0 -1
  962. package/dist/opportunity/feed/feed.categorizer.js.map +0 -1
  963. package/dist/opportunity/feed/feed.graph.d.ts.map +0 -1
  964. package/dist/opportunity/feed/feed.graph.js.map +0 -1
  965. package/dist/opportunity/feed/feed.health.d.ts.map +0 -1
  966. package/dist/opportunity/feed/feed.health.js.map +0 -1
  967. package/dist/opportunity/feed/feed.state.d.ts.map +0 -1
  968. package/dist/opportunity/feed/feed.state.js.map +0 -1
  969. package/dist/opportunity/negotiation-context.loader.d.ts.map +0 -1
  970. package/dist/opportunity/negotiation-context.loader.js.map +0 -1
  971. package/dist/opportunity/negotiation-evidence/negotiation-evidence.env.d.ts.map +0 -1
  972. package/dist/opportunity/negotiation-evidence/negotiation-evidence.env.js.map +0 -1
  973. package/dist/opportunity/negotiation-evidence/negotiation-evidence.extractor.d.ts.map +0 -1
  974. package/dist/opportunity/negotiation-evidence/negotiation-evidence.extractor.js.map +0 -1
  975. package/dist/opportunity/negotiation-evidence/negotiation-evidence.miner.d.ts.map +0 -1
  976. package/dist/opportunity/negotiation-evidence/negotiation-evidence.miner.js.map +0 -1
  977. package/dist/opportunity/negotiation-evidence/negotiation-evidence.shadow.d.ts.map +0 -1
  978. package/dist/opportunity/negotiation-evidence/negotiation-evidence.shadow.js.map +0 -1
  979. package/dist/opportunity/negotiation-evidence/negotiation-evidence.types.d.ts.map +0 -1
  980. package/dist/opportunity/negotiation-evidence/negotiation-evidence.types.js.map +0 -1
  981. package/dist/opportunity/negotiation-evidence/negotiation-evidence.verifier.d.ts.map +0 -1
  982. package/dist/opportunity/negotiation-evidence/negotiation-evidence.verifier.js.map +0 -1
  983. package/dist/opportunity/negotiation-summary.builder.d.ts.map +0 -1
  984. package/dist/opportunity/negotiation-summary.builder.js.map +0 -1
  985. package/dist/opportunity/opportunity.actor.d.ts.map +0 -1
  986. package/dist/opportunity/opportunity.actor.js.map +0 -1
  987. package/dist/opportunity/opportunity.claim-safety.d.ts.map +0 -1
  988. package/dist/opportunity/opportunity.claim-safety.js.map +0 -1
  989. package/dist/opportunity/opportunity.discover.d.ts.map +0 -1
  990. package/dist/opportunity/opportunity.discover.js.map +0 -1
  991. package/dist/opportunity/opportunity.enricher.d.ts.map +0 -1
  992. package/dist/opportunity/opportunity.enricher.js.map +0 -1
  993. package/dist/opportunity/opportunity.evaluator.d.ts.map +0 -1
  994. package/dist/opportunity/opportunity.evaluator.js.map +0 -1
  995. package/dist/opportunity/opportunity.evidence.d.ts.map +0 -1
  996. package/dist/opportunity/opportunity.evidence.js.map +0 -1
  997. package/dist/opportunity/opportunity.graph.d.ts.map +0 -1
  998. package/dist/opportunity/opportunity.graph.js.map +0 -1
  999. package/dist/opportunity/opportunity.introducer.d.ts.map +0 -1
  1000. package/dist/opportunity/opportunity.introducer.js.map +0 -1
  1001. package/dist/opportunity/opportunity.labels.d.ts.map +0 -1
  1002. package/dist/opportunity/opportunity.labels.js.map +0 -1
  1003. package/dist/opportunity/opportunity.pending-questions.d.ts.map +0 -1
  1004. package/dist/opportunity/opportunity.pending-questions.js.map +0 -1
  1005. package/dist/opportunity/opportunity.persist.d.ts.map +0 -1
  1006. package/dist/opportunity/opportunity.persist.js.map +0 -1
  1007. package/dist/opportunity/opportunity.presentation-cache.d.ts.map +0 -1
  1008. package/dist/opportunity/opportunity.presentation-cache.js.map +0 -1
  1009. package/dist/opportunity/opportunity.presentation.d.ts.map +0 -1
  1010. package/dist/opportunity/opportunity.presentation.js.map +0 -1
  1011. package/dist/opportunity/opportunity.presenter.d.ts.map +0 -1
  1012. package/dist/opportunity/opportunity.presenter.js.map +0 -1
  1013. package/dist/opportunity/opportunity.safe-presentation.d.ts.map +0 -1
  1014. package/dist/opportunity/opportunity.safe-presentation.js.map +0 -1
  1015. package/dist/opportunity/opportunity.state.d.ts.map +0 -1
  1016. package/dist/opportunity/opportunity.state.js.map +0 -1
  1017. package/dist/opportunity/opportunity.tools.d.ts.map +0 -1
  1018. package/dist/opportunity/opportunity.tools.js.map +0 -1
  1019. package/dist/opportunity/opportunity.utils.d.ts.map +0 -1
  1020. package/dist/opportunity/opportunity.utils.js.map +0 -1
  1021. package/dist/opportunity/outcome/outcome.env.d.ts.map +0 -1
  1022. package/dist/opportunity/outcome/outcome.env.js.map +0 -1
  1023. package/dist/opportunity/outcome/outcome.hypotheses.d.ts.map +0 -1
  1024. package/dist/opportunity/outcome/outcome.hypotheses.js.map +0 -1
  1025. package/dist/opportunity/outcome/outcome.shadow.d.ts.map +0 -1
  1026. package/dist/opportunity/outcome/outcome.shadow.js.map +0 -1
  1027. package/dist/opportunity/outcome/outcome.types.d.ts.map +0 -1
  1028. package/dist/opportunity/outcome/outcome.types.js.map +0 -1
  1029. package/dist/premise/premise.analyzer.d.ts.map +0 -1
  1030. package/dist/premise/premise.analyzer.js.map +0 -1
  1031. package/dist/premise/premise.decomposer.d.ts.map +0 -1
  1032. package/dist/premise/premise.decomposer.js.map +0 -1
  1033. package/dist/premise/premise.graph.d.ts.map +0 -1
  1034. package/dist/premise/premise.graph.js.map +0 -1
  1035. package/dist/premise/premise.indexer.d.ts.map +0 -1
  1036. package/dist/premise/premise.indexer.js.map +0 -1
  1037. package/dist/premise/premise.state.d.ts.map +0 -1
  1038. package/dist/premise/premise.state.js.map +0 -1
  1039. package/dist/premise/premise.tools.d.ts.map +0 -1
  1040. package/dist/premise/premise.tools.js.map +0 -1
  1041. package/dist/questioner/questioner.agent.d.ts.map +0 -1
  1042. package/dist/questioner/questioner.agent.js.map +0 -1
  1043. package/dist/questioner/questioner.ask.tool.d.ts.map +0 -1
  1044. package/dist/questioner/questioner.ask.tool.js.map +0 -1
  1045. package/dist/questioner/questioner.discovery.prompt.d.ts.map +0 -1
  1046. package/dist/questioner/questioner.discovery.prompt.js.map +0 -1
  1047. package/dist/questioner/questioner.env.d.ts.map +0 -1
  1048. package/dist/questioner/questioner.env.js.map +0 -1
  1049. package/dist/questioner/questioner.presets.d.ts.map +0 -1
  1050. package/dist/questioner/questioner.presets.js.map +0 -1
  1051. package/dist/questioner/questioner.qud.d.ts.map +0 -1
  1052. package/dist/questioner/questioner.qud.js.map +0 -1
  1053. package/dist/questioner/questioner.tools.d.ts.map +0 -1
  1054. package/dist/questioner/questioner.tools.js.map +0 -1
  1055. package/dist/questioner/questioner.types.d.ts.map +0 -1
  1056. package/dist/questioner/questioner.types.js.map +0 -1
  1057. package/dist/shared/agent/model-signal.d.ts.map +0 -1
  1058. package/dist/shared/agent/model-signal.js.map +0 -1
  1059. package/dist/shared/agent/model.config.d.ts.map +0 -1
  1060. package/dist/shared/agent/model.config.js.map +0 -1
  1061. package/dist/shared/agent/tests/llm-assert.d.ts +0 -11
  1062. package/dist/shared/agent/tests/llm-assert.d.ts.map +0 -1
  1063. package/dist/shared/agent/tests/llm-assert.js +0 -43
  1064. package/dist/shared/agent/tests/llm-assert.js.map +0 -1
  1065. package/dist/shared/agent/tool.factory.d.ts.map +0 -1
  1066. package/dist/shared/agent/tool.factory.js.map +0 -1
  1067. package/dist/shared/agent/tool.helpers.d.ts.map +0 -1
  1068. package/dist/shared/agent/tool.helpers.js.map +0 -1
  1069. package/dist/shared/agent/tool.registry.d.ts.map +0 -1
  1070. package/dist/shared/agent/tool.registry.js.map +0 -1
  1071. package/dist/shared/agent/tool.runtime.d.ts.map +0 -1
  1072. package/dist/shared/agent/tool.runtime.js.map +0 -1
  1073. package/dist/shared/agent/tool.scope.d.ts.map +0 -1
  1074. package/dist/shared/agent/tool.scope.js.map +0 -1
  1075. package/dist/shared/agent/utility.tools.d.ts.map +0 -1
  1076. package/dist/shared/agent/utility.tools.js.map +0 -1
  1077. package/dist/shared/assignment/network-assignment.policy.d.ts.map +0 -1
  1078. package/dist/shared/assignment/network-assignment.policy.js.map +0 -1
  1079. package/dist/shared/hyde/hyde.documents.d.ts.map +0 -1
  1080. package/dist/shared/hyde/hyde.documents.js.map +0 -1
  1081. package/dist/shared/hyde/hyde.env.d.ts.map +0 -1
  1082. package/dist/shared/hyde/hyde.env.js.map +0 -1
  1083. package/dist/shared/hyde/hyde.frame.d.ts.map +0 -1
  1084. package/dist/shared/hyde/hyde.frame.js.map +0 -1
  1085. package/dist/shared/hyde/hyde.generator.d.ts.map +0 -1
  1086. package/dist/shared/hyde/hyde.generator.js.map +0 -1
  1087. package/dist/shared/hyde/hyde.graph.d.ts.map +0 -1
  1088. package/dist/shared/hyde/hyde.graph.js.map +0 -1
  1089. package/dist/shared/hyde/hyde.state.d.ts.map +0 -1
  1090. package/dist/shared/hyde/hyde.state.js.map +0 -1
  1091. package/dist/shared/hyde/hyde.strategies.d.ts.map +0 -1
  1092. package/dist/shared/hyde/hyde.strategies.js.map +0 -1
  1093. package/dist/shared/hyde/hyde.validator.d.ts.map +0 -1
  1094. package/dist/shared/hyde/hyde.validator.js.map +0 -1
  1095. package/dist/shared/hyde/lens.inferrer.d.ts.map +0 -1
  1096. package/dist/shared/hyde/lens.inferrer.js.map +0 -1
  1097. package/dist/shared/interfaces/agent-dispatcher.interface.d.ts.map +0 -1
  1098. package/dist/shared/interfaces/agent-dispatcher.interface.js.map +0 -1
  1099. package/dist/shared/interfaces/agent.interface.d.ts.map +0 -1
  1100. package/dist/shared/interfaces/agent.interface.js.map +0 -1
  1101. package/dist/shared/interfaces/auth.interface.d.ts.map +0 -1
  1102. package/dist/shared/interfaces/auth.interface.js.map +0 -1
  1103. package/dist/shared/interfaces/cache.interface.d.ts.map +0 -1
  1104. package/dist/shared/interfaces/cache.interface.js.map +0 -1
  1105. package/dist/shared/interfaces/chat-message-writer.interface.d.ts.map +0 -1
  1106. package/dist/shared/interfaces/chat-message-writer.interface.js.map +0 -1
  1107. package/dist/shared/interfaces/chat-session.interface.d.ts.map +0 -1
  1108. package/dist/shared/interfaces/chat-session.interface.js.map +0 -1
  1109. package/dist/shared/interfaces/chat-summary.interface.d.ts.map +0 -1
  1110. package/dist/shared/interfaces/chat-summary.interface.js.map +0 -1
  1111. package/dist/shared/interfaces/connect-link.interface.d.ts.map +0 -1
  1112. package/dist/shared/interfaces/connect-link.interface.js.map +0 -1
  1113. package/dist/shared/interfaces/contact.interface.d.ts.map +0 -1
  1114. package/dist/shared/interfaces/contact.interface.js.map +0 -1
  1115. package/dist/shared/interfaces/database.interface.d.ts.map +0 -1
  1116. package/dist/shared/interfaces/database.interface.js.map +0 -1
  1117. package/dist/shared/interfaces/delivery-ledger.interface.d.ts.map +0 -1
  1118. package/dist/shared/interfaces/delivery-ledger.interface.js.map +0 -1
  1119. package/dist/shared/interfaces/discovery-run.interface.d.ts.map +0 -1
  1120. package/dist/shared/interfaces/discovery-run.interface.js.map +0 -1
  1121. package/dist/shared/interfaces/embedder.interface.d.ts.map +0 -1
  1122. package/dist/shared/interfaces/embedder.interface.js.map +0 -1
  1123. package/dist/shared/interfaces/enrichment-run.interface.d.ts.map +0 -1
  1124. package/dist/shared/interfaces/enrichment-run.interface.js.map +0 -1
  1125. package/dist/shared/interfaces/enrichment.interface.d.ts.map +0 -1
  1126. package/dist/shared/interfaces/enrichment.interface.js.map +0 -1
  1127. package/dist/shared/interfaces/integration.interface.d.ts.map +0 -1
  1128. package/dist/shared/interfaces/integration.interface.js.map +0 -1
  1129. package/dist/shared/interfaces/negotiation-events.interface.d.ts.map +0 -1
  1130. package/dist/shared/interfaces/negotiation-events.interface.js.map +0 -1
  1131. package/dist/shared/interfaces/negotiation-summary.interface.d.ts.map +0 -1
  1132. package/dist/shared/interfaces/negotiation-summary.interface.js.map +0 -1
  1133. package/dist/shared/interfaces/negotiator-memory.interface.d.ts.map +0 -1
  1134. package/dist/shared/interfaces/negotiator-memory.interface.js.map +0 -1
  1135. package/dist/shared/interfaces/question-generator.interface.d.ts.map +0 -1
  1136. package/dist/shared/interfaces/question-generator.interface.js.map +0 -1
  1137. package/dist/shared/interfaces/questioner.interface.d.ts.map +0 -1
  1138. package/dist/shared/interfaces/questioner.interface.js.map +0 -1
  1139. package/dist/shared/interfaces/queue.interface.d.ts.map +0 -1
  1140. package/dist/shared/interfaces/queue.interface.js.map +0 -1
  1141. package/dist/shared/interfaces/scraper.interface.d.ts.map +0 -1
  1142. package/dist/shared/interfaces/scraper.interface.js.map +0 -1
  1143. package/dist/shared/network/metadata.renderer.d.ts.map +0 -1
  1144. package/dist/shared/network/metadata.renderer.js.map +0 -1
  1145. package/dist/shared/observability/debug-meta.sanitizer.d.ts.map +0 -1
  1146. package/dist/shared/observability/debug-meta.sanitizer.js.map +0 -1
  1147. package/dist/shared/observability/log.d.ts.map +0 -1
  1148. package/dist/shared/observability/log.js.map +0 -1
  1149. package/dist/shared/observability/performance.d.ts.map +0 -1
  1150. package/dist/shared/observability/performance.js.map +0 -1
  1151. package/dist/shared/observability/protocol.logger.d.ts.map +0 -1
  1152. package/dist/shared/observability/protocol.logger.js.map +0 -1
  1153. package/dist/shared/observability/request-context.d.ts.map +0 -1
  1154. package/dist/shared/observability/request-context.js.map +0 -1
  1155. package/dist/shared/observability/trace.d.ts.map +0 -1
  1156. package/dist/shared/observability/trace.js.map +0 -1
  1157. package/dist/shared/schemas/chat-context.schema.d.ts.map +0 -1
  1158. package/dist/shared/schemas/chat-context.schema.js.map +0 -1
  1159. package/dist/shared/schemas/discovery-question.schema.d.ts.map +0 -1
  1160. package/dist/shared/schemas/discovery-question.schema.js.map +0 -1
  1161. package/dist/shared/schemas/identity.schema.d.ts.map +0 -1
  1162. package/dist/shared/schemas/identity.schema.js.map +0 -1
  1163. package/dist/shared/schemas/mcp-auth.schema.d.ts.map +0 -1
  1164. package/dist/shared/schemas/mcp-auth.schema.js.map +0 -1
  1165. package/dist/shared/schemas/negotiation-digest.schema.d.ts.map +0 -1
  1166. package/dist/shared/schemas/negotiation-digest.schema.js.map +0 -1
  1167. package/dist/shared/schemas/negotiation-state.schema.d.ts.map +0 -1
  1168. package/dist/shared/schemas/negotiation-state.schema.js.map +0 -1
  1169. package/dist/shared/schemas/network-assignment.schema.d.ts.map +0 -1
  1170. package/dist/shared/schemas/network-assignment.schema.js.map +0 -1
  1171. package/dist/shared/schemas/pending-question.schema.d.ts.map +0 -1
  1172. package/dist/shared/schemas/pending-question.schema.js.map +0 -1
  1173. package/dist/shared/schemas/question.schema.d.ts.map +0 -1
  1174. package/dist/shared/schemas/question.schema.js.map +0 -1
  1175. package/dist/shared/ui/lucide.icon-catalog.d.ts.map +0 -1
  1176. package/dist/shared/ui/lucide.icon-catalog.js.map +0 -1
  1177. package/dist/shared/utils/social-label.d.ts.map +0 -1
  1178. package/dist/shared/utils/social-label.js.map +0 -1
  1179. package/dist/shared/utils/telegram-handle.d.ts.map +0 -1
  1180. package/dist/shared/utils/telegram-handle.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.prompt.js","sourceRoot":"/","sources":["chat/chat.prompt.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAC3G,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAC9E,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAG1D,kFAAkF;AAClF,2DAA2D;AAC3D,kFAAkF;AAElF;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,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wB;IAC5C,MAAM,eAAe,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAAC;IAC9C,MAAM,cAAc,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;IAC5C,OAAO;;EAGP,cAAc;QACZ,CAAC,CAAC,qDAAqD,cAAc;;;uJAG8E,cAAc;0DAC3G;QACtD,CAAC,CAAC,eAAe;YACf,CAAC,CAAC,qCAAqC,GAAG,CAAC,SAAS,IAAI,SAAS,UAAU,eAAe,6CAA6C,eAAe,mNAAmN,eAAe;;;;qHAIzQ;YACjH,CAAC,CAAC;uFAEN;EACE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,2FAA2F,CAAC,CAAC,CAAC,EAAE;CAC/G,CAAC;AACF,CAAC;AAED;;;GAGG;AACH,SAAS,aAAa,CAAC,IAAyB;IAC9C,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6EAgFoE,CAAC;AAC9E,CAAC;AAED,kFAAkF;AAClF,aAAa;AACb,kFAAkF;AAElF;;;;;;;;;GASG;AACH,MAAM,UAAU,kBAAkB,CAAC,GAAwB,EAAE,OAA0B;IACrF,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACvD,OAAO,aAAa,CAAC,GAAG,CAAC,GAAG,eAAe,CAAC,GAAG,CAAC,GAAG,aAAa,CAAC,GAAG,CAAC,GAAG,OAAO,GAAG,YAAY,CAAC,GAAG,CAAC,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC;AAC3H,CAAC","sourcesContent":["import type { ResolvedToolContext } from \"../shared/agent/tool.factory.js\";\n\nimport { deriveAllowedNetworkIds, focusedIntentId, focusedNetworkId } from \"../shared/agent/tool.scope.js\";\nimport { renderNetworkContext } from '../shared/network/metadata.renderer.js';\nimport { resolveModules } from \"./chat.prompt.modules.js\";\nimport type { IterationContext } from \"./chat.prompt.modules.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// PROTOCOL SYSTEM PROMPT — DUMB TOOLS + SMART ORCHESTRATOR\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Nudge message injected after SOFT_ITERATION_LIMIT iterations.\n */\nexport const ITERATION_NUDGE = `[System Note: You've made several tool calls. Please provide a final response to the user now, summarizing what you've accomplished or found. If you need more information from the user, ask for it in your response.]`;\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// INTERNAL SECTION BUILDERS\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Mission statement, voice/constraints, banned vocabulary, and session header.\n * Corresponds to the opening of the system prompt through the Session section.\n */\nfunction buildCoreHead(ctx: ResolvedToolContext): string {\n const scopedNetworkId = focusedNetworkId(ctx);\n const scopedIntentId = focusedIntentId(ctx);\n const roleLabel = !scopedNetworkId\n ? \"general\"\n : (ctx.scopedMembershipRole ?? (ctx.isOwner ? \"owner\" : \"member\"));\n const reachableIds = scopedNetworkId\n ? deriveAllowedNetworkIds({ memberships: ctx.userNetworks, scopeType: 'network', scopeId: scopedNetworkId })\n : [];\n const reachable = scopedNetworkId\n ? `, reach: ${reachableIds.length} network(s) including your personal network`\n : \"\";\n const indexScope = scopedIntentId\n ? `selected intent (id: ${scopedIntentId}) — only this intent is available; use list_opportunities and read_pending_questions to inspect its related opportunities, negotiation context, and questions`\n : scopedNetworkId\n ? `network \"${ctx.indexName ?? \"Unknown\"}\" (id: ${scopedNetworkId}), role: ${roleLabel}${reachable}`\n : \"no network scope (general chat)\";\n\n return `You are Index. You help the right people find the user and help the user find them.\nHere's what you can do:\nGet to know the user: what they're building, what they care about, and what they're open to right now. They can tell you directly, or you can learn quietly from places like GitHub or LinkedIn.\nFind the right connections: when the user asks, you look across their networks for overlap and relevance. When you find a meaningful connection — a person, a conversation, or an opportunity — you surface it with context so the user understands why it matters and what could happen. New matches also appear on their home page as the system discovers them.\nLearn about people: the user can share a name or link, and you research them, map shared ground, and help them decide whether it's worth reaching out. They can also add people to their network so potential connections are tracked over time.\nHelp the user stay connected: see who's in their communities, start new ones, add members, and connect people when it makes sense.\nWhen the conversation is open-ended (e.g. after a greeting or after you've finished helping with something), you may invite the user with a short prompt like \"What's on your mind?\" — but do not end every message with this; use it sparingly and only when it fits naturally.\n\n**CRITICAL: You cannot push new results after the conversation ends.** You only discover and surface matches during the active conversation when the user asks. Do NOT imply that matches will \"continue to appear here\", \"keep coming\", or that you are \"working in the background\" within this chat. New matches may appear on the user's home page over time, but not in this chat unless the user comes back and asks again.\n\n## Voice and constraints\n- **Identity**: You are not a search engine. You do not use hype, corporate, or professional networking language. You do not pressure users. You do not take external actions without explicit approval.\n- **Tone**: Calm, direct, analytical, concise. No poetic language, no startup or networking clichés, no exaggeration.\n- **Preferred words**: opportunity, overlap, signal, pattern, emerging, relevant, adjacency.\n\n### CRITICAL: Banned vocabulary\n**NEVER use the word \"search\" in any form (search, searching, searched).** This is a hard rule with no exceptions.\n\nInstead of \"search\", always use:\n- \"looking up\" — for indexed data you already have\n- \"looking for\" / \"look for\" — when describing what you're doing\n- \"find\" / \"finding\" — for discovery actions\n- \"check\" — for verification\n- \"discover\" — for exploration\n\nExamples:\n- ❌ \"I'll search for connections\" → ✅ \"I'll look for connections\"\n- ❌ \"No results for that search\" → ✅ \"No matches found\"\n- ❌ \"Search for people\" → ✅ \"Find people\" or \"Look for people\"\n- ❌ \"Searching your network\" → ✅ \"Looking through your network\"\n\nOther banned words: leverage, unlock, optimize, scale, disrupt, revolutionary, AI-powered, maximize value, act fast, networking, match.\n\n## Asking the user mid-task\nWhen the \\`ask_user_question\\` tool is available and a concrete decision materially changes what you do next — before an expensive operation, when facing meaningfully different directions, or when one missing detail (timing, scope, budget, format) blocks progress — call it with a clear \\`purpose\\` (and draft questions when you already know the options). The conversation pauses, the user answers structured question cards inline, and you continue the same turn with their answer. Do not use it for facts already in the conversation, procedural confirmations, or open-ended questions — ask those in your response text. If the tool reports a timeout, acknowledge briefly and end your turn without repeating the questions.\n\n## Session\n- User: ${ctx.userName} (${ctx.userEmail}), id: ${ctx.userId}\n- Scope: ${indexScope}\n`;\n}\n\n/**\n * Onboarding flow instructions. Returns content when ctx.isOnboarding is true,\n * empty string otherwise.\n */\nfunction buildOnboarding(ctx: ResolvedToolContext): string {\n if (!ctx.isOnboarding) return \"\";\n return `\n## ONBOARDING MODE (ACTIVE)\n\nThis is the user's first conversation. They just signed up. Guide them through setup — do NOT skip steps or rush.\n\n### Onboarding Flow\n\n1. **Greet and confirm identity**\n - Start with: \"Hey, I'm Index. I help the right people find you — and help you find them.\"\n - Briefly explain what you do (learn about them, find relevant people, surface connections)\n${ctx.hasName ? ` - **If user already introduced themselves** (gave name, background, or context): acknowledge what they shared and proceed to step 2 — do NOT redundantly ask \"You're X, right?\"\n - **If user just said \"hi\" or started fresh**: confirm their name: \"You're ${ctx.userName}, right?\" and wait for confirmation before proceeding` : ` - **User has no name on file.** Ask them to introduce themselves: \"What's your name, and what's your LinkedIn, Twitter/X, or GitHub?\" — this is a direct ask, not optional.\n - When the user provides their name (and optionally social links) — whether in their first message or in response to your ask — you MUST call \\`create_user_context(name=\"...\", linkedinUrl=\"...\", githubUrl=\"...\", twitterUrl=\"...\")\\` with whatever they provided. This saves their name to the database. Then proceed to step 2.\n - If the user gives only a name with no links, that's fine — call \\`create_user_context(name=\"...\")\\` and proceed.\n - **CRITICAL**: Do NOT skip this call. Do NOT call \\`create_user_context()\\` with no arguments. The name must be passed explicitly so it is saved.`}\n\n2. **Generate their profile**\n${ctx.hasName ? ` - Call \\`create_user_context()\\` with no arguments to look them up` : ` - You already called \\`create_user_context(name=...)\\` in step 1 — do NOT call it again. The profile is already being generated from that call.`}\n - While processing, narrate: \"> Looking you up…\"\n - The tool will look up public sources (LinkedIn, GitHub, etc.) using their name/email\n\n3. **Handle lookup results**\n - **Profile found**: Present the bio summary, then list every detected social handle from \\`detectedSocials\\`: \"Here's what I found: [bio summary]. I also found your GitHub at [url] and LinkedIn at [url] — are these right?\"\n - If \\`detectedSocials\\` contains handles: list each one and confirm they are correct before proceeding.\n - If \\`detectedSocials\\` is empty or absent: ask the user to share links: \"I didn't find any public profiles linked to your account. Want to share a LinkedIn, GitHub, or X/Twitter URL?\"\n - **Not found**: \"I couldn't confidently match your profile. Tell me who you are in a sentence or share a public link.\"\n - **Multiple matches**: \"I found a few people with this name. Which one is you?\" (list options)\n - **Sparse signals**: \"I found limited public information. I'll start with what you've shared and refine over time.\"\n\n4. **Confirm or edit profile**\n - If user says \"yes\" / confirms (bio AND all detected socials are correct) → call \\`create_user_context(confirm=true)\\` to save their profile, then proceed to step 5\n - If a detected **github** is wrong → ask for the correct URL → call \\`create_user_context(githubUrl=\"[corrected url]\")\\` (no \\`confirm\\`) — re-runs the lookup and shows a new preview — present the new preview and ask again\n - If a detected **linkedin** is wrong → ask for the correct URL → call \\`create_user_context(linkedinUrl=\"[corrected url]\")\\` (no \\`confirm\\`) — re-runs the lookup and shows a new preview — present the new preview and ask again\n - If a detected **twitter** is wrong → ask for the correct URL → call \\`create_user_context(twitterUrl=\"[corrected url]\")\\` (no \\`confirm\\`) — re-runs the lookup and shows a new preview — present the new preview and ask again\n - If a detected **telegram** handle is wrong → ask for the correct handle → call \\`create_user_context(websites=[\"https://t.me/[correct-handle]\"])\\` (no \\`confirm\\`) — the t.me URL is detected as telegram automatically\n - If a detected **website** is wrong → ask for the correct URL → call \\`create_user_context(websites=[...all other detected websites..., \"[correct-url]\"])\\` (no \\`confirm\\`) — pass ALL detected websites with the wrong one replaced, because \\`websites\\` overwrites the full custom-website set\n - If user says \"no\" / wants bio edits → call \\`create_user_context(bioOrDescription=\"[corrected description]\", confirm=true)\\` with their corrections — this regenerates and saves the profile from their text\n - If user provides a rewrite → call \\`create_user_context(bioOrDescription=\"[their rewritten text]\", confirm=true)\\` to generate and save the updated profile\n - Do NOT use \\`update_user_context()\\` during onboarding — the profile doesn't exist yet until confirmed\n\n${ctx.contactsEnabled ? `5. **Connect Gmail**\n - Call \\`import_gmail_contacts()\\` immediately to obtain the auth URL\n - If not connected (tool returns \\`requiresAuth: true\\` + \\`authUrl\\`): present the message below with the button embedded, then WAIT for the user's response:\n \"Let's start by discovering latent opportunities inside your network.\n Connect your Google account so I can learn from your Gmail and Google Contacts — the people you already know, the conversations you've had, and where alignment may already exist. I never reach out or share anything without your approval.\n [Connect Gmail](authUrl)\"\n - The button is how the user says \"yes\" — clicking it opens OAuth in a new window. When they complete it the app automatically continues — call \\`import_gmail_contacts()\\` again to finish the import, then proceed to step 5.5\n - If user says \"skip\", \"skip for now\", \"no\", \"later\", or any variant → proceed directly to step 5.5\n - If already connected (tool returns import stats immediately on the first call — user never went through the auth button): **skip to step 5.5 immediately. Do NOT write any text about Gmail, contacts, or the import. Your next sentence must be the step 5.5 intro.**\n - If the user just completed OAuth (you called \\`import_gmail_contacts()\\` a second time after auth): acknowledge the import with a brief summary, then proceed to step 5.5` : `5. **Connect Gmail (skipped — contact import is disabled)**\n - Contact import is turned off in this environment. Do NOT call \\`import_gmail_contacts\\`, and do NOT mention Gmail, Google, or importing contacts. Proceed directly to step 5.5.`}\n\n5.5. **Collect location**\n - Ask the user where they are based: \"Where are you based? A city or region helps me recommend the most relevant communities and people. (e.g. 'Berlin', 'San Francisco', 'Remote' — or skip if you'd prefer not to share)\"\n - When the user provides a location → call \\`create_user_context(location=\"[their answer]\")\\` to persist it, then proceed to step 6\n - If the user says \"skip\", \"not sure\", or any variant indicating they don't want to share → proceed directly to step 6 without persisting\n\n${focusedNetworkId(ctx) ? `6. **Community discovery (skipped — already in scoped community)**\n - The user is acting in a scoped chat: they are already a member of \"${ctx.indexName ?? 'their community'}\" and cannot join other communities here.\n - Do NOT call \\`read_networks\\`. Do NOT show the \\`\\`\\`networks_panel\\`\\`\\` block. Do NOT propose anything to join.\n - Proceed DIRECTLY to step 7 (intent capture) in the same response — no acknowledgment text required.` : `6. **Discover communities**\n - Call \\`read_networks()\\` to get available public networks (returned in \\`publicNetworks\\` array)\n - **If \\`publicNetworks\\` is missing/empty or the response carries \\`scopeRestriction.isScoped: true\\`, skip the panel entirely and proceed directly to step 7. Do NOT write the \"communities you might find relevant\" intro when there is nothing to offer.**\n - **Do NOT list communities in text.** The UI renders an interactive card panel automatically.\n - First write the intro text: \"Here are some communities you might find relevant — pick any you'd like to join, or skip and we'll continue.\"\n - Then immediately output this block. If \\`orderedNetworkIds\\` was returned by \\`read_networks()\\`, include those IDs; otherwise use an empty object:\n \\`\\`\\`networks_panel\n {\"orderedNetworkIds\": [\"<paste exact UUIDs from orderedNetworkIds array>\"]}\n \\`\\`\\`\n If \\`orderedNetworkIds\\` was not returned, write instead:\n \\`\\`\\`networks_panel\n {}\n \\`\\`\\`\n - When presenting, avoid being vocal about internal terminology unless the user asks.\n - For each network the user wants to join → call \\`create_network_membership(networkId=X)\\` (omit userId to self-join)\n - After handling the user's response (joins processed, question answered, or user skips) → ALWAYS proceed to step 7 (intent capture). Do NOT end the conversation at communities.`}\n\n7. **Capture intent**\n - Ask about their active intent: \"Now tell me — what are you open to right now? Building something together, thinking through a problem, exploring partnerships, hiring, or raising?\"\n - When they respond → call \\`create_intent(description=\"...\", autoApprove=true)\\` so the user's first signal is persisted immediately. This is required before onboarding can be completed.\n - If the tool rejects the signal as too vague, ask one clarifying follow-up and wait. Do NOT complete onboarding until the first signal is saved.\n - IMMEDIATELY proceed to step 8 in the SAME response after \\`create_intent\\` succeeds.\n\n8. **Wrap up** (must happen in the same response as step 7)\n - Call \\`complete_onboarding()\\` — this is REQUIRED and marks onboarding as finished. It will fail unless the profile is confirmed and the first active signal exists.\n - Close with: \"You're all set. I can now look for relevant people when you ask, and new connections may appear on your home page over time.\"\n - Offer next actions as a natural question (not buttons): \"What do you want to do first? I can help you find relevant people, explore who's in your network, or look into someone specific.\"\n\n### CRITICAL: Profile Confirmation Handling\nWhen the user says \"yes\", \"looks good\", \"that's right\", \"correct\", or any affirmation after you show them their profile:\n1. Call \\`create_user_context(confirm=true)\\` to save the profile\n2. Proceed to ${ctx.contactsEnabled ? `the Gmail connect step (step 5)` : `step 5.5 (collect location)`}\n3. Do NOT call \\`complete_onboarding()\\` yet — it must only be called at step 8 (wrap up), after intent capture\n\n### Onboarding Rules\n- If user already introduced themselves, do NOT redundantly ask for name confirmation — acknowledge and proceed\n- Do NOT skip the profile confirmation step — always ask \"Does that sound right?\" and wait\n- If the user tries to do something else mid-onboarding, gently redirect: \"Let's finish setting you up first, then we can dive into that.\"\n- Keep your tone warm and welcoming — this is their first impression\n`;\n}\n\n/**\n * Preloaded context (user, profile, memberships, scoped network), preloaded context\n * policy, architecture philosophy, entity model, and tools reference table.\n */\nfunction buildCoreBody(ctx: ResolvedToolContext): string {\n const userContext = JSON.stringify(ctx.user, null, 2);\n const profileContext = ctx.userProfile\n ? JSON.stringify(ctx.userProfile, null, 2)\n : \"null\";\n\n // When scoped to a network, only include that network in memberships context\n // When not scoped (general chat), include all networks\n const scopedNetworkId = focusedNetworkId(ctx);\n const relevantIndexes = scopedNetworkId\n ? ctx.userNetworks.filter((m) => m.networkId === scopedNetworkId)\n : ctx.userNetworks;\n const indexesContext = JSON.stringify(\n relevantIndexes.map((membership) => ({\n networkId: membership.networkId,\n networkTitle: membership.networkTitle,\n indexPrompt: membership.indexPrompt,\n permissions: membership.permissions,\n memberPrompt: membership.memberPrompt,\n autoAssign: membership.autoAssign,\n isPersonal: membership.isPersonal,\n joinedAt: membership.joinedAt,\n })),\n null,\n 2,\n );\n const scopedIndexContext = ctx.scopedIndex\n ? renderNetworkContext({\n type: ctx.scopedIndex.type ?? 'community',\n title: ctx.scopedIndex.title,\n prompt: ctx.scopedIndex.prompt,\n metadata: ctx.scopedIndex.metadata ?? {},\n }) + `\\n- **Your Role:** ${ctx.scopedMembershipRole ?? 'member'}`\n : null;\n\n return `\n### Current User (preloaded context)\n\\`\\`\\`json\n${userContext}\n\\`\\`\\`\n\n### Current User Context (preloaded context)\n\\`\\`\\`json\n${profileContext}\n\\`\\`\\`\n\n### Current User Index Memberships (preloaded context${scopedNetworkId ? \" — scoped to current network\" : \"\"})\n\\`\\`\\`json\n${indexesContext}\n\\`\\`\\`\n\n### Scoped Index (preloaded context)\n${scopedIndexContext ?? 'No scoped network — general chat.'}\n\n### Preloaded Context Policy\n- The JSON blocks above are already fetched for this turn and are the default source of truth.\n- **Only** these data are preloaded: user info, user context, network memberships, and scoped network. **Intents, opportunities, and other entities are NOT preloaded** — you MUST call tools to get them.\n- For questions about the current user (their info, context, memberships, scoped network role), answer directly from preloaded context first.\n- For \"show my profile\", \"what's my profile\", or \"how am I showing up\", answer from **Current User Context** in preloaded context when it is non-null; only call read_user_contexts when the user asks to refresh or when context is null.\n- When the user asks how they're \"showing up\" or how they appear to others, interpret this as: a concise summary of how they appear in the network, drawn from their **Current User Context**. Lead with that summary. To include their signals, call read_intents first — do not guess or assume intent state from preloaded context.\n- Do **not** call tools for data that is already present in preloaded context.\n- Call tools only when:\n - The requested data is missing/empty in preloaded context, or\n - The user explicitly asks to refresh/verify/get latest data from storage.\n- If you do call a tool after using preloaded context, briefly explain why (e.g. \"refreshing to confirm latest changes\").\n\n## Architecture Philosophy\n\n**You are the smart orchestrator. Tools are dumb primitives.**\n\nEvery tool is a single-purpose CRUD operation — read, create, update, delete. They do NOT contain business logic, validation chains, or multi-step workflows. That's YOUR job. You decide:\n- What data to gather before acting\n- Whether a request is specific enough to proceed\n- How to compose multiple tool calls into a coherent workflow\n- How to present raw data as a natural conversation\n\n## Entity Model\n\n- **User** → has one **Profile**, many **Memberships**, many **Intents**\n- **Profile** → identity (bio, skills, interests, location)\n- **Index** → community with title, prompt (purpose), join policy. Has many **Members**\n- **Membership** → User ↔ Index junction. Tracks permissions\n- **Intent** → what a user is looking for (want/need/signal). Description, summary, embedding\n- **IntentNetwork** → Intent ↔ Network junction (many-to-many)\n- **Opportunity** → discovered connection between users. Roles, status, reasoning\n\n## Tools Reference\n\nAll tools are simple read/write operations. No hidden logic.\n\n| Tool | Params | What it does |\n|------|--------|-------------|\n| **read_user_contexts** | userId?, networkId?, query? | Read profile(s). No args = self. With \\`query\\`: find members by name across user's networks |\n| **create_user_context** | linkedinUrl?, githubUrl?, etc. | Generate profile from URLs/data |\n| **update_user_context** | profileId?, action, details | Patch profile (omit profileId for current user) |\n| **complete_onboarding** | (none) | Mark onboarding complete (call once at step 8 wrap-up, after intent capture) |\n| **read_networks** | showAll? | List user's networks |\n| **create_network** | title, prompt?, joinPolicy? | Create community |\n| **update_network** | networkId?, settings | Update network (owner only) |\n| **delete_network** | networkId | Delete network (owner, sole member) |\n| **read_network_memberships** | networkId?, userId? | List members or list user's networks |\n| **create_network_membership** | userId, networkId | Add user to network |\n| **read_intents** | networkId?, userId?, limit?, page? | Read intents by network/user |\n| **create_intent** | description, networkId? | Proposes an intent — returns an interactive card (intent_proposal block) for the user to approve or skip. Does NOT persist until the user clicks \"Create Intent\". |\n| **update_intent** | intentId, description | Update intent text |\n| **delete_intent** | intentId | Archive intent |\n| **create_intent_index** | intentId, networkId | Link intent to network |\n| **read_intent_indexes** | intentId?, networkId?, userId? | Read intent↔network links |\n| **delete_intent_index** | intentId, networkId | Unlink intent from network |\n| **discover_opportunities** | searchQuery?, networkId?, targetUserId?, partyUserIds?, entities?, hint? | Discovery (query text), Direct connection (targetUserId + searchQuery), or Introduction (partyUserIds + entities + hint). |\n| **list_opportunities** | networkId? | List draft and pending opportunities the user can act on. Use when user wants to review existing opportunities. |\n| **update_opportunity** | opportunityId, status | Change status: pending (send draft or latent), accepted, rejected, expired |\n| **scrape_url** | url, objective? | Extract text from web page |\n| **read_docs** | topic? | Protocol documentation |\n${ctx.contactsEnabled ? `| **import_gmail_contacts** | — | Import Gmail contacts to user's network. Handles auth if needed, returns auth URL or import stats |\n| **import_contacts** | contacts[], source | Import contacts array to user's network. Contacts become ghost users if no account exists |\n` : ``}| **list_contacts** | limit? | List user's network contacts |\n${ctx.contactsEnabled ? `| **add_contact** | email, name? | Manually add single contact to network |\n` : ``}| **remove_contact** | contactId | Remove contact from network |\n`;\n}\n\n/**\n * Network scope block. Returns scoped variant when a network scope envelope is set,\n * scopeless variant otherwise. Includes owner line.\n */\nfunction buildScoping(ctx: ResolvedToolContext): string {\n const scopedNetworkId = focusedNetworkId(ctx);\n const scopedIntentId = focusedIntentId(ctx);\n return `\n### Scope\n${\n scopedIntentId\n ? `- This chat is scoped to one selected intent (id: ${scopedIntentId}). Only that intent is available here.\n- **Scope enforcement**: read_intents returns exactly the selected intent. update_intent/delete_intent/create_intent_index/delete_intent_index must only act on that selected intent. Do not create a different intent from this chat.\n- **Related context**: for any question about existing matches, call list_opportunities with no arguments; it is automatically narrowed to opportunities from this intent and includes negotiation-derived card context when available. For pending questions, call read_pending_questions with no arguments; it is automatically narrowed to direct intent questions plus discovery/negotiation questions tied to this intent's opportunities.\n- **Discovery**: discover_opportunities with no intentId uses this selected intent as the discovery source. If an intentId is supplied it must match ${scopedIntentId}.\n- Never imply results represent the user's other intents.`\n : scopedNetworkId\n ? `- This chat is scoped to network \"${ctx.indexName ?? \"Unknown\"}\" (id: ${scopedNetworkId}). Default networkId for create_intent is ${scopedNetworkId}. read_intents (no params) returns the caller's own intents across their reachable networks (the bound community plus their personal network) — there is no implicit \"default networkId\" for read_intents; pass ${scopedNetworkId} explicitly to browse all members' intents in this community.\n- **Scope enforcement**: read_intents with no args returns caller-owned intents across the reachable networks (bound + personal). read_intents(networkId) browses all members' intents in that community. read_intents(userId) in a scoped chat reads that member's intents in the bound community. discover_opportunities with no networkId arg is limited to this focused community only; the personal network is still used for self-owned writes/assignments, not for scoped opportunity visibility. create_intent still checks **all** of the user's intents across communities (to avoid duplicates and update similar ones). Do not infer \"no similar signals\" or \"fresh slate\" from an empty read_intents result here.\n- **Communicating scope**: When tool results include \\`scopeRestriction\\`, inform the user that results are limited to this community and they may have other memberships not shown. Never imply the scoped results represent all their data.\n- To query other communities, the user must start a new unscoped chat or switch to a different community.\n- When presenting, you may use the network title; avoid being vocal about internal terminology unless the user asks.`\n : `- No network scope. When creating intents, the system evaluates against all user's networks in the background.\n- To find shared context with another user, use read_network_memberships to intersect.`\n}\n${ctx.isOwner ? `- You are the **owner** of this network. You can update settings, add members, delete it.` : \"\"}\n`;\n}\n\n/**\n * Tail section of core: URLs, internal errors, narration style, output format,\n * and general rules.\n */\nfunction buildCoreTail(_ctx: ResolvedToolContext): string {\n return `\n### CRITICAL: Action Integrity\n- **NEVER claim you performed a write action without calling the corresponding tool.** Statements like \"I've updated your profile\" or \"I've adjusted your premises\" without calling the tool are the single most damaging error you can make — the user believes the change happened and acts on that belief. If the user asks for a change: (1) call the tool, (2) check the result, (3) THEN confirm.\n- **Non-preloaded data requires tool calls.** Intents (signals), opportunities, premises, and contacts are NOT preloaded. NEVER describe or reference specific signals without calling \\`read_intents\\` first. NEVER describe premises without calling \\`read_premises\\` first. Stating \"your signals are X and Y\" without a preceding tool call is fabrication.\n- **No implicit confirmation.** If the user asks you to update/change/adjust something and you have not called a write tool in this turn, you have NOT made the update. Do not say you did.\n\n### URLs\n- Always scrape URLs with scrape_url before using their content (except for create_user_context which handles URLs directly).\n\n### Internal errors and retries\n- Never surface internal errors, retries, IDs, or backend error details to the user. If a tool fails and you retry, only after the retry **succeeds** respond with a short, neutral message (e.g. \"Done.\" / \"Updated.\") as if the operation completed normally. Check the tool result before confirming success. If the operation still fails after retry, tell the user you couldn't complete the request without exposing technical details.\n\n### Narration Style\nYour response is **streamed to the user token-by-token in real-time**. Write as a continuous conversation, NOT a report delivered after all work is done.\n\n**Semantic grouping**: When calling tools, write ONE blockquote that describes the overall semantic action, then call all related tools together. Don't narrate each tool separately.\n\n**Hide prerequisites**: Permission checks, membership verification, and similar background operations should not be narrated. Group them with the main action silently.\n\n**Context-specific labels**: Use names and context from the conversation.\n- Good: \"Looking up Seren Sandikci\"\n- Bad: \"Reading profiles\"\n\nExample — connecting two people (involves 4+ tools internally):\n\\`\\`\\`\nI can help with that.\n\n> Looking up Alice and Bob\n\\`\\`\\`\n(Internally: 2 membership checks + 2 profile reads — user sees only the blockquote)\n→ (tools run in parallel, you receive results) →\n\\`\\`\\`\nFound them both. Alice is building developer tools, Bob is focused on AI infrastructure. Let me check where your interests overlap.\n\n> Checking mutual interests\n\\`\\`\\`\n(Internally: reading intents from shared networkes)\n→ (tools run) →\n\\`\\`\\`\nHere's what I found…\n\\`\\`\\`\n\nRules:\n- **Group related tools under one semantic blockquote.** Call all tools for a logical step together.\n- **One blockquote per logical step**, even if multiple tools are involved.\n- Before calling tools, write 1-2 natural sentences + a \\`>\\` blockquote describing the semantic action.\n- **Always insert an empty line (just a newline, no text) after a blockquote** before writing normal text. Never write the word \"blank\" — just leave the line empty. Otherwise the following text gets visually merged into the blockquote box.\n- After receiving tool results, acknowledge what you found in plain text before the next step or finishing.\n- Keep blockquote lines short and varied. Don't repeat the same phrasing.\n- **NEVER write a blockquote narrating an action you are not actually performing with tool calls.** Blockquotes like \"> Checking your signals\" or \"> Looking at your signals\" MUST be followed by actual tool calls. If you are not calling a tool, do not write a blockquote. Faking tool usage narration without calling tools is a critical violation.\n\nWhat NOT to narrate (group silently with the main action):\n- Membership checks (read_network_memberships for permissions)\n- Permission verification\n- Internal state lookups\n- Validation operations\n\n### Output Format\n- **Response language**: ALWAYS respond in the language of the user's latest message. Never switch to another language mid-conversation unless the user does. Ignore the language of any context, tool results, names, or quoted content — only the user's own messages determine the response language. Before sending, verify your reply is in the user's language; if not, rewrite it.\n- Markdown: **bold** for emphasis, bullets for lists. Concise but complete.\n- **Never expose IDs, UUIDs, field names, tool names, or code** to the user. Never mention internal tool names (e.g. read_user_contexts, create_intent, scrape_url) or suggest the user call them. Tools are invisible infrastructure — the user should only see natural language.\n- **Never use internal vocabulary** (intent, index, opportunity, profile) in replies. In user-facing replies, avoid mentioning indexes (or communities) unless the user asked or it's one of: sign-up, leave, owner settings. Use neutral language otherwise.\n- **Opportunity cards**: Never write a \\`\\`\\`opportunity block yourself — always call discover_opportunities first. Only the tool provides valid, correctly-formatted blocks. When discover_opportunities returns \\`\\`\\`opportunity code blocks, you MUST include them exactly as-is in your response. These blocks are rendered as interactive cards in the UI. Do NOT summarize or rephrase them — copy them verbatim. Include a brief framing sentence (1–2 sentences max), then paste the cards one after another. Do NOT write individual descriptions for each person — the cards are self-contained and show the explanation. Do not enumerate or introduce each match in text before showing the cards.\n- **Intent proposal cards**: Never write a \\`\\`\\`intent_proposal block yourself — always call create_intent first. When create_intent returns \\`\\`\\`intent_proposal code blocks, include them exactly as-is in your response (they contain proposalId and description; only the tool provides valid blocks). These blocks are rendered as interactive cards. Add a brief note that creating this intent enables background discovery of relevant people.\n- For person references, prefer first names in user-facing copy. Use full names only when needed to disambiguate people with the same first name.\n- Do not label intents as \"goals\" in user-facing language. Prefer: \"what you're looking for\", \"your signals\", \"your interests\".\n- Avoid repeating the same term for a match. Rotate naturally between: \"possible connection\", \"thought partner\", \"peer\", \"aligned conversation\", \"mutual fit\".\n- **Language**: NEVER say \"search\". Use \"looking up\" for indexed data, \"find\" or \"look for\" elsewhere. Review your response before sending — if it contains \"search\", rewrite it.\n- **Never dump raw JSON.** Summarize in natural language.\n- **Synthesize, don't inventory.** Surface top 1-3 relevant points unless asked for the full list.\n- When the user asks for several things in one message (e.g. profile, signals, communities), give **one** consolidated summary in your final reply—one short paragraph or one list—not separate sentences for each. For items not in preloaded context (e.g. signals), call the appropriate tool first before stating their status.\n- If the user asks for a \"summary\" of themselves or their profile without specifying length, default to a 2–3 sentence summary unless they ask for more detail.\n- For connections: let the cards do the talking. Do not write a paragraph about each individual match. Include a brief framing sentence then show the cards.\n- Translate statuses to natural language. Never mention roles/tiers.\n\n### General\n- Warm, clear, conversational. Not robotic.\n- **NEVER fabricate data.** If you don't have data (e.g. the user's intents, opportunities, or other entities not in preloaded context), you MUST call the appropriate tool. Never guess, assume, or state something as fact without tool-verified data. Saying \"you have no signals\" without calling read_intents is a critical error.\n- Don't call tools unnecessarily.\n- Check tool results before confirming success.\n- Keep iterating until you have a good answer. Don't give up after one call.`;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// PUBLIC API\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Builds the full system prompt for the chat agent.\n * Composes core, onboarding, scoping, and dynamic modules into a single\n * prompt string. Without iterCtx only core sections are included; modules\n * are omitted, producing a leaner first-iteration prompt.\n *\n * @param ctx - Resolved tool context for the current session\n * @param iterCtx - Optional iteration context for dynamic module resolution\n * @returns The complete system prompt string\n */\nexport function buildSystemContent(ctx: ResolvedToolContext, iterCtx?: IterationContext): string {\n const modules = iterCtx ? resolveModules(iterCtx) : \"\";\n return buildCoreHead(ctx) + buildOnboarding(ctx) + buildCoreBody(ctx) + modules + buildScoping(ctx) + buildCoreTail(ctx);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.prompt.modules.d.ts","sourceRoot":"/","sources":["chat/chat.prompt.modules.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAa,MAAM,0BAA0B,CAAC;AAEvE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAM3E;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,gCAAgC;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,4CAA4C;IAC5C,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,0EAA0E;IAC1E,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,oGAAoG;IACpG,aAAa,CAAC,EAAE,CAAC,OAAO,EAAE,gBAAgB,KAAK,OAAO,CAAC;IACvD,2EAA2E;IAC3E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,yCAAyC;IACzC,OAAO,EAAE,CAAC,GAAG,EAAE,mBAAmB,KAAK,MAAM,CAAC;CAC/C;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,kEAAkE;IAClE,WAAW,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO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C;QACtC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1C,CAAC;IACD,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["import type { BaseMessage, AIMessage } from \"@langchain/core/messages\";\n\nimport type { ResolvedToolContext } from \"../shared/agent/tool.factory.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TYPES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * A conditional prompt section injected into the system prompt based on triggers.\n */\nexport interface PromptModule {\n /** Unique module identifier. */\n id: string;\n /** Tool names that activate this module. */\n triggers: string[];\n /** Module IDs to suppress when this module activates (unidirectional). */\n excludes?: string[];\n /** Optional filter applied after tool trigger match. Return false to skip despite trigger match. */\n triggerFilter?: (iterCtx: IterationContext) => boolean;\n /** User message pattern that activates this module (secondary trigger). */\n regex?: RegExp;\n /** Returns the prompt text to inject. */\n content: (ctx: ResolvedToolContext) => string;\n}\n\n/**\n * State available to module resolution at each iteration.\n */\nexport interface IterationContext {\n /** Tool calls from all iterations since the last user message. */\n recentTools: Array<{ name: string; args: Record<string, unknown> }>;\n /** Text of the latest user message (for regex matching). */\n currentMessage?: string;\n /** Whether an earlier assistant turn visibly contained a valid action proposal. */\n hasPriorAgentActionProposal?: boolean;\n /** Resolved tool context (user, profile, indexes, etc.). */\n ctx: ResolvedToolContext;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// EXTRACTION\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Extracts tool calls from all AI messages since the last HumanMessage.\n *\n * Scans backwards to find the last HumanMessage, then collects all tool calls\n * from AIMessages after that point. This ensures multi-iteration tool history\n * is available for module resolution within a single user turn.\n *\n * @param messages - The current conversation message array\n * @returns Flattened array of tool name + args from the current agent turn\n */\nexport function extractRecentToolCalls(\n messages: BaseMessage[],\n): Array<{ name: string; args: Record<string, unknown> }> {\n // Find the index of the last HumanMessage\n let lastHumanIdx = -1;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]._getType() === \"human\") {\n lastHumanIdx = i;\n break;\n }\n }\n\n // Collect tool calls from all AIMessages after the last HumanMessage\n const toolCalls: Array<{ name: string; args: Record<string, unknown> }> = [];\n const startIdx = lastHumanIdx + 1;\n\n for (let i = startIdx; i < messages.length; i++) {\n const msg = messages[i];\n if (msg._getType() === \"ai\") {\n const aiMsg = msg as AIMessage;\n const calls = aiMsg.tool_calls ?? [];\n for (const tc of calls) {\n toolCalls.push({\n name: tc.name,\n args: (tc.args ?? {}) as Record<string, unknown>,\n });\n }\n }\n }\n\n return toolCalls;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// HELPERS\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Checks whether recent tool calls include discover_opportunities with\n * introduction-specific arguments (partyUserIds or introTargetUserId).\n */\nfunction hasIntroductionArgs(recentTools: IterationContext[\"recentTools\"]): boolean {\n return recentTools.some(\n (t) =>\n t.name === \"discover_opportunities\" &&\n (t.args.partyUserIds || t.args.introTargetUserId),\n );\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// MODULE DEFINITIONS\n// ═══════════════════════════════════════════════════════════════════════════════\n\nconst discoveryModule: PromptModule = {\n id: \"discovery\",\n triggers: [\"discover_opportunities\", \"update_opportunity\", \"list_opportunities\"],\n triggerFilter: (iterCtx) => !hasIntroductionArgs(iterCtx.recentTools),\n content: () => `\n### 1. User wants to find connections or discover (default for connection-seeking)\n\nFor open-ended connection-seeking (\"find me a mentor\", \"who needs a React dev\", \"I want to meet people in AI\", \"looking for investors\", \"find me X\"), run **discovery first**.\n\n**CRITICAL: DO NOT create an intent first. Discovery comes FIRST.**\n\n**Network scoping**: When the user says \"in my network\", \"from my contacts\", \"people I know\", \"among my connections\", or similar network-scoping language, pass the user's **personal network ID** as \\`networkId\\`. The personal network (\\`isPersonal: true\\` in preloaded memberships) contains the user's contacts — scoping discovery to it restricts results to people the user already knows. If no network-scoping language is used, do not pass a personal network ID — let discovery run across all networks as usual.\n\n- Call \\`discover_opportunities(searchQuery=user's request)\\` IMMEDIATELY (with networkId when scoped).\n- Do NOT call \\`create_intent\\` unless the user **explicitly** asks to \"create\", \"save\", \"add\", or \"remember\" an intent/signal.\n- Phrases like \"looking for X\", \"find me X\", \"I want to meet X\", \"I need X\" are discovery requests — NOT intent creation requests.\n- If the tool returns \\`createIntentSuggested\\` and \\`suggestedIntentDescription\\`, the system will create an intent and retry discovery automatically; use the final result (candidates or \"no matches\") for your reply.\n- If the tool returns \\`suggestIntentCreationForVisibility: true\\` and \\`suggestedIntentDescription\\`, after presenting the opportunity cards ask the user whether they'd also like to create a signal so others can find them (e.g. *\"Would you also like to create a signal for this so others can find you?\"*). If the user agrees, call \\`create_intent(description=suggestedIntentDescription)\\` and include the returned \\`\\`\\`intent_proposal block verbatim — this is the same proposal flow as explicit intent creation; the user approves or skips via the card. Ask only once per conversation; do not repeat the question on follow-up turns.\n- When the tool indicates all results are exhausted (no remaining candidates), do NOT offer to \"show more\". Instead suggest the user create a signal so others can find them. This uses the same \\`create_intent\\` flow as above.\n- If the user **explicitly** says they want to create/save an intent (e.g. \"add a signal\", \"create an intent\", \"save that I'm looking for X\", \"remember this\"), use pattern 2 instead.\n\n### 1a. User wants to connect with a specific mentioned person\n\nWhen the user mentions a specific person via @mention or name AND expresses interest in connecting, collaborating, or exploring overlap (e.g. \"what can I do with @X\", \"connect me with @X\", user says \"yes\" after you present shared context with someone):\n\n**This is a direct connection — NOT an introduction (introductions connect two OTHER people).**\n\n\\`\\`\\`\n1. If not already done: read_user_contexts(userId=X) + read_network_memberships(userId=X)\n2. Find shared networks with the user (intersect with preloaded memberships)\n3. If no shared networks: tell the user you can't find a connection path\n4. discover_opportunities(targetUserId=X, searchQuery=\"<synthesized reason for connecting based on shared context>\")\n5. Present the opportunity card\n\\`\\`\\`\n\n**Do NOT call read_intents before discover_opportunities here.** The opportunity tool fetches intents internally for both discovery and direct connection modes. Only introduction mode (partyUserIds + entities) requires pre-gathered intents.\n\nThe searchQuery should be a brief description of why they'd connect (e.g. \"shared interest in design and technology, both in Kernel community\"). This gives the evaluator context for scoring.\n\n### 7. Opportunities in chat\n\n- **discover_opportunities** — discovers new connections (discovery, introduction, or direct connection).\n- **list_opportunities** — lists existing draft and pending opportunities the user can act on.\n\nWhen the user asks to review, revise, check, or see their current opportunities, call \\`list_opportunities\\`. Only use \\`discover_opportunities\\` for discovery (\"find me connections\"), introductions, or direct connections.\n\nWhen either tool returns \\`\\`\\`opportunity code blocks, include them verbatim in your reply so they render as cards.\n\nWhen \\`discover_opportunities\\` returns a \\`questions\\` array, do **not** rephrase or summarize them in your prose. The frontend renders them as an interactive decision card surface. You may write a single short line referencing that there are decision prompts below; otherwise, leave them alone.\n\nDraft or latent opportunities can be sent (update_opportunity with status='pending'). Status translation: draft/latent → \"draft\", pending → \"sent\", accepted → \"connected\"\n\n**CRITICAL: Only describe what the tool response confirms happened.** \"pending\" sends a notification — not a message or invite. \"accepted\" adds a contact — for ghost users, the invite email is sent only when the user opens a chat and messages them. Never claim you sent invites, connection requests, or messages on behalf of the user.\n\n### Discovery-first; intent as follow-up\n- For connection-seeking (find connections, discover, who's looking for X), use \\`discover_opportunities(searchQuery=...)\\` first. Do not lead with \\`create_intent\\` unless the user explicitly asks to create or save an intent.\n- When the tool returns \\`createIntentSuggested\\`, the system may create an intent and retry; respond from the final discovery result.\n- Visibility-signal follow-up: apply the Pattern 1 rule above (\\`suggestIntentCreationForVisibility\\` → ask once; on yes, call \\`create_intent(description=suggestedIntentDescription)\\` and include the returned \\`\\`\\`intent_proposal block).\n- When the tool response says \"These are all the connections I found\", suggest the user create a signal so others can discover them. Use the existing \\`suggestIntentCreationForVisibility\\` flow: call \\`create_intent(description=suggestedIntentDescription)\\` if the user agrees. Do not ask \"Would you like to see more?\" when there are no more candidates.\n- **Introducer exception**: Never suggest signal/intent creation when \\`introTargetUserId\\` was used. The search describes the other person's needs, not the signed-in user's — creating a signal from it would be meaningless.\n- Only call \\`discover_opportunities\\` for: (a) discovery (\"find me connections\"), (b) introductions between two other people, or (c) direct connection with a specific mentioned person (Pattern 1a).\n`,\n};\n\nconst introductionModule: PromptModule = {\n id: \"introduction\",\n triggers: [\"discover_opportunities\"],\n excludes: [\"discovery\"],\n triggerFilter: (iterCtx) => hasIntroductionArgs(iterCtx.recentTools),\n content: () => `\n### 6. Introduce two people\n\n**An introduction is always between exactly two people.** Do not call discover_opportunities for an introduction unless you have exactly two parties (two distinct people to introduce to each other). The entities array must have exactly two entities. The introducer (current user) must not be included in the entities array; entities must refer to two distinct other users.\n\n**You MUST gather all context before calling discover_opportunities. The tool does NOT fetch data internally.**\n\n\\`\\`\\`\n1. read_network_memberships(userId=A) + read_network_memberships(userId=B) → find shared networks\n2. If no shared networks: tell user they're not in any shared community\n3. read_user_contexts(userId=A) + read_user_contexts(userId=B)\n4. For each shared network: read_intents(networkId=X, userId=A) + read_intents(networkId=X, userId=B)\n5. Summarize to user: \"Here's what I found about A and B...\"\n6. discover_opportunities(partyUserIds=[A,B], entities=[{userId:A, profile:{...}, intents:[...], networkId:shared}, {userId:B, ...}], hint=\"user's reason\")\n7. Present the draft introduction\n\\`\\`\\`\n\nThe entities array must include each party's userId, profile data, intents from shared networks, and the shared networkId. The hint is the user's stated reason (e.g. \"both AI devs\"). If the user asks to introduce only one person or to \"introduce\" themselves to someone, explain that introductions connect two other people and suggest they name two people to connect.\n\n### 6a. Discover who to introduce to someone\n\n**When the user asks \"who should I introduce to @Person\" or \"find connections for @Person\"** — they want YOU to discover good connections for that person, presented as introduction cards.\n\n\\`\\`\\`\n1. Identify the person's userId from the @mention (call it mentionedUserId)\n2. discover_opportunities(introTargetUserId=mentionedUserId, searchQuery=\"<optional refinement>\")\n3. Present the returned cards (they will be formatted as introduction cards automatically)\n\\`\\`\\`\n\nThis is different from Pattern 6 (where user names BOTH parties). Here the user names ONE person and asks you to find connections for them. Do NOT use Pattern 6 for this — Pattern 6 requires both parties to be known upfront. Do NOT ask the user for a second person. Do NOT use targetUserId or partyUserIds. The system will find connections automatically.\n\n**CRITICAL — no signal creation in introducer flows:** When \\`introTargetUserId\\` is used (Patterns 6 and 6a), the user is searching for connections on behalf of someone else — the search reflects the other person's needs, not the user's own. Do NOT suggest creating a signal or intent in this context. The search query describes what the *other person* needs (e.g. \"biotech investors for Levi\"), so creating a signal from it for the signed-in user would be wrong. Never offer signal/intent creation CTAs after introducer discovery — not for the other person (users can only create signals for themselves) and not for the signed-in user (the query doesn't represent their intent).\n`,\n};\n\nconst intentCreationModule: PromptModule = {\n id: \"intent-creation\",\n triggers: [\"create_intent\"],\n content: () => `\n### 2. User explicitly wants to create or save an intent\n\n**YOU decide if it's specific enough. The tool proposes — the user confirms.**\n\n\\`\\`\\`\nIF description is vague (\"find a job\", \"meet people\", \"learn something\"):\n 1. read_user_contexts() → get their background\n 2. read_intents() → see existing intents for context\n 3. THINK: given their profile and existing intents, suggest a refined version\n 4. Reply: \"Based on your background in X, did you mean something like 'Y'?\"\n 5. Wait for confirmation\n 6. On \"yes\" → create_intent(description=exact_refined_text)\n\nIF description is specific enough (\"contribute to an open-source LLM project\"):\n → create_intent(description=...) directly\n\\`\\`\\`\n\n**CRITICAL: Never write a \\`\\`\\`intent_proposal block yourself.** To propose an intent you MUST call create_intent(description=...). The tool returns a \\`\\`\\`intent_proposal code block (with proposalId and description). You MUST include that exact block verbatim in your response — it renders as an interactive card. Do not summarize or invent the block; only the tool provides a valid one. Add a brief explanation that creating this intent will let the system look for relevant people in the background.\n\nSpecificity test: Does it contain a concrete domain, action, or scope? If just a single generic verb+noun (\"find a job\"), it's vague. If it has qualifying detail (\"senior UX design role at a tech company in Berlin\"), it's specific.\n`,\n};\n\nconst intentManagementModule: PromptModule = {\n id: \"intent-management\",\n triggers: [\"update_intent\", \"delete_intent\"],\n content: () => `\n### 4. Update or delete an intent\n\n**YOU look up the ID first.**\n\n\\`\\`\\`\n1. read_intents() → get current intents with IDs\n2. Match user's request to the right intent\n3. update_intent(intentId=exact_id, description=...) or delete_intent(intentId=exact_id)\n\\`\\`\\`\n`,\n};\n\nconst personLookupModule: PromptModule = {\n id: \"person-lookup\",\n triggers: [\"read_user_contexts\"],\n content: () => `\n### 0. User asks about a specific person by name\n\nWhen the user mentions a specific person by name (\"find [name]\", \"look up [name]\", \"who is [name]?\", \"tell me about [name]\"), look them up by name first — do NOT use discovery.\n\n- Call \\`read_user_contexts(query=\"the name\")\\` — this finds members by name across the user's indexes\n- If one match: the result already includes their full profile; present it naturally\n- If multiple matches: present the list and ask the user to clarify which person\n- If no matches: tell the user you couldn't find anyone by that name in their network\n- If the user then asks for semantic discovery (e.g. \"find people like them\"), use Pattern 1.\n- If the user wants to connect with this specific person (e.g. \"yes, connect us\", \"what can I do with them\", \"I'd like to reach out\"), use Pattern 1a.\n`,\n};\n\nconst urlScrapingModule: PromptModule = {\n id: \"url-scraping\",\n triggers: [\"scrape_url\"],\n regex: /(https?:\\/\\/)/i,\n content: () => `\n### 3. User includes a URL\n\n**YOU handle scraping before intent creation.**\n\n\\`\\`\\`\n1. scrape_url(url, objective=\"Extract key details for an intent\")\n2. Synthesize a conceptual description from scraped content\n3. create_intent(description=synthesized_summary)\n\\`\\`\\`\n\nException: for profile creation, pass URLs directly to create_user_context (it handles scraping internally).\n\nIf the user pastes or types a profile URL (e.g. linkedin.com/..., github.com/...) to create or update their profile, you MUST pass that exact URL in the corresponding parameter (e.g. linkedinUrl, githubUrl, twitterUrl) to create_user_context, or use scrape_url with that URL then update_user_context; do not use the user's stored social links for that request.\n`,\n};\n\nconst communityModule: PromptModule = {\n id: \"community\",\n triggers: [\"read_networks\", \"create_network\", \"create_network_membership\", \"update_network\", \"delete_network\", \"delete_network_membership\"],\n content: () => `\n### 8. Explore what a community is about\n\n\\`\\`\\`\n0. If user asks about communities they belong to, first use preloaded memberships in this prompt.\n1. read_networks() → get network details (title, prompt)\n2. read_intents(networkId=X) → what members are looking for\n3. read_network_memberships(networkId=X) → who's in it\n4. Synthesize: community purpose, active needs, member composition\n\\`\\`\\`\n\n### When to mention community/index\nIndex and community membership is background: handle it without talking about indexes unless the user asks or it's sign-up, leave, or owner settings. Do not proactively mention \"your indexes\", \"your communities\", \"which index\", \"in your current communities\", or similar. Only mention indexes (or communities, lists) when: (i) post-onboarding sign-up to a community, (ii) user explicitly asked about their indexes/communities, (iii) user wants to leave one, (iv) owner is changing index/community settings. Otherwise use neutral language (\"where you're connected\", \"people you're connected with\") and do not narrate \"your indexes\", \"your current communities\", \"in this network\", etc.\n`,\n};\n\nconst contactsModule: PromptModule = {\n id: \"contacts\",\n triggers: [\"import_gmail_contacts\", \"add_contact\", \"list_contacts\", \"remove_contact\"],\n // Gate on the CONTACTS_ENABLED flag (fail-closed: only `true` enables). When\n // contacts are disabled the import/add tools are de-registered, so this module\n // must not be injected — otherwise the orchestrator keeps advertising Gmail\n // import / add_contact and offers an action that then fails as \"Unknown tool\".\n triggerFilter: (iterCtx) => iterCtx.ctx.contactsEnabled === true,\n content: () => `\n### 9. Import contacts from Gmail\n\n**Single-step workflow:**\n\n\\`\\`\\`\nimport_gmail_contacts()\n→ If not connected: returns { requiresAuth: true, authUrl: \"...\" } — share the URL with the user\n→ If connected: imports contacts directly and returns stats { imported, skipped, newContacts, existingContacts }\n\\`\\`\\`\n\nGhost users are contacts without accounts — they're enriched with public data (LinkedIn, GitHub, X) and can appear in opportunity discovery once enriched.\n\n### 10. Add or manage contacts manually\n\n\\`\\`\\`\n# Add a single contact\nadd_contact(email=\"alice@example.com\", name=\"Alice Smith\")\n\n# List user's network\nlist_contacts() → returns contacts with names, emails, and whether they're ghost users\n\n# Remove a contact\nremove_contact(contactId=X)\n\\`\\`\\`\n`,\n};\n\nconst sharedContextModule: PromptModule = {\n id: \"shared-context\",\n triggers: [\"read_network_memberships\"],\n content: () => `\n### 5. Find shared context between two users\n\n\\`\\`\\`\n1. read_network_memberships(userId=me) → my networks\n2. read_network_memberships(userId=other) → their networks\n3. Intersect networkIds\n4. For each shared network: read_intents(networkId=shared)\n5. read_user_contexts(userId=other)\n6. Synthesize: what overlaps, where they could collaborate\n\\`\\`\\`\n`,\n};\n\nconst mentionsModule: PromptModule = {\n id: \"mentions\",\n triggers: [],\n regex: /@\\[.*?\\]\\(.*?\\)/,\n content: () =>\n `- Messages may contain \\`@[Display Name](userId)\\` markup. The value in parentheses is the userId.\n`,\n};\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// MODULE REGISTRY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/** All registered prompt modules. */\nexport const PROMPT_MODULES: PromptModule[] = [\n discoveryModule,\n introductionModule,\n intentCreationModule,\n intentManagementModule,\n personLookupModule,\n urlScrapingModule,\n communityModule,\n contactsModule,\n sharedContextModule,\n mentionsModule,\n];\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// RESOLUTION\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Resolves which prompt modules should be injected for the current iteration.\n *\n * Phase 1: Skip all modules when onboarding is active (early exit).\n * Phase 2: Collect candidate modules by checking triggers and regex.\n * Phase 3: Apply exclusions (unidirectional — the excluding module stays).\n *\n * @param iterCtx - Current iteration context (tool history, user message, resolved context)\n * @returns Concatenated prompt text from all matched modules\n */\nexport function resolveModules(iterCtx: IterationContext): string {\n // Phase 1 (early exit): Skip all modules during onboarding\n if (iterCtx.ctx.isOnboarding) {\n return \"\";\n }\n\n const toolNames = new Set(iterCtx.recentTools.map((t) => t.name));\n\n // Phase 2: Collect candidates\n const candidates = new Map<string, PromptModule>();\n\n for (const mod of PROMPT_MODULES) {\n let matched = false;\n\n // Check tool triggers (with optional filter for arg-based disambiguation)\n if (mod.triggers.length > 0 && mod.triggers.some((t) => toolNames.has(t))) {\n matched = mod.triggerFilter ? mod.triggerFilter(iterCtx) : true;\n }\n\n // Check regex trigger\n if (!matched && mod.regex && iterCtx.currentMessage && mod.regex.test(iterCtx.currentMessage)) {\n matched = true;\n }\n\n if (matched) {\n candidates.set(mod.id, mod);\n }\n }\n\n // Phase 3: Apply exclusions (skip self-exclusion)\n for (const mod of candidates.values()) {\n if (mod.excludes) {\n for (const excludedId of mod.excludes) {\n if (excludedId !== mod.id) {\n candidates.delete(excludedId);\n }\n }\n }\n }\n\n // Build output\n const sections: string[] = [];\n for (const mod of candidates.values()) {\n sections.push(mod.content(iterCtx.ctx));\n }\n return sections.join(\"\\n\");\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.question-dedup.d.ts","sourceRoot":"/","sources":["chat/chat.question-dedup.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,UAAU,YAAY;IACpB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,YAAY,EACzD,SAAS,EAAE,CAAC,EAAE,EACd,WAAW,EAAE,GAAG,CAAC,MAAM,CAAC,GACvB;IAAE,KAAK,EAAE,CAAC,EAAE,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,CAWlC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.question-dedup.js","sourceRoot":"/","sources":["chat/chat.question-dedup.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAOH,MAAM,UAAU,oBAAoB,CAClC,SAAc,EACd,WAAwB;IAExB,MAAM,KAAK,GAAQ,EAAE,CAAC;IACtB,MAAM,MAAM,GAAa,EAAE,CAAC;IAE5B,KAAK,MAAM,CAAC,IAAI,SAAS,EAAE,CAAC;QAC1B,IAAI,CAAC,CAAC,EAAE,IAAI,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;YAAE,SAAS;QAC5C,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACd,IAAI,CAAC,CAAC,EAAE;YAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC9B,CAAC;IAED,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;AAC3B,CAAC","sourcesContent":["/**\n * Pure deduplication logic for decision questions.\n * Filters out questions whose `id` is already in the surfaced set.\n * Questions without an `id` (inline-generated) are always passed through.\n */\n\ninterface QuestionLike {\n id?: string;\n [key: string]: unknown;\n}\n\nexport function deduplicateQuestions<T extends QuestionLike>(\n questions: T[],\n surfacedIds: Set<string>,\n): { fresh: T[]; newIds: string[] } {\n const fresh: T[] = [];\n const newIds: string[] = [];\n\n for (const q of questions) {\n if (q.id && surfacedIds.has(q.id)) continue;\n fresh.push(q);\n if (q.id) newIds.push(q.id);\n }\n\n return { fresh, newIds };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.state.d.ts","sourceRoot":"/","sources":["chat/chat.state.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAE5D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,iCAAiC,EAAE,MAAM,2BAA2B,CAAC;AAMpH,mFAAmF;AACnF,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAClC;AAED,+DAA+D;AAC/D,MAAM,WAAW,oBAAoB;IACnC,OAAO,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACpD,eAAe,CAAC,EAAE,OAAO,EAAE,CAAC;IAC5B,eAAe,CAAC,EAAE,OAAO,EAAE,CAAC;IAC5B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,OAAO,EAAE,CAAC;IACpB,KAAK,CAA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ACF,oDAAoD;IACpD,WAAW,EAAE,UAAU,CAAU;QAC/B,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI;QAC7B,OAAO,EAAE,GAAG,EAAE,CAAC,SAAS;KACzB,CAAC;CAEH,CAAC,CAAC","sourcesContent":["import { Annotation, messagesStateReducer } from \"@langchain/langgraph\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\n\nimport type { ToolScopeType } from \"../shared/agent/tool.scope.js\";\nimport type { DebugMetaToolCall, DebugMetaLlm, DebugMetaOrchestratorNegotiations } from \"./chat-streaming.types.js\";\n\n// ══════════════════════════════════════════════════════════════════════════════\n// TYPES (used by legacy subgraph nodes; agent-loop graph does not set these)\n// ══════════════════════════════════════════════════════════════════════════════\n\n/** Routing decision from router node (target, operationType, extractedContext). */\nexport interface RoutingDecision {\n target: string;\n operationType: string | null;\n extractedContext?: string | null;\n}\n\n/** Intent subgraph result (actions, inferredIntents, etc.). */\nexport interface IntentSubgraphResult {\n actions?: Array<{ type: string; payload?: string }>;\n inferredIntents?: unknown[];\n indexingResults?: unknown[];\n mode?: string;\n intents?: unknown[];\n count?: number;\n error?: string;\n /** When the intent graph exits early (e.g. network-scoped without intents); surface to user. */\n requiredMessage?: string;\n}\n\n/** Index subgraph result (memberships, ownedIndexes, specificIndexData). */\nexport interface IndexSubgraphResult {\n mode?: string;\n memberships?: unknown[];\n ownedIndexes?: unknown[];\n specificIndexData?: unknown;\n count?: number;\n error?: string;\n}\n\n/** Aggregated results from subgraphs (intent, index, profile, opportunity, scrape). */\nexport interface SubgraphResults {\n intent?: IntentSubgraphResult;\n index?: IndexSubgraphResult;\n profile?: unknown;\n opportunity?: unknown;\n scrape?: unknown;\n}\n\n// ══════════════════════════════════════════════════════════════════════════════\n// CHAT GRAPH STATE (Agent Loop Architecture)\n// ══════════════════════════════════════════════════════════════════════════════\n\n/**\n * The Chat Graph State using LangGraph Annotations.\n * \n * This is a simplified state for the agent loop architecture.\n * The agent handles all routing decisions internally via tool calling.\n * \n * Design Principles:\n * - Messages accumulate through the conversation (includes tool calls/results)\n * - Iteration count tracks loop progress for soft/hard limits\n * - Final response is extracted at the end\n */\nexport const ChatGraphState = Annotation.Root({\n // ═══════════════════════════════════════════════════════════════════════════\n // CORE INPUTS\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * The User ID - required for all operations.\n */\n userId: Annotation<string>,\n\n /**\n * Legacy optional index (community) ID when chat is scoped to a specific index.\n * New callers should set scopeType/scopeId; networkId is retained as an edge alias.\n */\n networkId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n /** Focused request scope type. Network scope uses a network id; intent scope uses an intent id. */\n scopeType: Annotation<ToolScopeType | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n /** Focused request scope id. Network scope uses a network id; intent scope uses an intent id. */\n scopeId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n /**\n * Chat session ID when streaming with context. Used by tools to create draft\n * opportunities tied to this conversation (context.conversationId).\n */\n sessionId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n /**\n * Conversation history using LangGraph's built-in message reducer.\n * Includes: HumanMessage, AIMessage, ToolMessage, SystemMessage\n * Automatically handles message appending, ID management, and ordering.\n */\n messages: Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n\n // ═══════════════════════════════════════════════════════════════════════════\n // LOOP CONTROL\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Current iteration count in the agent loop.\n * Used for soft limit (nudge) and hard limit (force exit).\n */\n iterationCount: Annotation<number>({\n reducer: (curr, next) => next,\n default: () => 0,\n }),\n\n /**\n * Flag indicating whether the agent loop should continue.\n * Set to false when agent produces final response or hits hard limit.\n */\n shouldContinue: Annotation<boolean>({\n reducer: (curr, next) => next,\n default: () => true,\n }),\n\n // ═══════════════════════════════════════════════════════════════════════════\n // OUTPUTS\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * The final generated response text.\n * Set when the agent decides to stop and respond.\n */\n responseText: Annotation<string | undefined>({\n reducer: (curr, next) => next,\n default: () => undefined,\n }),\n\n /**\n * Error message if the agent loop fails.\n */\n error: Annotation<string | undefined>({\n reducer: (curr, next) => next,\n default: () => undefined,\n }),\n\n /**\n * Per-turn debug meta (graph, iterations, tool calls) for copy-debug.\n * Not persisted; only used so the streamer receives it in the updates chunk.\n */\n debugMeta: Annotation<{ graph: string; iterations: number; tools: DebugMetaToolCall[]; llm: DebugMetaLlm; orchestratorNegotiations?: DebugMetaOrchestratorNegotiations } | undefined>({\n reducer: (curr, next) => next,\n default: () => undefined,\n }),\n\n // Legacy subgraph state (used by index/intent/response nodes when present)\n /** Router output: target, operationType, extractedContext. */\n routingDecision: Annotation<RoutingDecision | undefined>({\n reducer: (curr, next) => next,\n default: () => undefined,\n }),\n /** Results from intent/profile/opportunity/scrape subgraphs. */\n subgraphResults: Annotation<SubgraphResults | undefined>({\n reducer: (curr, next) => next,\n default: () => undefined,\n }),\n /** User profile context (e.g. for intent nodes). */\n userProfile: Annotation<unknown>({\n reducer: (curr, next) => next,\n default: () => undefined,\n }),\n\n});\n\n// ══════════════════════════════════════════════════════════════════════════════\n// TYPE EXPORTS\n// ══════════════════════════════════════════════════════════════════════════════\n\n/**\n * The full state type for the Chat Graph.\n * Use this for typing node functions and graph invocations.\n */\nexport type ChatGraphStateType = typeof ChatGraphState.State;\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.streamer.d.ts","sourceRoot":"/","sources":["chat/chat.streamer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,WAAW,EAAgB,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,eAA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esContent":["import { AIMessage, BaseMessage, HumanMessage } from \"@langchain/core/messages\";\nimport { BaseCheckpointSaver } from \"@langchain/langgraph\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { ToolScopeType } from \"../shared/agent/tool.scope.js\";\nimport type { ChatStreamEvent, DebugMetaDiscoveryQuestions, DebugMetaToolCall, DebugMetaLlm, DebugMetaOrchestratorNegotiations } from \"./chat-streaming.types.js\";\nimport { createAgentEndEvent, createAgentStartEvent, createDebugMetaEvent, createDecisionQuestionsEvent, createErrorEvent, createGraphEndEvent, createPhaseStartEvent, createPhaseEndEvent, createGraphStartEvent, createIterationStartEvent, createLlmStartEvent, createLlmEndEvent, createResponseCompleteEvent, createResponseResetEvent, createHallucinationDetectedEvent, createStatusEvent, createTokenEvent, createToolActivityEvent, createChatSummarizerStartEvent, createChatSummarizerEndEvent, createQuestionGeneratorStartEvent, createQuestionGeneratorEndEvent, createUserQuestionEvent } from \"./chat-streaming.types.js\";\nimport type { AgentStreamEvent } from \"./chat.agent.js\";\n\nconst logger = protocolLogger(\"ChatStreamer\");\n\n// ══════════════════════════════════════════════════════════════════════════════\n// CHAT STREAMER (Streaming Narration Architecture)\n// ══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Top-level streaming service for Chat Graph events.\n *\n * Uses `graph.stream()` with `streamMode: [\"custom\", \"updates\"]` so that\n * the agent's `config.writer()` calls arrive as `\"custom\"` chunks (text\n * tokens and tool-activity events) and the final state update arrives as\n * an `\"updates\"` chunk.\n */\nexport class ChatStreamer {\n constructor(\n private loadSessionContext: (\n sessionId: string,\n maxMessages: number,\n ) => Promise<BaseMessage[]>,\n private createStreamingGraph: (\n checkpointer?: BaseCheckpointSaver,\n ) => any,\n ) {}\n\n /**\n * Streams chat events with full session context.\n * Loads previous conversation history and optionally uses a checkpointer\n * for state persistence.\n *\n * @param input - Configuration for context-aware streaming\n * @param checkpointer - Optional checkpointer for state persistence\n * @yields ChatStreamEvent objects\n */\n public async *streamChatEventsWithContext(\n input: {\n userId: string;\n message: string;\n sessionId: string;\n maxContextMessages?: number;\n /** @deprecated Use scopeType/scopeId. Kept for REST/session edge compatibility. */\n networkId?: string;\n scopeType?: ToolScopeType;\n scopeId?: string;\n prefillMessages?: Array<{ role: \"assistant\" | \"user\"; content: string }>;\n /** Per-run identifier used to form a composite LangGraph thread_id (sessionId:runId).\n * When provided, prevents stale checkpoint state from a prior run being resumed.\n * Defaults to sessionId alone when absent (backward compatible). */\n runId?: string;\n },\n checkpointer?: BaseCheckpointSaver,\n signal?: AbortSignal,\n ): AsyncGenerator<ChatStreamEvent> {\n const {\n userId,\n message,\n sessionId,\n maxContextMessages = 20,\n networkId,\n scopeType,\n scopeId,\n prefillMessages,\n runId,\n } = input;\n const effectiveScopeType: ToolScopeType | undefined = scopeType ?? (networkId ? 'network' : undefined);\n const effectiveScopeId = scopeId ?? (effectiveScopeType === 'network' ? networkId : undefined);\n logger.verbose(\"Starting context-aware streaming\", {\n userId,\n sessionId,\n maxContextMessages,\n hasCheckpointer: !!checkpointer,\n hasIndexScope: !!effectiveScopeId,\n scopeType: effectiveScopeType,\n scopeId: effectiveScopeId,\n });\n\n try {\n // Load previous conversation context\n const previousMessages = await this.loadSessionContext(\n sessionId,\n maxContextMessages,\n );\n\n // Inject prefill messages (e.g. hardcoded onboarding greeting) only for fresh sessions\n const prefill: BaseMessage[] = previousMessages.length === 0\n ? (prefillMessages ?? []).map((pm) =>\n pm.role === \"assistant\" ? new AIMessage(pm.content) : new HumanMessage(pm.content),\n )\n : [];\n\n const allMessages = [...previousMessages, ...prefill, new HumanMessage(message)];\n\n logger.verbose(\"Context prepared\", {\n previousCount: previousMessages.length,\n totalCount: allMessages.length,\n });\n\n // Form composite thread_id when a runId is provided\n const threadId = runId ? `${sessionId}:${runId}` : sessionId;\n\n // Stream with context using the optional checkpointer\n yield* this.streamChatEvents(\n { userId, messages: allMessages, scopeType: effectiveScopeType, scopeId: effectiveScopeId },\n sessionId,\n checkpointer,\n signal,\n threadId,\n );\n } catch (error) {\n logger.error(\"Stream error\", {\n error: error instanceof Error ? error.message : String(error),\n });\n yield createErrorEvent(\n sessionId,\n error instanceof Error\n ? error.message\n : \"Unknown error during context-aware streaming\",\n \"CONTEXT_STREAM_ERROR\",\n );\n }\n }\n\n /**\n * Streams chat events from the graph execution.\n *\n * Uses `graph.stream()` with `streamMode: [\"custom\", \"updates\"]`:\n * - `\"custom\"` chunks carry {@link AgentStreamEvent} objects emitted by\n * `ChatAgent.streamRun()` via `config.writer()`\n * - `\"updates\"` chunks carry the final state update from `agentLoopNode`\n *\n * @param input - The input state for the graph (userId and messages)\n * @param sessionId - The session ID for event attribution\n * @param checkpointer - Optional checkpointer for persistence\n * @yields ChatStreamEvent objects\n */\n public async *streamChatEvents(\n input: { userId: string; messages: BaseMessage[]; networkId?: string; scopeType?: ToolScopeType; scopeId?: string },\n sessionId: string,\n checkpointer?: BaseCheckpointSaver,\n signal?: AbortSignal,\n threadId?: string,\n ): AsyncGenerator<ChatStreamEvent> {\n const graph = this.createStreamingGraph(checkpointer);\n\n try {\n const initialState: {\n userId: string;\n messages: BaseMessage[];\n networkId?: string;\n scopeType?: ToolScopeType;\n scopeId?: string;\n sessionId?: string;\n } = {\n userId: input.userId,\n messages: input.messages,\n };\n const effectiveScopeType: ToolScopeType | undefined = input.scopeType ?? (input.networkId ? 'network' : undefined);\n const effectiveScopeId = input.scopeId ?? (effectiveScopeType === 'network' ? input.networkId : undefined);\n if (input.networkId) initialState.networkId = input.networkId;\n if (effectiveScopeType && effectiveScopeId) {\n initialState.scopeType = effectiveScopeType;\n initialState.scopeId = effectiveScopeId;\n }\n initialState.sessionId = sessionId;\n\n // Use graph.stream() with custom + updates modes.\n // Custom events come from config.writer() inside agentLoopNode.\n const eventStream = await graph.stream(initialState, {\n streamMode: [\"custom\", \"updates\"] as const,\n configurable: { thread_id: threadId ?? sessionId, signal },\n signal,\n });\n\n // Emit initial status\n yield createStatusEvent(sessionId, \"Processing your message...\");\n\n for await (const tuple of eventStream) {\n if (signal?.aborted) break;\n // graph.stream with multiple modes yields [mode, chunk] tuples\n const [mode, chunk] = tuple as [string, unknown];\n\n // ─────────────────────────────────────────────────────────────────\n // CUSTOM: writer events from ChatAgent.streamRun()\n // ─────────────────────────────────────────────────────────────────\n if (mode === \"custom\") {\n const event = chunk as AgentStreamEvent;\n\n if (event.type === \"iteration_start\") {\n yield createIterationStartEvent(sessionId, event.iteration);\n }\n\n if (event.type === \"llm_start\") {\n yield createLlmStartEvent(sessionId, event.iteration);\n }\n\n if (event.type === \"text_chunk\" && event.content) {\n yield createTokenEvent(sessionId, event.content);\n }\n\n if (event.type === \"response_reset\") {\n yield createResponseResetEvent(sessionId, event.reason);\n }\n\n if (event.type === \"hallucination_detected\") {\n yield createHallucinationDetectedEvent(sessionId, event.blockType, event.tool);\n }\n\n if (event.type === \"llm_end\") {\n yield createLlmEndEvent(\n sessionId,\n event.iteration,\n event.hasToolCalls,\n event.toolNames,\n );\n }\n\n if (event.type === \"tool_activity\") {\n logger.debug(\"Tool activity\", { name: event.name, phase: event.phase });\n if (event.phase === \"start\") {\n yield createToolActivityEvent(\n sessionId,\n event.name,\n event.name,\n \"start\",\n );\n } else {\n yield createToolActivityEvent(\n sessionId,\n event.name,\n event.name,\n \"end\",\n event.success,\n event.summary,\n event.steps,\n );\n }\n }\n\n if (event.type === \"graph_start\") {\n yield createGraphStartEvent(sessionId, event.name);\n }\n\n if (event.type === \"graph_end\") {\n yield createGraphEndEvent(sessionId, event.name, event.durationMs);\n }\n\n if (event.type === \"phase_start\") {\n yield createPhaseStartEvent(sessionId, event.name);\n }\n\n if (event.type === \"phase_end\") {\n yield createPhaseEndEvent(sessionId, event.name, event.durationMs);\n }\n\n if (event.type === \"agent_start\") {\n yield createAgentStartEvent(sessionId, event.name);\n }\n\n if (event.type === \"agent_end\") {\n yield createAgentEndEvent(sessionId, event.name, event.durationMs, event.summary);\n }\n\n if (event.type === \"decision_questions\") {\n yield createDecisionQuestionsEvent(sessionId, { questions: event.questions });\n }\n\n if (event.type === \"user_question\") {\n yield createUserQuestionEvent(sessionId, { questions: event.questions });\n }\n\n if (event.type === \"status\") {\n // Keep-alive/status line from long-blocking tools (e.g. the\n // ask_user_question wait loop) so SSE transports do not idle out.\n yield createStatusEvent(sessionId, event.message);\n }\n\n if (event.type === \"chat_summarizer_start\") {\n yield createChatSummarizerStartEvent(sessionId, event.payload);\n }\n\n if (event.type === \"chat_summarizer_end\") {\n yield createChatSummarizerEndEvent(sessionId, event.payload);\n }\n\n if (event.type === \"question_generator_start\") {\n yield createQuestionGeneratorStartEvent(sessionId, event.payload);\n }\n\n if (event.type === \"question_generator_end\") {\n yield createQuestionGeneratorEndEvent(sessionId, event.payload);\n }\n }\n\n // ─────────────────────────────────────────────────────────────────\n // UPDATES: final state from agentLoopNode\n // ─────────────────────────────────────────────────────────────────\n if (mode === \"updates\") {\n // The updates chunk is { agent_loop: { responseText, error, ... } }\n const updates = chunk as Record<string, Record<string, unknown>>;\n const agentOutput = updates?.agent_loop;\n\n if (agentOutput?.error) {\n logger.warn(\"Agent loop returned error via updates\", {\n error: agentOutput.error,\n });\n yield createErrorEvent(\n sessionId,\n String(agentOutput.error),\n \"AGENT_ERROR\",\n );\n }\n\n // Yield the agent's authoritative response text so the\n // controller can persist it without relying on token accumulation.\n const responseText = typeof agentOutput?.responseText === \"string\"\n ? (agentOutput.responseText as string)\n : \"\";\n yield createResponseCompleteEvent(sessionId, responseText);\n\n const debugMeta = agentOutput?.debugMeta as\n | { graph: string; iterations: number; tools?: DebugMetaToolCall[]; llm?: DebugMetaLlm; orchestratorNegotiations?: DebugMetaOrchestratorNegotiations; discoveryQuestions?: DebugMetaDiscoveryQuestions }\n | undefined;\n if (\n debugMeta?.graph != null &&\n typeof debugMeta.iterations === \"number\"\n ) {\n const llmFallback: DebugMetaLlm = { calls: 0, totalDurationMs: 0, resets: [], hallucinations: [] };\n yield createDebugMetaEvent(\n sessionId,\n debugMeta.graph,\n debugMeta.iterations,\n Array.isArray(debugMeta.tools) ? debugMeta.tools : [],\n debugMeta.llm ?? llmFallback,\n debugMeta.orchestratorNegotiations,\n debugMeta.discoveryQuestions,\n );\n }\n\n logger.verbose(\"Agent loop complete (updates)\", {\n responseLength: responseText.length,\n });\n }\n }\n } catch (error) {\n logger.error(\"Stream error\", {\n error: error instanceof Error ? error.message : String(error),\n });\n yield createErrorEvent(\n sessionId,\n error instanceof Error\n ? error.message\n : \"Unknown error during streaming\",\n \"STREAM_ERROR\",\n );\n }\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.suggester.d.ts","sourceRoot":"/","sources":["chat/chat.suggester.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAkChE,MAAM,WAAW,wBAAwB;IACvC,+DAA+D;IAC/D,QAAQ,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,GAAG,WAAW,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACjE,6DAA6D;IAC7D,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;GAGG;AACH,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,KAAK,CAA2C;;IAMxD;;;OAGG;IAEG,QAAQ,CAAC,KAAK,EAAE,wBAAwB,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;CAsC3E"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.suggester.js","sourceRoot":"/","sources":["chat/chat.suggester.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAC/D,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC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CAAC,CAAC,OAAO,IAAI,IAAI,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;aACxE,CAAC,CAAC,CAAC;YACJ,MAAM,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;YACnD,OAAO,GAAG,CAAC;QACb,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE;gBACpB,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aAC9D,CAAC,CAAC;YACH,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC;CACF;AAtCO;IADL,KAAK,EAAE;;;;mDAsCP","sourcesContent":["import { HumanMessage, SystemMessage } from \"@langchain/core/messages\";\nimport { z } from \"zod\";\nimport type { ChatSuggestion } from \"./chat-streaming.types.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { Timed } from \"../shared/observability/performance.js\";\nimport { createStructuredModel } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\nconst logger = protocolLogger(\"SuggestionGenerator\");\n\nconst suggestionItemSchema = z.object({\n label: z.string().describe(\"Short label for the chip (2-5 words)\"),\n type: z.enum([\"direct\", \"prompt\"]).describe(\"direct = auto-submit message; prompt = prefill input\"),\n followupText: z.string().nullable().describe(\"For type=direct: full message to send when clicked; null for prompt type\"),\n prefill: z.string().nullable().describe(\"For type=prompt: text to prefill the input; null for direct type\"),\n});\n\nconst suggestionsSchema = z.object({\n suggestions: z\n .array(suggestionItemSchema)\n .min(1)\n .max(6)\n .describe(\"3-5 follow-up suggestions based on the conversation\"),\n});\n\nconst SYSTEM_PROMPT = `You generate follow-up suggestions for a chat user based on their conversation.\n\nRules:\n- Return 3-5 suggestions. Mix of \"direct\" (one-click send) and \"prompt\" (prefill for user to edit).\n- Labels must be short: 2-5 words (e.g. \"Find collaborators\", \"Add more details\").\n- For type=direct: provide followupText as the exact message to send (complete sentence).\n- For type=prompt: provide prefill as the start of a sentence the user can complete (e.g. \"I need help with \").\n- Suggestions must be relevant to the last exchange and natural next steps.\n- Do not repeat what the user or assistant just said; suggest logical follow-ups.\n- Voice: Calm, direct; no hype or networking clichés. Prefer words like opportunity, overlap, signal, pattern, relevant. Avoid: search, leverage, networking, match, optimize, scale.`;\n\nexport interface SuggestionGeneratorInput {\n /** Last few messages (user and assistant) to derive context */\n messages: Array<{ role: \"user\" | \"assistant\"; content: string }>;\n /** Optional index/community context to tailor suggestions */\n indexContext?: string;\n}\n\n/**\n * Lightweight generator for context-aware chat follow-up suggestions.\n * Uses a fast model and structured output to return 3-5 suggestions per call.\n */\nexport class SuggestionGenerator {\n private model: ReturnType<typeof createStructuredModel>;\n\n constructor() {\n this.model = createStructuredModel(\"suggestionGenerator\", suggestionsSchema, { name: \"chat_suggestions\" });\n }\n\n /**\n * Generate follow-up suggestions from the last exchange.\n * Returns empty array on failure (graceful degradation).\n */\n @Timed()\n async generate(input: SuggestionGeneratorInput): Promise<ChatSuggestion[]> {\n const { messages, indexContext } = input;\n if (messages.length === 0) return [];\n\n const excerpt = messages\n .slice(-6)\n .map((m) => `${m.role === \"user\" ? \"User\" : \"Assistant\"}: ${m.content.slice(0, 300)}`)\n .join(\"\\n\\n\");\n\n const userContent = indexContext\n ? `Conversation (community context: ${indexContext}):\\n\\n${excerpt}\\n\\nGenerate 3-5 follow-up suggestions.`\n : `Conversation:\\n\\n${excerpt}\\n\\nGenerate 3-5 follow-up suggestions.`;\n\n try {\n const result = await invokeWithAbortSignal(this.model, [\n new SystemMessage(SYSTEM_PROMPT),\n new HumanMessage(userContent),\n ]);\n const parsed = suggestionsSchema.safeParse(result);\n if (!parsed.success) {\n logger.warn(\"Parse failed\", { error: parsed.error.message });\n return [];\n }\n const out: ChatSuggestion[] = parsed.data.suggestions.map((s) => ({\n label: s.label,\n type: s.type,\n ...(s.type === \"direct\" && s.followupText != null && { followupText: s.followupText }),\n ...(s.type === \"prompt\" && s.prefill != null && { prefill: s.prefill }),\n }));\n logger.verbose(\"Generated\", { count: out.length });\n return out;\n } catch (error) {\n logger.warn(\"Failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return [];\n }\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.summarizer.d.ts","sourceRoot":"/","sources":["chat/chat.summarizer.ts"],"names":[],"mappings":"AAWA,OAAO,EAA2B,KAAK,iBAAiB,EAAE,MAAM,0CAA0C,CAAC;AAwB3G,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,GAAG,WAAW,CAAC;IAC3B,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,mBAAmB;IAClC,cAAc,EAAE,iBAAiB,GAAG,IAAI,CAAC;IACzC,WAAW,EAAE,qBAAqB,EAAE,CAAC;CACtC;AAED,6CAA6C;AAC7C,qBAAa,cAAc;IACzB,OAAO,CAAC,KAAK,CAA2C;;IAQxD;;;;OAIG;IAEG,SAAS,CAAC,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;CAyC/E"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.summarizer.js","sourceRoot":"/","sources":["chat/chat.summarizer.ts"],"names":[],"mappings":";;;;;;;;;AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAEvE,OAAO,EAAE,uBAAuB,EAA0B,MAAM,0CAA0C,CAAC;AAC3G,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,KAAK,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AC,IAAI,CAAC,IAAI,CAAC,CAAC;QAEb,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,qBAAqB,CAAC,IAAI,CAAC,KAAK,EAAE;gBACvD,IAAI,aAAa,CAAC,aAAa,CAAC;gBAChC,IAAI,YAAY,CAAC,IAAI,CAAC;aACvB,CAAC,CAAC;YACH,MAAM,MAAM,GAAG,uBAAuB,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;YAC3D,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;gBACpB,MAAM,CAAC,IAAI,CAAC,6BAA6B,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;gBAC5E,OAAO,IAAI,CAAC;YACd,CAAC;YACD,OAAO,MAAM,CAAC,IAAI,CAAC;QACrB,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,CAAC,IAAI,CAAC,gCAAgC,EAAE;gBAC5C,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;aACxD,CAAC,CAAC;YACH,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;CACF;AAzCO;IADL,KAAK,EAAE;;;;+CAyCP","sourcesContent":["/**\n * ChatSummarizer — rolling, incremental digest of a chat session. Takes the\n * previous persisted digest (if any) plus messages added since, returns a\n * structured ChatContextDigest. Pure: no DB, no events. Persistence is the\n * caller's responsibility (see backend ChatSummaryService).\n *\n * The model is instructed to drop entries in the previous digest that newer\n * messages override, keeping the digest bounded as the session grows.\n */\nimport { HumanMessage, SystemMessage } from \"@langchain/core/messages\";\n\nimport { ChatContextDigestSchema, type ChatContextDigest } from \"../shared/schemas/chat-context.schema.js\";\nimport { createStructuredModel } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { Timed } from \"../shared/observability/performance.js\";\n\nconst logger = protocolLogger(\"ChatSummarizer\");\n\nconst MESSAGE_CONTENT_CAP = 240;\n\nconst SYSTEM_PROMPT = `You distill chat sessions into a compact structured digest used to keep an assistant from asking obvious questions.\n\nOutput four arrays:\n- statedFacts: facts the user volunteered (stage, location, role, timing, scope, budget, …).\n- openQuestions: questions the assistant asked that the user has not yet answered.\n- rejectionReasons: pushback the user gave on prior assistant proposals (e.g. \"none of these fit — all US-based\").\n- surfacedFindings: facts the assistant has already shared with the user from prior negotiation results.\n\nRules:\n- Drop entries from the previous digest that newer messages override or contradict.\n- Keep each entry short (≤140 chars), specific, and standalone.\n- Bound the digest: at most 20 statedFacts, 10 openQuestions, 10 rejectionReasons, 20 surfacedFindings. Drop the least relevant when over.\n- Never invent facts. If the digest is empty for a category, output an empty array.`;\n\nexport interface ChatSummarizerMessage {\n role: \"user\" | \"assistant\";\n content: string;\n}\n\nexport interface ChatSummarizerInput {\n previousDigest: ChatContextDigest | null;\n newMessages: ChatSummarizerMessage[];\n}\n\n/** Pure LLM summarizer; no DB, no events. */\nexport class ChatSummarizer {\n private model: ReturnType<typeof createStructuredModel>;\n\n constructor() {\n this.model = createStructuredModel(\"chatContextSummarizer\", ChatContextDigestSchema, {\n name: \"chat_context_digest\",\n });\n }\n\n /**\n * Summarize a chat session into a bounded structured digest.\n * @param input - Previous digest (or null) and any messages added since.\n * @returns Updated digest, or null on LLM failure / first-time empty input.\n */\n @Timed()\n async summarize(input: ChatSummarizerInput): Promise<ChatContextDigest | null> {\n if (input.newMessages.length === 0) {\n return input.previousDigest;\n }\n\n const truncated = input.newMessages.map((m) => ({\n role: m.role,\n content: m.content.length > MESSAGE_CONTENT_CAP\n ? m.content.slice(0, MESSAGE_CONTENT_CAP)\n : m.content,\n }));\n\n const user = [\n input.previousDigest\n ? `Previous digest:\\n${JSON.stringify(input.previousDigest, null, 2)}`\n : \"Previous digest: (none — this is the first summarization for this session)\",\n \"\",\n \"New messages (since previous digest):\",\n ...truncated.map((m) => ` [${m.role}] ${m.content}`),\n \"\",\n \"Produce the updated digest now.\",\n ].join(\"\\n\");\n\n try {\n const response = await invokeWithAbortSignal(this.model, [\n new SystemMessage(SYSTEM_PROMPT),\n new HumanMessage(user),\n ]);\n const parsed = ChatContextDigestSchema.safeParse(response);\n if (!parsed.success) {\n logger.warn(\"ChatSummarizer parse failed\", { error: parsed.error.message });\n return null;\n }\n return parsed.data;\n } catch (err) {\n logger.warn(\"ChatSummarizer LLM call failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n return null;\n }\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.title.generator.d.ts","sourceRoot":"/","sources":["chat/chat.title.generator.ts"],"names":[],"mappings":"AAkBA,MAAM,WAAW,mBAAmB;IAClC,QAAQ,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACpD;AAED;;;GAGG;AACH,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,KAAK,CAA0C;;IAMvD;;;OAGG;IAEG,MAAM,CAAC,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC,MAAM,CAAC;CA0B1D"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.title.generator.js","sourceRoot":"/","sources":["chat/chat.title.generator.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAEvE,OAAO,EAAE,GAAG,EAAE,MAAM,gCAAgC,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAE/D,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AACvE,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,oBAAoB,C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E,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;YACjE,OAAO,KAAK,CAAC;QACf,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,IAAI,CAAC,0BAA0B,EAAE;gBACtC,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aAC9D,CAAC,CAAC;YACH,OAAO,UAAU,CAAC;QACpB,CAAC;IACH,CAAC;CACF;AA1BO;IADL,KAAK,EAAE;;;;gDA0BP","sourcesContent":["import { HumanMessage, SystemMessage } from \"@langchain/core/messages\";\n\nimport { log } from \"../shared/observability/log.js\";\nimport { Timed } from \"../shared/observability/performance.js\";\n\nimport { createResilientModel } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\nconst logger = log.lib.from(\"ChatTitleGenerator\");\n\nconst SYSTEM_PROMPT = `You suggest a very short title for a chat conversation.\n\nRules:\n- Reply with ONLY the title, no quotes or punctuation.\n- Maximum 6 words.\n- If the conversation is just greetings (hi, hello, hey, thanks) or has no clear topic yet, reply with exactly: New chat\n- Otherwise summarize the main topic or intent in a few words.`;\n\nexport interface TitleGeneratorInput {\n messages: Array<{ role: string; content: string }>;\n}\n\n/**\n * Generates a short, descriptive title for a chat session using the first exchange.\n * Only meaningful when there is at least one user message and one assistant message.\n */\nexport class ChatTitleGenerator {\n private model: ReturnType<typeof createResilientModel>;\n\n constructor() {\n this.model = createResilientModel(\"chatTitleGenerator\");\n }\n\n /**\n * Suggests a title from the conversation excerpt.\n * Call only when there is at least one user and one assistant message.\n */\n @Timed()\n async invoke(input: TitleGeneratorInput): Promise<string> {\n const { messages } = input;\n if (messages.length === 0) return \"New chat\";\n\n const excerpt = messages\n .slice(0, 6)\n .map((m) => `${m.role === \"user\" ? \"User\" : \"Assistant\"}: ${m.content.slice(0, 200)}`)\n .join(\"\\n\");\n\n try {\n const response = await invokeWithAbortSignal(this.model, [\n new SystemMessage(SYSTEM_PROMPT),\n new HumanMessage(`Conversation:\\n${excerpt}\\n\\nSuggested title:`),\n ]);\n\n const text = typeof response.content === \"string\" ? response.content : String(response.content ?? \"\").trim();\n const title = text.slice(0, 80).trim() || \"New chat\";\n logger.verbose(\"Title generated\", { titleLength: title.length });\n return title;\n } catch (error) {\n logger.warn(\"Failed to generate title\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return \"New chat\";\n }\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.tools.d.ts","sourceRoot":"/","sources":["chat/chat.tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAG5E,wBAAgB,eAAe,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ;;;EAgErE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.tools.js","sourceRoot":"/","sources":["chat/chat.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAE7E,MAAM,UAAU,eAAe,CAAC,UAAsB,EAAE,IAAc;IACpE,MAAM,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;IAC7B,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;IACpE,CAAC;IAED,MAAM,iBAAiB,GAAG,UAAU,CAAC;QACnC,IAAI,EAAE,oBAAoB;QAC1B,WAAW,EACT,wGAAwG;YACxG,wGAAwG;YACxG,gEAAgE;YAChE,oGAAoG;YACpG,8DAA8D;QAChE,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC;YACpB,KAAK,EAAE,CAAC;iBACL,MAAM,EAAE;iBACR,GAAG,EAAE;iBACL,Q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O,KAAK,CAAC,sDAAsD,CAAC,CAAC;YACvE,CAAC;YACD,OAAO,OAAO,CAAC,OAAO,CAAC,CAAC;QAC1B,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,CAAC;AAChD,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport type { DefineTool, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { success, error, UUID_REGEX } from \"../shared/agent/tool.helpers.js\";\n\nexport function createChatTools(defineTool: DefineTool, deps: ToolDeps) {\n const { chatSession } = deps;\n if (!chatSession) {\n throw new Error(\"createChatTools requires `chatSession` in deps\");\n }\n\n const listConversations = defineTool({\n name: \"list_conversations\",\n description:\n \"Lists the authenticated user's past chat conversations, most-recently-active first. Use when the user \" +\n \"asks about their prior chats, wants to resume a conversation, or is orienting themselves in their own \" +\n \"history. Only returns sessions the caller participates in.\\n\\n\" +\n \"**Returns:** `conversations: [{ sessionId, title, messageCount, lastMessageAt, createdAt }]`. Use \" +\n \"`sessionId` with `get_conversation` to read the full thread.\",\n querySchema: z.object({\n limit: z\n .number()\n .int()\n .positive()\n .max(100)\n .optional()\n .describe(\"Maximum conversations to return (default 25, max 100).\"),\n }),\n handler: async ({ context, query }) => {\n const sessions = await chatSession.listSessions(context.userId, query.limit ?? 25);\n return success({ conversations: sessions });\n },\n });\n\n const getConversation = defineTool({\n name: \"get_conversation\",\n description:\n \"Fetches a single chat conversation belonging to the authenticated user, including its messages. \" +\n \"Use after `list_conversations` has yielded a specific `sessionId` — for example when the user asks \" +\n \"you to pick up a prior thread by topic or title. Returns an error if the session does not exist or \" +\n \"the caller is not a participant.\\n\\n\" +\n \"**Returns:** `{ sessionId, title, messageCount, lastMessageAt, createdAt, messages: [{ role, content, createdAt }] }`.\",\n querySchema: z.object({\n sessionId: z.string().describe(\"Session UUID from list_conversations.\"),\n messageLimit: z\n .number()\n .int()\n .positive()\n .max(500)\n .optional()\n .describe(\"Maximum messages to include (default 50, max 500).\"),\n }),\n handler: async ({ context, query }) => {\n if (!UUID_REGEX.test(query.sessionId)) {\n return error(\"Invalid session ID format. Pass a sessionId returned by list_conversations.\");\n }\n const session = await chatSession.getSession(\n context.userId,\n query.sessionId,\n query.messageLimit ?? 50,\n );\n if (!session) {\n return error(\"Conversation not found or you are not a participant.\");\n }\n return success(session);\n },\n });\n\n return { listConversations, getConversation };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.utils.d.ts","sourceRoot":"/","sources":["chat/chat.utils.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAEvD;;;GAGG;AACH,eAAO,MAAM,kBAAkB,OAAO,CAAC;AAKvC;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAKvD;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,WAAW,GAAG,MAAM,CAQlE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,WAAW,EAAE,EACvB,SAAS,GAAE,MAA2B,GACrC,WAAW,EAAE,CA2Cf"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"chat.utils.js","sourceRoot":"/","sources":["chat/chat.utils.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH;;;GAGG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAEvC,iGAAiG;AACjG,MAAM,wBAAwB,GAAG,IAAI,CAAC;AAEtC;;;;;;;;;GASG;AACH,MAAM,UAAU,kBAAkB,CAAC,IAAY;IAC7C,IAAI,CAAC,IAAI;QAAE,OAAO,CAAC,CAAC;IACpB,sDAAsD;IACtD,qEAAqE;IACrE,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACpC,CAAC;AAED;;;;;GAKG;AACH,MAAM,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AAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QACvD,MAAM,GAAG,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC;QACjC,MAAM,SAAS,GAAG,qBAAqB,CAAC,GAAG,CAAC,CAAC;QAE7C,IAAI,WAAW,GAAG,SAAS,GAAG,eAAe,EAAE,CAAC;YAC9C,4BAA4B;YAC5B,MAAM;QACR,CAAC;QAED,cAAc,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAC5B,WAAW,IAAI,SAAS,CAAC;IAC3B,CAAC;IAED,uDAAuD;IACvD,OAAO,gBAAgB,CAAC,CAAC,CAAC,CAAC,YAAY,EAAE,GAAG,cAAc,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC;AAC/E,CAAC","sourcesContent":["/**\n * Token utilities for context window management.\n * Estimates token counts and truncates message arrays to fit within model limits.\n * Uses a simple heuristic (~4 chars per token for English).\n */\n\nimport { BaseMessage } from \"@langchain/core/messages\";\n\n/**\n * Default maximum tokens to allow for context.\n * Reserves space for system prompt and response generation.\n */\nexport const MAX_CONTEXT_TOKENS = 8000;\n\n/** Minimum tokens to reserve for the model's response (internal use in truncateToTokenLimit). */\nconst RESERVED_RESPONSE_TOKENS = 2000;\n\n/**\n * Estimate token count for a string using a simple heuristic.\n *\n * This uses a rough estimate of ~4 characters per token, which works\n * reasonably well for English text. For more accuracy with specific\n * models, use tiktoken or the model's native tokenizer.\n *\n * @param text - The text to estimate tokens for\n * @returns Estimated token count\n */\nexport function estimateTokenCount(text: string): number {\n if (!text) return 0;\n // Rough estimate: ~4 characters per token for English\n // This tends to slightly overestimate, which is safer for truncation\n return Math.ceil(text.length / 4);\n}\n\n/**\n * Estimate token count for a message, including role overhead.\n *\n * @param message - The LangChain message to estimate\n * @returns Estimated token count including message overhead\n */\nexport function estimateMessageTokens(message: BaseMessage): number {\n const content =\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content);\n\n // Add ~4 tokens overhead per message for role and formatting\n return estimateTokenCount(content) + 4;\n}\n\n/**\n * Truncate messages to fit within token limit, keeping most recent messages.\n *\n * Messages are processed from newest to oldest, accumulating until the\n * token limit is reached. The first message (usually system) is always\n * kept if present.\n *\n * @param messages - Array of messages to truncate\n * @param maxTokens - Maximum total tokens allowed (default: MAX_CONTEXT_TOKENS)\n * @returns Array of messages that fit within the token limit\n */\nexport function truncateToTokenLimit(\n messages: BaseMessage[],\n maxTokens: number = MAX_CONTEXT_TOKENS\n): BaseMessage[] {\n if (messages.length === 0) return [];\n\n // Calculate available tokens (reserve space for response)\n const availableTokens = maxTokens - RESERVED_RESPONSE_TOKENS;\n\n // If only one message, return it (truncation within message not supported)\n if (messages.length === 1) {\n return messages;\n }\n\n let totalTokens = 0;\n const result: BaseMessage[] = [];\n\n // Check if first message is a system message (should always be kept)\n const firstMessage = messages[0];\n const hasSystemMessage = firstMessage._getType() === \"system\";\n\n if (hasSystemMessage) {\n const systemTokens = estimateMessageTokens(firstMessage);\n totalTokens += systemTokens;\n result.push(firstMessage);\n }\n\n // Process remaining messages from newest to oldest\n const remainingMessages = hasSystemMessage ? messages.slice(1) : messages;\n const recentMessages: BaseMessage[] = [];\n\n for (let i = remainingMessages.length - 1; i >= 0; i--) {\n const msg = remainingMessages[i];\n const msgTokens = estimateMessageTokens(msg);\n\n if (totalTokens + msgTokens > availableTokens) {\n // Stop adding more messages\n break;\n }\n\n recentMessages.unshift(msg);\n totalTokens += msgTokens;\n }\n\n // Combine system message (if any) with recent messages\n return hasSystemMessage ? [firstMessage, ...recentMessages] : recentMessages;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"negotiator.persona.d.ts","sourceRoot":"/","sources":["chat/negotiator.persona.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,KAAK,SAAS,EAAE,KAAK,WAAW,EAAE,KAAK,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAC9H,OAAO,EAAmB,KAAK,iBAAiB,EAAE,MAAM,+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GAAG,EAAE,IAAI,EAAE,OAAO,CAAC;QACtF,WAAW,EAAE,CAAC,IAAI,EAAE,kBAAkB,EAAE,EAAE,CAAC,qBAAqB,CAAC,IAAI,EAAE,kBAAkB,CAAC;QAC1F,aAAa,EAAE;YACb,oBAAoB,EAAE,KAAK;YAC3B,qBAAqB,EAAE,IAAI;SAC5B;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { createChatTools, type ChatTools, type ToolContext, type ResolvedToolContext } from \"../shared/agent/tool.factory.js\";\nimport { focusedIntentId, type ToolScopeEnvelope } from \"../shared/agent/tool.scope.js\";\nimport type { ChatPersonaConfig } from \"./chat.persona.js\";\nimport { buildNegotiatorSystemContent, type NegotiatorPromptOptions } from \"./negotiator.prompt.js\";\nimport { createNegotiatorMemoryTools } from \"./negotiator.tools.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// NEGOTIATOR PERSONA (P4.1)\n// ═══════════════════════════════════════════════════════════════════════════════\n//\n// A pure persona addition on the P4.0 persona-neutral chat runtime: advocate\n// prompt, client-scoped toolset, and all orchestrator loop behaviors OFF.\n// Unlike the orchestrator (a static singleton), the negotiator persona is\n// created per session because its identity comes from the user's\n// `type='personal'` agent row (name/description).\n\n/**\n * Persona id for the user's personal negotiator. Matches the\n * `conversations.persona` column value for negotiator DM sessions.\n */\nexport const NEGOTIATOR_PERSONA_ID = \"negotiator\";\n\n/**\n * Client-scoped tool allowlist for the negotiator persona.\n *\n * P4.5 (IND-413) expanded this from the read-mostly P4.1 set: with direct\n * opportunity discovery retiring alongside the orchestrator, discovery is\n * purely signal-based — so the negotiator (the surviving personal-agent chat\n * surface) manages the client's signals, profile knowledge, memberships, and\n * contacts.\n *\n * Still deliberately excluded:\n * - discovery runs (`discover_opportunities`, `get/cancel_discovery_run`) —\n * retired capability; matching happens in the background from signals,\n * - whole-network administration (`create/update/delete_network`) — a\n * human/UI act for now (joins/leaves are allowed),\n * - onboarding plumbing (`complete_onboarding`,\n * `record_onboarding_privacy_consent`),\n * - agent management (`register/update/delete_agent`, permission grants),\n * - `confirm_opportunity_delivery` (OpenClaw ledger write, never chat).\n */\nexport const NEGOTIATOR_TOOL_NAMES = [\n // Negotiation record — the advocate core (P4.1)\n \"list_negotiations\",\n \"get_negotiation\",\n \"respond_to_negotiation\",\n \"list_opportunities\",\n \"update_opportunity\",\n // Pending questions — the system's open questions for the client. Added for\n // intent-pinned sessions (P4.2/IND-403); the tool clamps itself to the\n // focused intent scope when one is set. answer_pending_question (P4.3/IND-404)\n // records the client's explicit answers through the same pipeline the\n // question cards use.\n \"read_pending_questions\",\n \"answer_pending_question\",\n // Signals — the input surface of signal-based discovery (P4.5)\n \"read_intents\",\n \"create_intent\",\n \"update_intent\",\n \"delete_intent\",\n \"search_intents\",\n \"read_intent_indexes\",\n \"create_intent_index\",\n \"delete_intent_index\",\n // Profile knowledge (P4.5)\n \"read_user_contexts\",\n \"create_user_context\",\n \"update_user_context\",\n \"confirm_user_context\",\n \"preview_user_context\",\n // Premises (P4.5; read was already in P4.1)\n \"read_premises\",\n \"create_premise\",\n \"update_premise\",\n \"retract_premise\",\n // Networks — joins/leaves only, no network administration (P4.5)\n \"read_networks\",\n \"read_network_memberships\",\n \"create_network_membership\",\n \"delete_network_membership\",\n // Contacts — dormant while CONTACTS_ENABLED=false (P4.5)\n \"list_contacts\",\n \"search_contacts\",\n \"add_contact\",\n \"remove_contact\",\n \"import_contacts\",\n \"import_gmail_contacts\",\n // Utility — create_intent's own contract instructs scraping pasted URLs\n // before synthesizing a signal description (P4.5)\n \"scrape_url\",\n] as const;\n\nconst NEGOTIATOR_TOOL_ALLOWLIST: ReadonlySet<string> = new Set(NEGOTIATOR_TOOL_NAMES);\n\n/**\n * Filters a full chat-tool registry down to the negotiator allowlist.\n * Exported separately so the scoping rule is unit-testable without\n * constructing the full tool factory dependency graph.\n */\nexport function filterNegotiatorTools<T extends { name: string }>(tools: T[]): T[] {\n return tools.filter((t) => NEGOTIATOR_TOOL_ALLOWLIST.has(t.name));\n}\n\n/**\n * Applies negotiator tool availability rules that depend on the focused scope.\n * Intent-pinned chats use the adjacent Radar for opportunity listing, while all\n * other negotiator capabilities remain available.\n */\nexport function filterNegotiatorToolsForContext<T extends { name: string }>(\n tools: T[],\n context: ToolScopeEnvelope,\n): T[] {\n return focusedIntentId(context)\n ? tools.filter((tool) => tool.name !== \"list_opportunities\")\n : tools;\n}\n\n/**\n * Creates the negotiator persona's client-scoped toolset.\n *\n * Reuses the standard chat tool factory (so context resolution, scope\n * derivation, logging, and error handling stay identical) and filters the\n * registry to the allowlist. The negotiation tools are already context-bound\n * to `context.userId`, so every tool in this set can only read or act on the\n * calling client's own data.\n */\nexport async function createNegotiatorTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext,\n): Promise<ChatTools> {\n const tools = await createChatTools(deps, preResolvedContext);\n const filtered = filterNegotiatorTools(tools);\n // A supplied resolved context is authoritative. Direct callers without one\n // still get the canonical explicit scope envelope from ToolContext.\n const toolScope = preResolvedContext ?? { scopeType: deps.scopeType, scopeId: deps.scopeId };\n const contextFiltered = filterNegotiatorToolsForContext(filtered, toolScope);\n // P5.4 (IND-408): `remember`/`forget` are negotiator-exclusive — appended\n // AFTER the allowlist filter, and only when the composition root injected\n // the host bridge (i.e. negotiator memory writes are enabled). They never\n // enter the shared registry, so the orchestrator cannot see them.\n if (deps.negotiatorMemoryTools) {\n const memoryTools = createNegotiatorMemoryTools({\n host: deps.negotiatorMemoryTools,\n userId: deps.userId,\n ...(deps.sessionId ? { sessionId: deps.sessionId } : {}),\n });\n return [...contextFiltered, ...memoryTools] as ChatTools;\n }\n return contextFiltered;\n}\n\n/**\n * Creates a negotiator `ChatPersonaConfig` bound to the client's personal\n * negotiator agent row identity.\n *\n * Loop behaviors (P4.5):\n * - `hallucinationRecovery: true` — with `create_intent` in the toolset the\n * model can legitimately produce ```intent_proposal blocks, so unbacked\n * blocks must be detected/auto-invoked/stripped. The auto-invoke path is\n * confirm-safe: `create_intent` returns a proposal card that persists\n * nothing until the client approves it in the UI. A hallucinated\n * ```opportunity block maps to `discover_opportunities`, which is absent\n * from this toolset — the loop falls back to a correction message and the\n * final-response strip still removes the unbacked block.\n * - `createIntentCallback: false` — discovery-coupled (fires only off\n * `discover_opportunities` results); retired along with direct discovery.\n *\n * @param opts - Identity from the user's `type='personal'` agent row\n */\nexport function createNegotiatorPersona(opts: NegotiatorPromptOptions): ChatPersonaConfig {\n return {\n id: NEGOTIATOR_PERSONA_ID,\n buildSystemContent: (ctx, iterCtx) => buildNegotiatorSystemContent(ctx, opts, iterCtx),\n createTools: (deps, preResolvedContext) => createNegotiatorTools(deps, preResolvedContext),\n loopBehaviors: {\n createIntentCallback: false,\n hallucinationRecovery: true,\n },\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"negotiator.prompt.d.ts","sourceRoot":"/","sources":["chat/negotiator.prompt.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAE3E,OAAO,EAAqC,KAAK,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AACrH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAkBjE,+EAA+E;AAC/E,MAAM,WAAW,uBAAuB;IACtC,qEAAqE;IACrE,SAAS,EAAE,MAAM,CAAC;IAClB,qEAAqE;IACrE,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;;;;OAKG;IACH,MAAM,CAAC,EAAE,qBAAqB,EAAE,CAAC;IACjC;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAkDD;;;;;;;;;;;;GAYG;AACH,wBAAgB,4BAA4B,CAC1C,GAAG,EAAE,mBAAmB,EACxB,IAAI,EAAE,uBAAuB,EAC7B,QAAQ,CAAC,EAAE,gBAAgB,GAC1B,MAAM,CAgGR"}
@@ -1 +0,0 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AAmB,GAAG,cAAc;QACxC,CAAC,CAAC,wBAAwB,CAAC,cAAc,EAAE,IAAI,CAAC,iBAAiB,CAAC;QAClE,CAAC,CAAC,yBAAyB,EAAE,CAAC;IAChC,MAAM,aAAa,GAAG,iCAAiC,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;IAC3E,MAAM,kBAAkB,GAAG,IAAI,CAAC,kBAAkB,CAAC,CAAC,CAAC,uBAAuB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACpF,MAAM,eAAe,GAAG,IAAI,CAAC,kBAAkB;QAC7C,CAAC,CAAC,iQAAiQ;QACnQ,CAAC,CAAC,EAAE,CAAC;IACP,MAAM,mBAAmB,GAAG,cAAc;QACxC,CAAC,CAAC,iRAAiR;QACnR,CAAC,CAAC,sMAAsM,CAAC;IAC3M,MAAM,eAAe,GAAG,cAAc;QACpC,CAAC,CAAC,4GAA4G;QAC9G,CAAC,CAAC,iGAAiG,CAAC;IACtG,MAAM,yBAAyB,GAAG,cAAc;QAC9C,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,+EAA+E,CAAC;IAEpF,OAAO,WAAW,IAAI,CAAC,SAAS,+CAA+C,GAAG,CAAC,QAAQ;EAC3F,eAAe;mCACkB,GAAG,CAAC,QAAQ;;;;;EAK7C,mBAAmB;;;;;;EAMnB,mBAAmB,GAAG,aAAa,GAAG,kBAAkB;;0MAEgJ,eAAe;;;;;YAK7M,GAAG,CAAC,QAAQ,KAAK,GAAG,CAAC,SAAS,UAAU,GAAG,CAAC,MAAM;;;;EAI5D,WAAW;;;;;EAKX,cAAc;;;;;;;;;kHASkG,yBAAyB;;;;;;;;;;;;;;;6GAe9B,eAAe;;;;;;;;;;;;;8MAakF,CAAC;AAC/M,CAAC","sourcesContent":["import type { ResolvedToolContext } from \"../shared/agent/tool.factory.js\";\nimport { focusedIntentId } from \"../shared/agent/tool.scope.js\";\nimport { renderNegotiatorChatMemorySection, type NegotiatorMemoryEntry } from \"../negotiation/negotiation.memory.js\";\nimport type { IterationContext } from \"./chat.prompt.modules.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// NEGOTIATOR PERSONA SYSTEM PROMPT (P4.1)\n// ═══════════════════════════════════════════════════════════════════════════════\n//\n// The direct chat line between a user and their personal negotiator agent\n// (the `type='personal'` agent row). Unlike the orchestrator prompt, this\n// persona works for exactly one client: it reports on the client's\n// negotiations and opportunities, explains decisions from the negotiation\n// record, and acts only on explicit client instruction.\n//\n// P4.5 (IND-413): the negotiator also manages the client's signals, profile\n// knowledge, premises, community memberships, and contacts — discovery is\n// purely signal-based, so shaping signals here IS how the client steers\n// matching. It still has no direct discovery capability: matching runs in\n// the background from the signals.\n\n/** Identity options resolved from the user's personal negotiator agent row. */\nexport interface NegotiatorPromptOptions {\n /** The negotiator agent's display name (e.g. \"Ada's Negotiator\"). */\n agentName: string;\n /** The negotiator agent's description, when set on the agent row. */\n agentDescription?: string;\n /**\n * Human-readable label for the pinned signal when the session is\n * intent-scoped (P4.2/IND-403). The pin itself comes from the resolved\n * context's scope envelope; this label just saves a tool round-trip for\n * naming it. Ignored when the session has no intent scope.\n */\n pinnedIntentLabel?: string;\n /**\n * The client's negotiator memories (P5.3 read path) — accumulated notes\n * from negotiations and prior chats, rendered as a prompt section. The\n * audience is the client themself, so entries are shared context, not\n * secrets. Absent/empty → the prompt is byte-identical to before.\n */\n memory?: NegotiatorMemoryEntry[];\n /**\n * True when the `remember`/`forget` memory tools are registered for this\n * session (P5.4 — the composition root injects them only while negotiator\n * memory writes are enabled). Adds the memory-tool guidance section and\n * tool-reference rows; false/absent → prompt unchanged.\n */\n memoryToolsEnabled?: boolean;\n}\n\n/**\n * Renders the pinned-signal section for intent-scoped sessions (P4.2).\n * Awareness, not a sandbox: the conversation orbits this signal, but the\n * negotiator may still reference the client's other knowledge.\n */\nfunction buildPinnedSignalSection(intentId: string, label?: string): string {\n const labelLine = label?.trim() ? ` — “${label.trim()}”` : \"\";\n return `\n## Pinned signal\nThis conversation was opened from one of the client's signals (intent id: ${intentId}${labelLine}). Treat it as the working focus of this chat:\n- Open questions listed by read_pending_questions here are this signal's open questions — surface them early and work through them conversationally. The client answers them via the question cards shown in this chat, or conversationally: when they give you an explicit answer, record it with answer_pending_question.\n- Matches for this signal are already visible in the adjacent Radar. Do not repeat them or bulk-list them in chat. When the client explicitly references a match, use its opportunity and negotiation records to explain it or act on it; update_opportunity remains available only for their explicit instruction.\n- When summarizing negotiations, always state the scope: say “for this signal” for the default pinned view, or “across all your signals” when the client explicitly asks for full history. Separate CURRENT items (active or waiting on you) from CONCLUDED AGENT NEGOTIATIONS. If there are zero current items, say that plainly before mentioning concluded history. A concluded agent negotiation is not a completed connection. Never imply an ongoing negotiation that the same-turn list_negotiations result does not show.\n- When the client restates or sharpens what they want here, propose an update to this signal (update_intent) or a new premise — on their confirmation — so background matching reflects it.\n- This is a focus, not a wall: you may still read the client's profile, premises, and other signals when the conversation needs the fuller picture, and general questions about their negotiations remain fair game.`;\n}\n\n/**\n * Renders the question-inbox section for the unscoped DM (P4.3/IND-404).\n * The DM is the client's primary surface for the system's open questions:\n * signal refinements, negotiation follow-ups, profile gaps. Cards render in\n * the chat; conversational answers are recorded via answer_pending_question.\n */\nfunction buildQuestionInboxSection(): string {\n return `\n## Client question inbox\nThe system collects open questions for your client (signal refinements, negotiation follow-ups, profile gaps), and this chat is the primary place they get handled. Question cards also render directly in this chat.\n- Early in a conversation — or whenever the client asks what needs their attention — call read_pending_questions and surface what is open, briefly and in plain language.\n- When the client asks why something is being asked, explain the question's context from the record it came from (the negotiation, opportunity, or signal behind it) — look it up, don't guess.\n- When the client answers a question conversationally, record it with answer_pending_question — pass exactly what they said (their chosen options and/or their own words), never an answer you inferred. If the tool reports the question was already answered or dismissed, tell them instead of retrying.\n- Never pressure the client to answer; the questions keep for later and remain available in the app's Questions page.`;\n}\n\n/**\n * Renders the remember/forget guidance section (P5.4). Only rendered when the\n * memory tools are actually registered, so the model is never told about\n * capabilities it does not have.\n */\nfunction buildMemoryToolsSection(): string {\n return `\n## Remembering and forgetting\nYou keep a private working memory for negotiations: standing disclosure rules, thresholds, and playbook notes. The client can inspect, edit, and delete everything you remember on their agent page (Memory tab).\n- When the client states a standing rule that should outlive this conversation — especially about what to disclose or protect (\"never share my budget\", \"don't reveal who my current clients are\") — save it with remember. Pick the kind honestly: disclosure_rule for sharing constraints, threshold for hard limits, playbook for tactics. Confirm in one short sentence what you saved and that they can review it on your agent page.\n- Only remember what the client actually said. Never speculate a rule into memory, and don't save one-off instructions that only apply to the current request.\n- When the client asks you to forget or retract something, use forget with their description of it. If several memories match, lay out the candidates in plain language and ask which one they mean.\n- Disclosure rules are standing consent: treat a remembered disclosure rule as binding in every future negotiation until the client changes or deletes it.`;\n}\n\n/**\n * Builds the system prompt for the negotiator chat persona.\n *\n * Grounded in the client's preloaded user/profile context; everything else\n * (negotiations, opportunities, signals, premises) must be fetched through\n * the client-scoped toolset each turn.\n *\n * @param ctx - Resolved tool context for the current session\n * @param opts - Identity from the client's personal negotiator agent row\n * @param _iterCtx - Iteration context (unused — the negotiator prompt has no\n * dynamic modules; the nudge is injected by the agent loop)\n * @returns The complete system prompt string\n */\nexport function buildNegotiatorSystemContent(\n ctx: ResolvedToolContext,\n opts: NegotiatorPromptOptions,\n _iterCtx?: IterationContext,\n): string {\n const userContext = JSON.stringify(ctx.user, null, 2);\n const profileContext = ctx.userProfile\n ? JSON.stringify(ctx.userProfile, null, 2)\n : \"null\";\n const descriptionLine = opts.agentDescription?.trim()\n ? `\\n${opts.agentDescription.trim()}\\n`\n : \"\";\n const pinnedIntentId = focusedIntentId(ctx);\n // Pinned sessions clamp the question tools to the signal and carry their own\n // question guidance; the unscoped DM gets the full inbox instead.\n const pinnedSignalSection = pinnedIntentId\n ? buildPinnedSignalSection(pinnedIntentId, opts.pinnedIntentLabel)\n : buildQuestionInboxSection();\n const memorySection = renderNegotiatorChatMemorySection(opts.memory ?? []);\n const memoryToolsSection = opts.memoryToolsEnabled ? buildMemoryToolsSection() : \"\";\n const memoryToolsRows = opts.memoryToolsEnabled\n ? `\\n| **remember** | kind, content | Save a standing rule the client just stated into your private negotiator memory — ONLY what they actually said |\\n| **forget** | memoryId? / description? | Delete a remembered rule when the client asks you to forget it |`\n : \"\";\n const opportunityGuidance = pinnedIntentId\n ? \"- **Discuss referenced opportunities**: matches for this signal are already visible in the adjacent Radar. Do not repeat or bulk-list them in chat. Explain or update an opportunity only when the client explicitly references it, and act only on their explicit instruction.\"\n : \"- **Review and act on opportunities**: show the client the opportunities currently waiting on them and what accepting or passing would mean; accept or pass on one only when they explicitly say so.\";\n const matchVisibility = pinnedIntentId\n ? \"New matches for this pinned signal appear in the adjacent Radar rather than as a repeated listing in chat.\"\n : \"New matches appear on the client's home page and can be reviewed in this chat as opportunities.\";\n const opportunityListingToolRow = pinnedIntentId\n ? \"\"\n : \"\\n| **list_opportunities** | — | List the client's actionable opportunities |\";\n\n return `You are ${opts.agentName}, the personal negotiator agent working for ${ctx.userName}.\n${descriptionLine}\nYou work for exactly one client: ${ctx.userName}. You represent them in negotiations with other members' agents across the network, and this chat is your direct line to them. Your job here is to keep your client informed about what you have been doing on their behalf, explain your reasoning honestly, and act only on their explicit instructions.\n\n## What you do in this chat\n- **Report on negotiations**: when the client asks what is happening, look up their negotiations and summarize status, counterparties, and where things stand.\n- **Explain decisions**: when the client asks why something was pursued, declined, or stalled (\"why did you pass on X?\"), find the relevant negotiation and answer from the actual record — the messages, outcomes, and reasoning stored there. Never reconstruct a rationale from memory.\n${opportunityGuidance}\n- **Manage their signals**: their active intents (signals) define what you negotiate for — and matching is driven entirely by them. When the client tells you what they are looking for, draft a clear, specific signal and create it; refine or retire signals when they ask. If a signal request is vague, read their profile and existing signals first, then propose a sharper wording before creating it. If they paste a link describing what they want, read it first and synthesize the signal from its content.\n- **Keep their knowledge current**: when the client shares a new fact about themselves (\"I moved to Berlin\", \"I stopped consulting\"), update their profile context or premises so future negotiations reflect reality. Read before you write — update the existing entry instead of duplicating it.\n- **Handle memberships**: list the communities they belong to and join or leave communities when they ask.\n- **Manage their contacts**: look up, add, remove, or import contacts when they ask (when contact features are enabled).\n- **Act on instruction**: every write — a negotiation response, an opportunity decision, a signal, a profile or premise change, a membership change, a contact change — happens only when the client explicitly asks for it in this conversation. Never write anything the client did not just ask for.\n${pinnedSignalSection}${memorySection}${memoryToolsSection}\n## What you cannot do here\n- **No direct discovery.** You cannot run matching or search for people yourself. Matching happens automatically in the background from the client's signals — shaping the signals is how you steer it. ${matchVisibility}\n- **No community administration.** You can join or leave communities for the client, but you cannot create, rename, or delete communities — point them to the app for that.\n- You cannot push updates after this conversation ends. You only report when asked.\n\n## Session\n- Client: ${ctx.userName} (${ctx.userEmail}), id: ${ctx.userId}\n\n### Client (preloaded context)\n\\`\\`\\`json\n${userContext}\n\\`\\`\\`\n\n### Client Context (preloaded context)\n\\`\\`\\`json\n${profileContext}\n\\`\\`\\`\n\n## Tools Reference\n\n| Tool | Params | What it does |\n|------|--------|-------------|\n| **list_negotiations** | status?, scope?, limit?, detail? | List agent negotiations with lifecycle-explicit opportunity and owner-action labels (clamped to the pinned signal when one is set; pass scope:'all' for full history) |\n| **get_negotiation** | negotiationId | Full negotiation record: messages, outcome, reasoning |\n| **respond_to_negotiation** | negotiationId, ... | Act on a negotiation — ONLY on explicit client instruction |${opportunityListingToolRow}\n| **read_pending_questions** | limit? | The system's open questions for the client (clamped to the pinned signal when one is set) |\n| **answer_pending_question** | questionId, selectedOptions?, freeText? | Record the client's explicit answer to a pending question — ONLY with an answer they actually gave |\n| **update_opportunity** | opportunityId, status | Accept/pass an opportunity — ONLY on explicit client instruction |\n| **read_intents** / **search_intents** | — / query | The client's active signals (what they're looking for) |\n| **create_intent** | description, networkId? | Draft a new signal — returns a proposal card the client approves in the UI |\n| **update_intent** / **delete_intent** | intentId, ... | Refine or retire a signal on instruction |\n| **read_intent_indexes** / **create_intent_index** / **delete_intent_index** | intentId, networkId | Where a signal is placed across communities |\n| **read_user_contexts** / **create_user_context** / **update_user_context** | ... | The client's profile knowledge — read before writing |\n| **preview_user_context** / **confirm_user_context** | ... | Preview/confirm profile updates from sources |\n| **read_premises** / **create_premise** / **update_premise** / **retract_premise** | ... | The client's premises (facts they've established) |\n| **read_networks** / **read_network_memberships** | — | The client's communities and memberships |\n| **create_network_membership** / **delete_network_membership** | networkId | Join/leave a community on instruction |\n| **list_contacts** / **search_contacts** / **add_contact** / **remove_contact** | ... | The client's contacts |\n| **import_contacts** / **import_gmail_contacts** | ... | Bulk contact import on instruction |\n| **scrape_url** | url, objective | Read a link the client pasted (e.g. before drafting a signal from it) |${memoryToolsRows}\n\n## Grounding rules\n- **Never fabricate.** Every claim about a negotiation, opportunity, signal, or premise must come from a tool result in this conversation. If you have not looked it up this turn, look it up before answering. Only the client's identity and profile above are preloaded.\n- **Check tool results before confirming.** Never claim an action succeeded without a successful tool result for it.\n- **Be honest about your own actions.** If the record shows you made a judgment call the client disagrees with, explain the reasoning from the record — do not get defensive, and do not invent justifications the record does not support.\n- **Keep lifecycle states distinct.** A negotiation task with status \\`completed\\` means only that the agents concluded. Use the tool's \\`lifecycle\\` object and \\`lifecycleLabel\\` for user-facing wording. If the opportunity is \\`pending\\`, say the agents concluded with a potential match awaiting the owner's review. Agent-turn \\`accept\\`, \\`latestAction=accept\\`, and \\`outcome.hasOpportunity=true\\` are agent-side judgments: never translate them into “I accepted”, “you accepted”, “connected”, “completed connection”, or equivalent. Describe rejected, stalled, draft, expired, pending, and accepted opportunities separately; never aggregate them as completed connections.\n- **Owner actions require explicit evidence.** Say the owner accepted only when \\`lifecycle.ownerAction=accepted\\`. This reporting contract does not prove an owner pass, so a rejected opportunity must not be narrated as “you passed” unless a separate current-turn tool result explicitly establishes that owner action. Reporting and history narration are read-only; call \\`update_opportunity\\` only for the client's explicit current instruction.\n- **Never infer a direct chat.** Negotiation completion and every opportunity status, including \\`accepted\\`, are insufficient evidence that an H2H conversation or message thread exists. A \\`conversationId\\` with \\`conversationType=agent_negotiation\\` identifies only the A2A agent transcript. \\`lifecycle.directConversationEvidence=not_provided\\` means do not mention messages. Mention a direct conversation only when a current-turn tool result independently and explicitly supplies H2H conversation evidence.\n- **Pass proposal cards through verbatim.** When a tool result contains a fenced code block meant for the app (e.g. \\`\\`\\`intent_proposal from create_intent), include that block verbatim in your reply — the app renders it as an interactive card the client approves or skips. Never write such a block yourself without a backing tool result.\n- **Never expose IDs, UUIDs, tool names, or raw JSON** to the client. Translate everything into natural language; refer to people and opportunities by name. (Fenced proposal blocks from tool results are the one exception — they are rendered as cards, not shown as JSON.)\n- **Respond in the language of the client's latest message.**\n- **Voice**: first person, loyal but candid, calm and concise. No hype, no networking clichés, no exaggeration. You are their agent, not a salesperson.\n- When calling tools, first write a short natural sentence plus a \\`>\\` blockquote describing what you are checking (e.g. \"> Checking the record with Alice\"), then leave an empty line after the blockquote.`;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"negotiator.tools.d.ts","sourceRoot":"/","sources":["chat/negotiator.tools.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,yBAAyB,EAA4B,MAAM,qDAAqD,CAAC;AAyD/H;;;;GAIG;AACH,wBAAgB,2BAA2B,CAAC,IAAI,EAAE;IAChD,IAAI,EAAE,yBAAyB,CAAC;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iCA4FA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"negotiator.tools.js","sourceRoot":"/","sources":["chat/negotiator.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,kFAAkF;AAClF,iCAAiC;AACj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d,OAAO,IAAI,CAAC,SAAS,CAAC;wBACpB,MAAM,EAAE,WAAW;wBACnB,OAAO,EAAE,6EAA6E;qBACvF,CAAC,CAAC;YACP,CAAC;QACH,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,CAAC,KAAK,CAAC,aAAa,EAAE;gBAC1B,QAAQ,EAAE,QAAQ;gBAClB,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;aACxD,CAAC,CAAC;YACH,OAAO,IAAI,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,wDAAwD,EAAE,CAAC,CAAC;QAChH,CAAC;IACH,CAAC,EACD;QACE,IAAI,EAAE,QAAQ;QACd,WAAW,EACT,iQAAiQ;QACnQ,MAAM,EAAE,YAAY;KACrB,CACF,CAAC;IAEF,OAAO,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport type { NegotiatorMemoryToolsHost, NegotiatorMemoryToolView } from \"../shared/interfaces/negotiator-memory.interface.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// NEGOTIATOR MEMORY TOOLS (P5.4)\n// ═══════════════════════════════════════════════════════════════════════════════\n//\n// `remember` and `forget` exist ONLY in the negotiator persona's toolset —\n// they are appended by `createNegotiatorTools` after the allowlist filter and\n// never enter the shared chat-tool registry, so the orchestrator (and the MCP\n// tool listing built from the registry) cannot see them.\n//\n// Registration is host-gated: the tools are created only when the composition\n// root injects a `NegotiatorMemoryToolsHost` (which it does only while\n// negotiator memory writes are enabled). The host owns every policy decision\n// (flag, caps, embedding, matching); these wrappers only translate between\n// the model and the host bridge.\n\nconst logger = protocolLogger(\"NegotiatorMemoryTools\");\n\nconst RememberSchema = z.object({\n kind: z\n .enum([\"disclosure_rule\", \"playbook\", \"threshold\"])\n .describe(\n \"disclosure_rule: what may or may not be shared, and with whom. \" +\n \"threshold: a hard limit or reservation point (minimum rate, maximum scope). \" +\n \"playbook: a tactic or approach the client wants used.\",\n ),\n content: z\n .string()\n .min(1)\n .max(2000)\n .describe(\n \"The standing rule as ONE self-contained sentence, faithful to what the client actually said. No IDs, no meta-commentary.\",\n ),\n});\n\nconst ForgetSchema = z.object({\n memoryId: z\n .string()\n .uuid()\n .optional()\n .describe(\"Exact memory id, when known (e.g. from an ambiguous forget result).\"),\n description: z\n .string()\n .min(1)\n .max(500)\n .optional()\n .describe(\"The client's description of the memory to forget, used for matching.\"),\n});\n\nconst describeMemory = (m: NegotiatorMemoryToolView) => ({\n memoryId: m.id,\n kind: m.kind,\n content: m.content,\n});\n\n/**\n * Creates the negotiator persona's `remember`/`forget` memory tools bound to\n * the acting client. Both tools operate exclusively on the client's own\n * negotiator memory store — the host bridge is keyed on `userId`.\n */\nexport function createNegotiatorMemoryTools(opts: {\n host: NegotiatorMemoryToolsHost;\n userId: string;\n sessionId?: string;\n}) {\n const { host, userId, sessionId } = opts;\n\n const remember = tool(\n async (query: z.infer<typeof RememberSchema>) => {\n logger.info(\"Tool invoked\", { toolName: \"remember\", userId, kind: query.kind });\n try {\n const saved = await host.remember(userId, {\n kind: query.kind,\n content: query.content,\n ...(sessionId ? { sessionId } : {}),\n });\n if (!saved) {\n return JSON.stringify({\n status: \"disabled\",\n message:\n \"Negotiator memory is currently disabled, so this rule was not saved. Tell the client and suggest trying again later.\",\n });\n }\n return JSON.stringify({\n status: \"remembered\",\n memory: describeMemory(saved),\n message:\n \"Saved. Confirm to the client in one short sentence and mention they can review or edit everything you remember on their agent page.\",\n });\n } catch (err) {\n logger.error(\"Tool failed\", {\n toolName: \"remember\",\n error: err instanceof Error ? err.message : String(err),\n });\n return JSON.stringify({ status: \"error\", message: \"Failed to save the memory. Tell the client honestly.\" });\n }\n },\n {\n name: \"remember\",\n description:\n \"Save a standing rule the client just stated, into your private negotiator memory: a disclosure rule (what to protect or share), a threshold (hard limit), or a playbook note (preferred tactic). Use ONLY for durable guidance the client explicitly gave — never for one-off instructions or your own inferences.\",\n schema: RememberSchema,\n },\n );\n\n const forget = tool(\n async (query: z.infer<typeof ForgetSchema>) => {\n logger.info(\"Tool invoked\", { toolName: \"forget\", userId, byId: !!query.memoryId });\n if (!query.memoryId && !query.description?.trim()) {\n return JSON.stringify({\n status: \"error\",\n message: \"Provide either memoryId or a description of the memory to forget.\",\n });\n }\n try {\n const result = await host.forget(userId, {\n ...(query.memoryId ? { memoryId: query.memoryId } : {}),\n ...(query.description ? { description: query.description } : {}),\n });\n switch (result.status) {\n case \"deleted\":\n return JSON.stringify({\n status: \"forgotten\",\n memory: describeMemory(result.memory),\n message: \"Deleted. Confirm to the client what exactly was forgotten (quote the deleted rule).\",\n });\n case \"ambiguous\":\n return JSON.stringify({\n status: \"ambiguous\",\n candidates: result.candidates.map(describeMemory),\n message:\n \"Several memories match. Describe the candidates to the client in plain language and ask which one to forget; then call forget again with that memoryId.\",\n });\n case \"not_found\":\n return JSON.stringify({\n status: \"not_found\",\n message: \"No stored memory matches that. Tell the client nothing was found to forget.\",\n });\n }\n } catch (err) {\n logger.error(\"Tool failed\", {\n toolName: \"forget\",\n error: err instanceof Error ? err.message : String(err),\n });\n return JSON.stringify({ status: \"error\", message: \"Failed to delete the memory. Tell the client honestly.\" });\n }\n },\n {\n name: \"forget\",\n description:\n \"Delete an entry from your private negotiator memory when the client asks you to forget or retract it. Pass the client's description of it (or an exact memoryId after an ambiguous result). If several match, you'll get candidates to clarify with the client.\",\n schema: ForgetSchema,\n },\n );\n\n return [remember, forget];\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"onboarding.persona.d.ts","sourceRoot":"/","sources":["chat/onboarding.persona.ts"],"names":[],"mappings":"AAGA,OAAO,EAAmB,KAAK,SAAS,EAAE,KAAK,mBAAmB,EAAE,KAAK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ChatTools, type ResolvedToolContext, type ToolContext } from \"../shared/agent/tool.factory.js\";\nimport { resolveChatContext } from \"../shared/agent/tool.helpers.js\";\nimport { deriveAllowedNetworkIds, scopeFromNetworkId } from \"../shared/agent/tool.scope.js\";\nimport type { ChatPersonaConfig } from \"./chat.persona.js\";\nimport { narrowSignalTools } from \"./signal.persona.js\";\nimport { buildOnboardingSystemContent } from \"./onboarding.prompt.js\";\n\n/** Public kickoff marker used by the restricted web profile phase. */\nexport { ONBOARDING_PROFILE_KICKOFF } from \"./onboarding.prompt.js\";\n\n/** Stable persona id persisted for restricted web onboarding conversations. */\nexport const ONBOARDING_PERSONA_ID = \"onboarding\";\n\n/**\n * Exact positive allowlist for Onboarding Agent.\n *\n * Profile confirmation performs the approved premise decomposition internally,\n * so this persona does not need arbitrary premise writes. New shared tools stay\n * unavailable until explicitly reviewed here.\n */\nexport const ONBOARDING_TOOL_NAMES = [\n \"record_onboarding_privacy_consent\",\n \"read_user_contexts\",\n \"preview_user_context\",\n \"confirm_user_context\",\n \"ask_user_question\",\n \"create_intent\",\n \"complete_onboarding\",\n] as const;\n\nconst ONBOARDING_TOOL_ALLOWLIST: ReadonlySet<string> = new Set(ONBOARDING_TOOL_NAMES);\n\n/** Filters the shared registry through Onboarding Agent's exact allowlist. */\nexport function filterOnboardingTools<T extends { name: string }>(tools: T[]): T[] {\n return tools.filter((candidate) => ONBOARDING_TOOL_ALLOWLIST.has(candidate.name));\n}\n\n/**\n * Narrows shared onboarding tools whose generic schemas exceed the web flow.\n * Consent is public-lookup-only with server-fixed provenance, and chat-side\n * completion requires an exact intent ID (the direct REST tool remains the\n * browser's normal completion path).\n */\nexport function narrowOnboardingTools(allowed: ChatTools): ChatTools {\n return allowed.map((sharedTool) => {\n if (sharedTool.name === \"record_onboarding_privacy_consent\") {\n return tool(\n async (query: { publicProfileLookupGranted: boolean }) => sharedTool.invoke({\n publicProfileLookupGranted: query.publicProfileLookupGranted,\n source: \"web_onboarding\",\n }) as Promise<string>,\n {\n name: \"record_onboarding_privacy_consent\",\n description: \"Record the authenticated user's explicit public-profile lookup choice for web onboarding. Ask first; this does not perform lookup.\",\n schema: z.object({ publicProfileLookupGranted: z.boolean() }).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"complete_onboarding\") {\n return tool(\n async (query: { intentId: string }) => sharedTool.invoke({ intentId: query.intentId }) as Promise<string>,\n {\n name: \"complete_onboarding\",\n description: \"Validate completion only for the exact active first-signal ID returned after user confirmation.\",\n schema: z.object({ intentId: z.string().uuid() }).strict(),\n },\n );\n }\n\n return sharedTool;\n }) as ChatTools;\n}\n\n/** Creates the context-bound, allowlisted, proposal-only onboarding toolset. */\nexport async function createOnboardingTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext,\n): Promise<ChatTools> {\n const explicitScope = deps.scopeType && deps.scopeId\n ? { scopeType: deps.scopeType, scopeId: deps.scopeId }\n : scopeFromNetworkId(deps.networkId);\n const resolvedContext = preResolvedContext ?? await resolveChatContext({\n database: deps.database,\n userId: deps.userId,\n networkId: explicitScope.scopeType === \"network\" ? explicitScope.scopeId : deps.networkId,\n sessionId: deps.sessionId,\n contactsEnabled: deps.contactsEnabled,\n });\n if (explicitScope.scopeType && explicitScope.scopeId) {\n resolvedContext.scopeType = explicitScope.scopeType;\n resolvedContext.scopeId = explicitScope.scopeId;\n }\n\n const userDb = deps.userDb ?? deps.createUserDatabase(deps.database, resolvedContext.userId);\n const memberships = await userDb.getNetworkMemberships();\n const allowedNetworkIds = deriveAllowedNetworkIds({\n memberships,\n ...(resolvedContext.scopeType && resolvedContext.scopeId\n ? { scopeType: resolvedContext.scopeType, scopeId: resolvedContext.scopeId }\n : {}),\n });\n const systemDb = deps.systemDb\n ?? deps.createSystemDatabase(deps.database, resolvedContext.userId, allowedNetworkIds, deps.embedder);\n const allowed = filterOnboardingTools(\n await createChatTools(deps, resolvedContext),\n ) as ChatTools;\n\n // Reuse Signal's reviewed create_intent/self-read narrowing, then clamp the\n // onboarding-specific generic schemas to the exact web flow.\n return narrowOnboardingTools(\n narrowSignalTools(allowed, { context: resolvedContext, userDb, systemDb }),\n );\n}\n\n/** Restricted web onboarding persona on the persona-neutral chat runtime. */\nexport const ONBOARDING_PERSONA: ChatPersonaConfig = {\n id: ONBOARDING_PERSONA_ID,\n buildSystemContent: (ctx, iterCtx) => buildOnboardingSystemContent(ctx, iterCtx),\n createTools: (deps, preResolvedContext) => createOnboardingTools(deps, preResolvedContext),\n loopBehaviors: {\n createIntentCallback: false,\n hallucinationRecovery: true,\n },\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"onboarding.prompt.d.ts","sourceRoot":"/","sources":["chat/onboarding.prompt.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAGjE,kEAAkE;AAClE,eAAO,MAAM,0BAA0B,+BAA+B,CAAC;AA0BvE,oEAAoE;AACpE,wBAAgB,4BAA4B,CAC1C,GAAG,EAAE,mBAAmB,EACxB,OAAO,CAAC,EAAE,gBAAgB,GACzB,MAAM,CAmDR"}