@moureau/pipeflow 0.0.1 → 0.0.3

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 (336) hide show
  1. package/README.md +280 -130
  2. package/dist/cjs/agents/agent.js +1 -1
  3. package/dist/cjs/agents/agent.js.map +3 -3
  4. package/dist/cjs/agents/tools/tools.js +1 -1
  5. package/dist/cjs/agents/tools/tools.js.map +3 -3
  6. package/dist/cjs/client/client.js +2 -0
  7. package/dist/cjs/client/client.js.map +7 -0
  8. package/dist/cjs/client/index.js +2 -0
  9. package/dist/cjs/client/index.js.map +7 -0
  10. package/dist/cjs/client/json.js +2 -0
  11. package/dist/cjs/client/json.js.map +7 -0
  12. package/dist/cjs/client/protocol/websocket.js +2 -0
  13. package/dist/cjs/client/protocol/websocket.js.map +7 -0
  14. package/dist/cjs/client/protocol.js +2 -0
  15. package/dist/cjs/client/protocol.js.map +7 -0
  16. package/dist/cjs/conversations/conversation/conversation.js +1 -1
  17. package/dist/cjs/conversations/conversation/conversation.js.map +3 -3
  18. package/dist/cjs/conversations/conversations.js +1 -1
  19. package/dist/cjs/conversations/conversations.js.map +3 -3
  20. package/dist/cjs/conversations/index.js +1 -1
  21. package/dist/cjs/conversations/index.js.map +3 -3
  22. package/dist/cjs/conversations/orchestration/coordination/coordination.js +10 -0
  23. package/dist/cjs/conversations/orchestration/coordination/coordination.js.map +7 -0
  24. package/dist/cjs/conversations/orchestration/coordination/index.js +2 -0
  25. package/dist/cjs/conversations/orchestration/coordination/index.js.map +7 -0
  26. package/dist/cjs/conversations/orchestration/orchestrator/coordination-runner/coordination-runner.js +4 -0
  27. package/dist/cjs/conversations/orchestration/orchestrator/coordination-runner/coordination-runner.js.map +7 -0
  28. package/dist/cjs/conversations/orchestration/orchestrator/coordination-runner/index.js +2 -0
  29. package/dist/cjs/conversations/orchestration/orchestrator/coordination-runner/index.js.map +7 -0
  30. package/dist/cjs/conversations/orchestration/orchestrator/generation/generation.js +2 -0
  31. package/dist/cjs/conversations/orchestration/orchestrator/generation/generation.js.map +7 -0
  32. package/dist/cjs/conversations/orchestration/orchestrator/generation/index.js +2 -0
  33. package/dist/cjs/conversations/orchestration/orchestrator/generation/index.js.map +7 -0
  34. package/dist/cjs/conversations/orchestration/orchestrator/history/history.js +4 -0
  35. package/dist/cjs/conversations/orchestration/orchestrator/history/history.js.map +7 -0
  36. package/dist/cjs/conversations/orchestration/orchestrator/history/index.js +2 -0
  37. package/dist/cjs/conversations/orchestration/orchestrator/history/index.js.map +7 -0
  38. package/dist/cjs/conversations/orchestration/orchestrator/index.js +1 -1
  39. package/dist/cjs/conversations/orchestration/orchestrator/index.js.map +3 -3
  40. package/dist/cjs/conversations/orchestration/orchestrator/orchestrator.js +1 -2
  41. package/dist/cjs/conversations/orchestration/orchestrator/orchestrator.js.map +3 -3
  42. package/dist/cjs/conversations/orchestration/orchestrator/routing/index.js +2 -0
  43. package/dist/cjs/conversations/orchestration/orchestrator/routing/index.js.map +7 -0
  44. package/dist/cjs/conversations/orchestration/orchestrator/routing/routing.js +23 -0
  45. package/dist/cjs/conversations/orchestration/orchestrator/routing/routing.js.map +7 -0
  46. package/dist/cjs/conversations/orchestration/orchestrator/speech/index.js +2 -0
  47. package/dist/cjs/conversations/orchestration/orchestrator/speech/index.js.map +7 -0
  48. package/dist/cjs/conversations/orchestration/orchestrator/speech/speech.js +2 -0
  49. package/dist/cjs/conversations/orchestration/orchestrator/speech/speech.js.map +7 -0
  50. package/dist/cjs/conversations/orchestration/orchestrator/tools/index.js +2 -0
  51. package/dist/cjs/conversations/orchestration/orchestrator/tools/index.js.map +7 -0
  52. package/dist/cjs/conversations/orchestration/orchestrator/tools/tools.js +2 -0
  53. package/dist/cjs/conversations/orchestration/orchestrator/tools/tools.js.map +7 -0
  54. package/dist/cjs/conversations/orchestration/test-harness.js +2 -0
  55. package/dist/cjs/conversations/orchestration/test-harness.js.map +7 -0
  56. package/dist/cjs/conversations/orchestration/text-chunker/index.js +2 -0
  57. package/dist/cjs/conversations/orchestration/text-chunker/index.js.map +7 -0
  58. package/dist/cjs/conversations/orchestration/text-chunker/text-chunker.js +3 -0
  59. package/dist/cjs/conversations/orchestration/text-chunker/text-chunker.js.map +7 -0
  60. package/dist/cjs/conversations/stream/conversation-stream.js +2 -0
  61. package/dist/cjs/conversations/stream/conversation-stream.js.map +7 -0
  62. package/dist/cjs/conversations/stream/index.js +2 -0
  63. package/dist/cjs/conversations/stream/index.js.map +7 -0
  64. package/dist/cjs/conversations/types.js +1 -1
  65. package/dist/cjs/conversations/types.js.map +2 -2
  66. package/dist/cjs/index.js +1 -1
  67. package/dist/cjs/index.js.map +3 -3
  68. package/dist/cjs/persistence/adapters/sqlite/sqlite.js +18 -14
  69. package/dist/cjs/persistence/adapters/sqlite/sqlite.js.map +3 -3
  70. package/dist/cjs/pipeflow/index.js +2 -0
  71. package/dist/cjs/pipeflow/index.js.map +7 -0
  72. package/dist/cjs/pipeflow/pipeflow.js +2 -0
  73. package/dist/cjs/pipeflow/pipeflow.js.map +7 -0
  74. package/dist/cjs/providers/index.js +1 -1
  75. package/dist/cjs/providers/index.js.map +2 -2
  76. package/dist/cjs/providers/llm/adapters/claude/claude.js +5 -0
  77. package/dist/cjs/providers/llm/adapters/claude/claude.js.map +7 -0
  78. package/dist/cjs/providers/llm/adapters/claude/index.js +2 -0
  79. package/dist/cjs/providers/llm/adapters/claude/index.js.map +7 -0
  80. package/dist/cjs/providers/llm/adapters/deepseek/deepseek.js +1 -1
  81. package/dist/cjs/providers/llm/adapters/deepseek/deepseek.js.map +3 -3
  82. package/dist/cjs/providers/llm/adapters/index.js +1 -1
  83. package/dist/cjs/providers/llm/adapters/index.js.map +3 -3
  84. package/dist/cjs/providers/llm/adapters/openai/index.js +2 -0
  85. package/dist/cjs/providers/llm/adapters/openai/index.js.map +7 -0
  86. package/dist/cjs/providers/llm/adapters/openai/openai.js +2 -0
  87. package/dist/cjs/providers/llm/adapters/openai/openai.js.map +7 -0
  88. package/dist/cjs/providers/llm/adapters/openai-compatible.js +10 -0
  89. package/dist/cjs/providers/llm/adapters/openai-compatible.js.map +7 -0
  90. package/dist/cjs/providers/llm/adapters/openrouter/index.js +2 -0
  91. package/dist/cjs/providers/llm/adapters/openrouter/index.js.map +7 -0
  92. package/dist/cjs/providers/llm/adapters/openrouter/openrouter.js +2 -0
  93. package/dist/cjs/providers/llm/adapters/openrouter/openrouter.js.map +7 -0
  94. package/dist/cjs/providers/llm/index.js +1 -1
  95. package/dist/cjs/providers/llm/index.js.map +3 -3
  96. package/dist/cjs/providers/llm/toolmode/index.js +2 -0
  97. package/dist/cjs/providers/llm/toolmode/index.js.map +7 -0
  98. package/dist/cjs/providers/llm/toolmode/toolmode.js +2 -0
  99. package/dist/cjs/providers/llm/toolmode/toolmode.js.map +7 -0
  100. package/dist/cjs/providers/llm/types.js +1 -1
  101. package/dist/cjs/providers/llm/types.js.map +3 -3
  102. package/dist/cjs/providers/stt/adapters/deepgram/deepgram.js +1 -1
  103. package/dist/cjs/providers/stt/adapters/deepgram/deepgram.js.map +3 -3
  104. package/dist/cjs/providers/stt/adapters/index.js +1 -1
  105. package/dist/cjs/providers/stt/adapters/index.js.map +3 -3
  106. package/dist/cjs/providers/stt/adapters/openrouter/index.js +2 -0
  107. package/dist/cjs/providers/stt/adapters/openrouter/index.js.map +7 -0
  108. package/dist/cjs/providers/stt/adapters/openrouter/openrouter.js +2 -0
  109. package/dist/cjs/providers/stt/adapters/openrouter/openrouter.js.map +7 -0
  110. package/dist/cjs/providers/tts/adapters/index.js +1 -1
  111. package/dist/cjs/providers/tts/adapters/index.js.map +3 -3
  112. package/dist/cjs/providers/tts/adapters/kokoro/kokoro.js +4 -1
  113. package/dist/cjs/providers/tts/adapters/kokoro/kokoro.js.map +3 -3
  114. package/dist/cjs/providers/tts/adapters/openrouter/index.js +2 -0
  115. package/dist/cjs/providers/tts/adapters/openrouter/index.js.map +7 -0
  116. package/dist/cjs/providers/tts/adapters/openrouter/openrouter.js +2 -0
  117. package/dist/cjs/providers/tts/adapters/openrouter/openrouter.js.map +7 -0
  118. package/dist/cjs/transport/streamobject/field-stream/field-stream.js +2 -0
  119. package/dist/cjs/transport/streamobject/field-stream/field-stream.js.map +7 -0
  120. package/dist/cjs/transport/streamobject/field-stream/index.js +2 -0
  121. package/dist/cjs/transport/streamobject/field-stream/index.js.map +7 -0
  122. package/dist/cjs/transport/streamobject/index.js +2 -0
  123. package/dist/cjs/transport/streamobject/index.js.map +7 -0
  124. package/dist/cjs/transport/streamobject/json-adapter/index.js +2 -0
  125. package/dist/cjs/transport/streamobject/json-adapter/index.js.map +7 -0
  126. package/dist/cjs/transport/streamobject/json-adapter/json-adapter.js +4 -0
  127. package/dist/cjs/transport/streamobject/json-adapter/json-adapter.js.map +7 -0
  128. package/dist/cjs/transport/streamobject/reference/index.js +2 -0
  129. package/dist/cjs/transport/streamobject/reference/index.js.map +7 -0
  130. package/dist/cjs/transport/streamobject/reference/reference.js +2 -0
  131. package/dist/cjs/transport/streamobject/reference/reference.js.map +7 -0
  132. package/dist/cjs/transport/streamobject/stream-object/index.js +2 -0
  133. package/dist/cjs/transport/streamobject/stream-object/index.js.map +7 -0
  134. package/dist/cjs/transport/streamobject/stream-object/stream-object.js +2 -0
  135. package/dist/cjs/transport/streamobject/stream-object/stream-object.js.map +7 -0
  136. package/dist/esm/agents/agent.js +1 -1
  137. package/dist/esm/agents/agent.js.map +3 -3
  138. package/dist/esm/agents/tools/tools.js +1 -1
  139. package/dist/esm/agents/tools/tools.js.map +3 -3
  140. package/dist/esm/client/client.js +2 -0
  141. package/dist/esm/client/client.js.map +7 -0
  142. package/dist/esm/client/index.js +2 -0
  143. package/dist/esm/client/index.js.map +7 -0
  144. package/dist/esm/client/json.js +2 -0
  145. package/dist/esm/client/json.js.map +7 -0
  146. package/dist/esm/client/protocol/websocket.js +2 -0
  147. package/dist/esm/client/protocol/websocket.js.map +7 -0
  148. package/dist/esm/client/protocol.js +1 -0
  149. package/dist/esm/client/protocol.js.map +7 -0
  150. package/dist/esm/conversations/conversation/conversation.js +1 -1
  151. package/dist/esm/conversations/conversation/conversation.js.map +3 -3
  152. package/dist/esm/conversations/conversations.js +1 -1
  153. package/dist/esm/conversations/conversations.js.map +3 -3
  154. package/dist/esm/conversations/index.js +1 -1
  155. package/dist/esm/conversations/index.js.map +3 -3
  156. package/dist/esm/conversations/orchestration/coordination/coordination.js +10 -0
  157. package/dist/esm/conversations/orchestration/coordination/coordination.js.map +7 -0
  158. package/dist/esm/conversations/orchestration/coordination/index.js +2 -0
  159. package/dist/esm/conversations/orchestration/coordination/index.js.map +7 -0
  160. package/dist/esm/conversations/orchestration/orchestrator/coordination-runner/coordination-runner.js +4 -0
  161. package/dist/esm/conversations/orchestration/orchestrator/coordination-runner/coordination-runner.js.map +7 -0
  162. package/dist/esm/conversations/orchestration/orchestrator/coordination-runner/index.js +2 -0
  163. package/dist/esm/conversations/orchestration/orchestrator/coordination-runner/index.js.map +7 -0
  164. package/dist/esm/conversations/orchestration/orchestrator/generation/generation.js +2 -0
  165. package/dist/esm/conversations/orchestration/orchestrator/generation/generation.js.map +7 -0
  166. package/dist/esm/conversations/orchestration/orchestrator/generation/index.js +2 -0
  167. package/dist/esm/conversations/orchestration/orchestrator/generation/index.js.map +7 -0
  168. package/dist/esm/conversations/orchestration/orchestrator/history/history.js +4 -0
  169. package/dist/esm/conversations/orchestration/orchestrator/history/history.js.map +7 -0
  170. package/dist/esm/conversations/orchestration/orchestrator/history/index.js +2 -0
  171. package/dist/esm/conversations/orchestration/orchestrator/history/index.js.map +7 -0
  172. package/dist/esm/conversations/orchestration/orchestrator/index.js +1 -1
  173. package/dist/esm/conversations/orchestration/orchestrator/index.js.map +3 -3
  174. package/dist/esm/conversations/orchestration/orchestrator/orchestrator.js +1 -2
  175. package/dist/esm/conversations/orchestration/orchestrator/orchestrator.js.map +3 -3
  176. package/dist/esm/conversations/orchestration/orchestrator/routing/index.js +2 -0
  177. package/dist/esm/conversations/orchestration/orchestrator/routing/index.js.map +7 -0
  178. package/dist/esm/conversations/orchestration/orchestrator/routing/routing.js +23 -0
  179. package/dist/esm/conversations/orchestration/orchestrator/routing/routing.js.map +7 -0
  180. package/dist/esm/conversations/orchestration/orchestrator/speech/index.js +2 -0
  181. package/dist/esm/conversations/orchestration/orchestrator/speech/index.js.map +7 -0
  182. package/dist/esm/conversations/orchestration/orchestrator/speech/speech.js +2 -0
  183. package/dist/esm/conversations/orchestration/orchestrator/speech/speech.js.map +7 -0
  184. package/dist/esm/conversations/orchestration/orchestrator/tools/index.js +2 -0
  185. package/dist/esm/conversations/orchestration/orchestrator/tools/index.js.map +7 -0
  186. package/dist/esm/conversations/orchestration/orchestrator/tools/tools.js +2 -0
  187. package/dist/esm/conversations/orchestration/orchestrator/tools/tools.js.map +7 -0
  188. package/dist/esm/conversations/orchestration/test-harness.js +2 -0
  189. package/dist/esm/conversations/orchestration/test-harness.js.map +7 -0
  190. package/dist/esm/conversations/orchestration/text-chunker/index.js +2 -0
  191. package/dist/esm/conversations/orchestration/text-chunker/index.js.map +7 -0
  192. package/dist/esm/conversations/orchestration/text-chunker/text-chunker.js +3 -0
  193. package/dist/esm/conversations/orchestration/text-chunker/text-chunker.js.map +7 -0
  194. package/dist/esm/conversations/stream/conversation-stream.js +2 -0
  195. package/dist/esm/conversations/stream/conversation-stream.js.map +7 -0
  196. package/dist/esm/conversations/stream/index.js +2 -0
  197. package/dist/esm/conversations/stream/index.js.map +7 -0
  198. package/dist/esm/conversations/types.js +1 -1
  199. package/dist/esm/conversations/types.js.map +2 -2
  200. package/dist/esm/index.js +1 -1
  201. package/dist/esm/index.js.map +3 -3
  202. package/dist/esm/persistence/adapters/sqlite/sqlite.js +18 -14
  203. package/dist/esm/persistence/adapters/sqlite/sqlite.js.map +3 -3
  204. package/dist/esm/pipeflow/index.js +2 -0
  205. package/dist/esm/pipeflow/index.js.map +7 -0
  206. package/dist/esm/pipeflow/pipeflow.js +2 -0
  207. package/dist/esm/pipeflow/pipeflow.js.map +7 -0
  208. package/dist/esm/providers/index.js +1 -1
  209. package/dist/esm/providers/index.js.map +3 -3
  210. package/dist/esm/providers/llm/adapters/claude/claude.js +5 -0
  211. package/dist/esm/providers/llm/adapters/claude/claude.js.map +7 -0
  212. package/dist/esm/providers/llm/adapters/claude/index.js +2 -0
  213. package/dist/esm/providers/llm/adapters/claude/index.js.map +7 -0
  214. package/dist/esm/providers/llm/adapters/deepseek/deepseek.js +1 -1
  215. package/dist/esm/providers/llm/adapters/deepseek/deepseek.js.map +3 -3
  216. package/dist/esm/providers/llm/adapters/index.js +1 -1
  217. package/dist/esm/providers/llm/adapters/index.js.map +3 -3
  218. package/dist/esm/providers/llm/adapters/openai/index.js +2 -0
  219. package/dist/esm/providers/llm/adapters/openai/index.js.map +7 -0
  220. package/dist/esm/providers/llm/adapters/openai/openai.js +2 -0
  221. package/dist/esm/providers/llm/adapters/openai/openai.js.map +7 -0
  222. package/dist/esm/providers/llm/adapters/openai-compatible.js +10 -0
  223. package/dist/esm/providers/llm/adapters/openai-compatible.js.map +7 -0
  224. package/dist/esm/providers/llm/adapters/openrouter/index.js +2 -0
  225. package/dist/esm/providers/llm/adapters/openrouter/index.js.map +7 -0
  226. package/dist/esm/providers/llm/adapters/openrouter/openrouter.js +2 -0
  227. package/dist/esm/providers/llm/adapters/openrouter/openrouter.js.map +7 -0
  228. package/dist/esm/providers/llm/index.js +1 -1
  229. package/dist/esm/providers/llm/index.js.map +3 -3
  230. package/dist/esm/providers/llm/toolmode/index.js +2 -0
  231. package/dist/esm/providers/llm/toolmode/index.js.map +7 -0
  232. package/dist/esm/providers/llm/toolmode/toolmode.js +2 -0
  233. package/dist/esm/providers/llm/toolmode/toolmode.js.map +7 -0
  234. package/dist/esm/providers/llm/types.js +1 -0
  235. package/dist/esm/providers/llm/types.js.map +4 -4
  236. package/dist/esm/providers/stt/adapters/deepgram/deepgram.js +1 -1
  237. package/dist/esm/providers/stt/adapters/deepgram/deepgram.js.map +3 -3
  238. package/dist/esm/providers/stt/adapters/index.js +1 -1
  239. package/dist/esm/providers/stt/adapters/index.js.map +3 -3
  240. package/dist/esm/providers/stt/adapters/openrouter/index.js +2 -0
  241. package/dist/esm/providers/stt/adapters/openrouter/index.js.map +7 -0
  242. package/dist/esm/providers/stt/adapters/openrouter/openrouter.js +2 -0
  243. package/dist/esm/providers/stt/adapters/openrouter/openrouter.js.map +7 -0
  244. package/dist/esm/providers/tts/adapters/index.js +1 -1
  245. package/dist/esm/providers/tts/adapters/index.js.map +3 -3
  246. package/dist/esm/providers/tts/adapters/kokoro/kokoro.js +4 -1
  247. package/dist/esm/providers/tts/adapters/kokoro/kokoro.js.map +3 -3
  248. package/dist/esm/providers/tts/adapters/openrouter/index.js +2 -0
  249. package/dist/esm/providers/tts/adapters/openrouter/index.js.map +7 -0
  250. package/dist/esm/providers/tts/adapters/openrouter/openrouter.js +2 -0
  251. package/dist/esm/providers/tts/adapters/openrouter/openrouter.js.map +7 -0
  252. package/dist/esm/transport/streamobject/field-stream/field-stream.js +2 -0
  253. package/dist/esm/transport/streamobject/field-stream/field-stream.js.map +7 -0
  254. package/dist/esm/transport/streamobject/field-stream/index.js +2 -0
  255. package/dist/esm/transport/streamobject/field-stream/index.js.map +7 -0
  256. package/dist/esm/transport/streamobject/index.js +2 -0
  257. package/dist/esm/transport/streamobject/index.js.map +7 -0
  258. package/dist/esm/transport/streamobject/json-adapter/index.js +2 -0
  259. package/dist/esm/transport/streamobject/json-adapter/index.js.map +7 -0
  260. package/dist/esm/transport/streamobject/json-adapter/json-adapter.js +4 -0
  261. package/dist/esm/transport/streamobject/json-adapter/json-adapter.js.map +7 -0
  262. package/dist/esm/transport/streamobject/reference/index.js +2 -0
  263. package/dist/esm/transport/streamobject/reference/index.js.map +7 -0
  264. package/dist/esm/transport/streamobject/reference/reference.js +2 -0
  265. package/dist/esm/transport/streamobject/reference/reference.js.map +7 -0
  266. package/dist/esm/transport/streamobject/stream-object/index.js +2 -0
  267. package/dist/esm/transport/streamobject/stream-object/index.js.map +7 -0
  268. package/dist/esm/transport/streamobject/stream-object/stream-object.js +2 -0
  269. package/dist/esm/transport/streamobject/stream-object/stream-object.js.map +7 -0
  270. package/dist/types/agents/agent.d.ts +3 -0
  271. package/dist/types/agents/tools/tools.d.ts +28 -6
  272. package/dist/types/client/client.d.ts +186 -0
  273. package/dist/types/client/index.d.ts +31 -0
  274. package/dist/types/client/json.d.ts +13 -0
  275. package/dist/types/client/protocol/websocket.d.ts +56 -0
  276. package/dist/types/client/protocol.d.ts +46 -0
  277. package/dist/types/conversations/conversation/conversation.d.ts +130 -6
  278. package/dist/types/conversations/conversations.d.ts +35 -1
  279. package/dist/types/conversations/index.d.ts +2 -1
  280. package/dist/types/conversations/orchestration/coordination/coordination.d.ts +192 -0
  281. package/dist/types/conversations/orchestration/coordination/index.d.ts +2 -0
  282. package/dist/types/conversations/orchestration/orchestrator/coordination-runner/coordination-runner.d.ts +108 -0
  283. package/dist/types/conversations/orchestration/orchestrator/coordination-runner/index.d.ts +2 -0
  284. package/dist/types/conversations/orchestration/orchestrator/generation/generation.d.ts +60 -0
  285. package/dist/types/conversations/orchestration/orchestrator/generation/index.d.ts +2 -0
  286. package/dist/types/conversations/orchestration/orchestrator/history/history.d.ts +62 -0
  287. package/dist/types/conversations/orchestration/orchestrator/history/index.d.ts +1 -0
  288. package/dist/types/conversations/orchestration/orchestrator/index.d.ts +10 -0
  289. package/dist/types/conversations/orchestration/orchestrator/orchestrator.d.ts +68 -31
  290. package/dist/types/conversations/orchestration/orchestrator/routing/index.d.ts +1 -0
  291. package/dist/types/conversations/orchestration/orchestrator/routing/routing.d.ts +19 -0
  292. package/dist/types/conversations/orchestration/orchestrator/speech/index.d.ts +2 -0
  293. package/dist/types/conversations/orchestration/orchestrator/speech/speech.d.ts +78 -0
  294. package/dist/types/conversations/orchestration/orchestrator/tools/index.d.ts +2 -0
  295. package/dist/types/conversations/orchestration/orchestrator/tools/tools.d.ts +65 -0
  296. package/dist/types/conversations/orchestration/test-harness.d.ts +100 -0
  297. package/dist/types/conversations/orchestration/text-chunker/index.d.ts +1 -0
  298. package/dist/types/conversations/orchestration/text-chunker/text-chunker.d.ts +39 -0
  299. package/dist/types/conversations/stream/conversation-stream.d.ts +42 -0
  300. package/dist/types/conversations/stream/index.d.ts +1 -0
  301. package/dist/types/conversations/types.d.ts +32 -0
  302. package/dist/types/index.d.ts +5 -38
  303. package/dist/types/pipeflow/index.d.ts +2 -0
  304. package/dist/types/pipeflow/pipeflow.d.ts +43 -0
  305. package/dist/types/providers/index.d.ts +1 -1
  306. package/dist/types/providers/llm/adapters/claude/claude.d.ts +45 -0
  307. package/dist/types/providers/llm/adapters/claude/index.d.ts +2 -0
  308. package/dist/types/providers/llm/adapters/deepseek/deepseek.d.ts +23 -2
  309. package/dist/types/providers/llm/adapters/index.d.ts +3 -0
  310. package/dist/types/providers/llm/adapters/openai/index.d.ts +2 -0
  311. package/dist/types/providers/llm/adapters/openai/openai.d.ts +45 -0
  312. package/dist/types/providers/llm/adapters/openai-compatible.d.ts +44 -0
  313. package/dist/types/providers/llm/adapters/openrouter/index.d.ts +2 -0
  314. package/dist/types/providers/llm/adapters/openrouter/openrouter.d.ts +60 -0
  315. package/dist/types/providers/llm/index.d.ts +5 -2
  316. package/dist/types/providers/llm/toolmode/index.d.ts +2 -0
  317. package/dist/types/providers/llm/toolmode/toolmode.d.ts +99 -0
  318. package/dist/types/providers/llm/types.d.ts +65 -0
  319. package/dist/types/providers/stt/adapters/deepgram/deepgram.d.ts +4 -1
  320. package/dist/types/providers/stt/adapters/index.d.ts +1 -0
  321. package/dist/types/providers/stt/adapters/openrouter/index.d.ts +2 -0
  322. package/dist/types/providers/stt/adapters/openrouter/openrouter.d.ts +196 -0
  323. package/dist/types/providers/tts/adapters/index.d.ts +1 -0
  324. package/dist/types/providers/tts/adapters/kokoro/kokoro.d.ts +18 -3
  325. package/dist/types/providers/tts/adapters/openrouter/index.d.ts +2 -0
  326. package/dist/types/providers/tts/adapters/openrouter/openrouter.d.ts +64 -0
  327. package/dist/types/transport/streamobject/field-stream/field-stream.d.ts +85 -0
  328. package/dist/types/transport/streamobject/field-stream/index.d.ts +2 -0
  329. package/dist/types/transport/streamobject/index.d.ts +8 -0
  330. package/dist/types/transport/streamobject/json-adapter/index.d.ts +2 -0
  331. package/dist/types/transport/streamobject/json-adapter/json-adapter.d.ts +65 -0
  332. package/dist/types/transport/streamobject/reference/index.d.ts +2 -0
  333. package/dist/types/transport/streamobject/reference/reference.d.ts +127 -0
  334. package/dist/types/transport/streamobject/stream-object/index.d.ts +2 -0
  335. package/dist/types/transport/streamobject/stream-object/stream-object.d.ts +31 -0
  336. package/package.json +29 -2
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../src/conversations/orchestration/coordination/coordination.ts"],
4
+ "sourcesContent": ["import type { Agent } from \"../../../agents/agent\";\nimport { z } from \"zod\";\nimport type { LLM, LLMMessage, LLMToolCall, LLMToolDefinition } from \"../../../providers/llm/types\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * One task delegated to an agent: a self-contained prompt for a roster member.\n */\nexport interface DelegatedTask {\n agent: string;\n prompt: string;\n}\n\n/**\n * The outcome of a delegated agent run (or sub-coordination, via `error`).\n */\nexport interface DelegationResult {\n agent: string;\n text: string;\n error?: string;\n}\n\n/** What a coordination's LLM may decide to do next. */\nexport type DelegateAction =\n | { action: \"agents\"; tasks: DelegatedTask[] }\n | { action: \"coordination\"; coordination: string; input?: unknown }\n | { action: \"clarify\"; missing: string[] }\n | { action: \"user\"; question: string }\n | { action: \"complete\"; output: string };\n\n/**\n * The runtime a coordination reasons against: the roster, every registered\n * coordination, and the primitives for delegating work. Supplied by the\n * orchestrator, so coordinations never couple to it directly.\n */\nexport interface CoordinationRuntime {\n readonly agents: readonly Agent[];\n readonly coordinations: readonly Coordination[];\n /** Shared LLM used for coordination reasoning. */\n readonly llm: LLM;\n /** Shared conversation history, seeded into fresh runs. */\n readonly history: readonly LLMMessage[];\n\n /** Run one or more agents in parallel (text-only) and return their outputs. */\n delegateAgentTasks(tasks: DelegatedTask[]): Promise<DelegationResult[]>;\n /**\n * Ask the user a question. Never returns: it throws `CoordinationSuspension`\n * carrying the innermost frame, which the orchestrator catches to park the\n * execution until the user answers.\n */\n askUser(frame: PendingFrame, question: string): Promise<never>;\n /** Stream a delta to speech (TTS narration). */\n onDelta(delta: string): void;\n /** Flush pending narration (e.g. before delegating or suspending). */\n flushSpeech(): void;\n /** Speak a standalone sentence (e.g. a `complete` output). */\n speak(sentence: string): void;\n /** True once an interrupt/stop has cancelled this run. */\n isCancelled(): boolean;\n /** Throw if the run exceeded the coordination step budget. */\n checkBudget(): void;\n}\n\nexport interface CoordinationOptions {\n name: string;\n /** System prompt describing the coordination's reasoning role. */\n prompt?: string;\n /** Overrides the runtime's shared LLM for this coordination. */\n llm?: LLM;\n maxTokens?: number;\n /** Hard wall-clock limit for a single run (including suspensions). */\n maxDurationMs?: number;\n /**\n * Deterministic cap on user-question rounds per run (both the structured\n * `clarify` action and open-ended `user` questions, across suspensions).\n * Once exhausted, the coordination is told to state reasonable\n * assumptions and complete. Defaults to 2.\n */\n maxQuestionRounds?: number;\n}\n\n/**\n * A coordination registered in the orchestrator by name \u2014 the registry key\n * is the coordination's name, so it is not repeated here.\n */\nexport type CoordinationRegistration = Omit<CoordinationOptions, \"name\">;\n\n/**\n * Render a batched clarification question from the missing details, so the\n * wording is deterministic regardless of how the model phrases the labels.\n */\nexport function renderClarifyQuestion(missing: string[]): string {\n const list = new Intl.ListFormat(\"en\", { style: \"long\", type: \"conjunction\" }).format(missing);\n return `Before I continue, could you tell me: ${list}?`;\n}\n\n/**\n * The system prompt for a `clarify` coordination: a generic,\n * domain-agnostic information-acquisition unit. It turns an underspecified\n * request into a clear one by asking the user for missing details via the\n * structured `clarify` action (batched), with a hard two-round cap enforced\n * by the runtime. Register it alongside `understand`:\n *\n * ```ts\n * coordinations: { clarify: { prompt: buildClarifyPrompt() } }\n * ```\n */\nexport function buildClarifyPrompt(): string {\n return `You are the \"clarify\" coordination: a generic information-acquisition unit.\n\nYour job is to turn an underspecified request into a sufficiently clear one by asking the user for whatever is missing. You know nothing about the request's domain \u2014 you only notice missing details and ask for them.\n\nUse the delegate tool:\n- action \"clarify\": list every missing detail in the \"missing\" array in one call \u2014 one round-trip covers all of them, never one question at a time, and never ask for anything that can be reasonably inferred.\n- action \"complete\": finish once the request is clear enough to act on, restating it precisely including every answer the user gave.\n\nYou may ask the user questions at most twice per run. After each answer, reassess: is the request now clear enough to act on? If yes, complete. If not, call \"clarify\" again with the remaining missing details. After the second round, if anything is still missing, state reasonable assumptions and complete. Never delegate to agents \u2014 your job is only to gather information.`;\n}\n\n/**\n * The resumable state of one coordination invocation. Plain data so it can be\n * parked in a `PendingExecution` while waiting for the user.\n */\nexport interface CoordinationState {\n messages: LLMMessage[];\n startedAt: number;\n /** Everything the coordination has spoken so far, for the final record. */\n narration: string;\n /** How many user-question rounds this run has used (across suspensions). */\n questionRounds: number;\n /** Tool call id awaiting a sub-coordination result, for resume replies. */\n pendingToolCallId?: string;\n}\n\n/** One frame of a suspended execution stack (outermost first). */\nexport interface PendingFrame {\n coordination: Coordination;\n state: CoordinationState;\n}\n\n/** Thrown when a coordination asks the user; carries the whole frame stack. */\nexport class CoordinationSuspension extends Error {\n readonly frames: PendingFrame[];\n readonly question: string;\n\n constructor(frames: PendingFrame[], question: string) {\n super(`Coordination suspended: ${question}`);\n this.name = \"CoordinationSuspension\";\n this.frames = frames;\n this.question = question;\n }\n}\n\n/** Thrown when a coordination run is cancelled (interrupt/stop). */\nexport class CoordinationCancelled extends Error {\n constructor() {\n super(\"Coordination cancelled\");\n this.name = \"CoordinationCancelled\";\n }\n}\n\n/** Thrown when a coordination exceeded its step or duration budget. */\nexport class CoordinationBudgetExceeded extends Error {\n constructor(detail: string) {\n super(`Coordination budget exceeded: ${detail}`);\n this.name = \"CoordinationBudgetExceeded\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Delegate tool\n// ---------------------------------------------------------------------------\n\nconst DELEGATE_DESCRIPTION =\n \"Decide what should happen next in order to produce the desired result. \" +\n \"You may run one or more agents (each with a self-contained prompt), pass the work to \" +\n \"another coordination, ask the user for missing information (batched into one call), or \" +\n \"complete with the final spoken answer. Only ever take one action per call.\";\n\n/** Non-empty zod enum, or a plain string when there are no targets. */\nfunction targetsEnum(targets: string[]): z.ZodType<string> {\n return targets.length > 0\n ? z.enum(targets as [string, ...string[]])\n : z.string();\n}\n\n/**\n * The strict schema a coordination's LLM output must satisfy. A discriminated\n * union on `action` \u2014 each variant carries exactly its own fields.\n */\nfunction delegateActionSchema(\n agents: readonly Agent[],\n coordinations: readonly Coordination[],\n): z.ZodType<DelegateAction> {\n const agentTargets = agents.map((agent) => [agent.name, ...agent.aliases]).flat();\n const coordinationTargets = coordinations.map((coordination) => coordination.name);\n return z.discriminatedUnion(\"action\", [\n z.object({\n action: z.literal(\"agents\"),\n tasks: z\n .array(\n z.object({\n agent: targetsEnum(agentTargets).describe(\"Agent name or alias from the roster.\"),\n prompt: z.string().trim().min(1, \"a prompt is required\").describe(\"Self-contained instruction for that agent.\"),\n }),\n )\n .describe(\"Agents to run in parallel.\")\n .min(1, \"at least one task is required\"),\n }),\n z.object({\n action: z.literal(\"coordination\"),\n coordination: targetsEnum(coordinationTargets).describe(\n \"The coordination to pass the work to.\",\n ),\n input: z.unknown().describe(\"Input for the delegated coordination.\").optional(),\n }),\n z.object({\n action: z.literal(\"clarify\"),\n missing: z\n .array(z.string().trim().min(1, \"a missing detail is required\"))\n .min(1, \"at least one missing detail is required\")\n .describe(\"The missing details to ask the user for, batched into one turn.\"),\n }),\n z.object({\n action: z.literal(\"user\"),\n question: z.string().trim().min(1, \"a question is required\").describe(\"Clarifying question for the user.\"),\n }),\n z.object({\n action: z.literal(\"complete\"),\n output: z.string().trim().min(1, \"an output is required\").describe(\"The final spoken answer.\"),\n }),\n ]);\n}\n\n/**\n * The tool definition that lets a coordination's LLM choose the next execution\n * target: agents (one or more, in parallel), another coordination, the user,\n * or completion.\n *\n * The parameters are deliberately FLAT (action enum + optional fields) even\n * though the parser enforces a discriminated union per action. Why: Amazon\n * Bedrock (nova) ignores `oneOf` in tool input schemas, which makes the tool\n * effectively empty \u2014 the model stops calling it and answers directly instead\n * (measured: 0/2 tool calls and ~5k-token essays vs reliable ~1s calls with\n * the flat shape). The flat schema works across every provider tested; the\n * discriminated contract is enforced when the call is parsed, and an invalid\n * combination costs one bounded retry rather than a broken tool.\n */\nexport function delegateToolDefinition(\n agents: readonly Agent[],\n coordinations: readonly Coordination[],\n): LLMToolDefinition {\n const agentTargets = agents.map((agent) => [agent.name, ...agent.aliases]).flat();\n const coordinationTargets = coordinations.map((coordination) => coordination.name);\n const parameters = z.object({\n action: z\n .enum([\"agents\", \"coordination\", \"clarify\", \"user\", \"complete\"])\n .describe(\"What to do next.\"),\n tasks: z\n .array(\n z.object({\n agent: targetsEnum(agentTargets).describe(\"Agent name or alias from the roster.\"),\n prompt: z.string().trim().min(1, \"a prompt is required\").describe(\"Self-contained instruction for that agent.\"),\n }),\n )\n .describe(\"Agents to run in parallel (action 'agents').\")\n .optional(),\n coordination: targetsEnum(coordinationTargets)\n .describe(\"The coordination to pass the work to (action 'coordination').\")\n .optional(),\n input: z\n .unknown()\n .describe(\"Input for the delegated coordination (action 'coordination').\")\n .optional(),\n missing: z\n .array(z.string().trim().min(1, \"a missing detail is required\"))\n .min(1, \"at least one missing detail is required\")\n .describe(\"The missing details to ask the user for (action 'clarify'), batched into one turn.\")\n .optional(),\n question: z\n .string()\n .trim()\n .min(1, \"a question is required\")\n .describe(\"Clarifying question for the user (action 'user').\")\n .optional(),\n output: z\n .string()\n .trim()\n .min(1, \"an output is required\")\n .describe(\"The final spoken answer (action 'complete').\")\n .optional(),\n });\n const jsonSchema = z.toJSONSchema(parameters) as Record<string, unknown>;\n delete jsonSchema.$schema;\n return { name: \"delegate\", description: DELEGATE_DESCRIPTION, parameters: jsonSchema };\n}\n\nexport function parseDelegateAction(\n argumentsJson: string,\n agents: readonly Agent[],\n coordinations: readonly Coordination[],\n): DelegateAction {\n let parsed: unknown;\n try {\n parsed = JSON.parse(argumentsJson);\n } catch {\n throw new Error(\"delegate arguments must be valid JSON\");\n }\n const result = delegateActionSchema(agents, coordinations).safeParse(parsed);\n if (!result.success) {\n const details = result.error.issues\n .map((issue) => (issue.path.length > 0 ? `${issue.path.join(\".\")}: ${issue.message}` : issue.message))\n .join(\"; \");\n throw new Error(`invalid delegate arguments: ${details}`);\n }\n return result.data;\n}\n\n// ---------------------------------------------------------------------------\n// Coordination\n// ---------------------------------------------------------------------------\n\n/**\n * A hardcoded reasoning/control-flow unit. Unlike an `Agent` (input \u2192 LLM \u2192\n * output), a coordination decides *what should happen next*: run agents, pass\n * work to another coordination, ask the user, or complete. Definitions are\n * stateless; each invocation carries its own `CoordinationState`, which can be\n * parked (suspended) while waiting for the user and resumed later.\n */\nexport class Coordination {\n readonly name: string;\n readonly prompt: string;\n readonly maxTokens: number | undefined;\n readonly maxDurationMs: number | undefined;\n readonly maxQuestionRounds: number;\n private readonly runtime: CoordinationRuntime;\n private readonly llm: LLM;\n private cachedToolDefinition: LLMToolDefinition | null = null;\n private cachedSchema: ReturnType<typeof delegateActionSchema> | null = null;\n\n constructor(options: CoordinationOptions, runtime: CoordinationRuntime) {\n if (!options.name.trim()) {\n throw new Error(\"Coordination requires a non-empty name\");\n }\n this.name = options.name.trim();\n this.prompt = options.prompt?.trim() ?? \"\";\n this.maxTokens = options.maxTokens;\n this.maxDurationMs = options.maxDurationMs;\n this.maxQuestionRounds = options.maxQuestionRounds ?? 2;\n this.runtime = runtime;\n this.llm = options.llm ?? runtime.llm;\n }\n\n /** The delegate tool definition, generated once from the roster. */\n private toolDefinition(): LLMToolDefinition {\n this.cachedToolDefinition ??= delegateToolDefinition(\n this.runtime.agents,\n this.runtime.coordinations,\n );\n return this.cachedToolDefinition;\n }\n\n /** Parse a `delegate` tool call against the roster's strict schema. */\n private parseDelegate(argumentsJson: string): DelegateAction {\n this.cachedSchema ??= delegateActionSchema(\n this.runtime.agents,\n this.runtime.coordinations,\n );\n let parsed: unknown;\n try {\n parsed = JSON.parse(argumentsJson);\n } catch {\n throw new Error(\"delegate arguments must be valid JSON\");\n }\n const result = this.cachedSchema.safeParse(parsed);\n if (!result.success) {\n const details = result.error.issues\n .map((issue) =>\n issue.path.length > 0\n ? `${issue.path.join(\".\")}: ${issue.message}`\n : issue.message,\n )\n .join(\"; \");\n throw new Error(`invalid delegate arguments: ${details}`);\n }\n return result.data;\n }\n\n /** Run the coordination with fresh state (seeded with the shared history). */\n async run(input?: unknown): Promise<unknown> {\n const state: CoordinationState = {\n messages: [],\n startedAt: Date.now(),\n narration: \"\",\n questionRounds: 0,\n };\n if (this.prompt) {\n state.messages.push({ role: \"system\", name: this.name, content: this.prompt });\n }\n state.messages.push(...this.runtime.history);\n if (input !== undefined) {\n state.messages.push({\n role: \"user\",\n content: typeof input === \"string\" ? input : JSON.stringify(input),\n });\n }\n return this.loop(state);\n }\n\n /** Resume a suspended state with the user's answer. */\n async resume(state: CoordinationState, answer: string): Promise<unknown> {\n // The pre-suspension narration was already recorded as the question.\n state.narration = \"\";\n state.messages.push({ role: \"user\", content: answer });\n return this.loop(state);\n }\n\n /** Continue a suspended state with an injected message (e.g. a sub-result). */\n async continueWith(state: CoordinationState, message: LLMMessage): Promise<unknown> {\n state.narration = \"\";\n state.messages.push(message);\n return this.loop(state);\n }\n\n /**\n * The coordination loop: one LLM round trip per iteration, choosing the next\n * execution target via the `delegate` tool. Throws `CoordinationSuspension`\n * when asking the user; the state carried in the suspension is resumable.\n */\n private async loop(state: CoordinationState): Promise<unknown> {\n const startedAt = state.startedAt;\n\n for (;;) {\n this.runtime.checkBudget();\n if (this.runtime.isCancelled()) throw new CoordinationCancelled();\n if (this.maxDurationMs && Date.now() - startedAt > this.maxDurationMs) {\n throw new CoordinationBudgetExceeded(`\"${this.name}\" exceeded ${this.maxDurationMs}ms`);\n }\n\n const toolCalls: LLMToolCall[] = [];\n let done = false;\n\n for await (const event of this.llm.stream({\n messages: state.messages,\n tools: [this.toolDefinition()],\n maxTokens: this.maxTokens,\n })) {\n if (this.runtime.isCancelled()) throw new CoordinationCancelled();\n switch (event.type) {\n case \"delta\":\n state.narration += event.content;\n this.runtime.onDelta(event.content);\n break;\n case \"tool_call\":\n toolCalls.push({ id: event.id, name: event.name, arguments: event.arguments });\n break;\n case \"error\":\n throw event.error;\n case \"done\":\n done = true;\n }\n }\n\n // Re-check the wall-clock limit after the round trip: a single slow\n // iteration must still count against maxDurationMs.\n if (this.maxDurationMs && Date.now() - startedAt > this.maxDurationMs) {\n throw new CoordinationBudgetExceeded(`\"${this.name}\" exceeded ${this.maxDurationMs}ms`);\n }\n\n if (toolCalls.length > 0) {\n this.runtime.flushSpeech();\n state.messages.push({\n role: \"assistant\",\n name: this.name,\n content: state.narration,\n toolCalls,\n });\n for (const call of toolCalls) {\n let action: DelegateAction;\n try {\n action = this.parseDelegate(call.arguments);\n } catch (error) {\n // Malformed arguments: report to the coordination's LLM so it can\n // recover instead of crashing the run.\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify({\n error: error instanceof Error ? error.message : String(error),\n }),\n });\n continue;\n }\n switch (action.action) {\n case \"agents\": {\n const results = await this.runtime.delegateAgentTasks(action.tasks);\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify(results),\n });\n break;\n }\n case \"coordination\": {\n const target = this.runtime.coordinations.find(\n (coordination) => coordination.name === action.coordination,\n );\n if (!target) {\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify({\n error: `Unknown coordination \"${action.coordination}\"`,\n }),\n });\n break;\n }\n try {\n const result = await this.delegateToCoordination(\n target,\n action.input,\n state,\n call.id,\n );\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify(result),\n });\n } catch (error) {\n if (error instanceof CoordinationBudgetExceeded) {\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify({ error: error.message }),\n });\n } else {\n throw error; // suspension or cancellation propagates\n }\n }\n break;\n }\n case \"clarify\": {\n // Structured, batched clarification: the model declares which\n // details are missing; the framework renders and speaks the\n // question so batching and the round cap are deterministic.\n if (state.questionRounds >= this.maxQuestionRounds) {\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify({\n error: `question budget exceeded (max ${this.maxQuestionRounds} rounds) \u2014 state reasonable assumptions and complete`,\n }),\n });\n continue;\n }\n state.questionRounds++;\n const question = renderClarifyQuestion(action.missing);\n this.runtime.speak(question);\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify({ action: \"clarify\", missing: action.missing }),\n });\n await this.runtime.askUser({ coordination: this, state }, question);\n throw new Error(\"unreachable\");\n }\n case \"user\": {\n // Open-ended questions count against the same deterministic\n // question-round budget as structured clarification.\n if (state.questionRounds >= this.maxQuestionRounds) {\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify({\n error: `question budget exceeded (max ${this.maxQuestionRounds} rounds) \u2014 state reasonable assumptions and complete`,\n }),\n });\n continue;\n }\n state.questionRounds++;\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify({ action: \"user\", question: action.question }),\n });\n await this.runtime.askUser({ coordination: this, state }, action.question);\n throw new Error(\"unreachable\");\n }\n case \"complete\":\n this.runtime.speak(action.output);\n return this.completeOutput(state.narration, action.output);\n }\n }\n continue;\n }\n\n if (done) {\n // No delegate call: the coordination answered directly.\n return this.completeOutput(state.narration, \"\");\n }\n }\n }\n\n /** Delegate to a sub-coordination, attaching this frame on suspension. */\n private async delegateToCoordination(\n target: Coordination,\n input: unknown,\n state: CoordinationState,\n toolCallId: string,\n ): Promise<unknown> {\n state.pendingToolCallId = toolCallId;\n try {\n return await target.run(input);\n } catch (error) {\n if (error instanceof CoordinationSuspension) {\n error.frames.unshift({ coordination: this, state });\n throw error;\n }\n throw error;\n }\n }\n\n private completeOutput(narration: string, output: string): string {\n const trimmed = narration.trim();\n return output ? `${trimmed ? trimmed + \" \" : \"\"}${output}` : trimmed;\n }\n}\n"],
5
+ "mappings": "4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,+BAAAC,EAAA,0BAAAC,EAAA,2BAAAC,EAAA,uBAAAC,EAAA,2BAAAC,EAAA,wBAAAC,EAAA,0BAAAC,IAAA,eAAAC,EAAAV,GACA,IAAAW,EAAkB,eA6FX,SAASC,EAAsBC,EAA2B,CAE/D,MAAO,yCADM,IAAI,KAAK,WAAW,KAAM,CAAE,MAAO,OAAQ,KAAM,aAAc,CAAC,EAAE,OAAOA,CAAO,CACzC,GACtD,CAHgBC,EAAAF,EAAA,yBAgBT,SAASG,GAA6B,CAC3C,MAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0XAST,CAVgBD,EAAAC,EAAA,sBAkCT,MAAMC,UAA+B,KAAM,CAhJlD,MAgJkD,CAAAF,EAAA,+BACvC,OACA,SAET,YAAYG,EAAwBC,EAAkB,CACpD,MAAM,2BAA2BA,CAAQ,EAAE,EAC3C,KAAK,KAAO,yBACZ,KAAK,OAASD,EACd,KAAK,SAAWC,CAClB,CACF,CAGO,MAAMC,UAA8B,KAAM,CA7JjD,MA6JiD,CAAAL,EAAA,8BAC/C,aAAc,CACZ,MAAM,wBAAwB,EAC9B,KAAK,KAAO,uBACd,CACF,CAGO,MAAMM,UAAmC,KAAM,CArKtD,MAqKsD,CAAAN,EAAA,mCACpD,YAAYO,EAAgB,CAC1B,MAAM,iCAAiCA,CAAM,EAAE,EAC/C,KAAK,KAAO,4BACd,CACF,CAMA,MAAMC,E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ceeded", "CoordinationCancelled", "CoordinationSuspension", "buildClarifyPrompt", "delegateToolDefinition", "parseDelegateAction", "renderClarifyQuestion", "__toCommonJS", "import_zod", "renderClarifyQuestion", "missing", "__name", "buildClarifyPrompt", "CoordinationSuspension", "frames", "question", "CoordinationCancelled", "CoordinationBudgetExceeded", "detail", "DELEGATE_DESCRIPTION", "targetsEnum", "targets", "delegateActionSchema", "agents", "coordinations", "agentTargets", "agent", "coordinationTargets", "coordination", "delegateToolDefinition", "parameters", "jsonSchema", "parseDelegateAction", "argumentsJson", "parsed", "result", "details", "issue", "Coordination", "options", "runtime", "input", "state", "answer", "message", "startedAt", "toolCalls", "done", "event", "call", "action", "error", "results", "target", "toolCallId", "narration", "output", "trimmed"]
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var a=Object.defineProperty;var r=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var g=(n,e)=>{for(var t in e)a(n,t,{get:e[t],enumerable:!0})},p=(n,e,t,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of l(e))!C.call(n,i)&&i!==t&&a(n,i,{get:()=>e[i],enumerable:!(d=r(e,i))||d.enumerable});return n};var s=n=>p(a({},"__esModule",{value:!0}),n);var c={};g(c,{Coordination:()=>o.Coordination,CoordinationBudgetExceeded:()=>o.CoordinationBudgetExceeded,CoordinationCancelled:()=>o.CoordinationCancelled,CoordinationSuspension:()=>o.CoordinationSuspension,delegateToolDefinition:()=>o.delegateToolDefinition,parseDelegateAction:()=>o.parseDelegateAction});module.exports=s(c);var o=require("./coordination.js");
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../src/conversations/orchestration/coordination/index.ts"],
4
+ "sourcesContent": ["export {\n Coordination,\n CoordinationSuspension,\n CoordinationCancelled,\n CoordinationBudgetExceeded,\n delegateToolDefinition,\n parseDelegateAction,\n} from \"./coordination\";\nexport type {\n CoordinationOptions,\n CoordinationRuntime,\n CoordinationState,\n DelegateAction,\n DelegatedTask,\n DelegationResult,\n PendingFrame,\n} from \"./coordination\";\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sTAAAE,EAAAF,GAAA,IAAAG,EAOO",
6
+ "names": ["coordination_exports", "__export", "__toCommonJS", "import_coordination"]
7
+ }
@@ -0,0 +1,4 @@
1
+ "use strict";var p=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var a=(d,t)=>p(d,"name",{value:t,configurable:!0});var w=(d,t)=>{for(var n in t)p(d,n,{get:t[n],enumerable:!0})},x=(d,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of y(t))!C.call(d,e)&&e!==n&&p(d,e,{get:()=>t[e],enumerable:!(o=f(t,e))||o.enumerable});return d};var E=d=>x(p({},"__esModule",{value:!0}),d);var S={};w(S,{CoordinationRunner:()=>T});module.exports=E(S);var i=require("../../coordination/coordination.js"),g=require("../history/history.js"),l=require("../routing/routing.js");class T{static{a(this,"CoordinationRunner")}coordinations={};understand=null;conversation;agents;llm;history;historyWindow;speech;generation;tools;maxCoordinationSteps;maxToolIterations;temperature;maxTokens;currentEpoch;isCurrent;coordinationEpoch=0;coordinationStepCount=0;coordinationRunId="";pendingExecution=null;constructor(t){this.conversation=t.conversation,this.agents=t.agents,this.llm=t.llm,this.history=t.history,this.historyWindow=t.historyWindow,this.speech=t.speech,this.generation=t.generation,this.tools=t.tools,this.maxCoordinationSteps=t.maxCoordinationSteps,this.maxToolIterations=t.maxToolIterations,this.temperature=t.temperature,this.maxTokens=t.maxTokens,this.currentEpoch=t.currentEpoch,this.isCurrent=t.isCurrent}register(t,n){const o={...t};n.length>1&&!o.understand&&(o.understand={prompt:(0,l.buildUnderstandPrompt)(n)});for(const[e,s]of Object.entries(o))this.coordinations[e]=new i.Coordination({name:e,...s},this.runtime());this.understand=this.coordinations.understand??null}hasPending(){return this.pendingExecution!==null}cancel(){this.pendingExecution=null}async runDefault(t){const n=this.understand,o=this.llm();if(!(!n||!o)){this.coordinationEpoch=this.currentEpoch(),this.coordinationStepCount=0,this.coordinationRunId=crypto.randomUUID(),await this.conversation.pushGeneration({id:this.coordinationRunId,conversationId:this.conversation.id,agentName:this.agents()[0].name,text:"",status:"streaming",startedAt:Date.now()});try{const e=await n.run();await this.finalizeOutput(String(e))}catch(e){e instanceof i.CoordinationSuspension?await this.recordSuspension(e):e instanceof i.CoordinationCancelled||this.emitError(e)}}}async resume(t){const n=this.pendingExecution;if(!n)return;this.pendingExecution=null,this.coordinationEpoch=this.currentEpoch(),this.coordinationStepCount=n.stepCount,this.coordinationRunId=crypto.randomUUID(),await this.conversation.pushGeneration({id:this.coordinationRunId,conversationId:this.conversation.id,agentName:this.agents()[0].name,text:"",status:"streaming",startedAt:Date.now()});const o=[...n.frames],e=o.pop();if(!e)return;let s;try{s=await e.coordination.resume(e.state,t.text)}catch(r){r instanceof i.CoordinationSuspension?(r.frames.unshift(...o),await this.recordSuspension(r)):r instanceof i.CoordinationCancelled||this.emitError(r);return}for(;o.length>0;){const r=o.pop(),m=r.state.pendingToolCallId??crypto.randomUUID();try{s=await r.coordination.continueWith(r.state,{role:"tool",toolCallId:m,name:"delegate",content:JSON.stringify(s)})}catch(h){h instanceof i.CoordinationSuspension?(h.frames.unshift(...o),await this.recordSuspension(h)):h instanceof i.CoordinationCancelled||this.emitError(h);return}}await this.finalizeOutput(String(s))}runtime(){const t=this;return{get agents(){return t.agents()},get coordinations(){return Object.values(t.coordinations)},get llm(){return t.llm()},get history(){return t.history.windowed(t.historyWindow)},delegateAgentTasks:a(n=>this.delegateAgentTasks(n),"delegateAgentTasks"),askUser:a((n,o)=>this.askUser(n,o),"askUser"),onDelta:a(n=>this.speech.feed(n,this.currentEpoch()),"onDelta"),flushSpeech:a(()=>this.speech.flush(this.currentEpoch()),"flushSpeech"),speak:a(n=>this.speech.speak(n,this.currentEpoch()),"speak"),isCancelled:a(()=>this.currentEpoch()!==this.coordinationEpoch,"isCancelled"),checkBudget:a(()=>this.checkBudget(),"checkBudget")}}async finalizeOutput(t){this.speech.flush(this.currentEpoch()),await this.speech.waitForIdle(),this.currentEpoch()===this.coordinationEpoch&&(await this.conversation.completeGeneration(t),await this.conversation.pushTranscript({speaker:this.agents()[0].name,speakerKind:"agent",text:t}),this.history.addAssistant(this.agents()[0].name,t))}async recordSuspension(t){await this.conversation.completeGeneration(t.question),await this.conversation.pushTranscript({speaker:this.agents()[0].name,speakerKind:"agent",text:t.question}),this.history.addAssistant(this.agents()[0].name,t.question),this.pendingExecution={frames:t.frames,question:t.question,stepCount:this.coordinationStepCount}}askUser(t,n){throw new i.CoordinationSuspension([t],n)}checkBudget(){if(this.coordinationStepCount++,this.coordinationStepCount>this.maxCoordinationSteps)throw new i.CoordinationBudgetExceeded(`exceeded ${this.maxCoordinationSteps} coordination steps`)}emitError(t){this.conversation.emit("error",{conversationId:this.conversation.id,error:t instanceof Error?t:new Error(String(t))}),this.currentEpoch()===this.coordinationEpoch&&this.conversation.completeGeneration("")}async delegateAgentTasks(t){const n=await Promise.all(t.map(o=>this.runSubGeneration(this.coordinationEpoch,o,this.coordinationRunId)));if(!this.isCurrent(this.coordinationEpoch))return n.map(({agent:o,text:e,error:s})=>({agent:o,text:e,error:s}));for(const o of n)o.text&&!o.error&&await this.conversation.pushTranscript({speaker:o.agent,speakerKind:"agent",text:o.text});return n}async runSubGeneration(t,n,o){const e=(0,l.findAgentByName)(this.agents(),n.agent);if(!e)return{agent:n.agent,text:"",error:`Unknown agent "${n.agent}"`};const s=e.llm??this.llm();if(!s)return{agent:e.name,text:"",error:`Agent "${e.name}" has no LLM configured`};const r=crypto.randomUUID();await this.conversation.pushSubGeneration({id:r,conversationId:this.conversation.id,agentName:e.name,text:"",status:"streaming",startedAt:Date.now(),kind:"sub",parentGenerationId:o});const m=e.tools.map(u=>({name:u.name,description:u.description,parameters:u.parameters??{type:"object",properties:{}}})),h=[];e.context&&h.push({role:"system",name:e.name,content:e.context}),h.push(...this.history.windowed(this.historyWindow)),h.push({role:"user",content:`${n.prompt}
2
+
3
+ ${(0,g.formatTimeContext)()}`});const c=await this.generation.run({agentName:e.name,llm:s,messages:h,tools:m,temperature:this.temperature,maxTokens:this.maxTokens,maxToolIterations:this.maxToolIterations,isCurrent:a(()=>this.isCurrent(t),"isCurrent"),onDelta:a((u,v)=>{v.length===0&&this.conversation.noteTiming("firstToken",r)},"onDelta"),resolveToolCalls:a(u=>this.tools.resolveCalls(u),"resolveToolCalls")});return!this.isCurrent(t)||c.status==="interrupted"?(await this.conversation.cancelSubGeneration(r),{agent:e.name,text:"",error:"interrupted"}):(await this.conversation.completeSubGeneration(r,c.text),c.status==="error"?(this.conversation.emit("error",{conversationId:this.conversation.id,error:c.error instanceof Error?c.error:new Error(String(c.error))}),{agent:e.name,text:c.text,error:c.error instanceof Error?c.error.message:String(c.error)}):{agent:e.name,text:c.text})}}
4
+ //# sourceMappingURL=coordination-runner.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/conversations/orchestration/orchestrator/coordination-runner/coordination-runner.ts"],
4
+ "sourcesContent": ["import type { Agent } from \"../../../../agents/agent\";\nimport type { Conversation } from \"../../../conversation/conversation\";\nimport type { LLM, LLMMessage, LLMToolDefinition } from \"../../../../providers/llm/types\";\nimport type { Turn } from \"../../../types\";\nimport {\n Coordination,\n CoordinationBudgetExceeded,\n CoordinationCancelled,\n CoordinationSuspension,\n type CoordinationRegistration,\n type CoordinationRuntime,\n type DelegatedTask,\n type DelegationResult,\n type PendingFrame,\n} from \"../../coordination/coordination\";\nimport { ConversationHistory, formatTimeContext } from \"../history/history\";\nimport { buildUnderstandPrompt, findAgentByName } from \"../routing/routing\";\nimport type { GenerationRunner } from \"../generation/generation\";\nimport type { SpeechPipeline } from \"../speech/speech\";\nimport type { ToolCallManager } from \"../tools/tools\";\n\nexport interface CoordinationRunnerOptions {\n conversation: Conversation;\n /** Live roster accessor (read at coordination-run time). */\n agents(): Agent[];\n /** Live shared-LLM accessor (undefined in transcription-only mode). */\n llm(): LLM | undefined;\n /** The conversation's message log, seeded into fresh coordination runs. */\n history: ConversationHistory;\n historyWindow: Parameters<ConversationHistory[\"windowed\"]>[0];\n speech: SpeechPipeline;\n generation: GenerationRunner;\n tools: ToolCallManager;\n /** Safety bound on LLM reasoning steps per coordination execution. */\n maxCoordinationSteps: number;\n maxToolIterations: number;\n temperature?: number;\n maxTokens?: number;\n /** The orchestrator's current generation epoch (bumped on interrupt/stop). */\n currentEpoch(): number;\n /** True while the orchestrator is started and the epoch is current. */\n isCurrent(epoch: number): boolean;\n}\n\n/** A coordination execution parked while waiting for the user to answer. */\ninterface PendingExecution {\n /** Execution stack, outermost frame first. */\n frames: PendingFrame[];\n question: string;\n /** Coordination step count so the budget survives the suspension. */\n stepCount: number;\n}\n\n/**\n * The application-specific execution of coordinations: binds the generic\n * `Coordination` primitives to the orchestrator's machinery (roster, shared\n * LLM, history, speech, delegation, budgets, cancellation) and owns the\n * suspension/resume lifecycle \u2014 the parked frame stack, the step budget, and\n * the coordination generation records.\n */\nexport class CoordinationRunner {\n /** Coordinations registered by name (the key is the coordination's name). */\n readonly coordinations: Record<string, Coordination> = {};\n /** The built-in `understand` coordination, when one is active. */\n understand: Coordination | null = null;\n\n private readonly conversation: Conversation;\n private readonly agents: () => Agent[];\n private readonly llm: () => LLM | undefined;\n private readonly history: ConversationHistory;\n private readonly historyWindow: Parameters<ConversationHistory[\"windowed\"]>[0];\n private readonly speech: SpeechPipeline;\n private readonly generation: GenerationRunner;\n private readonly tools: ToolCallManager;\n private readonly maxCoordinationSteps: number;\n private readonly maxToolIterations: number;\n private readonly temperature: number | undefined;\n private readonly maxTokens: number | undefined;\n private readonly currentEpoch: () => number;\n private readonly isCurrent: (epoch: number) => boolean;\n\n private coordinationEpoch = 0;\n private coordinationStepCount = 0;\n private coordinationRunId = \"\";\n private pendingExecution: PendingExecution | null = null;\n\n constructor(options: CoordinationRunnerOptions) {\n this.conversation = options.conversation;\n this.agents = options.agents;\n this.llm = options.llm;\n this.history = options.history;\n this.historyWindow = options.historyWindow;\n this.speech = options.speech;\n this.generation = options.generation;\n this.tools = options.tools;\n this.maxCoordinationSteps = options.maxCoordinationSteps;\n this.maxToolIterations = options.maxToolIterations;\n this.temperature = options.temperature;\n this.maxTokens = options.maxTokens;\n this.currentEpoch = options.currentEpoch;\n this.isCurrent = options.isCurrent;\n }\n\n /**\n * Register coordinations by name. The built-in `understand` runs unaddressed\n * turns: it decides whether to delegate to agents, ask the user, or answer\n * directly. Apps can override it by registering their own \"understand\" key,\n * and add their own (e.g. clarify, review).\n */\n register(\n registrations: Record<string, CoordinationRegistration>,\n agents: readonly Agent[],\n ): void {\n const merged: Record<string, CoordinationRegistration> = {\n ...registrations,\n };\n if (agents.length > 1 && !merged.understand) {\n merged.understand = { prompt: buildUnderstandPrompt(agents) };\n }\n for (const [name, registration] of Object.entries(merged)) {\n this.coordinations[name] = new Coordination(\n { name, ...registration },\n this.runtime(),\n );\n }\n this.understand = this.coordinations[\"understand\"] ?? null;\n }\n\n /** True while a coordination is parked waiting for the user to answer. */\n hasPending(): boolean {\n return this.pendingExecution !== null;\n }\n\n /** Drop a parked execution (interrupt, stop). */\n cancel(): void {\n this.pendingExecution = null;\n }\n\n /**\n * Run the built-in `understand` coordination on an unaddressed turn. A\n * streaming generation is opened for the conversation's default agent; the\n * coordination's final answer (or question) completes it.\n */\n async runDefault(turn: Turn): Promise<void> {\n const understand = this.understand;\n const llm = this.llm();\n if (!understand || !llm) return;\n this.coordinationEpoch = this.currentEpoch();\n this.coordinationStepCount = 0;\n this.coordinationRunId = crypto.randomUUID();\n await this.conversation.pushGeneration({\n id: this.coordinationRunId,\n conversationId: this.conversation.id,\n agentName: this.agents()[0]!.name,\n text: \"\",\n status: \"streaming\",\n startedAt: Date.now(),\n });\n\n try {\n // The current turn is already in history, so no separate input message.\n const output = await understand.run();\n await this.finalizeOutput(String(output));\n } catch (error) {\n if (error instanceof CoordinationSuspension) {\n await this.recordSuspension(error);\n } else if (error instanceof CoordinationCancelled) {\n // Discarded by an interrupt \u2014 nothing to finalize.\n } else {\n this.emitError(error);\n }\n }\n }\n\n /**\n * Resume a parked coordination with the user's answer, propagating the\n * result back up the frame stack to the outermost coordination.\n */\n async resume(turn: Turn): Promise<void> {\n const pending = this.pendingExecution;\n if (!pending) return;\n this.pendingExecution = null;\n this.coordinationEpoch = this.currentEpoch();\n this.coordinationStepCount = pending.stepCount;\n this.coordinationRunId = crypto.randomUUID();\n await this.conversation.pushGeneration({\n id: this.coordinationRunId,\n conversationId: this.conversation.id,\n agentName: this.agents()[0]!.name,\n text: \"\",\n status: \"streaming\",\n startedAt: Date.now(),\n });\n\n const frames = [...pending.frames]; // outermost first\n const innermost = frames.pop();\n if (!innermost) return;\n\n let result: unknown;\n try {\n result = await innermost.coordination.resume(innermost.state, turn.text);\n } catch (error) {\n if (error instanceof CoordinationSuspension) {\n error.frames.unshift(...frames);\n await this.recordSuspension(error);\n } else if (!(error instanceof CoordinationCancelled)) {\n this.emitError(error);\n }\n return;\n }\n\n // Feed the result back into each remaining parent frame, innermost first.\n while (frames.length > 0) {\n const parent = frames.pop()!;\n const toolCallId = parent.state.pendingToolCallId ?? crypto.randomUUID();\n try {\n result = await parent.coordination.continueWith(parent.state, {\n role: \"tool\",\n toolCallId,\n name: \"delegate\",\n content: JSON.stringify(result),\n });\n } catch (error) {\n if (error instanceof CoordinationSuspension) {\n error.frames.unshift(...frames);\n await this.recordSuspension(error);\n } else if (!(error instanceof CoordinationCancelled)) {\n this.emitError(error);\n }\n return;\n }\n }\n\n await this.finalizeOutput(String(result));\n }\n\n /**\n * The runtime the coordinations reason against. Binds the coordination\n * primitives (delegate to agents, ask the user, speech, budget, cancellation)\n * to the runner's machinery without coupling `Coordination` to it.\n */\n runtime(): CoordinationRuntime {\n const runner = this;\n return {\n // Getters: read the current state at call time (the coordinations are\n // built after the runtime object is created).\n get agents() {\n return runner.agents();\n },\n get coordinations() {\n return Object.values(runner.coordinations);\n },\n get llm() {\n return runner.llm()!;\n },\n get history() {\n return runner.history.windowed(runner.historyWindow);\n },\n delegateAgentTasks: (tasks) => this.delegateAgentTasks(tasks),\n askUser: (frame, question) => this.askUser(frame, question),\n onDelta: (delta) => this.speech.feed(delta, this.currentEpoch()),\n flushSpeech: () => this.speech.flush(this.currentEpoch()),\n speak: (sentence) => this.speech.speak(sentence, this.currentEpoch()),\n isCancelled: () => this.currentEpoch() !== this.coordinationEpoch,\n checkBudget: () => this.checkBudget(),\n };\n }\n\n /** Complete the current generation and record the coordination's answer. */\n private async finalizeOutput(text: string): Promise<void> {\n this.speech.flush(this.currentEpoch());\n await this.speech.waitForIdle();\n if (this.currentEpoch() !== this.coordinationEpoch) return;\n await this.conversation.completeGeneration(text);\n await this.conversation.pushTranscript({\n speaker: this.agents()[0]!.name,\n speakerKind: \"agent\",\n text,\n });\n this.history.addAssistant(this.agents()[0]!.name, text);\n }\n\n /** Park a suspended coordination: record the question and store the stack. */\n private async recordSuspension(suspension: CoordinationSuspension): Promise<void> {\n await this.conversation.completeGeneration(suspension.question);\n await this.conversation.pushTranscript({\n speaker: this.agents()[0]!.name,\n speakerKind: \"agent\",\n text: suspension.question,\n });\n this.history.addAssistant(this.agents()[0]!.name, suspension.question);\n this.pendingExecution = {\n frames: suspension.frames,\n question: suspension.question,\n stepCount: this.coordinationStepCount,\n };\n }\n\n /** Throw the suspension that parks a coordination waiting for the user. */\n private askUser(frame: PendingFrame, question: string): never {\n // Recording (transcript, history, generation) happens when the suspension\n // is caught at the top of the stack, where the full frame set is known.\n throw new CoordinationSuspension([frame], question);\n }\n\n /** Enforce the per-execution reasoning step budget. */\n private checkBudget(): void {\n this.coordinationStepCount++;\n if (this.coordinationStepCount > this.maxCoordinationSteps) {\n throw new CoordinationBudgetExceeded(\n `exceeded ${this.maxCoordinationSteps} coordination steps`,\n );\n }\n }\n\n private emitError(error: unknown): void {\n this.conversation.emit(\"error\", {\n conversationId: this.conversation.id,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n // Finalize the current coordination generation so an errored run does not\n // leave a dangling \"streaming\" record. The narration was streamed to\n // speech; the failure surfaces through the error event.\n if (this.currentEpoch() === this.coordinationEpoch) {\n void this.conversation.completeGeneration(\"\");\n }\n }\n\n /** Run delegated agent tasks in parallel and surface their work. */\n private async delegateAgentTasks(tasks: DelegatedTask[]): Promise<DelegationResult[]> {\n const results = await Promise.all(\n tasks.map((task) =>\n this.runSubGeneration(this.coordinationEpoch, task, this.coordinationRunId),\n ),\n );\n\n if (!this.isCurrent(this.coordinationEpoch)) {\n return results.map(({ agent, text, error }) => ({ agent, text, error }));\n }\n\n // Surface each specialist's work in the transcript, in task order.\n for (const result of results) {\n if (result.text && !result.error) {\n await this.conversation.pushTranscript({\n speaker: result.agent,\n speakerKind: \"agent\",\n text: result.text,\n });\n }\n }\n return results;\n }\n\n /**\n * Execute one dispatched task as a sub-generation: the target agent's own\n * LLM, context, and tools, running text-only (no TTS). The final text is\n * returned so the coordinator can merge it into the spoken answer.\n */\n private async runSubGeneration(\n epoch: number,\n task: DelegatedTask,\n parentGenerationId: string,\n ): Promise<DelegationResult> {\n const agent = findAgentByName(this.agents(), task.agent);\n if (!agent) {\n return { agent: task.agent, text: \"\", error: `Unknown agent \"${task.agent}\"` };\n }\n const llm = agent.llm ?? this.llm();\n if (!llm) {\n return {\n agent: agent.name,\n text: \"\",\n error: `Agent \"${agent.name}\" has no LLM configured`,\n };\n }\n\n const id = crypto.randomUUID();\n await this.conversation.pushSubGeneration({\n id,\n conversationId: this.conversation.id,\n agentName: agent.name,\n text: \"\",\n status: \"streaming\",\n startedAt: Date.now(),\n kind: \"sub\",\n parentGenerationId,\n });\n\n const definitions: LLMToolDefinition[] = agent.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters ?? { type: \"object\", properties: {} },\n }));\n\n const messages: LLMMessage[] = [];\n if (agent.context) {\n messages.push({ role: \"system\", name: agent.name, content: agent.context });\n }\n messages.push(...this.history.windowed(this.historyWindow));\n // The prompt carries a time stamp so time-sensitive tasks (flights,\n // meetings, deadlines) don't reason about a stale \"now\".\n messages.push({ role: \"user\", content: `${task.prompt}\\n\\n${formatTimeContext()}` });\n\n const outcome = await this.generation.run({\n agentName: agent.name,\n llm,\n messages,\n tools: definitions,\n temperature: this.temperature,\n maxTokens: this.maxTokens,\n maxToolIterations: this.maxToolIterations,\n isCurrent: () => this.isCurrent(epoch),\n onDelta: (delta, textBefore) => {\n if (textBefore.length === 0) this.conversation.noteTiming(\"firstToken\", id);\n },\n resolveToolCalls: (calls) => this.tools.resolveCalls(calls),\n });\n\n if (!this.isCurrent(epoch) || outcome.status === \"interrupted\") {\n await this.conversation.cancelSubGeneration(id);\n return { agent: agent.name, text: \"\", error: \"interrupted\" };\n }\n\n await this.conversation.completeSubGeneration(id, outcome.text);\n if (outcome.status === \"error\") {\n this.conversation.emit(\"error\", {\n conversationId: this.conversation.id,\n error: outcome.error instanceof Error ? outcome.error : new Error(String(outcome.error)),\n });\n return {\n agent: agent.name,\n text: outcome.text,\n error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),\n };\n }\n return { agent: agent.name, text: outcome.text };\n }\n}\n"],
5
+ "mappings": "4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,IAAA,eAAAC,EAAAH,GAIA,IAAAI,EAUO,2CACPC,EAAuD,8BACvDC,EAAuD,8BA4ChD,MAAMC,CAAmB,CA5DhC,MA4DgC,CAAAC,EAAA,2BAErB,cAA8C,CAAC,EAExD,WAAkC,KAEjB,aACA,OACA,IACA,QACA,cACA,OACA,WACA,MACA,qBACA,kBACA,YACA,UACA,aACA,UAET,kBAAoB,EACpB,sBAAwB,EACxB,kBAAoB,GACpB,iBAA4C,KAEpD,YAAYC,EAAoC,CAC9C,KAAK,aAAeA,EAAQ,aAC5B,KAAK,OAASA,EAA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sB,EAAOc,IAAe,CAC1BA,EAAW,SAAW,GAAG,KAAK,aAAa,WAAW,aAAcL,CAAE,CAC5E,EAFS,WAGT,iBAAkB/B,EAACqC,GAAU,KAAK,MAAM,aAAaA,CAAK,EAAxC,mBACpB,CAAC,EAED,MAAI,CAAC,KAAK,UAAUR,CAAK,GAAKM,EAAQ,SAAW,eAC/C,MAAM,KAAK,aAAa,oBAAoBJ,CAAE,EACvC,CAAE,MAAOH,EAAM,KAAM,KAAM,GAAI,MAAO,aAAc,IAG7D,MAAM,KAAK,aAAa,sBAAsBG,EAAII,EAAQ,IAAI,EAC1DA,EAAQ,SAAW,SACrB,KAAK,aAAa,KAAK,QAAS,CAC9B,eAAgB,KAAK,aAAa,GAClC,MAAOA,EAAQ,iBAAiB,MAAQA,EAAQ,MAAQ,IAAI,MAAM,OAAOA,EAAQ,KAAK,CAAC,CACzF,CAAC,EACM,CACL,MAAOP,EAAM,KACb,KAAMO,EAAQ,KACd,MAAOA,EAAQ,iBAAiB,MAAQA,EAAQ,MAAM,QAAU,OAAOA,EAAQ,KAAK,CACtF,GAEK,CAAE,MAAOP,EAAM,KAAM,KAAMO,EAAQ,IAAK,EACjD,CACF",
6
+ "names": ["coordination_runner_exports", "__export", "CoordinationRunner", "__toCommonJS", "import_coordination", "import_history", "import_routing", "CoordinationRunner", "__name", "options", "registrations", "agents", "merged", "name", "registration", "turn", "understand", "llm", "output", "error", "pending", "frames", "innermost", "result", "parent", "toolCallId", "runner", "tasks", "frame", "question", "delta", "sentence", "text", "suspension", "results", "task", "agent", "epoch", "parentGenerationId", "id", "definitions", "tool", "messages", "outcome", "textBefore", "calls"]
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var t=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var d=Object.getOwnPropertyNames;var u=Object.prototype.hasOwnProperty;var f=(n,o)=>{for(var i in o)t(n,i,{get:o[i],enumerable:!0})},m=(n,o,i,e)=>{if(o&&typeof o=="object"||typeof o=="function")for(let r of d(o))!u.call(n,r)&&r!==i&&t(n,r,{get:()=>o[r],enumerable:!(e=a(o,r))||e.enumerable});return n};var x=n=>m(t({},"__esModule",{value:!0}),n);var C={};f(C,{CoordinationRunner:()=>p.CoordinationRunner});module.exports=x(C);var p=require("./coordination-runner.js");
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/conversations/orchestration/orchestrator/coordination-runner/index.ts"],
4
+ "sourcesContent": ["export { CoordinationRunner } from \"./coordination-runner\";\nexport type { CoordinationRunnerOptions } from \"./coordination-runner\";\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,8DAAAE,EAAAF,GAAA,IAAAG,EAAmC",
6
+ "names": ["coordination_runner_exports", "__export", "__toCommonJS", "import_coordination_runner"]
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var c=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var d=(o,e)=>c(o,"name",{value:e,configurable:!0});var w=(o,e)=>{for(var t in e)c(o,t,{get:e[t],enumerable:!0})},G=(o,e,t,l)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of k(e))!v.call(o,r)&&r!==t&&c(o,r,{get:()=>e[r],enumerable:!(l=y(e,r))||l.enumerable});return o};var N=o=>G(c({},"__esModule",{value:!0}),o);var I={};w(I,{GenerationRunner:()=>R});module.exports=N(I);class R{static{d(this,"GenerationRunner")}async run(e){const{agentName:t,llm:l,messages:r,tools:L,temperature:g,maxTokens:M,maxToolIterations:T,isCurrent:i,agentNames:b=!0,onDelta:x,resolveToolCalls:C}=e;let s="",f=0;try{for(let u=0;u<T;u++){if(!i())return{text:s,status:"interrupted"};const m=[];let p=!1;const h=b?r:D(r);for await(const n of l.stream({messages:h,tools:L,temperature:g,maxTokens:M})){if(!i())return{text:s,status:"interrupted"};switch(n.type){case"delta":{const a=s;s+=n.content,n.content.length>0&&x?.(n.content,a);break}case"tool_call":m.push({id:n.id,name:n.name,arguments:n.arguments});break;case"error":throw n.error;case"done":p=!0}}if(!i())return{text:s,status:"interrupted"};if(m.length>0){f++,r.push({role:"assistant",name:t,content:s,toolCalls:m});const n=await C(m);if(!i())return{text:s,status:"interrupted"};for(const a of n)r.push({role:"tool",toolCallId:a.id,name:a.name,content:JSON.stringify(a.error!==void 0?{error:a.error}:a.result)});continue}if(p)break}return{text:s,status:"done"}}catch(u){return{text:s,status:"error",error:u,...f>0?{toolRounds:f}:{}}}}}function D(o){let e=!1;for(const t of o)if(t.name&&(t.role==="system"||t.role==="assistant")){e=!0;break}return e?o.map(t=>t.name&&(t.role==="system"||t.role==="assistant")?{...t,name:void 0}:t):o}d(D,"withoutAgentNames");
2
+ //# sourceMappingURL=generation.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/conversations/orchestration/orchestrator/generation/generation.ts"],
4
+ "sourcesContent": ["import type {\n LLM,\n LLMToolCall,\n LLMToolDefinition,\n LLMMessage,\n} from \"../../../../providers/llm/types\";\nimport type { ResolvedToolCall } from \"../tools/tools\";\n\nexport interface GenerationRequest {\n /** Display name stamped on assistant tool-call messages. */\n agentName: string;\n llm: LLM;\n /**\n * The conversation messages; the loop appends the assistant tool-call\n * message and the resolved tool results onto this array.\n */\n messages: LLMMessage[];\n tools: LLMToolDefinition[];\n temperature?: number;\n maxTokens?: number;\n /** Safety bound on tool-call round trips per generation. */\n maxToolIterations: number;\n /** False once the run is stale (interrupt/stop); aborts the loop. */\n isCurrent(): boolean;\n /**\n * Whether outgoing messages keep per-agent `name` fields on system and\n * assistant messages. Multi-agent conversations need them so the model can\n * tell which agent said what in the shared history. Single-agent\n * conversations drop them: with one agent the names carry no information,\n * and some providers render a message `name` as a role header (\"Scout:\")\n * that weaker models imitate \u2014 every reply then starts by speaking the\n * agent's name. Default true.\n */\n agentNames?: boolean;\n /** Streamed text; `textBefore` is the running text prior to this delta. */\n onDelta?(delta: string, textBefore: string): void;\n /** Hand tool calls to the application and resolve their results. */\n resolveToolCalls(calls: LLMToolCall[]): Promise<ResolvedToolCall[]>;\n}\n\nexport type GenerationStatus = \"done\" | \"interrupted\" | \"error\";\n\nexport interface GenerationOutcome {\n /** Everything the model produced (or produced before failing). */\n text: string;\n status: GenerationStatus;\n /** The provider error, when `status` is \"error\". */\n error?: unknown;\n /**\n * How many tool rounds were resolved before the run ended (only present\n * when at least one). Lets callers retry a no-output failure safely:\n * re-running a generation whose tools already executed would repeat their\n * side effects.\n */\n toolRounds?: number;\n}\n\n/**\n * Owns the LLM tool loop shared by top-level generations and delegated\n * sub-generations: stream deltas, collect tool calls, resolve them through\n * the application, and repeat up to `maxToolIterations`.\n *\n * It is deliberately ignorant of the conversation lifecycle \u2014 persistence,\n * transcripts, speech, and history are the caller's concern, decided from\n * the returned `GenerationOutcome`.\n */\nexport class GenerationRunner {\n async run(request: GenerationRequest): Promise<GenerationOutcome> {\n const {\n agentName,\n llm,\n messages,\n tools,\n temperature,\n maxTokens,\n maxToolIterations,\n isCurrent,\n agentNames = true,\n onDelta,\n resolveToolCalls,\n } = request;\n\n let text = \"\";\n let toolRounds = 0;\n\n try {\n for (let iteration = 0; iteration < maxToolIterations; iteration++) {\n if (!isCurrent()) return { text, status: \"interrupted\" };\n\n const toolCalls: LLMToolCall[] = [];\n let done = false;\n\n // Single-agent conversations don't need per-agent `name` fields (see\n // GenerationRequest.agentNames): strip them before every call, since\n // the tool loop appends fresh messages between iterations. Never\n // mutate the caller's array.\n const wireMessages = agentNames ? messages : withoutAgentNames(messages);\n\n for await (const event of llm.stream({ messages: wireMessages, tools, temperature, maxTokens })) {\n if (!isCurrent()) return { text, status: \"interrupted\" };\n switch (event.type) {\n case \"delta\": {\n const before = text;\n text += event.content;\n if (event.content.length > 0) onDelta?.(event.content, before);\n break;\n }\n case \"tool_call\":\n toolCalls.push({ id: event.id, name: event.name, arguments: event.arguments });\n break;\n case \"error\":\n throw event.error;\n case \"done\":\n done = true;\n }\n }\n\n if (!isCurrent()) return { text, status: \"interrupted\" };\n\n if (toolCalls.length > 0) {\n toolRounds++;\n // Pause the response: hand the calls to the application, then\n // resume once they are resolved.\n messages.push({ role: \"assistant\", name: agentName, content: text, toolCalls });\n const results = await resolveToolCalls(toolCalls);\n if (!isCurrent()) return { text, status: \"interrupted\" };\n for (const result of results) {\n messages.push({\n role: \"tool\",\n toolCallId: result.id,\n name: result.name,\n content: JSON.stringify(\n result.error !== undefined ? { error: result.error } : result.result,\n ),\n });\n }\n continue;\n }\n\n if (done) break;\n }\n\n return { text, status: \"done\" };\n } catch (error) {\n return {\n text,\n status: \"error\",\n error,\n ...(toolRounds > 0 ? { toolRounds } : {}),\n };\n }\n }\n}\n\n/**\n * Clone the messages with per-agent `name` fields removed from system and\n * assistant messages. Tool messages keep their `name` (the wire format\n * requires it on `role: \"tool\"`), and user messages never carry one.\n */\nfunction withoutAgentNames(messages: LLMMessage[]): LLMMessage[] {\n let hasNames = false;\n for (const message of messages) {\n if (message.name && (message.role === \"system\" || message.role === \"assistant\")) {\n hasNames = true;\n break;\n }\n }\n if (!hasNames) return messages;\n return messages.map((message) =>\n message.name && (message.role === \"system\" || message.role === \"assistant\")\n ? { ...message, name: undefined }\n : message,\n );\n}\n"],
5
+ "mappings": "4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,IAAA,eAAAC,EAAAH,GAkEO,MAAMI,CAAiB,CAlE9B,MAkE8B,CAAAC,EAAA,yBAC5B,MAAM,IAAIC,EAAwD,CAChE,KAAM,CACJ,UAAAC,EACA,IAAAC,EACA,SAAAC,EACA,MAAAC,EACA,YAAAC,EACA,UAAAC,EACA,kBAAAC,EACA,UAAAC,EACA,WAAAC,EAAa,GACb,QAAAC,EACA,iBAAAC,CACF,EAAIX,EAEJ,IAAIY,EAAO,GACPC,EAAa,EAEjB,GAAI,CACF,QAASC,EAAY,EAAGA,EAAYP,EAAmBO,IAA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O,CAChC,OAASW,EAAO,CACd,MAAO,CACL,KAAAX,EACA,OAAQ,QACR,MAAAW,EACA,GAAIV,EAAa,EAAI,CAAE,WAAAA,CAAW,EAAI,CAAC,CACzC,CACF,CACF,CACF,CAOA,SAASK,EAAkBf,EAAsC,CAC/D,IAAIqB,EAAW,GACf,UAAWC,KAAWtB,EACpB,GAAIsB,EAAQ,OAASA,EAAQ,OAAS,UAAYA,EAAQ,OAAS,aAAc,CAC/ED,EAAW,GACX,KACF,CAEF,OAAKA,EACErB,EAAS,IAAKsB,GACnBA,EAAQ,OAASA,EAAQ,OAAS,UAAYA,EAAQ,OAAS,aAC3D,CAAE,GAAGA,EAAS,KAAM,MAAU,EAC9BA,CACN,EALsBtB,CAMxB,CAdSJ,EAAAmB,EAAA",
6
+ "names": ["generation_exports", "__export", "GenerationRunner", "__toCommonJS", "GenerationRunner", "__name", "request", "agentName", "llm", "messages", "tools", "temperature", "maxTokens", "maxToolIterations", "isCurrent", "agentNames", "onDelta", "resolveToolCalls", "text", "toolRounds", "iteration", "toolCalls", "done", "wireMessages", "withoutAgentNames", "event", "before", "results", "result", "error", "hasNames", "message"]
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var r=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var p=(n,e)=>{for(var o in e)r(n,o,{get:e[o],enumerable:!0})},f=(n,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of G(e))!m.call(n,t)&&t!==o&&r(n,t,{get:()=>e[t],enumerable:!(a=u(e,t))||a.enumerable});return n};var s=n=>f(r({},"__esModule",{value:!0}),n);var x={};p(x,{GenerationRunner:()=>i.GenerationRunner});module.exports=s(x);var i=require("./generation.js");
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/conversations/orchestration/orchestrator/generation/index.ts"],
4
+ "sourcesContent": ["export { GenerationRunner } from \"./generation\";\nexport type {\n GenerationOutcome,\n GenerationRequest,\n GenerationStatus,\n} from \"./generation\";\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,0DAAAE,EAAAF,GAAA,IAAAG,EAAiC",
6
+ "names": ["generation_exports", "__export", "__toCommonJS", "import_generation"]
7
+ }
@@ -0,0 +1,4 @@
1
+ "use strict";var u=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var h=Object.prototype.hasOwnProperty;var o=(s,t)=>u(s,"name",{value:t,configurable:!0});var y=(s,t)=>{for(var n in t)u(s,n,{get:t[n],enumerable:!0})},M=(s,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of f(t))!h.call(s,r)&&r!==n&&u(s,r,{get:()=>t[r],enumerable:!(a=m(t,r))||a.enumerable});return s};var $=s=>M(u({},"__esModule",{value:!0}),s);var w={};y(w,{ConversationHistory:()=>v,formatTimeContext:()=>d,formatTurnContext:()=>l,windowHistory:()=>g});module.exports=$(w);const x=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];function d(s=new Date){const t=s.getDate(),n=x[s.getMonth()],a=s.getFullYear(),r=String(s.getHours()).padStart(2,"0"),e=String(s.getMinutes()).padStart(2,"0");return`Now it is ${t} ${n} ${a}, ${r}:${e}.`}o(d,"formatTimeContext");function l(s,t,n=new Date){const a=o(i=>{const c=i.aliases[0]??i.userId,p=i.aliases.length>0?` (aliases: ${i.aliases.join(", ")})`:"";return`${c} with user id ${i.userId}${p}`},"describe"),r=t.filter(i=>i.userId!==s.userId),e=r.length>0?` The other participants are ${r.map(a).join(", ")}.`:"";return`
2
+
3
+ Additional context: ${d(n)} The current user is ${a(s)}.${e}`}o(l,"formatTurnContext");function g(s,{maxTurns:t,maxChars:n}){if(s.length===0)return s;let a=0,r=0;for(let i=s.length-1;i>=0;i--)if(s[i].role==="user"&&(r++,r===t)){a=i;break}let e=a>0?s.slice(a):s;if(n>0)for(;e.length>1&&e.reduce((i,c)=>i+c.content.length,0)>n;)e=e.slice(1);return e}o(g,"windowHistory");class v{static{o(this,"ConversationHistory")}messages=[];turnMessage(t,n){const a=n.state.participants.get(t.participantId),r=[...n.state.participants.values()],e=a?l(a,r,new Date(t.startedAt)):"";return`${t.participantName}: ${t.text}${e}`}addUserTurn(t,n){this.messages.push({role:"user",content:this.turnMessage(t,n)})}addAssistant(t,n){this.messages.push({role:"assistant",name:t,content:n})}rehydrate(t,n,a){const r=[...t.map(e=>({at:e.startedAt,kind:"turn",turn:e})),...n.filter(e=>e.status==="completed"&&e.kind!=="sub").map(e=>({at:e.startedAt,kind:"generation",agentName:e.agentName,text:e.text}))].sort((e,i)=>e.at-i.at);for(const e of r)e.kind==="turn"?this.addUserTurn(e.turn,a):this.addAssistant(e.agentName,e.text)}get all(){return this.messages}windowed(t){return t===!1?this.messages:g(this.messages,t)}}
4
+ //# sourceMappingURL=history.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/conversations/orchestration/orchestrator/history/history.ts"],
4
+ "sourcesContent": ["import type { Conversation } from \"../../../conversation/conversation\";\nimport type { Generation, Participant, Turn } from \"../../../types\";\nimport type { LLMMessage } from \"../../../../providers/llm/types\";\n\nconst MONTHS = [\n \"jan\",\n \"feb\",\n \"mar\",\n \"apr\",\n \"may\",\n \"jun\",\n \"jul\",\n \"aug\",\n \"sep\",\n \"oct\",\n \"nov\",\n \"dec\",\n];\n\n/**\n * A human-readable \"now\" stamp appended to dispatched prompts so\n * time-sensitive tasks (flights, meetings, deadlines) have temporal context.\n */\nexport function formatTimeContext(date = new Date()): string {\n const day = date.getDate();\n const month = MONTHS[date.getMonth()]!;\n const year = date.getFullYear();\n const hours = String(date.getHours()).padStart(2, \"0\");\n const minutes = String(date.getMinutes()).padStart(2, \"0\");\n return `Now it is ${day} ${month} ${year}, ${hours}:${minutes}.`;\n}\n\n/**\n * A short context suffix appended automatically to every user turn, so the\n * model knows the time and who is speaking (and who else is in the\n * conversation) \u2014 e.g. \"enhance the message I just sent\" resolves to a real\n * user id. Applied once, when the turn enters history; every generation path\n * (direct, coordination, delegated) seeds from that history.\n */\nexport function formatTurnContext(\n participant: Participant,\n participants: readonly Participant[],\n date = new Date(),\n): string {\n const describe = (p: Participant): string => {\n const displayName = p.aliases[0] ?? p.userId;\n const aliases = p.aliases.length > 0 ? ` (aliases: ${p.aliases.join(\", \")})` : \"\";\n return `${displayName} with user id ${p.userId}${aliases}`;\n };\n const others = participants.filter((p) => p.userId !== participant.userId);\n const othersLine =\n others.length > 0\n ? ` The other participants are ${others.map(describe).join(\", \")}.`\n : \"\";\n return `\\n\\nAdditional context: ${formatTimeContext(date)} The current user is ${describe(participant)}.${othersLine}`;\n}\n\n/** How much conversational history an LLM request may carry. */\nexport interface HistoryWindow {\n /** Keep at most this many user turns (the current turn is always kept). */\n maxTurns: number;\n /** Drop oldest whole messages until the window fits this many characters. */\n maxChars: number;\n}\n\n/**\n * Bounds conversation history for an LLM request: keep the most recent\n * `maxTurns` user turns (plus anything after them), then drop oldest whole\n * messages until the window fits `maxChars`. The current turn is the last\n * user message and always survives. Provider TTFT grows with input size, so\n * a bounded window keeps requests in the fast regime.\n */\nexport function windowHistory(\n history: LLMMessage[],\n { maxTurns, maxChars }: HistoryWindow,\n): LLMMessage[] {\n if (history.length === 0) return history;\n\n let start = 0;\n let userSeen = 0;\n for (let i = history.length - 1; i >= 0; i--) {\n if (history[i]!.role === \"user\") {\n userSeen++;\n if (userSeen === maxTurns) {\n start = i;\n break;\n }\n }\n }\n let windowed = start > 0 ? history.slice(start) : history;\n\n if (maxChars > 0) {\n while (\n windowed.length > 1 &&\n windowed.reduce((sum, message) => sum + message.content.length, 0) > maxChars\n ) {\n windowed = windowed.slice(1);\n }\n }\n return windowed;\n}\n\n/**\n * The conversation's LLM message log: every user turn and agent reply, plus\n * the turn-context formatting and windowing applied when a request is built.\n * The orchestrator's `Conversation` remains the source of truth for turns,\n * transcripts, and generations \u2014 this is the derived prompt log only.\n */\nexport class ConversationHistory {\n private readonly messages: LLMMessage[] = [];\n\n /**\n * The user-message form of a turn: display name, text, and the automatic\n * context suffix (time + speaker + roster) baked in at history time.\n */\n turnMessage(turn: Turn, conversation: Conversation): string {\n const participant = conversation.state.participants.get(turn.participantId);\n const participants = [...conversation.state.participants.values()];\n const context = participant\n ? formatTurnContext(participant, participants, new Date(turn.startedAt))\n : \"\";\n return `${turn.participantName}: ${turn.text}${context}`;\n }\n\n /** Append a participant turn as a user message. */\n addUserTurn(turn: Turn, conversation: Conversation): void {\n this.messages.push({ role: \"user\", content: this.turnMessage(turn, conversation) });\n }\n\n /** Append an agent reply as an assistant message. */\n addAssistant(agentName: string, text: string): void {\n this.messages.push({ role: \"assistant\", name: agentName, content: text });\n }\n\n /**\n * Rehydrate from persisted turns and completed top-level generations.\n * Sub-generations are summarized inside the coordinator's own answer, so\n * only top-level responses rehydrate into history.\n */\n rehydrate(\n turns: readonly Turn[],\n generations: readonly Generation[],\n conversation: Conversation,\n ): void {\n const entries: Array<\n | { at: number; kind: \"turn\"; turn: Turn }\n | { at: number; kind: \"generation\"; agentName: string; text: string }\n > = [\n ...turns.map((turn) => ({ at: turn.startedAt, kind: \"turn\" as const, turn })),\n ...generations\n .filter(\n (generation) =>\n generation.status === \"completed\" && generation.kind !== \"sub\",\n )\n .map((generation) => ({\n at: generation.startedAt,\n kind: \"generation\" as const,\n agentName: generation.agentName,\n text: generation.text,\n })),\n ].sort((a, b) => a.at - b.at);\n\n for (const entry of entries) {\n if (entry.kind === \"turn\") {\n this.addUserTurn(entry.turn, conversation);\n } else {\n this.addAssistant(entry.agentName, entry.text);\n }\n }\n }\n\n /** The full message log. */\n get all(): readonly LLMMessage[] {\n return this.messages;\n }\n\n /**\n * The message log bounded for an LLM request: the full log when `window`\n * is `false`, otherwise the bounded window.\n */\n windowed(window: HistoryWindow | false): LLMMessage[] {\n return window === false ? this.messages : windowHistory(this.messages, window);\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M,EACA,OACEE,GACCA,EAAW,SAAW,aAAeA,EAAW,OAAS,KAC7D,EACC,IAAKA,IAAgB,CACpB,GAAIA,EAAW,UACf,KAAM,aACN,UAAWA,EAAW,UACtB,KAAMA,EAAW,IACnB,EAAE,CACN,EAAE,KAAK,CAACC,EAAGC,IAAMD,EAAE,GAAKC,EAAE,EAAE,EAE5B,UAAWC,KAASJ,EACdI,EAAM,OAAS,OACjB,KAAK,YAAYA,EAAM,KAAMV,CAAY,EAEzC,KAAK,aAAaU,EAAM,UAAWA,EAAM,IAAI,CAGnD,CAGA,IAAI,KAA6B,CAC/B,OAAO,KAAK,QACd,CAMA,SAASC,EAA6C,CACpD,OAAOA,IAAW,GAAQ,KAAK,SAAWtB,EAAc,KAAK,SAAUsB,CAAM,CAC/E,CACF",
6
+ "names": ["history_exports", "__export", "ConversationHistory", "formatTimeContext", "formatTurnContext", "windowHistory", "__toCommonJS", "MONTHS", "formatTimeContext", "date", "day", "month", "year", "hours", "minutes", "__name", "formatTurnContext", "participant", "participants", "describe", "p", "displayName", "aliases", "others", "othersLine", "windowHistory", "history", "maxTurns", "maxChars", "start", "userSeen", "windowed", "sum", "message", "ConversationHistory", "turn", "conversation", "context", "agentName", "text", "turns", "generations", "entries", "generation", "a", "b", "entry", "window"]
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var e=Object.defineProperty;var s=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var a=Object.prototype.hasOwnProperty;var f=(r,o)=>{for(var n in o)e(r,n,{get:o[n],enumerable:!0})},w=(r,o,n,m)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of y(o))!a.call(r,i)&&i!==n&&e(r,i,{get:()=>o[i],enumerable:!(m=s(o,i))||m.enumerable});return r};var x=r=>w(e({},"__esModule",{value:!0}),r);var C={};f(C,{ConversationHistory:()=>t.ConversationHistory,formatTimeContext:()=>t.formatTimeContext,formatTurnContext:()=>t.formatTurnContext,windowHistory:()=>t.windowHistory});module.exports=x(C);var t=require("./history.js");
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/conversations/orchestration/orchestrator/history/index.ts"],
4
+ "sourcesContent": ["export {\n ConversationHistory,\n formatTimeContext,\n formatTurnContext,\n windowHistory,\n type HistoryWindow,\n} from \"./history\";\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sLAAAE,EAAAF,GAAA,IAAAG,EAMO",
6
+ "names": ["history_exports", "__export", "__toCommonJS", "import_history"]
7
+ }
@@ -1,2 +1,2 @@
1
- "use strict";var p=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var O=Object.prototype.hasOwnProperty;var f=(t,r)=>{for(var e in r)p(t,e,{get:r[e],enumerable:!0})},m=(t,r,e,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of h(r))!O.call(t,o)&&o!==e&&p(t,o,{get:()=>r[o],enumerable:!(s=c(r,o))||s.enumerable});return t};var x=t=>m(p({},"__esModule",{value:!0}),t);var i={};f(i,{Orchestrator:()=>a.Orchestrator});module.exports=x(i);var a=require("./orchestrator.js");
1
+ "use strict";var p=Object.defineProperty;var l=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var u=(t,o)=>{for(var i in o)p(t,i,{get:o[i],enumerable:!0})},C=(t,o,i,a)=>{if(o&&typeof o=="object"||typeof o=="function")for(let n of y(o))!c.call(t,n)&&n!==i&&p(t,n,{get:()=>o[n],enumerable:!(a=l(o,n))||a.enumerable});return t};var h=t=>C(p({},"__esModule",{value:!0}),t);var O={};u(O,{ConversationHistory:()=>e.ConversationHistory,CoordinationRunner:()=>x.CoordinationRunner,GenerationRunner:()=>s.GenerationRunner,Orchestrator:()=>m.Orchestrator,SpeechPipeline:()=>f.SpeechPipeline,ToolCallManager:()=>d.ToolCallManager,buildUnderstandPrompt:()=>r.buildUnderstandPrompt,findAddressedAgent:()=>r.findAddressedAgent,findAgentByName:()=>r.findAgentByName,formatTimeContext:()=>e.formatTimeContext,formatTurnContext:()=>e.formatTurnContext,pickAgent:()=>r.pickAgent,windowHistory:()=>e.windowHistory});module.exports=h(O);var m=require("./orchestrator.js"),e=require("./history.js"),r=require("./routing.js"),s=require("./generation.js"),f=require("./speech.js"),d=require("./tools.js"),x=require("./coordination-runner.js");
2
2
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/conversations/orchestration/orchestrator/index.ts"],
4
- "sourcesContent": ["export { Orchestrator } from \"./orchestrator\";\nexport type { OrchestratorOptions } from \"./orchestrator\";\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kDAAAE,EAAAF,GAAA,IAAAG,EAA6B",
6
- "names": ["orchestrator_exports", "__export", "__toCommonJS", "import_orchestrator"]
4
+ "sourcesContent": ["export { Orchestrator } from \"./orchestrator\";\nexport type { OrchestratorOptions } from \"./orchestrator\";\n\n// Extracted execution domains. The orchestrator composes these; re-exporting\n// them keeps the folder's public surface under one roof.\nexport {\n ConversationHistory,\n formatTimeContext,\n formatTurnContext,\n windowHistory,\n type HistoryWindow,\n} from \"./history\";\nexport { buildUnderstandPrompt, findAddressedAgent, findAgentByName, pickAgent } from \"./routing\";\nexport { GenerationRunner } from \"./generation\";\nexport type { GenerationOutcome, GenerationRequest, GenerationStatus } from \"./generation\";\nexport { SpeechPipeline } from \"./speech\";\nexport type { SpeechPipelineOptions } from \"./speech\";\nexport { ToolCallManager } from \"./tools\";\nexport type { ResolvedToolCall } from \"./tools\";\nexport { CoordinationRunner } from \"./coordination-runner\";\nexport type { CoordinationRunnerOptions } from \"./coordination-runner\";\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,khBAAAE,EAAAF,GAAA,IAAAG,EAA6B,0BAK7BC,EAMO,qBACPC,EAAsF,qBACtFC,EAAiC,wBAEjCC,EAA+B,oBAE/BC,EAAgC,mBAEhCC,EAAmC",
6
+ "names": ["orchestrator_exports", "__export", "__toCommonJS", "import_orchestrator", "import_history", "import_routing", "import_generation", "import_speech", "import_tools", "import_coordination_runner"]
7
7
  }
@@ -1,3 +1,2 @@
1
- "use strict";var p=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var g=Object.prototype.hasOwnProperty;var m=(a,t)=>p(a,"name",{value:t,configurable:!0});var T=(a,t)=>{for(var e in t)p(a,e,{get:t[e],enumerable:!0})},y=(a,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of f(t))!g.call(a,s)&&s!==e&&p(a,s,{get:()=>t[s],enumerable:!(r=v(t,s))||r.enumerable});return a};var w=a=>y(p({},"__esModule",{value:!0}),a);var b={};T(b,{Orchestrator:()=>S});module.exports=w(b);class S{static{m(this,"Orchestrator")}conversation;agent;llm;stt;tts;persistence;toolTimeoutMs;maxToolIterations;temperature;maxTokens;started=!1;generating=!1;epoch=0;unsubscribers=[];sttSessions=new Map;history=[];toolWaiters=new Map;generationChain=Promise.resolve();speechChain=Promise.resolve();speechBuffer="";pendingTurns=0;pendingGenerations=0;audioSequence=0;turnSequence=0;constructor(t){const e=t.llm??t.agent?.llm;if(!t.stt)throw new Error("Orchestrator requires an STT provider");if(t.agent&&!e)throw new Error("Orchestrator requires an LLM when an agent is attached: pass one explicitly or configure the agent with one");if(t.agent&&!t.tts)throw new Error("Orchestrator requires a TTS provider when an agent is attached");this.conversation=t.conversation,this.agent=t.agent,this.llm=e,this.stt=t.stt,this.tts=t.tts,this.persistence=t.persistence,this.toolTimeoutMs=t.toolTimeoutMs??3e4,this.maxToolIterations=t.maxToolIterations??10,this.temperature=t.temperature,this.maxTokens=t.maxTokens}async start(){if(!this.started){if(this.started=!0,this.persistence){const[t,e]=await Promise.all([this.persistence.listTurns(this.conversation.id),this.persistence.listGenerations(this.conversation.id)]),r=[...t.map(s=>({at:s.startedAt,kind:"turn",turn:s})),...e.filter(s=>s.status==="completed").map(s=>({at:s.startedAt,kind:"generation",text:s.text}))].sort((s,i)=>s.at-i.at);for(const s of r)s.kind==="turn"?this.history.push({role:"user",content:`${s.turn.participantName}: ${s.turn.text}`}):this.history.push({role:"assistant",content:s.text})}this.unsubscribers.push(this.conversation.on("stop",()=>{this.stop()}),this.conversation.on("audio-in",t=>this.onAudioIn(t)),this.conversation.on("interrupt",()=>this.onInterrupt()),this.conversation.on("tool-call-result",t=>this.onToolCallResult(t.result)))}}async stop(){if(!this.started)return;this.started=!1,this.epoch++,this.llm?.stop(),this.tts?.stop(),this.cancelToolWaiters("conversation stopped"),this.speechBuffer="";for(const e of this.unsubscribers)e();this.unsubscribers.length=0;const t=[...this.sttSessions.values()];this.sttSessions.clear();for(const{session:e}of t)await e.end().catch(()=>{})}async whenIdle(){for(;;){for(;this.pendingTurns>0||this.pendingGenerations>0||this.generating;)await Bun.sleep(1);if(await Promise.resolve(),this.pendingTurns===0&&this.pendingGenerations===0&&!this.generating)return}}onAudioIn(t){let e=this.sttSessions.get(t.userId);if(!e){const r=this.stt.start({});r.on("partial",s=>this.onPartial(t.userId,s)),r.on("final",s=>this.onFinal(t.userId,s)),r.on("error",s=>this.onProviderError(s)),e={session:r,turnStartedAt:null},this.sttSessions.set(t.userId,e)}e.turnStartedAt===null&&(e.turnStartedAt=Date.now()),e.session.write(t.audio.data),this.pendingGenerations>0&&this.conversation.interrupt()}onPartial(t,e){const r=e.trim();r&&this.conversation.emit("partial-transcript",{conversationId:this.conversation.id,userId:t,text:r})}onFinal(t,e){const r=e.trim();if(!r)return;const s=this.conversation.state.participants.get(t);if(!s)return;const i=this.sttSessions.get(t),n=i?.turnStartedAt??Date.now();i&&(i.turnStartedAt=null);const o={id:crypto.randomUUID(),conversationId:this.conversation.id,participantId:t,participantName:s.aliases[0]??t,text:r,sequence:this.turnSequence++,startedAt:n,endedAt:Date.now()};this.pendingTurns++,this.processTurn(o)}async processTurn(t){try{await this.conversation.pushTurn(t),await this.conversation.pushTranscript({speaker:t.participantName,speakerKind:"participant",text:t.text}),this.history.push({role:"user",content:`${t.participantName}: ${t.text}`}),this.agent&&this.queueGeneration()}finally{this.pendingTurns--}}onInterrupt(){this.epoch++,this.llm?.stop(),this.tts?.stop(),this.cancelToolWaiters("interrupted"),this.speechBuffer=""}onToolCallResult(t){const e=this.toolWaiters.get(t.id);e&&(this.toolWaiters.delete(t.id),e(t))}onProviderError(t){this.conversation.emit("error",{conversationId:this.conversation.id,error:t})}queueGeneration(){this.pendingGenerations++;const t=this.epoch;this.generationChain=this.generationChain.then(async()=>{if(this.epoch!==t){this.pendingGenerations--;return}try{await this.generate()}finally{this.pendingGenerations--}})}async generate(){const{agent:t,llm:e,tts:r}=this;if(!(!t||!e||!r)){this.generating=!0;try{await this.runGeneration(this.epoch,t,e,r)}finally{this.generating=!1}}}async runGeneration(t,e,r,s){await this.conversation.pushGeneration({id:crypto.randomUUID(),conversationId:this.conversation.id,agentName:e.name,text:"",status:"streaming",startedAt:Date.now()});const i=e.tools.map(h=>({name:h.name,description:h.description,parameters:h.parameters??{type:"object",properties:{}}})),n=[];e.context&&n.push({role:"system",content:e.context}),n.push(...this.history);let o="";try{for(let h=0;h<this.maxToolIterations;h++){if(this.epoch!==t)return;const u=[];let d=!1;for await(const c of r.stream({messages:n,tools:i,temperature:this.temperature,maxTokens:this.maxTokens})){if(this.epoch!==t)return;switch(c.type){case"delta":o+=c.content,this.feedDelta(c.content);break;case"tool_call":u.push({id:c.id,name:c.name,arguments:c.arguments});break;case"error":throw c.error;case"done":d=!0}}if(this.epoch!==t)return;if(u.length>0){this.flushSpeech(),n.push({role:"assistant",content:o,toolCalls:u});const c=await this.resolveToolCalls(u,t);if(this.epoch!==t)return;for(const l of c)n.push({role:"tool",toolCallId:l.id,name:l.name,content:JSON.stringify(l.error!==void 0?{error:l.error}:l.result)});continue}if(d)break}if(this.epoch!==t||(this.flushSpeech(),await this.speechChain,this.epoch!==t))return;await this.conversation.completeGeneration(o),await this.conversation.pushTranscript({speaker:e.name,speakerKind:"agent",text:o}),this.history.push({role:"assistant",content:o})}catch(h){if(this.epoch!==t)return;this.conversation.emit("error",{conversationId:this.conversation.id,error:h instanceof Error?h:new Error(String(h))}),await this.conversation.completeGeneration(o),o&&(await this.conversation.pushTranscript({speaker:e.name,speakerKind:"agent",text:o}),this.history.push({role:"assistant",content:o}))}}async resolveToolCalls(t,e){const r=t.map(i=>this.waitForToolResult(i.id,e));for(const i of t){let n;try{n=JSON.parse(i.arguments)}catch{n=i.arguments}this.conversation.requestToolCall({id:i.id,name:i.name,arguments:n})}return(await Promise.all(r)).map((i,n)=>{const o=t[n];return{id:i.id,name:o.name,result:"result"in i?i.result:void 0,error:"error"in i?i.error:void 0}})}waitForToolResult(t,e){return new Promise(r=>{const s=setTimeout(()=>{this.toolWaiters.delete(t),r({id:t,error:`Tool call "${t}" timed out`})},this.toolTimeoutMs);this.toolWaiters.set(t,i=>{clearTimeout(s),r(i)})})}cancelToolWaiters(t){for(const[e,r]of[...this.toolWaiters])this.toolWaiters.delete(e),r({id:e,error:t})}feedDelta(t){for(this.speechBuffer+=t;;){let e=-1;for(let s=0;s<this.speechBuffer.length;s++){const i=this.speechBuffer[s];if(i==="."||i==="!"||i==="?"||i===`
2
- `){e=s;break}}if(e<0)break;const r=this.speechBuffer.slice(0,e+1).trim();this.speechBuffer=this.speechBuffer.slice(e+1),r&&this.speak(r)}}flushSpeech(){const t=this.speechBuffer.trim();this.speechBuffer="",t&&this.speak(t)}speak(t){const e=this.tts;if(!e)return;const r=this.epoch;this.speechChain=this.speechChain.then(async()=>{if(!(!this.started||this.epoch!==r))try{for await(const s of e.stream({text:t})){if(!this.started||this.epoch!==r)break;this.conversation.pushAudio({data:s,timestamp:Date.now(),sequence:this.audioSequence++})}}catch(s){if(this.epoch!==r)return;this.conversation.emit("error",{conversationId:this.conversation.id,error:s instanceof Error?s:new Error(String(s))})}})}}
1
+ "use strict";var p=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var a=(r,t)=>p(r,"name",{value:t,configurable:!0});var S=(r,t)=>{for(var e in t)p(r,e,{get:t[e],enumerable:!0})},C=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of w(t))!x.call(r,i)&&i!==e&&p(r,i,{get:()=>t[i],enumerable:!(n=T(t,i))||n.enumerable});return r};var I=r=>C(p({},"__esModule",{value:!0}),r);var P={};S(P,{Orchestrator:()=>L});module.exports=I(P);var m=require("./history/history.js"),l=require("./routing/routing.js"),v=require("./generation/generation.js"),g=require("./speech/speech.js"),f=require("./tools/tools.js"),y=require("./coordination-runner/coordination-runner.js");const b=1;function A(r){return r instanceof Error?/aborted the stream|timed out|idle timeout|\b(429|50[0-9])\b/i.test(r.message):!1}a(A,"isTransientProviderError");class L{static{a(this,"Orchestrator")}conversation;agents;llm;stt;tts;persistence;maxToolIterations;historyWindow;temperature;maxTokens;history;speech;tools;generation;coordination;started=!1;generating=!1;epoch=0;generationChain=Promise.resolve();unsubscribers=[];sttSessions=new Map;pendingTurns=0;pendingGenerations=0;turnSequence=0;constructor(t){const e=t.agents??[],n=t.llm??e[0]?.llm;if(e.length>0&&!n)throw new Error("Orchestrator requires an LLM when agents are attached: pass one explicitly or configure an agent with one");this.conversation=t.conversation,this.agents=e,this.llm=n,this.stt=t.stt,this.tts=t.tts,this.persistence=t.persistence,this.maxToolIterations=t.maxToolIterations??10,this.historyWindow=t.historyWindow??{maxTurns:5,maxChars:4e3},this.temperature=t.temperature,this.maxTokens=t.maxTokens,this.history=new m.ConversationHistory,this.speech=new g.SpeechPipeline({tts:this.tts,conversation:this.conversation,isCurrent:a(o=>this.started&&o===this.epoch,"isCurrent"),...t.maxConcurrentTtsRequests!==void 0?{maxConcurrentRequests:t.maxConcurrentTtsRequests}:{}});const i=new Map;for(const o of e)for(const h of o.tools)i.set(h.name,h);this.tools=new f.ToolCallManager(this.conversation,t.toolTimeoutMs??3e4,{tools:i,autoExecute:t.autoExecuteTools??!0}),this.generation=new v.GenerationRunner,this.coordination=new y.CoordinationRunner({conversation:this.conversation,agents:a(()=>this.agents,"agents"),llm:a(()=>this.llm,"llm"),history:this.history,historyWindow:this.historyWindow,speech:this.speech,generation:this.generation,tools:this.tools,maxCoordinationSteps:t.maxCoordinationSteps??20,maxToolIterations:this.maxToolIterations,temperature:this.temperature,maxTokens:this.maxTokens,currentEpoch:a(()=>this.epoch,"currentEpoch"),isCurrent:a(o=>this.started&&o===this.epoch,"isCurrent")}),this.coordination.register(t.coordinations??{},e)}async start(){if(!this.started){if(this.started=!0,this.persistence){const[t,e]=await Promise.all([this.persistence.listTurns(this.conversation.id),this.persistence.listGenerations(this.conversation.id)]);this.history.rehydrate(t,e,this.conversation)}this.unsubscribers.push(this.conversation.on("stop",()=>{this.stop()}),this.conversation.on("audio-in",t=>this.onAudioIn(t)),this.conversation.on("text-in",({userId:t,text:e})=>this.onFinal(t,e)),this.conversation.on("interrupt",()=>this.onInterrupt()),this.conversation.on("tool-call-result",({result:t})=>this.tools.handleResult(t)))}}async stop(){if(!this.started)return;this.started=!1,this.epoch++,this.coordination.cancel(),this.stopLlms(),this.speech.stop(),this.tools.cancelAll("conversation stopped");for(const e of this.unsubscribers)e();this.unsubscribers.length=0;const t=[...this.sttSessions.values()];this.sttSessions.clear();for(const{session:e}of t)await e.end().catch(()=>{})}async whenIdle(){for(;;){for(;this.pendingTurns>0||this.pendingGenerations>0||this.generating;)await Bun.sleep(1);if(await Promise.resolve(),this.pendingTurns===0&&this.pendingGenerations===0&&!this.generating)return}}onAudioIn(t){if(!this.stt)return;let e=this.sttSessions.get(t.userId);if(!e){const n=this.stt.start({});n.on("partial",i=>this.onPartial(t.userId,i)),n.on("final",i=>this.onFinal(t.userId,i)),n.on("error",i=>this.onProviderError(i)),e={session:n,turnStartedAt:null},this.sttSessions.set(t.userId,e)}if(e.turnStartedAt===null&&(e.turnStartedAt=Date.now()),e.session.write(t.audio.data),this.coordination.hasPending()){this.speech.stop();return}this.pendingGenerations>0&&this.conversation.interrupt()}onPartial(t,e){const n=e.trim();n&&this.conversation.emit("partial-transcript",{conversationId:this.conversation.id,userId:t,text:n})}onFinal(t,e){const n=e.trim();if(!n)return;const i=this.conversation.state.participants.get(t);if(!i)return;const o=this.sttSessions.get(t),h=o?.turnStartedAt??Date.now();o&&(o.turnStartedAt=null);const d={id:crypto.randomUUID(),conversationId:this.conversation.id,participantId:t,participantName:i.aliases[0]??t,text:n,sequence:this.turnSequence++,startedAt:h,endedAt:Date.now()};this.pendingTurns++,this.processTurn(d)}async processTurn(t){try{if(await this.conversation.pushTurn(t),await this.conversation.pushTranscript({speaker:t.participantName,speakerKind:"participant",text:t.text}),this.history.addUserTurn(t,this.conversation),this.agents.length===0)return;if(this.coordination.hasPending()){this.enqueueCoordinationRun(()=>this.coordination.resume(t));return}if(this.agents.length===1||(0,l.findAddressedAgent)(this.agents,t.text)){this.queueGeneration(t);return}this.enqueueCoordinationRun(()=>this.coordination.runDefault(t))}finally{this.pendingTurns--}}onInterrupt(){this.epoch++,this.coordination.cancel(),this.stopLlms(),this.speech.stop(),this.tools.cancelAll("interrupted")}stopLlms(){const t=new Set;this.llm&&t.add(this.llm);for(const e of this.agents)e.llm&&t.add(e.llm);for(const e of t)e.stop()}onProviderError(t){this.conversation.emit("error",{conversationId:this.conversation.id,error:t})}queueGeneration(t){this.pendingGenerations++;const e=this.epoch;this.generationChain=this.generationChain.then(async()=>{if(this.epoch!==e){this.pendingGenerations--;return}try{await this.generate(t)}finally{this.pendingGenerations--}})}async generate(t){if(this.agents.length===0)return;const e=(0,l.pickAgent)(this.agents,t.text);if(!e)return;const n=e.llm??this.llm;if(n){this.generating=!0;try{await this.runGeneration(this.epoch,t,e,n)}finally{this.generating=!1}}}async runGeneration(t,e,n,i){const o=crypto.randomUUID();await this.conversation.pushGeneration({id:o,conversationId:this.conversation.id,agentName:n.name,text:"",status:"streaming",startedAt:Date.now()});const h=n.tools.map(c=>({name:c.name,description:c.description,parameters:c.parameters??{type:"object",properties:{}}})),d=[];n.context&&d.push({role:"system",name:n.name,content:n.context}),d.push(...this.history.windowed(this.historyWindow));let s;for(let c=0;;c++){if(s=await this.generation.run({agentName:n.name,llm:i,messages:d,tools:h,temperature:this.temperature,maxTokens:this.maxTokens,maxToolIterations:this.maxToolIterations,isCurrent:a(()=>this.epoch===t,"isCurrent"),agentNames:this.agents.length>1,onDelta:a(u=>this.speech.feed(u,t),"onDelta"),resolveToolCalls:a(u=>this.tools.resolveCalls(u),"resolveToolCalls")}),this.epoch!==t)return;if(!(c<b&&s.status==="error"&&s.text.length===0&&(s.toolRounds??0)===0&&A(s.error)))break}if(this.epoch===t&&s.status!=="interrupted"){if(s.status==="error"){this.conversation.emit("error",{conversationId:this.conversation.id,error:s.error instanceof Error?s.error:new Error(String(s.error))}),await this.conversation.completeGeneration(s.text),s.text&&(await this.conversation.pushTranscript({speaker:n.name,speakerKind:"agent",text:s.text}),this.history.addAssistant(n.name,s.text));return}this.speech.flush(t),await this.speech.waitForIdle(),this.epoch===t&&(await this.conversation.completeGeneration(s.text),await this.conversation.pushTranscript({speaker:n.name,speakerKind:"agent",text:s.text}),this.history.addAssistant(n.name,s.text))}}enqueueCoordinationRun(t){this.pendingGenerations++,this.generationChain=this.generationChain.then(async()=>{this.generating=!0;try{await t()}finally{this.generating=!1,this.pendingGenerations--}})}}
3
2
  //# sourceMappingURL=orchestrator.js.map