@indexnetwork/protocol 22.0.0-rc.498.1 → 64.0.0-rc.604.2

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 (561) hide show
  1. package/CHANGELOG.md +1841 -0
  2. package/IMPLEMENTATION.md +140 -181
  3. package/README.md +16 -20
  4. package/STABILITY.md +16 -11
  5. package/dist/{intents/intent.module.d.ts → capabilities/intents.d.ts} +182 -192
  6. package/dist/capabilities/intents.js +88 -0
  7. package/dist/capabilities/negotiations.d.ts +17 -0
  8. package/dist/capabilities/negotiations.js +16 -0
  9. package/dist/{networks/network.module.d.ts → capabilities/networks.d.ts} +33 -169
  10. package/dist/{networks/network.module.js → capabilities/networks.js} +6 -17
  11. package/dist/index.d.ts +57 -132
  12. package/dist/index.js +41 -100
  13. package/dist/internal/agents/agent.repository.port.d.ts +59 -0
  14. package/dist/internal/agents/agent.repository.port.js +7 -0
  15. package/dist/internal/agents/agent.types.d.ts +35 -0
  16. package/dist/{agents → internal/agents}/agent.types.js +1 -6
  17. package/dist/{intents → internal/intents}/graph/intent.graph.d.ts +142 -151
  18. package/dist/{intents → internal/intents}/graph/intent.graph.execute.d.ts +5 -1
  19. package/dist/{intents → internal/intents}/graph/intent.graph.execute.js +165 -46
  20. package/dist/internal/intents/graph/intent.graph.infer.d.ts +78 -0
  21. package/dist/internal/intents/graph/intent.graph.infer.js +122 -0
  22. package/dist/internal/intents/graph/intent.graph.js +108 -0
  23. package/dist/{intents → internal/intents}/graph/intent.graph.reconcile.d.ts +18 -9
  24. package/dist/internal/intents/graph/intent.graph.reconcile.js +173 -0
  25. package/dist/internal/intents/graph/intent.graph.shared.d.ts +55 -0
  26. package/dist/{intents → internal/intents}/graph/intent.graph.shared.js +25 -70
  27. package/dist/{intents → internal/intents}/graph/intent.graph.state.d.ts +96 -32
  28. package/dist/{intents → internal/intents}/graph/intent.graph.state.js +42 -31
  29. package/dist/internal/intents/intent.admission.d.ts +16 -0
  30. package/dist/internal/intents/intent.admission.js +30 -0
  31. package/dist/{intents → internal/intents}/intent.inferrer.d.ts +1 -40
  32. package/dist/{intents → internal/intents}/intent.inferrer.js +13 -49
  33. package/dist/internal/intents/intent.preparer.d.ts +52 -0
  34. package/dist/internal/intents/intent.preparer.js +87 -0
  35. package/dist/{intents → internal/intents}/intent.verifier.d.ts +3 -36
  36. package/dist/{intents → internal/intents}/intent.verifier.js +0 -17
  37. package/dist/{networks → internal/networks}/indexer.graph.d.ts +15 -200
  38. package/dist/{networks → internal/networks}/indexer.graph.js +19 -128
  39. package/dist/{networks → internal/networks}/indexer.state.d.ts +8 -63
  40. package/dist/internal/networks/indexer.state.js +70 -0
  41. package/dist/{networks → internal/networks}/membership.graph.d.ts +6 -6
  42. package/dist/{networks → internal/networks}/membership.graph.js +3 -3
  43. package/dist/{networks → internal/networks}/membership.state.d.ts +2 -2
  44. package/dist/{networks → internal/networks}/membership.state.js +2 -2
  45. package/dist/{networks → internal/networks}/network.graph.d.ts +9 -22
  46. package/dist/{networks → internal/networks}/network.graph.js +13 -27
  47. package/dist/{networks → internal/networks}/network.recommender.d.ts +2 -2
  48. package/dist/{networks → internal/networks}/network.recommender.js +2 -2
  49. package/dist/{networks → internal/networks}/network.state.d.ts +4 -7
  50. package/dist/{networks → internal/networks}/network.state.js +4 -4
  51. package/dist/internal/opportunities/negotiation-context.loader.d.ts +26 -0
  52. package/dist/internal/opportunities/negotiation-context.loader.js +36 -0
  53. package/dist/{opportunities → internal/opportunities}/opportunity.actor.d.ts +1 -1
  54. package/dist/{opportunities → internal/opportunities}/opportunity.actor.js +7 -1
  55. package/dist/internal/opportunities/opportunity.counterparties.d.ts +17 -0
  56. package/dist/internal/opportunities/opportunity.counterparties.js +19 -0
  57. package/dist/internal/opportunities/opportunity.events.d.ts +38 -0
  58. package/dist/internal/opportunities/opportunity.events.js +94 -0
  59. package/dist/{opportunities → internal/opportunities}/opportunity.feed-selection.d.ts +3 -9
  60. package/dist/internal/opportunities/opportunity.feed-selection.js +40 -0
  61. package/dist/internal/opportunities/opportunity.graph.modes.d.ts +39 -0
  62. package/dist/internal/opportunities/opportunity.graph.modes.js +138 -0
  63. package/dist/{opportunities → internal/opportunities}/opportunity.labels.d.ts +2 -3
  64. package/dist/internal/opportunities/opportunity.labels.js +9 -0
  65. package/dist/{opportunities → internal/opportunities}/opportunity.presentation.d.ts +17 -86
  66. package/dist/{opportunities → internal/opportunities}/opportunity.presentation.js +54 -447
  67. package/dist/{opportunities → internal/opportunities}/opportunity.update-admission.d.ts +2 -2
  68. package/dist/internal/opportunities/opportunity.utils.d.ts +105 -0
  69. package/dist/internal/opportunities/opportunity.utils.js +165 -0
  70. package/dist/{opportunities → internal/opportunities}/radar/radar.graph.d.ts +17 -17
  71. package/dist/{opportunities → internal/opportunities}/radar/radar.graph.js +41 -161
  72. package/dist/{opportunities → internal/opportunities}/radar/radar.state.d.ts +4 -11
  73. package/dist/{shared → internal/shared}/agent/model-signal.d.ts +1 -1
  74. package/dist/{shared → internal/shared}/agent/model-signal.js +1 -1
  75. package/dist/{shared → internal/shared}/agent/model.config.d.ts +28 -86
  76. package/dist/{shared → internal/shared}/agent/model.config.js +58 -69
  77. package/dist/internal/shared/agent/model.resolver.d.ts +33 -0
  78. package/dist/{shared → internal/shared}/agent/model.resolver.js +18 -33
  79. package/dist/internal/shared/agent/scope.d.ts +20 -0
  80. package/dist/internal/shared/agent/scope.js +24 -0
  81. package/dist/internal/shared/assignment/network-assignment.policy.d.ts +23 -0
  82. package/dist/internal/shared/assignment/network-assignment.policy.js +28 -0
  83. package/dist/{shared → internal/shared}/observability/log.d.ts +3 -6
  84. package/dist/{shared → internal/shared}/observability/log.js +9 -18
  85. package/dist/{shared → internal/shared}/observability/protocol.logger.d.ts +1 -1
  86. package/dist/{shared → internal/shared}/observability/protocol.logger.js +1 -1
  87. package/dist/internal/shared/observability/request-context.d.ts +29 -0
  88. package/dist/internal/shared/observability/request-context.js +17 -0
  89. package/dist/{shared → internal/shared}/utils/social-label.d.ts +2 -2
  90. package/dist/{shared → internal/shared}/utils/social-label.js +1 -1
  91. package/dist/platform/database/capabilities.d.ts +59 -0
  92. package/dist/{shared/interfaces/database.entities.d.ts → platform/database/entities.d.ts} +81 -121
  93. package/dist/{shared/interfaces/database.identity-queries.d.ts → platform/database/identity-queries.d.ts} +55 -20
  94. package/dist/platform/database/member-queries.d.ts +55 -0
  95. package/dist/platform/database/member-queries.js +4 -0
  96. package/dist/platform/database/negotiation.d.ts +38 -0
  97. package/dist/{shared/interfaces/database.network-queries.d.ts → platform/database/network-queries.d.ts} +66 -67
  98. package/dist/platform/database/network-queries.js +4 -0
  99. package/dist/{shared/interfaces/database.opportunity-queries.d.ts → platform/database/opportunity-queries.d.ts} +25 -109
  100. package/dist/{shared/interfaces/database.port.d.ts → platform/database/port.d.ts} +52 -117
  101. package/dist/{shared/interfaces/database.port.js → platform/database/port.js} +3 -5
  102. package/dist/platform/database.d.ts +23 -0
  103. package/dist/{shared/interfaces/database.interface.js → platform/database.js} +1 -1
  104. package/dist/{shared/interfaces/cache.interface.d.ts → platform/discovery/cache.d.ts} +2 -4
  105. package/dist/{shared/interfaces/cache.interface.js → platform/discovery/cache.js} +1 -1
  106. package/dist/platform/discovery/embedder.d.ts +31 -0
  107. package/dist/platform/runtime/errors.d.ts +6 -0
  108. package/dist/platform/runtime/errors.js +9 -0
  109. package/dist/platform/runtime/follow-up.d.ts +36 -0
  110. package/dist/platform/runtime/follow-up.js +4 -0
  111. package/dist/platform/runtime/observability.d.ts +34 -0
  112. package/dist/protocol/core.d.ts +11 -0
  113. package/dist/protocol/discovery.rules.d.ts +21 -0
  114. package/dist/protocol/discovery.rules.js +29 -0
  115. package/dist/protocol/negotiation.constants.d.ts +3 -0
  116. package/dist/protocol/negotiation.constants.js +3 -0
  117. package/dist/protocol/negotiation.rules.d.ts +73 -0
  118. package/dist/protocol/negotiation.rules.js +68 -0
  119. package/dist/protocol/protocol.prompt.d.ts +13 -0
  120. package/dist/protocol/protocol.prompt.js +190 -0
  121. package/dist/{shared → protocol}/schemas/discovery-question.schema.d.ts +13 -13
  122. package/dist/{shared → protocol}/schemas/discovery-question.schema.js +2 -2
  123. package/dist/{shared → protocol}/schemas/identity.schema.d.ts +4 -4
  124. package/dist/{shared → protocol}/schemas/identity.schema.js +4 -4
  125. package/dist/{shared → protocol}/schemas/network-assignment.schema.d.ts +11 -20
  126. package/dist/{shared → protocol}/schemas/network-assignment.schema.js +2 -9
  127. package/dist/protocol/schemas/underspecification.schema.d.ts +9 -0
  128. package/dist/protocol/schemas/underspecification.schema.js +12 -0
  129. package/package.json +7 -15
  130. package/dist/agents/agent.dispatcher.port.d.ts +0 -25
  131. package/dist/agents/agent.module.d.ts +0 -19
  132. package/dist/agents/agent.module.js +0 -11
  133. package/dist/agents/agent.repository.port.d.ts +0 -118
  134. package/dist/agents/agent.repository.port.js +0 -10
  135. package/dist/agents/agent.tools.d.ts +0 -16
  136. package/dist/agents/agent.tools.js +0 -351
  137. package/dist/agents/agent.tools.port.d.ts +0 -22
  138. package/dist/agents/agent.tools.port.js +0 -18
  139. package/dist/agents/agent.types.d.ts +0 -76
  140. package/dist/chat/chat-streaming.types.d.ts +0 -618
  141. package/dist/chat/chat-streaming.types.js +0 -297
  142. package/dist/chat/chat.agent.d.ts +0 -292
  143. package/dist/chat/chat.agent.js +0 -1010
  144. package/dist/chat/chat.graph.d.ts +0 -424
  145. package/dist/chat/chat.graph.js +0 -257
  146. package/dist/chat/chat.interrupt.classifier.d.ts +0 -25
  147. package/dist/chat/chat.interrupt.classifier.js +0 -64
  148. package/dist/chat/chat.persona.d.ts +0 -39
  149. package/dist/chat/chat.prompt.d.ts +0 -4
  150. package/dist/chat/chat.prompt.js +0 -12
  151. package/dist/chat/chat.prompt.modules.d.ts +0 -30
  152. package/dist/chat/chat.prompt.modules.js +0 -40
  153. package/dist/chat/chat.question-dedup.d.ts +0 -14
  154. package/dist/chat/chat.question-dedup.js +0 -17
  155. package/dist/chat/chat.state.d.ts +0 -135
  156. package/dist/chat/chat.state.js +0 -120
  157. package/dist/chat/chat.streamer.d.ts +0 -64
  158. package/dist/chat/chat.streamer.js +0 -217
  159. package/dist/chat/chat.suggester.d.ts +0 -23
  160. package/dist/chat/chat.suggester.js +0 -95
  161. package/dist/chat/chat.summarizer.d.ts +0 -20
  162. package/dist/chat/chat.summarizer.js +0 -97
  163. package/dist/chat/chat.title.generator.d.ts +0 -19
  164. package/dist/chat/chat.title.generator.js +0 -66
  165. package/dist/chat/chat.tools.d.ts +0 -5
  166. package/dist/chat/chat.tools.js +0 -62
  167. package/dist/chat/chat.utils.d.ts +0 -41
  168. package/dist/chat/chat.utils.js +0 -88
  169. package/dist/chat/negotiator.persona.d.ts +0 -74
  170. package/dist/chat/negotiator.persona.js +0 -154
  171. package/dist/chat/negotiator.prompt.d.ts +0 -45
  172. package/dist/chat/negotiator.prompt.js +0 -160
  173. package/dist/chat/negotiator.tools.d.ts +0 -42
  174. package/dist/chat/negotiator.tools.js +0 -134
  175. package/dist/chat/onboarding.persona.d.ts +0 -28
  176. package/dist/chat/onboarding.persona.js +0 -86
  177. package/dist/chat/onboarding.prompt.d.ts +0 -6
  178. package/dist/chat/onboarding.prompt.js +0 -63
  179. package/dist/chat/signal.persona.d.ts +0 -47
  180. package/dist/chat/signal.persona.js +0 -319
  181. package/dist/chat/signal.prompt.d.ts +0 -39
  182. package/dist/chat/signal.prompt.js +0 -136
  183. package/dist/contacts/contact.module.d.ts +0 -8
  184. package/dist/contacts/contact.module.js +0 -6
  185. package/dist/contacts/contact.repository.port.d.ts +0 -21
  186. package/dist/contacts/contact.repository.port.js +0 -12
  187. package/dist/contacts/contact.tools.d.ts +0 -17
  188. package/dist/contacts/contact.tools.js +0 -108
  189. package/dist/contacts/contact.tools.port.d.ts +0 -20
  190. package/dist/contacts/contact.tools.port.js +0 -16
  191. package/dist/contacts/contact.types.d.ts +0 -24
  192. package/dist/contacts/contact.types.js +0 -8
  193. package/dist/contexts/context.generator.d.ts +0 -95
  194. package/dist/contexts/context.generator.js +0 -127
  195. package/dist/contexts/context.module.d.ts +0 -13
  196. package/dist/contexts/context.module.js +0 -12
  197. package/dist/contexts/context.tools.port.d.ts +0 -9
  198. package/dist/discovery/hyde.documents.d.ts +0 -9
  199. package/dist/discovery/hyde.documents.js +0 -49
  200. package/dist/discovery/hyde.env.d.ts +0 -8
  201. package/dist/discovery/hyde.env.js +0 -9
  202. package/dist/discovery/hyde.frame.d.ts +0 -150
  203. package/dist/discovery/hyde.frame.js +0 -107
  204. package/dist/discovery/hyde.generator.d.ts +0 -38
  205. package/dist/discovery/hyde.generator.js +0 -103
  206. package/dist/discovery/hyde.graph.d.ts +0 -209
  207. package/dist/discovery/hyde.graph.js +0 -482
  208. package/dist/discovery/hyde.state.d.ts +0 -70
  209. package/dist/discovery/hyde.state.js +0 -85
  210. package/dist/discovery/hyde.strategies.d.ts +0 -17
  211. package/dist/discovery/hyde.strategies.js +0 -34
  212. package/dist/discovery/hyde.validator.d.ts +0 -78
  213. package/dist/discovery/hyde.validator.js +0 -48
  214. package/dist/discovery/index.d.ts +0 -26
  215. package/dist/discovery/index.js +0 -19
  216. package/dist/discovery/lens.inferrer.d.ts +0 -214
  217. package/dist/discovery/lens.inferrer.js +0 -152
  218. package/dist/enrichment/enrichment.generator.d.ts +0 -68
  219. package/dist/enrichment/enrichment.generator.js +0 -95
  220. package/dist/enrichment/enrichment.graph.d.ts +0 -544
  221. package/dist/enrichment/enrichment.graph.js +0 -695
  222. package/dist/enrichment/enrichment.state.d.ts +0 -141
  223. package/dist/enrichment/enrichment.state.js +0 -115
  224. package/dist/enrichment/enrichment.tools.context-read.d.ts +0 -10
  225. package/dist/enrichment/enrichment.tools.context-read.js +0 -353
  226. package/dist/enrichment/enrichment.tools.context-write.d.ts +0 -9
  227. package/dist/enrichment/enrichment.tools.context-write.js +0 -417
  228. package/dist/enrichment/enrichment.tools.d.ts +0 -13
  229. package/dist/enrichment/enrichment.tools.helpers.d.ts +0 -139
  230. package/dist/enrichment/enrichment.tools.helpers.js +0 -234
  231. package/dist/enrichment/enrichment.tools.js +0 -153
  232. package/dist/intents/graph/intent.graph.infer.d.ts +0 -44
  233. package/dist/intents/graph/intent.graph.infer.js +0 -97
  234. package/dist/intents/graph/intent.graph.js +0 -134
  235. package/dist/intents/graph/intent.graph.reconcile.js +0 -274
  236. package/dist/intents/graph/intent.graph.shared.d.ts +0 -68
  237. package/dist/intents/intake/intake.orchestrator.d.ts +0 -203
  238. package/dist/intents/intake/intake.orchestrator.js +0 -255
  239. package/dist/intents/intake/intake.pack.generator.d.ts +0 -57
  240. package/dist/intents/intake/intake.pack.generator.js +0 -90
  241. package/dist/intents/intent.clarifier.d.ts +0 -51
  242. package/dist/intents/intent.clarifier.js +0 -201
  243. package/dist/intents/intent.indexer.d.ts +0 -82
  244. package/dist/intents/intent.indexer.js +0 -170
  245. package/dist/intents/intent.module.js +0 -103
  246. package/dist/intents/intent.proposal.d.ts +0 -37
  247. package/dist/intents/intent.proposal.js +0 -14
  248. package/dist/intents/intent.reconciler.d.ts +0 -105
  249. package/dist/intents/intent.reconciler.js +0 -186
  250. package/dist/intents/intent.tools.d.ts +0 -27
  251. package/dist/intents/intent.tools.js +0 -808
  252. package/dist/maintenance/maintenance.graph.d.ts +0 -239
  253. package/dist/maintenance/maintenance.graph.js +0 -199
  254. package/dist/maintenance/maintenance.state.d.ts +0 -35
  255. package/dist/maintenance/maintenance.state.js +0 -55
  256. package/dist/mcp/elicitation.builder.d.ts +0 -53
  257. package/dist/mcp/elicitation.builder.js +0 -74
  258. package/dist/mcp/elicitation.dispatcher.d.ts +0 -36
  259. package/dist/mcp/elicitation.dispatcher.js +0 -86
  260. package/dist/mcp/mcp.authorization-policy.d.ts +0 -252
  261. package/dist/mcp/mcp.authorization-policy.js +0 -535
  262. package/dist/mcp/mcp.server.d.ts +0 -90
  263. package/dist/mcp/mcp.server.js +0 -631
  264. package/dist/negotiations/insight.generator.d.ts +0 -31
  265. package/dist/negotiations/insight.generator.js +0 -105
  266. package/dist/negotiations/negotiation.agent.d.ts +0 -130
  267. package/dist/negotiations/negotiation.agent.js +0 -396
  268. package/dist/negotiations/negotiation.answer-consumption.d.ts +0 -223
  269. package/dist/negotiations/negotiation.answer-consumption.js +0 -275
  270. package/dist/negotiations/negotiation.attribution.d.ts +0 -91
  271. package/dist/negotiations/negotiation.attribution.js +0 -109
  272. package/dist/negotiations/negotiation.candidates.d.ts +0 -83
  273. package/dist/negotiations/negotiation.candidates.js +0 -162
  274. package/dist/negotiations/negotiation.client-dm.d.ts +0 -50
  275. package/dist/negotiations/negotiation.client-dm.js +0 -66
  276. package/dist/negotiations/negotiation.consultation-policy.d.ts +0 -95
  277. package/dist/negotiations/negotiation.consultation-policy.js +0 -159
  278. package/dist/negotiations/negotiation.deadlock.contracts.d.ts +0 -10
  279. package/dist/negotiations/negotiation.deadlock.d.ts +0 -87
  280. package/dist/negotiations/negotiation.deadlock.js +0 -150
  281. package/dist/negotiations/negotiation.detail-reader.d.ts +0 -94
  282. package/dist/negotiations/negotiation.detail-reader.js +0 -91
  283. package/dist/negotiations/negotiation.expected-speaker.d.ts +0 -33
  284. package/dist/negotiations/negotiation.expected-speaker.js +0 -59
  285. package/dist/negotiations/negotiation.graph.d.ts +0 -694
  286. package/dist/negotiations/negotiation.graph.finalize.d.ts +0 -5
  287. package/dist/negotiations/negotiation.graph.finalize.js +0 -403
  288. package/dist/negotiations/negotiation.graph.init.d.ts +0 -54
  289. package/dist/negotiations/negotiation.graph.init.js +0 -256
  290. package/dist/negotiations/negotiation.graph.js +0 -94
  291. package/dist/negotiations/negotiation.graph.screen.d.ts +0 -23
  292. package/dist/negotiations/negotiation.graph.screen.js +0 -108
  293. package/dist/negotiations/negotiation.graph.shared.d.ts +0 -111
  294. package/dist/negotiations/negotiation.graph.shared.js +0 -168
  295. package/dist/negotiations/negotiation.graph.turn.d.ts +0 -134
  296. package/dist/negotiations/negotiation.graph.turn.js +0 -662
  297. package/dist/negotiations/negotiation.hermes-contract.d.ts +0 -31
  298. package/dist/negotiations/negotiation.hermes-contract.js +0 -72
  299. package/dist/negotiations/negotiation.intent-snapshot-provenance.d.ts +0 -21
  300. package/dist/negotiations/negotiation.intent-snapshot-provenance.js +0 -28
  301. package/dist/negotiations/negotiation.lifecycle-narration.d.ts +0 -18
  302. package/dist/negotiations/negotiation.lifecycle-narration.js +0 -87
  303. package/dist/negotiations/negotiation.memory.d.ts +0 -65
  304. package/dist/negotiations/negotiation.memory.js +0 -83
  305. package/dist/negotiations/negotiation.module.d.ts +0 -36
  306. package/dist/negotiations/negotiation.module.js +0 -23
  307. package/dist/negotiations/negotiation.protocol.d.ts +0 -1018
  308. package/dist/negotiations/negotiation.protocol.js +0 -224
  309. package/dist/negotiations/negotiation.question-safety.d.ts +0 -52
  310. package/dist/negotiations/negotiation.question-safety.js +0 -119
  311. package/dist/negotiations/negotiation.reflect.d.ts +0 -194
  312. package/dist/negotiations/negotiation.reflect.js +0 -145
  313. package/dist/negotiations/negotiation.scope.d.ts +0 -41
  314. package/dist/negotiations/negotiation.scope.js +0 -39
  315. package/dist/negotiations/negotiation.screen.contracts.d.ts +0 -88
  316. package/dist/negotiations/negotiation.screen.contracts.js +0 -58
  317. package/dist/negotiations/negotiation.screen.d.ts +0 -78
  318. package/dist/negotiations/negotiation.screen.js +0 -112
  319. package/dist/negotiations/negotiation.stall-gap.d.ts +0 -83
  320. package/dist/negotiations/negotiation.stall-gap.js +0 -152
  321. package/dist/negotiations/negotiation.stance.contracts.d.ts +0 -123
  322. package/dist/negotiations/negotiation.stance.contracts.js +0 -317
  323. package/dist/negotiations/negotiation.state.d.ts +0 -597
  324. package/dist/negotiations/negotiation.state.js +0 -286
  325. package/dist/negotiations/negotiation.summarizer.d.ts +0 -25
  326. package/dist/negotiations/negotiation.summarizer.js +0 -101
  327. package/dist/negotiations/negotiation.task-lock-policy.d.ts +0 -10
  328. package/dist/negotiations/negotiation.task-lock-policy.js +0 -22
  329. package/dist/negotiations/negotiation.tools.d.ts +0 -18
  330. package/dist/negotiations/negotiation.tools.js +0 -842
  331. package/dist/negotiations/negotiation.tools.port.d.ts +0 -17
  332. package/dist/negotiations/negotiation.turn-cap.d.ts +0 -9
  333. package/dist/negotiations/negotiation.turn-cap.js +0 -12
  334. package/dist/networks/indexer.state.js +0 -112
  335. package/dist/networks/network.tools.d.ts +0 -36
  336. package/dist/networks/network.tools.js +0 -594
  337. package/dist/opportunities/delivery-card.cache.d.ts +0 -25
  338. package/dist/opportunities/delivery-card.cache.js +0 -43
  339. package/dist/opportunities/discovery.env.d.ts +0 -20
  340. package/dist/opportunities/discovery.env.js +0 -109
  341. package/dist/opportunities/discriminator/discriminator.adjustments.d.ts +0 -90
  342. package/dist/opportunities/discriminator/discriminator.adjustments.js +0 -141
  343. package/dist/opportunities/discriminator/discriminator.assigner.d.ts +0 -78
  344. package/dist/opportunities/discriminator/discriminator.assigner.js +0 -153
  345. package/dist/opportunities/discriminator/discriminator.env.d.ts +0 -103
  346. package/dist/opportunities/discriminator/discriminator.env.js +0 -103
  347. package/dist/opportunities/discriminator/discriminator.miner.d.ts +0 -114
  348. package/dist/opportunities/discriminator/discriminator.miner.js +0 -228
  349. package/dist/opportunities/discriminator/discriminator.push.d.ts +0 -13
  350. package/dist/opportunities/discriminator/discriminator.push.js +0 -19
  351. package/dist/opportunities/discriminator/discriminator.question.d.ts +0 -58
  352. package/dist/opportunities/discriminator/discriminator.question.js +0 -155
  353. package/dist/opportunities/discriminator/discriminator.scorer.d.ts +0 -32
  354. package/dist/opportunities/discriminator/discriminator.scorer.js +0 -105
  355. package/dist/opportunities/discriminator/discriminator.shadow.d.ts +0 -32
  356. package/dist/opportunities/discriminator/discriminator.shadow.js +0 -90
  357. package/dist/opportunities/discriminator/discriminator.types.d.ts +0 -93
  358. package/dist/opportunities/discriminator/discriminator.types.js +0 -18
  359. package/dist/opportunities/negotiation-context.loader.d.ts +0 -59
  360. package/dist/opportunities/negotiation-context.loader.js +0 -90
  361. package/dist/opportunities/negotiation-evidence/negotiation-evidence.env.d.ts +0 -43
  362. package/dist/opportunities/negotiation-evidence/negotiation-evidence.env.js +0 -44
  363. package/dist/opportunities/negotiation-evidence/negotiation-evidence.extractor.d.ts +0 -24
  364. package/dist/opportunities/negotiation-evidence/negotiation-evidence.extractor.js +0 -188
  365. package/dist/opportunities/negotiation-evidence/negotiation-evidence.miner.d.ts +0 -26
  366. package/dist/opportunities/negotiation-evidence/negotiation-evidence.miner.js +0 -112
  367. package/dist/opportunities/negotiation-evidence/negotiation-evidence.shadow.d.ts +0 -19
  368. package/dist/opportunities/negotiation-evidence/negotiation-evidence.shadow.js +0 -61
  369. package/dist/opportunities/negotiation-evidence/negotiation-evidence.types.d.ts +0 -191
  370. package/dist/opportunities/negotiation-evidence/negotiation-evidence.types.js +0 -18
  371. package/dist/opportunities/negotiation-evidence/negotiation-evidence.verifier.d.ts +0 -34
  372. package/dist/opportunities/negotiation-evidence/negotiation-evidence.verifier.js +0 -91
  373. package/dist/opportunities/negotiation-summary.builder.d.ts +0 -37
  374. package/dist/opportunities/negotiation-summary.builder.js +0 -66
  375. package/dist/opportunities/opportunity.discovery-negotiation-summary.d.ts +0 -14
  376. package/dist/opportunities/opportunity.discovery-negotiation-summary.js +0 -46
  377. package/dist/opportunities/opportunity.enricher.d.ts +0 -71
  378. package/dist/opportunities/opportunity.enricher.js +0 -280
  379. package/dist/opportunities/opportunity.evaluator.d.ts +0 -289
  380. package/dist/opportunities/opportunity.evaluator.js +0 -516
  381. package/dist/opportunities/opportunity.evidence.d.ts +0 -22
  382. package/dist/opportunities/opportunity.evidence.js +0 -87
  383. package/dist/opportunities/opportunity.existing-negotiation.d.ts +0 -79
  384. package/dist/opportunities/opportunity.existing-negotiation.js +0 -118
  385. package/dist/opportunities/opportunity.feed-selection.js +0 -96
  386. package/dist/opportunities/opportunity.graph.d.ts +0 -1611
  387. package/dist/opportunities/opportunity.graph.discovery-strategies.d.ts +0 -109
  388. package/dist/opportunities/opportunity.graph.discovery-strategies.js +0 -451
  389. package/dist/opportunities/opportunity.graph.discovery.d.ts +0 -69
  390. package/dist/opportunities/opportunity.graph.discovery.js +0 -397
  391. package/dist/opportunities/opportunity.graph.evaluation.d.ts +0 -82
  392. package/dist/opportunities/opportunity.graph.evaluation.js +0 -608
  393. package/dist/opportunities/opportunity.graph.js +0 -193
  394. package/dist/opportunities/opportunity.graph.modes.d.ts +0 -538
  395. package/dist/opportunities/opportunity.graph.modes.js +0 -538
  396. package/dist/opportunities/opportunity.graph.negotiate.d.ts +0 -109
  397. package/dist/opportunities/opportunity.graph.negotiate.js +0 -392
  398. package/dist/opportunities/opportunity.graph.persist-node.d.ts +0 -93
  399. package/dist/opportunities/opportunity.graph.persist-node.js +0 -765
  400. package/dist/opportunities/opportunity.graph.prep.d.ts +0 -150
  401. package/dist/opportunities/opportunity.graph.prep.js +0 -381
  402. package/dist/opportunities/opportunity.graph.shared.d.ts +0 -173
  403. package/dist/opportunities/opportunity.graph.shared.js +0 -199
  404. package/dist/opportunities/opportunity.introducer-feature.d.ts +0 -2
  405. package/dist/opportunities/opportunity.introducer-feature.js +0 -4
  406. package/dist/opportunities/opportunity.introducer.d.ts +0 -77
  407. package/dist/opportunities/opportunity.introducer.js +0 -99
  408. package/dist/opportunities/opportunity.labels.js +0 -10
  409. package/dist/opportunities/opportunity.lifecycle.d.ts +0 -63
  410. package/dist/opportunities/opportunity.lifecycle.js +0 -181
  411. package/dist/opportunities/opportunity.module.d.ts +0 -54
  412. package/dist/opportunities/opportunity.module.js +0 -39
  413. package/dist/opportunities/opportunity.newborn-stamping.d.ts +0 -41
  414. package/dist/opportunities/opportunity.newborn-stamping.js +0 -81
  415. package/dist/opportunities/opportunity.owner-approval.d.ts +0 -118
  416. package/dist/opportunities/opportunity.owner-approval.js +0 -34
  417. package/dist/opportunities/opportunity.owner-provenance.d.ts +0 -6
  418. package/dist/opportunities/opportunity.owner-provenance.js +0 -28
  419. package/dist/opportunities/opportunity.persist.d.ts +0 -58
  420. package/dist/opportunities/opportunity.persist.js +0 -145
  421. package/dist/opportunities/opportunity.persistence-admission.d.ts +0 -39
  422. package/dist/opportunities/opportunity.persistence-admission.js +0 -59
  423. package/dist/opportunities/opportunity.state.d.ts +0 -451
  424. package/dist/opportunities/opportunity.state.js +0 -256
  425. package/dist/opportunities/opportunity.tools.cards.d.ts +0 -138
  426. package/dist/opportunities/opportunity.tools.cards.js +0 -212
  427. package/dist/opportunities/opportunity.tools.d.ts +0 -12
  428. package/dist/opportunities/opportunity.tools.js +0 -236
  429. package/dist/opportunities/opportunity.tools.list.d.ts +0 -10
  430. package/dist/opportunities/opportunity.tools.list.js +0 -489
  431. package/dist/opportunities/opportunity.tools.port.d.ts +0 -16
  432. package/dist/opportunities/opportunity.utils.d.ts +0 -217
  433. package/dist/opportunities/opportunity.utils.js +0 -395
  434. package/dist/opportunities/outcome/outcome.env.d.ts +0 -60
  435. package/dist/opportunities/outcome/outcome.env.js +0 -63
  436. package/dist/opportunities/outcome/outcome.hypotheses.d.ts +0 -29
  437. package/dist/opportunities/outcome/outcome.hypotheses.js +0 -117
  438. package/dist/opportunities/outcome/outcome.shadow.d.ts +0 -56
  439. package/dist/opportunities/outcome/outcome.shadow.js +0 -87
  440. package/dist/opportunities/outcome/outcome.types.d.ts +0 -110
  441. package/dist/opportunities/outcome/outcome.types.js +0 -26
  442. package/dist/opportunities/radar/radar.health.d.ts +0 -31
  443. package/dist/opportunities/radar/radar.health.js +0 -75
  444. package/dist/premises/premise.analyzer.d.ts +0 -35
  445. package/dist/premises/premise.analyzer.js +0 -115
  446. package/dist/premises/premise.decomposer.d.ts +0 -69
  447. package/dist/premises/premise.decomposer.js +0 -213
  448. package/dist/premises/premise.graph.d.ts +0 -345
  449. package/dist/premises/premise.graph.js +0 -278
  450. package/dist/premises/premise.indexer.d.ts +0 -35
  451. package/dist/premises/premise.indexer.js +0 -86
  452. package/dist/premises/premise.state.d.ts +0 -67
  453. package/dist/premises/premise.state.js +0 -94
  454. package/dist/premises/premise.tools.d.ts +0 -3
  455. package/dist/premises/premise.tools.js +0 -248
  456. package/dist/questions/question.env.d.ts +0 -27
  457. package/dist/questions/question.env.js +0 -27
  458. package/dist/questions/question.input.d.ts +0 -107
  459. package/dist/questions/question.module.d.ts +0 -30
  460. package/dist/questions/question.module.js +0 -28
  461. package/dist/questions/question.schema.d.ts +0 -1529
  462. package/dist/questions/question.schema.js +0 -420
  463. package/dist/shared/agent/activity-projection.d.ts +0 -271
  464. package/dist/shared/agent/activity-projection.js +0 -254
  465. package/dist/shared/agent/canonical-guidance.d.ts +0 -30
  466. package/dist/shared/agent/canonical-guidance.js +0 -246
  467. package/dist/shared/agent/model.resolver.d.ts +0 -48
  468. package/dist/shared/agent/tool.factory.d.ts +0 -17
  469. package/dist/shared/agent/tool.factory.js +0 -221
  470. package/dist/shared/agent/tool.helpers.d.ts +0 -482
  471. package/dist/shared/agent/tool.helpers.js +0 -232
  472. package/dist/shared/agent/tool.registry.d.ts +0 -25
  473. package/dist/shared/agent/tool.registry.js +0 -76
  474. package/dist/shared/agent/tool.runtime.d.ts +0 -28
  475. package/dist/shared/agent/tool.runtime.js +0 -194
  476. package/dist/shared/agent/tool.scope.d.ts +0 -44
  477. package/dist/shared/agent/tool.scope.js +0 -50
  478. package/dist/shared/agent/utility.tools.d.ts +0 -15
  479. package/dist/shared/agent/utility.tools.js +0 -322
  480. package/dist/shared/assignment/network-assignment.policy.d.ts +0 -61
  481. package/dist/shared/assignment/network-assignment.policy.js +0 -105
  482. package/dist/shared/interfaces/agent-dispatcher.interface.d.ts +0 -100
  483. package/dist/shared/interfaces/agent-dispatcher.interface.js +0 -12
  484. package/dist/shared/interfaces/auth.interface.d.ts +0 -37
  485. package/dist/shared/interfaces/auth.interface.js +0 -1
  486. package/dist/shared/interfaces/chat-message-writer.interface.d.ts +0 -18
  487. package/dist/shared/interfaces/chat-message-writer.interface.js +0 -1
  488. package/dist/shared/interfaces/chat-session.interface.d.ts +0 -23
  489. package/dist/shared/interfaces/chat-session.interface.js +0 -18
  490. package/dist/shared/interfaces/chat-summary.interface.d.ts +0 -16
  491. package/dist/shared/interfaces/chat-summary.interface.js +0 -1
  492. package/dist/shared/interfaces/database.capabilities.d.ts +0 -100
  493. package/dist/shared/interfaces/database.interface.d.ts +0 -16
  494. package/dist/shared/interfaces/database.member-queries.d.ts +0 -219
  495. package/dist/shared/interfaces/database.member-queries.js +0 -4
  496. package/dist/shared/interfaces/database.negotiation.d.ts +0 -329
  497. package/dist/shared/interfaces/database.negotiation.js +0 -26
  498. package/dist/shared/interfaces/database.network-queries.js +0 -4
  499. package/dist/shared/interfaces/database.opportunity-queries.js +0 -4
  500. package/dist/shared/interfaces/delivery-ledger.interface.d.ts +0 -40
  501. package/dist/shared/interfaces/delivery-ledger.interface.js +0 -5
  502. package/dist/shared/interfaces/embedder.interface.d.ts +0 -92
  503. package/dist/shared/interfaces/embedder.interface.js +0 -4
  504. package/dist/shared/interfaces/enrichment-run.interface.d.ts +0 -62
  505. package/dist/shared/interfaces/enrichment-run.interface.js +0 -1
  506. package/dist/shared/interfaces/enrichment.interface.js +0 -1
  507. package/dist/shared/interfaces/negotiation-events.interface.d.ts +0 -77
  508. package/dist/shared/interfaces/negotiation-events.interface.js +0 -6
  509. package/dist/shared/interfaces/negotiation-summary.interface.d.ts +0 -25
  510. package/dist/shared/interfaces/negotiation-summary.interface.js +0 -1
  511. package/dist/shared/interfaces/negotiator-memory.interface.d.ts +0 -58
  512. package/dist/shared/interfaces/negotiator-memory.interface.js +0 -11
  513. package/dist/shared/interfaces/queue.interface.d.ts +0 -23
  514. package/dist/shared/interfaces/queue.interface.js +0 -4
  515. package/dist/shared/interfaces/scraper.interface.js +0 -1
  516. package/dist/shared/interfaces/tool-request-context.interface.d.ts +0 -11
  517. package/dist/shared/interfaces/tool-request-context.interface.js +0 -1
  518. package/dist/shared/observability/request-context.d.ts +0 -27
  519. package/dist/shared/observability/request-context.js +0 -6
  520. package/dist/shared/schemas/mcp-auth.schema.d.ts +0 -87
  521. package/dist/shared/schemas/mcp-auth.schema.js +0 -56
  522. package/dist/shared/schemas/negotiation-digest.schema.d.ts +0 -58
  523. package/dist/shared/schemas/negotiation-digest.schema.js +0 -38
  524. package/dist/shared/schemas/negotiation-state.schema.d.ts +0 -343
  525. package/dist/shared/schemas/negotiation-state.schema.js +0 -81
  526. package/dist/shared/schemas/question-block.fixture.d.ts +0 -12
  527. package/dist/shared/schemas/question-block.fixture.js +0 -39
  528. package/dist/shared/schemas/question-block.schema.d.ts +0 -111
  529. package/dist/shared/schemas/question-block.schema.js +0 -124
  530. package/dist/shared/schemas/structured-question.schema.d.ts +0 -66
  531. package/dist/shared/schemas/structured-question.schema.js +0 -31
  532. package/dist/shared/schemas/underspecification.schema.d.ts +0 -13
  533. package/dist/shared/schemas/underspecification.schema.js +0 -16
  534. /package/dist/{opportunities → internal/opportunities}/opportunity.update-admission.js +0 -0
  535. /package/dist/{opportunities → internal/opportunities}/radar/radar.state.js +0 -0
  536. /package/dist/{shared → internal/shared}/network/metadata.renderer.d.ts +0 -0
  537. /package/dist/{shared → internal/shared}/network/metadata.renderer.js +0 -0
  538. /package/dist/{shared → internal/shared}/observability/debug-meta.sanitizer.d.ts +0 -0
  539. /package/dist/{shared → internal/shared}/observability/debug-meta.sanitizer.js +0 -0
  540. /package/dist/{shared → internal/shared}/observability/performance.d.ts +0 -0
  541. /package/dist/{shared → internal/shared}/observability/performance.js +0 -0
  542. /package/dist/{shared → internal/shared}/observability/trace.d.ts +0 -0
  543. /package/dist/{shared → internal/shared}/observability/trace.js +0 -0
  544. /package/dist/{shared → internal/shared}/utils/claim-safety.d.ts +0 -0
  545. /package/dist/{shared → internal/shared}/utils/claim-safety.js +0 -0
  546. /package/dist/{shared → internal/shared}/utils/telegram-handle.d.ts +0 -0
  547. /package/dist/{shared → internal/shared}/utils/telegram-handle.js +0 -0
  548. /package/dist/{shared/interfaces/database.capabilities.js → platform/database/capabilities.js} +0 -0
  549. /package/dist/{shared/interfaces/database.entities.js → platform/database/entities.js} +0 -0
  550. /package/dist/{shared/interfaces/database.identity-queries.js → platform/database/identity-queries.js} +0 -0
  551. /package/dist/{agents/agent.dispatcher.port.js → platform/database/negotiation.js} +0 -0
  552. /package/dist/{chat/chat.persona.js → platform/database/opportunity-queries.js} +0 -0
  553. /package/dist/{contexts/context.tools.port.js → platform/discovery/embedder.js} +0 -0
  554. /package/dist/{shared/interfaces/scraper.interface.d.ts → platform/discovery/scraper.d.ts} +0 -0
  555. /package/dist/{negotiations/negotiation.deadlock.contracts.js → platform/discovery/scraper.js} +0 -0
  556. /package/dist/{shared/interfaces/enrichment.interface.d.ts → platform/enrichment/ports.d.ts} +0 -0
  557. /package/dist/{negotiations/negotiation.tools.port.js → platform/enrichment/ports.js} +0 -0
  558. /package/dist/{opportunities/opportunity.tools.port.js → platform/runtime/observability.js} +0 -0
  559. /package/dist/{questions/question.input.js → protocol/core.js} +0 -0
  560. /package/dist/{shared → protocol}/schemas/chat-context.schema.d.ts +0 -0
  561. /package/dist/{shared → protocol}/schemas/chat-context.schema.js +0 -0
@@ -1,1010 +0,0 @@
1
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
6
- };
7
- var __metadata = (this && this.__metadata) || function (k, v) {
8
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
- };
10
- import { AIMessage, SystemMessage, ToolMessage } from "@langchain/core/messages";
11
- import { resolveChatContext } from "../shared/agent/tool.helpers.js";
12
- import { scopeFromNetworkId } from "../shared/agent/tool.scope.js";
13
- import { ITERATION_NUDGE } from "./chat.prompt.js";
14
- import { extractRecentToolCalls } from "./chat.prompt.modules.js";
15
- import { protocolLogger } from "../shared/observability/protocol.logger.js";
16
- import { createModel } from "../shared/agent/model.config.js";
17
- import { invokeWithAbortSignal } from "../shared/agent/model-signal.js";
18
- import { sanitizeForDebugMeta } from "../shared/observability/debug-meta.sanitizer.js";
19
- import { Timed } from "../shared/observability/performance.js";
20
- import { requestContext } from "../shared/observability/request-context.js";
21
- import { deduplicateQuestions } from "./chat.question-dedup.js";
22
- const logger = protocolLogger("ChatAgent");
23
- // Re-export for external consumers
24
- export { ITERATION_NUDGE } from "./chat.prompt.js";
25
- // ═══════════════════════════════════════════════════════════════════════════════
26
- // CONFIGURATION
27
- // ═══════════════════════════════════════════════════════════════════════════════
28
- /**
29
- * Soft limit: After this many iterations, inject a nudge message.
30
- */
31
- export const SOFT_ITERATION_LIMIT = 8;
32
- /**
33
- * Hard limit: Force exit after this many iterations to prevent infinite loops.
34
- */
35
- export const HARD_ITERATION_LIMIT = 12;
36
- /**
37
- * Extract plain text from message content (string or structured block array).
38
- * Filters to only `type: "text"` blocks, discarding tool metadata.
39
- */
40
- function extractTextContent(content) {
41
- if (typeof content === "string")
42
- return content;
43
- if (Array.isArray(content)) {
44
- return content
45
- .filter((b) => b.type === "text")
46
- .map((b) => b.text ?? "")
47
- .join("");
48
- }
49
- return "";
50
- }
51
- /**
52
- * Extract plain text from an AIMessageChunk (string content or text blocks).
53
- */
54
- function extractTextFromChunk(chunk) {
55
- return extractTextContent(chunk.content);
56
- }
57
- /**
58
- * ChatAgent: ReAct-style agent that uses tools to help users.
59
- *
60
- * The agent operates in a loop:
61
- * 1. Receive messages (conversation history + tool results)
62
- * 2. Decide: call tools OR respond to user
63
- * 3. If tools called: execute them, add results, loop back
64
- * 4. If response: return final text
65
- *
66
- * Use `ChatAgent.create(context)` to construct (async factory).
67
- */
68
- export class ChatAgent {
69
- /**
70
- * Private constructor — use `ChatAgent.create()` instead.
71
- */
72
- constructor(resolvedContext, persona, tools, modelConfig) {
73
- this.resolvedContext = resolvedContext;
74
- this.persona = persona;
75
- this.model = createModel("chat", modelConfig);
76
- // Store tools and index by name
77
- this.tools = tools;
78
- this.toolsByName = new Map();
79
- for (const tool of this.tools) {
80
- this.toolsByName.set(tool.name, tool);
81
- }
82
- // Bind tools to model
83
- this.model = this.model.bindTools(this.tools);
84
- }
85
- /**
86
- * Extracts the text content of the most recent HumanMessage.
87
- */
88
- static getCurrentUserMessage(messages) {
89
- for (let i = messages.length - 1; i >= 0; i--) {
90
- if (messages[i]._getType() === "human") {
91
- const content = messages[i].content;
92
- return typeof content === "string" ? content : undefined;
93
- }
94
- }
95
- return undefined;
96
- }
97
- /**
98
- * Async factory: creates a ChatAgent with resolved user/index context.
99
- * Resolves user/network identity from DB during tool initialization.
100
- *
101
- * @param context - Tool context (database, userId, scope, deps)
102
- * @param persona - Persona config (prompt builder, toolset, loop behaviors).
103
- * Required — there is no default persona.
104
- */
105
- static async create(context, persona) {
106
- const { networkId: legacyNetworkId } = context;
107
- const explicitScope = context.scopeType && context.scopeId
108
- ? { scopeType: context.scopeType, scopeId: context.scopeId }
109
- : scopeFromNetworkId(legacyNetworkId);
110
- const scopedNetworkId = explicitScope.scopeType === 'network' ? explicitScope.scopeId : undefined;
111
- const resolved = await resolveChatContext({
112
- database: context.database,
113
- userId: context.userId,
114
- networkId: scopedNetworkId,
115
- sessionId: context.sessionId,
116
- });
117
- if (explicitScope.scopeType && explicitScope.scopeId) {
118
- resolved.scopeType = explicitScope.scopeType;
119
- resolved.scopeId = explicitScope.scopeId;
120
- }
121
- const tools = await persona.createTools(context, resolved);
122
- return new ChatAgent(resolved, persona, tools, context.modelConfig);
123
- }
124
- /**
125
- * Run a single iteration of the agent loop.
126
- *
127
- * @param messages - Current conversation including any tool results
128
- * @param iterationCount - Current iteration number (for soft limit)
129
- * @returns Result indicating whether to continue and any tool calls/response
130
- */
131
- async runIteration(messages, iterationCount) {
132
- const iterCtx = {
133
- recentTools: extractRecentToolCalls(messages),
134
- currentMessage: ChatAgent.getCurrentUserMessage(messages),
135
- ctx: this.resolvedContext,
136
- };
137
- const deterministicResponse = this.persona.resolveDeterministicResponse?.(this.resolvedContext, iterCtx);
138
- if (deterministicResponse !== undefined && deterministicResponse !== null) {
139
- const response = new AIMessage(deterministicResponse);
140
- return {
141
- shouldContinue: false,
142
- responseText: deterministicResponse,
143
- messages: [...messages, response],
144
- };
145
- }
146
- const systemContent = this.persona.buildSystemContent(this.resolvedContext, iterCtx);
147
- const fullMessages = [
148
- new SystemMessage(systemContent),
149
- ...messages,
150
- ];
151
- // Add nudge if past soft limit
152
- if (iterationCount >= SOFT_ITERATION_LIMIT) {
153
- fullMessages.push(new SystemMessage(ITERATION_NUDGE));
154
- }
155
- logger.verbose("Agent iteration", {
156
- iteration: iterationCount,
157
- messageCount: messages.length,
158
- pastSoftLimit: iterationCount >= SOFT_ITERATION_LIMIT,
159
- });
160
- // Invoke model
161
- const response = await invokeWithAbortSignal(this.model, fullMessages);
162
- logger.debug("Chat model response", {
163
- content: typeof response.content === "string"
164
- ? response.content
165
- : JSON.stringify(response.content),
166
- toolCalls: response.tool_calls?.length ?? 0,
167
- toolCallNames: response.tool_calls?.map((tc) => tc.name) ?? [],
168
- });
169
- // Check if model made tool calls
170
- const toolCalls = response.tool_calls || [];
171
- if (toolCalls.length > 0) {
172
- logger.verbose("Agent made tool calls", {
173
- iteration: iterationCount,
174
- toolCount: toolCalls.length,
175
- tools: toolCalls.map((tc) => tc.name),
176
- });
177
- // Execute tools (can be parallelized if independent)
178
- const toolResults = await this.executeToolCalls(toolCalls);
179
- // Build updated messages
180
- const updatedMessages = [
181
- ...messages,
182
- response, // AIMessage with tool_calls
183
- ...toolResults.map((tr) => new ToolMessage({
184
- tool_call_id: tr.toolCallId,
185
- content: tr.result,
186
- name: tr.name,
187
- })),
188
- ];
189
- return {
190
- shouldContinue: true,
191
- toolCalls: toolCalls.map((tc) => ({
192
- id: tc.id,
193
- name: tc.name,
194
- args: tc.args,
195
- })),
196
- toolResults,
197
- messages: updatedMessages,
198
- };
199
- }
200
- // No tool calls - agent is responding
201
- const responseText = extractTextContent(response.content);
202
- logger.debug("Agent produced response (raw)", {
203
- iteration: iterationCount,
204
- responseText,
205
- });
206
- logger.verbose("Agent produced response", {
207
- iteration: iterationCount,
208
- responseLength: responseText.length,
209
- });
210
- return {
211
- shouldContinue: false,
212
- responseText,
213
- messages: [...messages, response],
214
- };
215
- }
216
- /**
217
- * Execute tool calls, potentially in parallel.
218
- */
219
- async executeToolCalls(toolCalls) {
220
- // Execute all tool calls in parallel
221
- const results = await Promise.all(toolCalls.map(async (tc) => {
222
- const tool = this.toolsByName.get(tc.name);
223
- if (!tool) {
224
- logger.error("Unknown tool", { name: tc.name });
225
- return {
226
- toolCallId: tc.id || `unknown-${Date.now()}`,
227
- name: tc.name,
228
- result: JSON.stringify({
229
- success: false,
230
- error: `Unknown tool: ${tc.name}`,
231
- }),
232
- };
233
- }
234
- try {
235
- logger.verbose("Executing tool", { name: tc.name, args: tc.args });
236
- const result = await tool.invoke(tc.args);
237
- const resultStr = typeof result === "string" ? result : JSON.stringify(result);
238
- logger.debug("Tool response", { name: tc.name, result: resultStr });
239
- logger.verbose("Tool completed", {
240
- name: tc.name,
241
- resultLength: resultStr.length,
242
- });
243
- return {
244
- toolCallId: tc.id || `${tc.name}-${Date.now()}`,
245
- name: tc.name,
246
- result: resultStr,
247
- };
248
- }
249
- catch (error) {
250
- logger.error("Tool execution failed", {
251
- name: tc.name,
252
- error: error instanceof Error ? error.message : String(error),
253
- });
254
- return {
255
- toolCallId: tc.id || `${tc.name}-${Date.now()}`,
256
- name: tc.name,
257
- result: JSON.stringify({
258
- success: false,
259
- error: `Tool execution failed: ${error instanceof Error ? error.message : "Unknown error"}`,
260
- }),
261
- };
262
- }
263
- }));
264
- return results;
265
- }
266
- /**
267
- * Check whether `list_opportunities` returned valid opportunity blocks.
268
- * Persisted cards from that tool are the only valid source.
269
- */
270
- static hasOpportunitySource(toolsUsed) {
271
- return toolsUsed.some((t) => t.name === "list_opportunities" &&
272
- t.success &&
273
- !t.resultSummary?.startsWith("Found 0") &&
274
- !t.resultSummary?.startsWith("No matches") &&
275
- !t.resultSummary?.startsWith("No opportunities"));
276
- }
277
- /**
278
- * Detect hallucinated ```intent_proposal or ```opportunity blocks in model text
279
- * that were NOT generated by the corresponding tool call.
280
- *
281
- * A tool call that returned 0 cards (e.g. "Found 0 match(es)") counts as
282
- * NOT having produced valid blocks — the LLM must not fabricate them.
283
- *
284
- * @returns Block info if hallucination detected, null otherwise
285
- */
286
- detectHallucinatedBlock(text, toolsUsed, userMessage) {
287
- const hasSuccessfulCreateIntent = toolsUsed.some((t) => t.name === "create_intent" && t.success);
288
- // Check for hallucinated intent_proposal
289
- if (text.includes("```intent_proposal") && !hasSuccessfulCreateIntent) {
290
- const match = text.match(/```intent_proposal\s*\n\s*\{[^}]*"description"\s*:\s*"([^"]+)"/);
291
- if (match) {
292
- return { type: "intent_proposal", tool: "create_intent", description: match[1] };
293
- }
294
- }
295
- return null;
296
- }
297
- /**
298
- * Strip ```opportunity and ```intent_proposal code blocks from text
299
- * when no corresponding successful tool call was made.
300
- * Defense-in-depth: catches hallucinated blocks that slip past detectHallucinatedBlock
301
- * (e.g. after a correction iteration that still hallucinates).
302
- *
303
- * @param text - The response text to sanitize
304
- * @param toolsUsed - Tool call records from the agent loop
305
- * @returns Sanitized text with unbacked blocks removed
306
- */
307
- stripUnbackedBlocks(text, toolsUsed) {
308
- let result = text;
309
- let removedBlock = false;
310
- const hasSuccessfulCreateIntent = toolsUsed.some((t) => t.name === "create_intent" && t.success);
311
- if (!ChatAgent.hasOpportunitySource(toolsUsed) && result.includes("```opportunity")) {
312
- const next = result.replace(/```opportunity\s*\n[\s\S]*?```/g, "");
313
- removedBlock || (removedBlock = next !== result);
314
- result = next;
315
- }
316
- if (!hasSuccessfulCreateIntent && result.includes("```intent_proposal")) {
317
- const next = result.replace(/```intent_proposal\s*\n[\s\S]*?```/g, "");
318
- removedBlock || (removedBlock = next !== result);
319
- result = next;
320
- }
321
- // Clean up leftover double blank lines only when a block was actually removed
322
- if (removedBlock) {
323
- result = result.replace(/\n{3,}/g, "\n\n").trim();
324
- }
325
- return result;
326
- }
327
- /**
328
- * Detect when the model claims to have performed a write action
329
- * without having called any tools in the turn.
330
- */
331
- static detectPhantomWrite(responseText, toolsUsed) {
332
- if (toolsUsed.length > 0)
333
- return false;
334
- return ChatAgent.PHANTOM_WRITE_PATTERNS.some(pattern => pattern.test(responseText));
335
- }
336
- /**
337
- * Post-process a tool result: strip _graphTimings, extract summary/debugSteps,
338
- * and optionally normalize a tool result before a create_intent callback.
339
- *
340
- * Returns the normalized result string and extracted debug metadata so both
341
- * the normal streaming tool loop and the hallucination-recovery branch
342
- * produce identical LLM-facing payloads.
343
- */
344
- async normalizeToolResult(toolName, resultStr, toolArgs) {
345
- let normalized = resultStr;
346
- let summary = "Done";
347
- let debugSteps;
348
- let graphTimings;
349
- let decisionQuestions;
350
- try {
351
- const parsed = JSON.parse(normalized);
352
- const payload = parsed.success && parsed.data != null ? parsed.data : parsed;
353
- summary = payload.summary ?? parsed.summary ?? "Done";
354
- const rawSteps = payload.debugSteps ?? parsed.debugSteps;
355
- if (Array.isArray(rawSteps) && rawSteps.length > 0) {
356
- debugSteps = rawSteps.map((s) => ({
357
- step: String(s.step ?? "").slice(0, ChatAgent.STEP_NAME_MAX),
358
- detail: s.detail != null
359
- ? String(s.detail).slice(0, ChatAgent.STEP_DETAIL_MAX)
360
- : undefined,
361
- ...(s.data && typeof s.data === "object" ? { data: s.data } : {}),
362
- }));
363
- }
364
- const rawGraphTimings = payload._graphTimings ?? parsed._graphTimings;
365
- if (Array.isArray(rawGraphTimings) && rawGraphTimings.length > 0) {
366
- graphTimings = rawGraphTimings;
367
- // Strip _graphTimings from the result string sent back to the LLM
368
- try {
369
- const cleanedResult = JSON.parse(normalized);
370
- delete cleanedResult._graphTimings;
371
- if (cleanedResult.data && typeof cleanedResult.data === "object") {
372
- delete cleanedResult.data._graphTimings;
373
- }
374
- normalized = JSON.stringify(cleanedResult);
375
- }
376
- catch { /* keep original if can't clean */ }
377
- }
378
- const rawQuestions = payload.questions ?? parsed.questions;
379
- if (Array.isArray(rawQuestions)) {
380
- decisionQuestions = rawQuestions;
381
- }
382
- }
383
- catch {
384
- /* not JSON, keep default */
385
- }
386
- return {
387
- resultStr: normalized,
388
- summary,
389
- debugSteps,
390
- graphTimings,
391
- ...(decisionQuestions !== undefined ? { decisionQuestions } : {}),
392
- };
393
- }
394
- /**
395
- * Run the full agent loop until completion or hard limit.
396
- *
397
- * @param initialMessages - Starting conversation messages
398
- * @returns Final response text and full message history
399
- */
400
- async run(initialMessages) {
401
- let messages = initialMessages;
402
- let iterationCount = 0;
403
- while (iterationCount < HARD_ITERATION_LIMIT) {
404
- const result = await this.runIteration(messages, iterationCount);
405
- iterationCount++;
406
- messages = result.messages;
407
- if (!result.shouldContinue) {
408
- const responseText = result.responseText ||
409
- "I apologize, but I couldn't generate a response.";
410
- logger.debug("Agent final response", { responseText });
411
- return {
412
- responseText,
413
- messages,
414
- iterationCount,
415
- };
416
- }
417
- }
418
- // Hit hard limit - force a response
419
- logger.warn("Hit hard iteration limit", { iterationCount });
420
- const forceResponseMessages = [
421
- ...messages,
422
- new SystemMessage("You have reached the maximum number of tool calls. You MUST provide a final response now. Summarize what you've accomplished and what might still be needed."),
423
- ];
424
- const forcedResponse = await invokeWithAbortSignal(this.model, forceResponseMessages);
425
- const responseText = extractTextContent(forcedResponse.content);
426
- logger.debug("Agent forced response", { responseText });
427
- return {
428
- responseText,
429
- messages: [...messages, forcedResponse],
430
- iterationCount,
431
- };
432
- }
433
- // ═══════════════════════════════════════════════════════════════════════════
434
- // STREAMING RUN (for narration-style output)
435
- // ═══════════════════════════════════════════════════════════════════════════
436
- /**
437
- * Run the full agent loop with streaming narration.
438
- *
439
- * Instead of returning a single blob at the end, this method calls
440
- * `writer()` for every text token and tool-activity event so the
441
- * consumer (graph node) can push them out via `config.writer`.
442
- *
443
- * @param initialMessages - Starting conversation messages
444
- * @param writer - Callback to emit streaming events (from `config.writer`)
445
- * @param signal - Optional AbortSignal to cancel the streaming LLM call and tool execution
446
- * @returns Final response metadata (same shape as `run()`)
447
- */
448
- async streamRun(initialMessages, writer, signal) {
449
- const llm = { calls: 0, totalDurationMs: 0, resets: [], hallucinations: [] };
450
- const negotiationIds = new Set();
451
- let lastLlmStart = 0;
452
- const emit = (event) => {
453
- if (event.type === "llm_start") {
454
- llm.calls += 1;
455
- lastLlmStart = Date.now();
456
- }
457
- else if (event.type === "llm_end") {
458
- if (lastLlmStart > 0) {
459
- llm.totalDurationMs += Date.now() - lastLlmStart;
460
- lastLlmStart = 0;
461
- }
462
- }
463
- else if (event.type === "response_reset") {
464
- llm.resets.push({ reason: event.reason, at: Date.now() });
465
- }
466
- else if (event.type === "hallucination_detected") {
467
- llm.hallucinations.push({ blockType: event.blockType, tool: event.tool, at: Date.now() });
468
- }
469
- else if (event.type === "negotiation_session_start") {
470
- negotiationIds.add(event.opportunityId);
471
- }
472
- try {
473
- writer?.(event);
474
- }
475
- catch {
476
- /* swallow if writer is gone */
477
- }
478
- };
479
- let messages = initialMessages;
480
- let iterationCount = 0;
481
- const toolsDebug = [];
482
- const surfacedQuestionIds = new Set();
483
- const hallucinationAutoInvokeCounts = new Map();
484
- while (iterationCount < HARD_ITERATION_LIMIT) {
485
- if (signal?.aborted) {
486
- logger.verbose("Stream aborted by client", { iterationCount });
487
- break;
488
- }
489
- emit({ type: "iteration_start", iteration: iterationCount });
490
- const iterCtx = {
491
- recentTools: extractRecentToolCalls(messages),
492
- currentMessage: ChatAgent.getCurrentUserMessage(messages),
493
- ctx: this.resolvedContext,
494
- };
495
- const deterministicResponse = this.persona.resolveDeterministicResponse?.(this.resolvedContext, iterCtx);
496
- if (deterministicResponse !== undefined && deterministicResponse !== null) {
497
- emit({ type: "text_chunk", content: deterministicResponse });
498
- messages = [...messages, new AIMessage(deterministicResponse)];
499
- iterationCount++;
500
- return {
501
- responseText: deterministicResponse,
502
- messages,
503
- iterationCount,
504
- debugMeta: {
505
- graph: "agent_loop",
506
- iterations: iterationCount,
507
- tools: toolsDebug,
508
- llm,
509
- },
510
- };
511
- }
512
- const systemContent = this.persona.buildSystemContent(this.resolvedContext, iterCtx);
513
- const fullMessages = [
514
- new SystemMessage(systemContent),
515
- ...messages,
516
- ];
517
- if (iterationCount >= SOFT_ITERATION_LIMIT) {
518
- fullMessages.push(new SystemMessage(ITERATION_NUDGE));
519
- }
520
- logger.verbose("Streaming iteration", {
521
- iteration: iterationCount,
522
- messageCount: messages.length,
523
- pastSoftLimit: iterationCount >= SOFT_ITERATION_LIMIT,
524
- });
525
- // ── Stream the model response token-by-token ──────────────────────
526
- emit({ type: "llm_start", iteration: iterationCount });
527
- let accumulated;
528
- let iterationText = "";
529
- try {
530
- const stream = await this.model.stream(fullMessages, { signal });
531
- for await (const chunk of stream) {
532
- // Accumulate using AIMessageChunk.concat() so tool_call_chunks merge and tool_calls is populated
533
- accumulated = accumulated ? accumulated.concat(chunk) : chunk;
534
- // Emit text content tokens to the user immediately
535
- const textPart = extractTextFromChunk(chunk);
536
- if (textPart) {
537
- emit({ type: "text_chunk", content: textPart });
538
- iterationText += textPart;
539
- }
540
- }
541
- }
542
- catch (err) {
543
- if (err instanceof Error && err.name === "AbortError") {
544
- logger.verbose("LLM stream aborted by client", { iterationCount });
545
- break; // breaks the outer while loop
546
- }
547
- throw err; // re-throw non-abort errors
548
- }
549
- if (!accumulated) {
550
- logger.warn("Empty model response in streaming iteration", {
551
- iterationCount,
552
- });
553
- iterationCount++;
554
- continue;
555
- }
556
- // ── Check for tool calls ──────────────────────────────────────────
557
- const toolCalls = accumulated.tool_calls || [];
558
- emit({
559
- type: "llm_end",
560
- iteration: iterationCount,
561
- hasToolCalls: toolCalls.length > 0,
562
- toolNames: toolCalls.length > 0 ? toolCalls.map((tc) => tc.name) : undefined,
563
- });
564
- if (toolCalls.length > 0) {
565
- logger.verbose("Streaming: agent made tool calls", {
566
- iteration: iterationCount,
567
- tools: toolCalls.map((tc) => tc.name),
568
- });
569
- // Clear any narration text streamed before tool calls — this text is
570
- // intermediate reasoning and should not appear in the final response.
571
- // The next iteration (after tool execution) will produce the real response.
572
- if (iterationText) {
573
- emit({ type: "response_reset", reason: "Tool calls detected" });
574
- }
575
- // Execute tools one-by-one.
576
- const toolResults = [];
577
- for (const tc of toolCalls) {
578
- if (signal?.aborted) {
579
- logger.verbose("Stream aborted by client during tool execution");
580
- break;
581
- }
582
- emit({ type: "tool_activity", phase: "start", name: tc.name });
583
- const tool = this.toolsByName.get(tc.name);
584
- if (!tool) {
585
- const errResult = JSON.stringify({
586
- success: false,
587
- error: `Unknown tool: ${tc.name}`,
588
- });
589
- toolsDebug.push({
590
- name: tc.name,
591
- args: sanitizeForDebugMeta(tc.args),
592
- resultSummary: "Unknown tool",
593
- success: false,
594
- durationMs: 0,
595
- });
596
- emit({
597
- type: "tool_activity",
598
- phase: "end",
599
- name: tc.name,
600
- success: false,
601
- summary: "Unknown tool",
602
- });
603
- toolResults.push({
604
- toolCallId: tc.id || `unknown-${Date.now()}`,
605
- name: tc.name,
606
- result: errResult,
607
- });
608
- continue;
609
- }
610
- const toolStart = Date.now();
611
- try {
612
- logger.verbose("Streaming: executing tool", { name: tc.name });
613
- const currentCtx = requestContext.getStore() ?? {};
614
- let result = await requestContext.run({
615
- ...currentCtx,
616
- traceEmitter: (e) => emit(e),
617
- // Propagate the caller's AbortSignal into requestContext so
618
- // long-running graph nodes (orchestrator negotiation fan-out)
619
- // can suppress event emits after the chat session closes.
620
- ...(signal && { abortSignal: signal }),
621
- }, () => tool.invoke(tc.args));
622
- const toolDurationMs = Date.now() - toolStart;
623
- let resultStr = typeof result === "string" ? result : JSON.stringify(result);
624
- const normalized = await this.normalizeToolResult(tc.name, resultStr, tc.args);
625
- resultStr = normalized.resultStr;
626
- result = resultStr;
627
- if (normalized.decisionQuestions && normalized.decisionQuestions.length > 0) {
628
- const { fresh, newIds } = deduplicateQuestions(normalized.decisionQuestions, surfacedQuestionIds);
629
- if (fresh.length > 0) {
630
- emit({ type: "decision_questions", questions: fresh });
631
- for (const id of newIds)
632
- surfacedQuestionIds.add(id);
633
- }
634
- }
635
- logger.verbose("Streaming: tool completed", {
636
- name: tc.name,
637
- resultLength: resultStr.length,
638
- });
639
- toolsDebug.push({
640
- name: tc.name,
641
- args: sanitizeForDebugMeta(tc.args),
642
- resultSummary: normalized.summary,
643
- success: true,
644
- durationMs: toolDurationMs,
645
- ...(normalized.debugSteps?.length ? { steps: normalized.debugSteps } : {}),
646
- ...(normalized.graphTimings?.length ? { graphs: normalized.graphTimings } : {}),
647
- });
648
- emit({
649
- type: "tool_activity",
650
- phase: "end",
651
- name: tc.name,
652
- success: true,
653
- summary: normalized.summary,
654
- steps: normalized.debugSteps,
655
- });
656
- toolResults.push({
657
- toolCallId: tc.id || `${tc.name}-${Date.now()}`,
658
- name: tc.name,
659
- result: resultStr,
660
- });
661
- }
662
- catch (error) {
663
- const errMsg = error instanceof Error ? error.message : "Unknown error";
664
- logger.error("Streaming: tool failed", {
665
- name: tc.name,
666
- error: errMsg,
667
- });
668
- toolsDebug.push({
669
- name: tc.name,
670
- args: sanitizeForDebugMeta(tc.args),
671
- resultSummary: errMsg,
672
- success: false,
673
- durationMs: Date.now() - toolStart,
674
- });
675
- emit({
676
- type: "tool_activity",
677
- phase: "end",
678
- name: tc.name,
679
- success: false,
680
- summary: errMsg,
681
- });
682
- toolResults.push({
683
- toolCallId: tc.id || `${tc.name}-${Date.now()}`,
684
- name: tc.name,
685
- result: JSON.stringify({
686
- success: false,
687
- error: `Tool execution failed: ${errMsg}`,
688
- }),
689
- });
690
- }
691
- }
692
- // If aborted during tool execution, discard partial results
693
- if (signal?.aborted) {
694
- logger.verbose("Stream aborted after partial tool execution, discarding results");
695
- break; // break outer while loop — don't append partial toolResults to messages
696
- }
697
- // Build updated messages and loop
698
- messages = [
699
- ...messages,
700
- accumulated, // AIMessage with tool_calls
701
- ...toolResults.map((tr) => new ToolMessage({
702
- tool_call_id: tr.toolCallId,
703
- content: tr.result,
704
- name: tr.name,
705
- })),
706
- ];
707
- iterationCount++;
708
- continue;
709
- }
710
- // ── No tool calls → check for hallucinated code blocks ──────────
711
- // LLMs sometimes write ```intent_proposal or ```opportunity blocks
712
- // directly instead of calling the corresponding tool. These blocks
713
- // lack valid proposalIds / data and won't work in the frontend.
714
- // Auto-invoke the correct tool directly instead of re-asking the LLM.
715
- // Persona-gated: only personas with hallucinationRecovery enabled run
716
- // detection/auto-invoke — other personas never trigger this branch.
717
- const hallucinatedBlock = this.persona.loopBehaviors.hallucinationRecovery
718
- ? this.detectHallucinatedBlock(iterationText, toolsDebug, iterCtx.currentMessage)
719
- : null;
720
- const priorAutoInvokes = hallucinatedBlock ? (hallucinationAutoInvokeCounts.get(hallucinatedBlock.type) ?? 0) : 0;
721
- if (hallucinatedBlock && priorAutoInvokes < 2 && iterationCount < HARD_ITERATION_LIMIT - 1) {
722
- hallucinationAutoInvokeCounts.set(hallucinatedBlock.type, priorAutoInvokes + 1);
723
- logger.warn("Streaming: detected hallucinated block, auto-invoking tool", {
724
- iteration: iterationCount,
725
- blockType: hallucinatedBlock.type,
726
- tool: hallucinatedBlock.tool,
727
- extractedDescription: hallucinatedBlock.description,
728
- autoInvokeAttempt: priorAutoInvokes + 1,
729
- });
730
- // Tell the frontend to discard all streamed tokens from this iteration
731
- emit({ type: "response_reset", reason: `Hallucinated ${hallucinatedBlock.type} block detected` });
732
- emit({ type: "hallucination_detected", blockType: hallucinatedBlock.type, tool: hallucinatedBlock.tool });
733
- const tool = this.toolsByName.get(hallucinatedBlock.tool);
734
- if (tool) {
735
- const toolCallId = `auto-${hallucinatedBlock.tool}-${Date.now()}`;
736
- const toolArgs = hallucinatedBlock.type === "opportunity"
737
- ? { searchQuery: hallucinatedBlock.description }
738
- : { description: hallucinatedBlock.description };
739
- emit({ type: "tool_activity", phase: "start", name: hallucinatedBlock.tool });
740
- const toolStart = Date.now();
741
- try {
742
- const currentCtx = requestContext.getStore() ?? {};
743
- const result = await requestContext.run({
744
- ...currentCtx,
745
- traceEmitter: (e) => emit(e),
746
- // Propagate the caller's AbortSignal into requestContext so
747
- // long-running graph nodes (orchestrator negotiation fan-out)
748
- // can suppress event emits after the chat session closes.
749
- ...(signal && { abortSignal: signal }),
750
- }, () => tool.invoke(toolArgs));
751
- const rawResultStr = typeof result === "string" ? result : JSON.stringify(result);
752
- const toolDurationMs = Date.now() - toolStart;
753
- // Same normalization as the main tool loop: callback + _graphTimings strip
754
- const normalized = await this.normalizeToolResult(hallucinatedBlock.tool, rawResultStr, toolArgs);
755
- toolsDebug.push({
756
- name: hallucinatedBlock.tool,
757
- args: sanitizeForDebugMeta(toolArgs),
758
- resultSummary: normalized.summary,
759
- success: true,
760
- durationMs: toolDurationMs,
761
- ...(normalized.debugSteps?.length ? { steps: normalized.debugSteps } : {}),
762
- ...(normalized.graphTimings?.length ? { graphs: normalized.graphTimings } : {}),
763
- });
764
- // Mirror the main tool loop's handling: forward decision questions
765
- // and capture debug metadata even when the discovery tool was invoked
766
- // via the hallucination-recovery path.
767
- if (normalized.decisionQuestions && normalized.decisionQuestions.length > 0) {
768
- const { fresh: freshHallucination, newIds: newIdsHallucination } = deduplicateQuestions(normalized.decisionQuestions, surfacedQuestionIds);
769
- if (freshHallucination.length > 0) {
770
- emit({ type: "decision_questions", questions: freshHallucination });
771
- for (const id of newIdsHallucination)
772
- surfacedQuestionIds.add(id);
773
- }
774
- }
775
- emit({
776
- type: "tool_activity",
777
- phase: "end",
778
- name: hallucinatedBlock.tool,
779
- success: true,
780
- summary: normalized.summary,
781
- steps: normalized.debugSteps,
782
- });
783
- // Build synthetic tool call message + tool result so the next LLM
784
- // iteration can narrate around real data instead of hallucinated blocks.
785
- const syntheticAIMessage = new AIMessage({
786
- content: "",
787
- tool_calls: [{ id: toolCallId, name: hallucinatedBlock.tool, args: toolArgs }],
788
- });
789
- messages = [
790
- ...messages,
791
- syntheticAIMessage,
792
- new ToolMessage({ tool_call_id: toolCallId, content: normalized.resultStr, name: hallucinatedBlock.tool }),
793
- ];
794
- }
795
- catch (error) {
796
- const errMsg = error instanceof Error ? error.message : "Unknown error";
797
- logger.error("Streaming: auto-invoked tool failed after hallucination", {
798
- tool: hallucinatedBlock.tool,
799
- error: errMsg,
800
- });
801
- toolsDebug.push({
802
- name: hallucinatedBlock.tool,
803
- args: sanitizeForDebugMeta(toolArgs),
804
- resultSummary: errMsg,
805
- success: false,
806
- durationMs: Date.now() - toolStart,
807
- });
808
- emit({ type: "tool_activity", phase: "end", name: hallucinatedBlock.tool, success: false, summary: errMsg });
809
- // Fall back to correction message if tool invocation fails
810
- messages = [
811
- ...messages,
812
- accumulated,
813
- new SystemMessage(`CORRECTION: You wrote a \`\`\`${hallucinatedBlock.type} block without calling ${hallucinatedBlock.tool}. ` +
814
- `The auto-retry failed (${errMsg}). Please try calling the tool directly.`),
815
- ];
816
- }
817
- }
818
- else {
819
- // Tool not found — fall back to correction message
820
- messages = [
821
- ...messages,
822
- accumulated,
823
- new SystemMessage(`CORRECTION: You wrote a \`\`\`${hallucinatedBlock.type} block without calling ${hallucinatedBlock.tool}. ` +
824
- `That block is INVALID. Call the tool directly instead.`),
825
- ];
826
- }
827
- iterationCount++;
828
- continue;
829
- }
830
- // ── Circuit breaker: hallucination detected but auto-invoke cap reached ──
831
- if (hallucinatedBlock && priorAutoInvokes >= 2) {
832
- logger.warn("Streaming: hallucination auto-invoke cap reached, stripping blocks", {
833
- iteration: iterationCount,
834
- blockType: hallucinatedBlock.type,
835
- attempts: priorAutoInvokes,
836
- });
837
- emit({ type: "response_reset", reason: `Hallucination cap reached for ${hallucinatedBlock.type}` });
838
- const stripped = this.stripUnbackedBlocks(iterationText, toolsDebug);
839
- if (stripped.trim()) {
840
- emit({ type: "text_chunk", content: stripped });
841
- }
842
- else {
843
- messages = [
844
- ...messages,
845
- accumulated,
846
- new SystemMessage("Your previous response only contained invalid code blocks that were removed. " +
847
- "Write a plain text response now — summarize the results of the tools you used. " +
848
- "Do NOT include ```opportunity or ```intent_proposal blocks."),
849
- ];
850
- iterationCount++;
851
- continue;
852
- }
853
- }
854
- // ── Phantom write: model claims a write action without calling any tools ──
855
- if (ChatAgent.detectPhantomWrite(iterationText, toolsDebug) &&
856
- iterationCount < HARD_ITERATION_LIMIT - 1) {
857
- logger.warn("Streaming: detected phantom write claim without tool calls", {
858
- iteration: iterationCount,
859
- });
860
- emit({ type: "response_reset", reason: "Phantom write detected — no tools were called" });
861
- emit({ type: "hallucination_detected", blockType: "phantom_write", tool: "none" });
862
- messages = [
863
- ...messages,
864
- accumulated,
865
- new SystemMessage("CORRECTION: You claimed to have performed an action (update, create, modify) but you did NOT call any tools. " +
866
- "The user's request has NOT been fulfilled. You MUST call the appropriate tool(s) to actually make the change, " +
867
- "then confirm based on the tool result. Do it now."),
868
- ];
869
- iterationCount++;
870
- continue;
871
- }
872
- // ── Final response already streamed ─────────────────────────────
873
- // Defense-in-depth: strip any code blocks that require tool backing
874
- // but slipped through without a successful tool call (persona-gated,
875
- // same flag as detection since both police tool-backed block types).
876
- const sanitizedText = this.persona.loopBehaviors.hallucinationRecovery
877
- ? this.stripUnbackedBlocks(iterationText, toolsDebug)
878
- : iterationText;
879
- if (sanitizedText !== iterationText) {
880
- logger.warn("Streaming: stripped unbacked code blocks from final response", {
881
- originalLength: iterationText.length,
882
- sanitizedLength: sanitizedText.length,
883
- });
884
- emit({ type: "response_reset", reason: "Sanitized unbacked blocks from response" });
885
- // Re-emit the sanitized text so the frontend displays clean content
886
- if (sanitizedText.trim()) {
887
- emit({ type: "text_chunk", content: sanitizedText });
888
- }
889
- // If stripping removed ALL content, force a recovery iteration so the
890
- // user sees an actual response instead of a blank message.
891
- if (!sanitizedText.trim() && iterationCount < HARD_ITERATION_LIMIT - 1) {
892
- logger.warn("Streaming: sanitized text is empty, forcing recovery iteration", {
893
- iteration: iterationCount,
894
- });
895
- messages = [
896
- ...messages,
897
- accumulated,
898
- new SystemMessage("Your previous response only contained invalid code blocks that were removed. " +
899
- "Write a plain text response now — summarize the results of the tools you used. " +
900
- "Do NOT include ```opportunity or ```intent_proposal blocks."),
901
- ];
902
- iterationCount++;
903
- continue;
904
- }
905
- }
906
- logger.verbose("Streaming: agent produced response", {
907
- iteration: iterationCount,
908
- responseLength: sanitizedText.length,
909
- });
910
- messages = [...messages, accumulated];
911
- iterationCount++;
912
- return {
913
- responseText: sanitizedText,
914
- messages,
915
- iterationCount,
916
- debugMeta: {
917
- graph: "agent_loop",
918
- iterations: iterationCount,
919
- tools: toolsDebug,
920
- llm,
921
- ...(negotiationIds.size > 0 && {
922
- orchestratorNegotiations: { opportunityIds: [...negotiationIds] },
923
- }),
924
- },
925
- };
926
- }
927
- // If aborted, return immediately without making another LLM call
928
- if (signal?.aborted) {
929
- return {
930
- responseText: "",
931
- messages,
932
- iterationCount,
933
- debugMeta: {
934
- graph: "agent_loop",
935
- iterations: iterationCount,
936
- tools: toolsDebug,
937
- llm,
938
- ...(negotiationIds.size > 0 && {
939
- orchestratorNegotiations: { opportunityIds: [...negotiationIds] },
940
- }),
941
- },
942
- };
943
- }
944
- // ── Hard limit: force a response ──────────────────────────────────────
945
- logger.warn("Streaming: hit hard iteration limit", { iterationCount });
946
- const forceMessages = [
947
- ...messages,
948
- new SystemMessage("You have reached the maximum number of tool calls. You MUST provide a final response now. Summarize what you've accomplished and what might still be needed."),
949
- ];
950
- let forcedAccumulated;
951
- let forcedResponseText = "";
952
- const forceStream = await this.model.stream(forceMessages);
953
- for await (const chunk of forceStream) {
954
- forcedAccumulated = forcedAccumulated
955
- ? forcedAccumulated.concat(chunk)
956
- : chunk;
957
- const textPart = extractTextFromChunk(chunk);
958
- if (textPart) {
959
- emit({ type: "text_chunk", content: textPart });
960
- forcedResponseText += textPart;
961
- }
962
- }
963
- return {
964
- responseText: forcedResponseText,
965
- messages: [
966
- ...messages,
967
- ...(forcedAccumulated ? [forcedAccumulated] : []),
968
- ],
969
- iterationCount,
970
- debugMeta: {
971
- graph: "agent_loop",
972
- iterations: iterationCount,
973
- tools: toolsDebug,
974
- llm,
975
- ...(negotiationIds.size > 0 && {
976
- orchestratorNegotiations: { opportunityIds: [...negotiationIds] },
977
- }),
978
- },
979
- };
980
- }
981
- }
982
- // ─── Phantom write detection ─────────────────────────────────────────────
983
- ChatAgent.PHANTOM_WRITE_PATTERNS = [
984
- /\bI(?:'ve| have) (?:updated|adjusted|changed|modified|edited|created|added|removed|deleted|saved|set up)\b/i,
985
- /\bI (?:updated|adjusted|changed|modified|edited|created|added|removed|deleted|saved|set up)\b/i,
986
- /\b(?:Updated|Adjusted|Changed|Modified|Edited|Created|Added|Removed|Deleted|Saved) (?:your|the|their)\b/i,
987
- /\bEverything is (?:now )?(?:updated|changed|adjusted|saved|set)\b/i,
988
- /\b(?:profile|bio|premise|signal|intent|membership|narrative) (?:has been|is now) (?:updated|changed|modified|adjusted|saved)\b/i,
989
- ];
990
- // ─── Shared tool-result post-processing types ─────────────────────────────
991
- ChatAgent.STEP_DETAIL_MAX = 300;
992
- ChatAgent.STEP_NAME_MAX = 100;
993
- __decorate([
994
- Timed(),
995
- __metadata("design:type", Function),
996
- __metadata("design:paramtypes", [Array, Number]),
997
- __metadata("design:returntype", Promise)
998
- ], ChatAgent.prototype, "runIteration", null);
999
- __decorate([
1000
- Timed(),
1001
- __metadata("design:type", Function),
1002
- __metadata("design:paramtypes", [Array]),
1003
- __metadata("design:returntype", Promise)
1004
- ], ChatAgent.prototype, "run", null);
1005
- __decorate([
1006
- Timed(),
1007
- __metadata("design:type", Function),
1008
- __metadata("design:paramtypes", [Array, Function, AbortSignal]),
1009
- __metadata("design:returntype", Promise)
1010
- ], ChatAgent.prototype, "streamRun", null);