@dxos/assistant 0.8.4-main.f9ba587 → 0.8.4-main.fcc0d83b33

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 (197) hide show
  1. package/README.md +1 -0
  2. package/dist/lib/neutral/extraction/index.mjs +202 -0
  3. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  4. package/dist/lib/neutral/index.mjs +1693 -0
  5. package/dist/lib/neutral/index.mjs.map +7 -0
  6. package/dist/lib/neutral/meta.json +1 -0
  7. package/dist/types/src/conversation/context.d.ts +152 -0
  8. package/dist/types/src/conversation/context.d.ts.map +1 -0
  9. package/dist/types/src/conversation/context.test.d.ts +2 -0
  10. package/dist/types/src/conversation/context.test.d.ts.map +1 -0
  11. package/dist/types/src/conversation/index.d.ts +2 -1
  12. package/dist/types/src/conversation/index.d.ts.map +1 -1
  13. package/dist/types/src/conversation/session.d.ts +78 -0
  14. package/dist/types/src/conversation/session.d.ts.map +1 -0
  15. package/dist/types/src/diff.d.ts +17 -0
  16. package/dist/types/src/diff.d.ts.map +1 -0
  17. package/dist/types/src/diff.test.d.ts +2 -0
  18. package/dist/types/src/diff.test.d.ts.map +1 -0
  19. package/dist/types/src/errors.d.ts +67 -0
  20. package/dist/types/src/errors.d.ts.map +1 -0
  21. package/dist/types/src/execution-graph.d.ts +85 -0
  22. package/dist/types/src/execution-graph.d.ts.map +1 -0
  23. package/dist/types/src/execution-graph.test.d.ts +2 -0
  24. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  25. package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
  26. package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
  27. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts +1 -1
  28. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  29. package/dist/types/src/extraction/extraction.d.ts +1066 -215
  30. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  31. package/dist/types/src/extraction/index.d.ts +0 -1
  32. package/dist/types/src/extraction/index.d.ts.map +1 -1
  33. package/dist/types/src/extraction/quotes.d.ts +3 -3
  34. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  35. package/dist/types/src/functions/index.d.ts +2 -0
  36. package/dist/types/src/functions/index.d.ts.map +1 -0
  37. package/dist/types/src/functions/services.d.ts +17 -0
  38. package/dist/types/src/functions/services.d.ts.map +1 -0
  39. package/dist/types/src/index.d.ts +6 -5
  40. package/dist/types/src/index.d.ts.map +1 -1
  41. package/dist/types/src/session/artifact-diff.d.ts +27 -0
  42. package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
  43. package/dist/types/src/session/error-handling.d.ts +4 -0
  44. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  45. package/dist/types/src/session/format.d.ts +16 -0
  46. package/dist/types/src/session/format.d.ts.map +1 -0
  47. package/dist/types/src/session/index.d.ts +5 -1
  48. package/dist/types/src/session/index.d.ts.map +1 -1
  49. package/dist/types/src/session/observer.d.ts +23 -0
  50. package/dist/types/src/session/observer.d.ts.map +1 -0
  51. package/dist/types/src/session/request.d.ts +106 -0
  52. package/dist/types/src/session/request.d.ts.map +1 -0
  53. package/dist/types/src/session/toolkit.d.ts +16 -0
  54. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  55. package/dist/types/src/session/version-pin.d.ts +5 -5
  56. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  57. package/dist/types/src/templates/index.d.ts +2 -0
  58. package/dist/types/src/templates/index.d.ts.map +1 -0
  59. package/dist/types/src/templates/system.d.ts +17 -0
  60. package/dist/types/src/templates/system.d.ts.map +1 -0
  61. package/dist/types/src/tracing.d.ts +223 -0
  62. package/dist/types/src/tracing.d.ts.map +1 -0
  63. package/dist/types/src/types/artifact.d.ts +28 -0
  64. package/dist/types/src/types/artifact.d.ts.map +1 -0
  65. package/dist/types/src/types/index.d.ts +2 -0
  66. package/dist/types/src/types/index.d.ts.map +1 -0
  67. package/dist/types/tsconfig.tsbuildinfo +1 -1
  68. package/package.json +42 -29
  69. package/src/conversation/context.test.ts +52 -0
  70. package/src/conversation/context.ts +403 -0
  71. package/src/conversation/index.ts +2 -1
  72. package/src/conversation/session.ts +300 -0
  73. package/src/diff.test.ts +74 -0
  74. package/src/diff.ts +93 -0
  75. package/src/errors.ts +15 -0
  76. package/src/execution-graph.test.ts +740 -0
  77. package/src/execution-graph.ts +519 -0
  78. package/src/extraction/extraction-ner-function/index.ts +0 -1
  79. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  80. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +3 -1
  81. package/src/extraction/extraction.ts +44 -15
  82. package/src/extraction/index.ts +0 -1
  83. package/src/extraction/quotes.test.ts +3 -3
  84. package/src/extraction/quotes.ts +6 -7
  85. package/src/functions/index.ts +5 -0
  86. package/src/functions/services.ts +214 -0
  87. package/src/functions.conversations.json +1 -0
  88. package/src/index.ts +6 -5
  89. package/src/session/artifact-diff.ts +41 -0
  90. package/src/session/error-handling.ts +41 -0
  91. package/src/session/format.ts +149 -0
  92. package/src/session/index.ts +5 -1
  93. package/src/session/observer.ts +62 -0
  94. package/src/session/request.conversations.json +1 -0
  95. package/src/session/request.ts +344 -0
  96. package/src/session/toolkit.ts +47 -0
  97. package/src/session/version-pin.ts +12 -12
  98. package/src/templates/index.ts +5 -0
  99. package/src/templates/instructions/format.tpl +57 -0
  100. package/src/templates/instructions/system.tpl +85 -0
  101. package/src/templates/system.ts +42 -0
  102. package/src/tracing.ts +43 -0
  103. package/src/types/artifact.ts +89 -0
  104. package/src/types/index.ts +5 -0
  105. package/src/typings.d.ts +5 -0
  106. package/dist/lib/browser/index.mjs +0 -2019
  107. package/dist/lib/browser/index.mjs.map +0 -7
  108. package/dist/lib/browser/meta.json +0 -1
  109. package/dist/lib/node-esm/index.mjs +0 -2021
  110. package/dist/lib/node-esm/index.mjs.map +0 -7
  111. package/dist/lib/node-esm/meta.json +0 -1
  112. package/dist/types/bin/chat.d.ts +0 -2
  113. package/dist/types/bin/chat.d.ts.map +0 -1
  114. package/dist/types/src/blueprint/blueprint.d.ts +0 -41
  115. package/dist/types/src/blueprint/blueprint.d.ts.map +0 -1
  116. package/dist/types/src/blueprint/index.d.ts +0 -3
  117. package/dist/types/src/blueprint/index.d.ts.map +0 -1
  118. package/dist/types/src/blueprint/registry.d.ts +0 -7
  119. package/dist/types/src/blueprint/registry.d.ts.map +0 -1
  120. package/dist/types/src/context/binder.d.ts +0 -34
  121. package/dist/types/src/context/binder.d.ts.map +0 -1
  122. package/dist/types/src/context/binding.d.ts +0 -38
  123. package/dist/types/src/context/binding.d.ts.map +0 -1
  124. package/dist/types/src/context/index.d.ts +0 -3
  125. package/dist/types/src/context/index.d.ts.map +0 -1
  126. package/dist/types/src/conversation/conversation.d.ts +0 -44
  127. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  128. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
  129. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
  130. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
  131. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
  132. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
  133. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
  134. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -208
  135. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
  136. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
  137. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
  138. package/dist/types/src/research/exa.d.ts +0 -7
  139. package/dist/types/src/research/exa.d.ts.map +0 -1
  140. package/dist/types/src/research/graph.d.ts +0 -41
  141. package/dist/types/src/research/graph.d.ts.map +0 -1
  142. package/dist/types/src/research/graph.test.d.ts +0 -2
  143. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  144. package/dist/types/src/research/index.d.ts +0 -4
  145. package/dist/types/src/research/index.d.ts.map +0 -1
  146. package/dist/types/src/research/research.d.ts +0 -10
  147. package/dist/types/src/research/research.d.ts.map +0 -1
  148. package/dist/types/src/research/research.test.d.ts +0 -2
  149. package/dist/types/src/research/research.test.d.ts.map +0 -1
  150. package/dist/types/src/session/session.d.ts +0 -283
  151. package/dist/types/src/session/session.d.ts.map +0 -1
  152. package/dist/types/src/session/session.test.d.ts +0 -2
  153. package/dist/types/src/session/session.test.d.ts.map +0 -1
  154. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  155. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  156. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  157. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  158. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  159. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  160. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  161. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  162. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  163. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  164. package/dist/types/src/testing/index.d.ts +0 -3
  165. package/dist/types/src/testing/index.d.ts.map +0 -1
  166. package/dist/types/src/types.d.ts +0 -3
  167. package/dist/types/src/types.d.ts.map +0 -1
  168. package/src/blueprint/blueprint.ts +0 -75
  169. package/src/blueprint/index.ts +0 -6
  170. package/src/blueprint/registry.ts +0 -15
  171. package/src/context/binder.ts +0 -101
  172. package/src/context/binding.ts +0 -31
  173. package/src/context/index.ts +0 -6
  174. package/src/conversation/conversation.ts +0 -103
  175. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -95
  176. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -66
  177. package/src/extraction/extraction-llm-function/index.ts +0 -5
  178. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -115
  179. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -54
  180. package/src/research/exa.ts +0 -100
  181. package/src/research/graph.test.ts +0 -15
  182. package/src/research/graph.ts +0 -337
  183. package/src/research/index.ts +0 -7
  184. package/src/research/instructions-research.tpl +0 -97
  185. package/src/research/research.test.ts +0 -190
  186. package/src/research/research.ts +0 -90
  187. package/src/session/session.test.ts +0 -275
  188. package/src/session/session.ts +0 -582
  189. package/src/session/version-pin.test.ts +0 -26
  190. package/src/summarization/summarization.test.ts +0 -221
  191. package/src/testing/exa-search-1748337321991.ts +0 -131
  192. package/src/testing/exa-search-1748337331526.ts +0 -144
  193. package/src/testing/exa-search-1748337344119.ts +0 -133
  194. package/src/testing/index.ts +0 -11
  195. package/src/typedefs.d.ts +0 -8
  196. package/src/types.ts +0 -8
  197. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -0,0 +1 @@
1
+ {"conversations":[{"parameters":{"model":"@anthropic/claude-opus-4-6","stream":true,"tools":[]},"prompt":{"content":[{"role":"user","content":"Hello world!","options":{"anthropic":{"cacheControl":{"ttl":"5m","type":"ephemeral"}}}}]},"response":[{"type":"response-metadata","id":"msg_01P4EFfYrn2XLAaSd6uaAwEe","modelId":"claude-opus-4-6","timestamp":"1970-01-01T00:00:00.000Z","metadata":{}},{"type":"reasoning-start","id":"0","metadata":{}},{"type":"reasoning-delta","id":"0","delta":"The","metadata":{}},{"type":"reasoning-delta","id":"0","delta":" user is saying \"Hello world!\" - a classic greeting. I'll respond in a friendly way.","metadata":{}},{"type":"reasoning-delta","id":"0","delta":"","metadata":{}},{"type":"reasoning-delta","id":"0","delta":"","metadata":{"anthropic":{"type":"thinking","signature":"EpICClkIDRgCKkD/kOgik1cgXVWa8rx+X6LFo9HvEBwZ7hEthnH1/FoiWiE//6BCJe4yobp2eUQ59wsNovlHzvu42pvDz+HrqdXfMg9jbGF1ZGUtb3B1cy00LTY4ABIMVgmAeJGtdlGLI9xhGgzKg78+pGfELSb0yJQiMI/HgJQKbergs7rT4xclgyLM9N/xxHsDdCAY9KUaeEIC3RZR84UAmT5sbfJNA1iviCpnQXuNeYdJDLcmfTityQm+c0fKlzUJ4glWpeLGfc4UiSqUbMk224KJ9U49hylck4vS+bx9qQDztEhnLfyRjuNm2v1p7e3UDxT0AeouZWl9O6mgWbezLG+B06hL9nm7PG8vd4jj8Gwo3RgB"}}},{"type":"reasoning-end","id":"0","metadata":{}},{"type":"text-start","id":"1","metadata":{}},{"type":"text-delta","id":"1","delta":"Hello! 👋 Welcome! How can I help you today? Whether you have","metadata":{}},{"type":"text-delta","id":"1","delta":" questions, need assistance with something, or just want to chat, I'm here for you. 😊","metadata":{}},{"type":"text-end","id":"1","metadata":{}},{"type":"finish","reason":"stop","usage":{"inputTokens":10,"outputTokens":80,"totalTokens":90},"metadata":{"anthropic":{"usage":{"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":10,"output_tokens":9,"server_tool_use":null,"service_tier":"standard"}}}}]},{"parameters":{"model":"@anthropic/claude-opus-4-6","stream":true,"tools":[{"name":"Calculator","description":"Basic calculator tool","inputSchema":{"type":"object","required":["input"],"properties":{"input":{"type":"string","description":"The calculation to perform."}},"additionalProperties":false}}]},"prompt":{"content":[{"role":"user","content":"What is 10 + 30?","options":{"anthropic":{"cacheControl":{"ttl":"5m","type":"ephemeral"}}}}]},"response":[{"type":"response-metadata","id":"msg_01Tiw1p1D6XEuQVk2bAxrGTn","modelId":"claude-opus-4-6","timestamp":"1970-01-01T00:00:00.000Z","metadata":{}},{"type":"reasoning-start","id":"0","metadata":{}},{"type":"reasoning-delta","id":"0","delta":"The","metadata":{}},{"type":"reasoning-delta","id":"0","delta":" user wants to calculate 10 + 30.","metadata":{}},{"type":"reasoning-delta","id":"0","delta":"","metadata":{"anthropic":{"type":"thinking","signature":"Et8BClkIDRgCKkB/0K0xQQQoenGVXh0VGAdSnkIX3gjXTelz+K0GBhpvk5FcfTPrgKU5HivTbsmhgLGs2LUMRc2mO/YcVzMMzqJqMg9jbGF1ZGUtb3B1cy00LTY4ABIMjxj4INjd+yZEsnEgGgwh2O9IY8I3CzpgM7siMCmsq9Vx4CquyYUx5D16IaDEyJSziOp/Lmzv45pGPfal+63iVnH2fPCHdd147EFgbCo0U0V5wQb1Ys9h6NU53sdkaZ8heyTJ3ZHIPZ1U3X0BmRKC40w34VJ9o8TCbQZwFjY6l5PRPxgB"}}},{"type":"reasoning-end","id":"0","metadata":{}},{"type":"tool-params-start","id":"toolu_01MjKitXaVxMmP53UKeVQDnY","name":"Calculator","providerExecuted":false,"metadata":{}},{"type":"tool-params-delta","id":"toolu_01MjKitXaVxMmP53UKeVQDnY","delta":"","metadata":{}},{"type":"tool-params-delta","id":"toolu_01MjKitXaVxMmP53UKeVQDnY","delta":"{\"inpu","metadata":{}},{"type":"tool-params-delta","id":"toolu_01MjKitXaVxMmP53UKeVQDnY","delta":"t\": ","metadata":{}},{"type":"tool-params-delta","id":"toolu_01MjKitXaVxMmP53UKeVQDnY","delta":"\"10 + ","metadata":{}},{"type":"tool-params-delta","id":"toolu_01MjKitXaVxMmP53UKeVQDnY","delta":"30\"}","metadata":{}},{"type":"tool-params-end","id":"toolu_01MjKitXaVxMmP53UKeVQDnY","metadata":{}},{"type":"finish","reason":"tool-calls","usage":{"inputTokens":578,"outputTokens":83,"totalTokens":661},"metadata":{"anthropic":{"usage":{"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":578,"output_tokens":9,"server_tool_use":null,"service_tier":"standard"}}}}]},{"parameters":{"model":"@anthropic/claude-opus-4-6","stream":true,"tools":[{"name":"Calculator","description":"Basic calculator tool","inputSchema":{"type":"object","required":["input"],"properties":{"input":{"type":"string","description":"The calculation to perform."}},"additionalProperties":false}}]},"prompt":{"content":[{"role":"user","content":"What is 10 + 30?","options":{}},{"role":"assistant","content":[{"type":"reasoning","text":"The user wants to calculate 10 + 30.","options":{}},{"type":"tool-call","id":"toolu_01MjKitXaVxMmP53UKeVQDnY","name":"Calculator","params":{"input":"10 + 30"},"providerExecuted":false,"options":{}}],"options":{}},{"role":"tool","content":[{"type":"tool-result","id":"toolu_01MjKitXaVxMmP53UKeVQDnY","name":"Calculator","isFailure":false,"result":{"result":40},"providerExecuted":false,"options":{}}],"options":{"anthropic":{"cacheControl":{"ttl":"5m","type":"ephemeral"}}}}]},"response":[{"type":"response-metadata","id":"msg_016uWLkUCfQZ6mGvDGXoKvSe","modelId":"claude-opus-4-6","timestamp":"1970-01-01T00:00:00.000Z","metadata":{}},{"type":"text-start","id":"0","metadata":{}},{"type":"text-delta","id":"0","delta":"10","metadata":{}},{"type":"text-delta","id":"0","delta":" + 30 = **40**.","metadata":{}},{"type":"text-end","id":"0","metadata":{}},{"type":"finish","reason":"stop","usage":{"inputTokens":650,"outputTokens":13,"totalTokens":663},"metadata":{"anthropic":{"usage":{"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":650,"output_tokens":1,"server_tool_use":null,"service_tier":"standard"}}}}]},{"parameters":{"model":"@anthropic/claude-opus-4-6","stream":true,"tools":[{"name":"Calculator","description":"Basic calculator tool","inputSchema":{"type":"object","required":["input"],"properties":{"input":{"type":"string","description":"The calculation to perform."}},"additionalProperties":false}}]},"prompt":{"content":[{"role":"user","content":"I am testing error handling in tool paramter parsing. I want you to call the calculator tool but omit the input parameter to intentionally differ from the tool schema.","options":{"anthropic":{"cacheControl":{"ttl":"5m","type":"ephemeral"}}}}]},"response":[{"type":"response-metadata","id":"msg_01XDAKUT19TrSEueFFq4KJNN","modelId":"claude-opus-4-6","timestamp":"1970-01-01T00:00:00.000Z","metadata":{}},{"type":"reasoning-start","id":"0","metadata":{}},{"type":"reasoning-delta","id":"0","delta":"The user is asking me to intentionally call the Calculator tool without providing the required \"","metadata":{}},{"type":"reasoning-delta","id":"0","delta":"input\" parameter to test error handling. They want to see what happens when a required parameter is omitted.\n\nI should be","metadata":{}},{"type":"reasoning-delta","id":"0","delta":" transparent about this. The \"input\" parameter is marked as \"required\" in the schema","metadata":{}},{"type":"reasoning-delta","id":"0","delta":". Let me attempt the call as the user requests, omitting the required","metadata":{}},{"type":"reasoning-delta","id":"0","delta":" parameter, to help them test error handling.","metadata":{}},{"type":"reasoning-delta","id":"0","delta":"","metadata":{"anthropic":{"type":"thinking","signature":"EtsEClkIDRgCKkAX2ymsRtz1YoTibcGufK2UrveSRjyGaR8voyX9fdgYa1R/D34pdZw5MFbt5ju52GDm9S8sRTeM71WxMuzN+nC0Mg9jbGF1ZGUtb3B1cy00LTY4ABIM3UiIvuTf53XoYDhAGgwUgDabFIahkO3RmhQiMEo9KTbcz0KD+SM3wYYuJrPB6N1DE1bihQPTIcbsrPnTljVmYBpTcEAR+u7qaTVkbCqvA7gcGvE9JjfVi8j6ChFOQUJW7S3evbtkfr47FmEKgkNdKtabAe/b3nefFYIF6Hojn+LfQdFRnRHfB6iOoXT2/CUWCs1Isv0ETjgAFvKteDJB0biUC81luyCg00egHkySOFGA0Frf7BnDEg3MwXz1opK1D6+HDF6dCkHMDOtL0dkTslV7rZej/iEJigvHbVzoCZ47DWVFitZ/DUqpIn54Z1TPH+m+EyLPCws4yUgzIUy7z/JH51xAb/u1hteAhROcXKS+OrIbGrTIVBVlwUaXxKKL8pT5F30iHdGKifso1HDdoR1Gm1qwoUtONJh0SvyW6ti3zjDMHN4jAG3YsvfXYn0rGGJ/Is2hKmvz+ETEB+9hYTPhDjdpf1VMpn7YYoicUIua3FTYGXvs78cIEqYzbanebT0L88VRo/ZkB+rxRsf6EcAYQjeHX+motmzL7Xo9hKHZCMTuZLJbLd84XcNmnb/Vfrfz3jw/Znu9MW0ed2DyLyqu465mmEOjNteRq0wF/USjFB8F1p0CF/P3kjL5KbbqUK5NTqi/KoZt5MWcsp7lwzdZYdffINteTJ83R6ExGAE="}}},{"type":"reasoning-end","id":"0","metadata":{}},{"type":"text-start","id":"1","metadata":{}},{"type":"text-delta","id":"1","delta":"I understand you want to test error handling by intent","metadata":{}},{"type":"text-delta","id":"1","delta":"ionally making a malformed tool call. I'll attempt to call the Calculator tool without the required","metadata":{}},{"type":"text-delta","id":"1","delta":" `input` parameter as you've requested:","metadata":{}},{"type":"text-end","id":"1","metadata":{}},{"type":"tool-params-start","id":"toolu_01EN5ueREDjY2Dkn4DtQT98p","name":"Calculator","providerExecuted":false,"metadata":{}},{"type":"tool-params-delta","id":"toolu_01EN5ueREDjY2Dkn4DtQT98p","delta":"","metadata":{}},{"type":"tool-params-end","id":"toolu_01EN5ueREDjY2Dkn4DtQT98p","metadata":{}}]},{"parameters":{"model":"@anthropic/claude-opus-4-6","stream":true,"tools":[{"name":"Calculator","description":"Basic calculator tool","inputSchema":{"type":"object","required":["input"],"properties":{"input":{"type":"string","description":"The calculation to perform."}},"additionalProperties":false}}]},"prompt":{"content":[{"role":"user","content":"I am testing error handling in tool paramter parsing. I want you to call the calculator tool but omit the input parameter to intentionally differ from the tool schema.","options":{}},{"role":"assistant","content":[{"type":"reasoning","text":"The user is asking me to intentionally call the Calculator tool without providing the required \"input\" parameter to test error handling. They want to see what happens when a required parameter is omitted.\n\nI should be transparent about this. The \"input\" parameter is marked as \"required\" in the schema. Let me attempt the call as the user requests, omitting the required parameter, to help them test error handling.","options":{}},{"type":"text","text":"I understand you want to test error handling by intentionally making a malformed tool call. I'll attempt to call the Calculator tool without the required `input` parameter as you've requested:","options":{}},{"type":"tool-call","id":"toolu_01EN5ueREDjY2Dkn4DtQT98p","name":"Calculator","params":{},"providerExecuted":false,"options":{}}],"options":{}},{"role":"tool","content":[{"type":"tool-result","id":"toolu_01EN5ueREDjY2Dkn4DtQT98p","name":"Calculator","isFailure":true,"result":"MalformedOutput: { \"module\": \"Toolkit\", \"method\": \"Calculator.handle\", \"description\": \"Failed to decode tool call parameters for tool 'Calculator' from:\\n'{}'\", \"cause\": { readonly input: string }\n└─ [\"input\"]\n └─ is missing }\ncaused by:\nParseError: { readonly input: string }\n└─ [\"input\"]\n └─ is missing","providerExecuted":false,"options":{}}],"options":{"anthropic":{"cacheControl":{"ttl":"5m","type":"ephemeral"}}}}]},"response":[{"type":"response-metadata","id":"msg_01H2AnoBfNtCYSMVrB9EofxM","modelId":"claude-opus-4-6","timestamp":"1970-01-01T00:00:00.000Z","metadata":{}},{"type":"reasoning-start","id":"0","metadata":{}},{"type":"reasoning-delta","id":"0","delta":"The error","metadata":{}},{"type":"reasoning-delta","id":"0","delta":" was returned as expected. Let me explain what happened.","metadata":{}},{"type":"reasoning-delta","id":"0","delta":"","metadata":{"anthropic":{"type":"thinking","signature":"EvwBClkIDRgCKkCwoArrVhufw9O5jGNvlEhPLfP86nuapk2Sn3w7HQPwA6x/ZDavxvxNApMetymuM474yxHB+NZANvov3igozby0Mg9jbGF1ZGUtb3B1cy00LTY4ABIMO0f4i8xYIEfyqjvbGgyTlNkCKKfVpWC42MkiMDyCKZwXLycBfZPby82k9IK+I/jyDYQ1tl32IaSDXneYK9iFqZf0hwUZW/qcivZKWSpRp1Kx07laulxgxFuOuSq4eatbyLPKbwFnPHJhD537B6Q8sU5vq6IhwtasW0ahelaItDeaDp1h/QNeP8gjaqyG2o98UnYi6BaAOLQT9NW2q6fEGAE="}}},{"type":"reasoning-end","id":"0","metadata":{}},{"type":"text-start","id":"1","metadata":{}},{"type":"text-delta","id":"1","delta":"As expected, the call failed and returned a **parse error**. Here's a","metadata":{}},{"type":"text-delta","id":"1","delta":" breakdown of what happened:\n\n1. **What I did:** Called the `Calculator` tool with an","metadata":{}},{"type":"text-delta","id":"1","delta":" empty parameter set `{}`, omitting the required `input` parameter.\n2. **Error","metadata":{}},{"type":"text-delta","id":"1","delta":" returned:** `MalformedOutput` — The system detected that the tool call parameters","metadata":{}},{"type":"text-delta","id":"1","delta":" failed to decode because the required `input` field (of type `string`) **","metadata":{}},{"type":"text-delta","id":"1","delta":"is missing**.\n3. **Error chain:** The root cause is a `ParseError` confirming that the schema validation","metadata":{}},{"type":"text-delta","id":"1","delta":" caught the missing required field at path `[\"input\"]`.\n\nThis","metadata":{}},{"type":"text-delta","id":"1","delta":" shows that the tool parameter parsing correctly validates against the defined JSON","metadata":{}},{"type":"text-delta","id":"1","delta":" schema and rejects calls that don't include all required parameters. The error","metadata":{}},{"type":"text-delta","id":"1","delta":" message is quite descriptive, pointing to exactly which","metadata":{}},{"type":"text-delta","id":"1","delta":" field is missing and what type it expected. \n\nWould","metadata":{}},{"type":"text-delta","id":"1","delta":" you like to test any other error handling scenarios?","metadata":{}},{"type":"text-end","id":"1","metadata":{}},{"type":"finish","reason":"stop","usage":{"inputTokens":809,"outputTokens":222,"totalTokens":1031},"metadata":{"anthropic":{"usage":{"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":809,"output_tokens":9,"server_tool_use":null,"service_tier":"standard"}}}}]},{"parameters":{"model":"@anthropic/claude-opus-4-6","stream":false,"tools":[]},"prompt":{"content":[{"role":"system","content":"<instructions>\n You are an agent that summarizes conversations.\n You will be given a conversation and you will need to summarize it to compact context.\n Your summary will be used by AI model to continue the conversation without seeing the original messages.\n Remove unnecessary details and focus on the most important information.\n Keep user requests, method of action, and progress.\n Keep the important objects and references in original format.\n It is very important you maintain unchanged ECHO DXNs and IDs of the objects.\n Output only the summary.\n</instructions>\n\n<example_output>\n Processing a flight booking confirmation email. The user requested a round-trip flight from Warsaw to Barcelona for March 15–22, 2026.\n\n Action taken:\n - Found existing booking object `dxn:echo:@:01KHZWKQ9HPJYG147HV7CP5ARX` (type `dxn:echo:@:01KHXAMH4F3V94RCYC7P7M2H0C` / `com.example.type.flight-booking`) matching confirmation code ABC123.\n - Updated the booking status from \"pending\" to \"confirmed\".\n - Added flight details: Outbound WAW→BCN Mar 15 08:30, Return BCN→WAW Mar 22 14:15, carrier LOT Polish Airlines.\n - Stored passenger info and seat assignments in notes.\n\n Booking details preserved: Confirmation ABC123, total 1,240 PLN, booked 2026-02-18, airline LOT Polish Airlines, flight numbers LO391/LO392.\n\n Status enum mapping for the booking schema: pending=Awaiting payment, confirmed=Booked, cancelled=Cancelled, completed=Flown.\n</example_output>\n\nTASK: Reply with the summary of the prior conversation.","options":{}},{"role":"user","content":"How many apples are in the basket?","options":{}},{"role":"assistant","content":"There are 10 apples in the basket.","options":{}},{"role":"user","content":"<instructions>\n You are an agent that summarizes conversations.\n You will be given a conversation and you will need to summarize it to compact context.\n Your summary will be used by AI model to continue the conversation without seeing the original messages.\n Remove unnecessary details and focus on the most important information.\n Keep user requests, method of action, and progress.\n Keep the important objects and references in original format.\n It is very important you maintain unchanged ECHO DXNs and IDs of the objects.\n Output only the summary.\n</instructions>\n\n<example_output>\n Processing a flight booking confirmation email. The user requested a round-trip flight from Warsaw to Barcelona for March 15–22, 2026.\n\n Action taken:\n - Found existing booking object `dxn:echo:@:01KHZWKQ9HPJYG147HV7CP5ARX` (type `dxn:echo:@:01KHXAMH4F3V94RCYC7P7M2H0C` / `com.example.type.flight-booking`) matching confirmation code ABC123.\n - Updated the booking status from \"pending\" to \"confirmed\".\n - Added flight details: Outbound WAW→BCN Mar 15 08:30, Return BCN→WAW Mar 22 14:15, carrier LOT Polish Airlines.\n - Stored passenger info and seat assignments in notes.\n\n Booking details preserved: Confirmation ABC123, total 1,240 PLN, booked 2026-02-18, airline LOT Polish Airlines, flight numbers LO391/LO392.\n\n Status enum mapping for the booking schema: pending=Awaiting payment, confirmed=Booked, cancelled=Cancelled, completed=Flown.\n</example_output>\n\nTASK: Reply with the summary of the prior conversation.","options":{}}]},"response":[{"type":"response-metadata","id":"msg_013JQyMpNyup8yd9gfQtz1sK","modelId":"claude-opus-4-6","timestamp":"1970-01-01T00:00:00.000Z","metadata":{}},{"type":"reasoning","text":"The conversation is very simple - the user asked how many apples are in the basket, and the assistant answered 10. There are no ECHO DXNs, no complex objects, and no real context to preserve. This appears to be a trivial exchange with no prior context or tools involved.","metadata":{"anthropic":{"type":"thinking","signature":"EsoDClkIDRgCKkATKz5csAkAGkfvuEctWM4RDkW59XDzgRDBqVJSoUkrn7sH98NL6X4FerfTUJbq3YrYUxUwj2IjzXTI27XlVqc6Mg9jbGF1ZGUtb3B1cy00LTY4ABIMT/tDfruFSjlciBFYGgyTdl8IxDG9mzlTn5UiMFMOqm36jmi4HNgGu6HR4mwonVPi8KhcOF7flqctd56f4V11qOMTiaX/P9f1rZpB0yqeAlZX160VMP2VXB7IlmZWKlJZBAI3gMIs3ef7s1b+mKSSJf20F4wpg1ECrPdsnnIciHQVKxCc3qoTNnGuwff7C4U5O5s9SDNVhEMNdW8fSy5PAkFPPP/XH7Seac6RzDAIT4aJvRA2UwhqjvDwJszwZQl6Xb7Ng1fsGlAu2ywWBjRzKuoJDJCBySfrxGfjl5cH/Jrg80f9Pp2QHJgIYoTNNtQtB7GS3i1btjNp/N/TsKMf3so5iK2FQ6qtl5Ot9H9qjbYhTRq23zKQnkUkav27evOpE5kSOittzJ3MdblXMXhO09SvJ69n6la0MSIDm50XVFuLDe6819UeGI4LE5S0TQj8bM43n0gk+Z9omi6UAw8JjltCKkaBp5ws6pOozbQYAQ=="}}},{"type":"text","text":"The user asked how many apples are in the basket. The assistant responded that there are 10 apples in the basket. No additional context, objects, or references were involved.","metadata":{}},{"type":"finish","reason":"stop","usage":{"inputTokens":896,"outputTokens":119,"totalTokens":1015,"cachedInputTokens":0},"metadata":{"anthropic":{"usage":{"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":896,"output_tokens":119,"server_tool_use":null,"service_tier":"standard"}}}}]},{"parameters":{"model":"@anthropic/claude-opus-4-6","stream":true,"tools":[]},"prompt":{"content":[{"role":"assistant","content":"This is the continuation of a conversation that was compacted to preserve context-window space. Summary of what happened in this conversation previously: <summary>The user asked how many apples are in the basket. The assistant responded that there are 10 apples in the basket. No additional context, objects, or references were involved.</summary>","options":{}},{"role":"user","content":"What did we talk about?","options":{"anthropic":{"cacheControl":{"ttl":"5m","type":"ephemeral"}}}}]},"response":[{"type":"response-metadata","id":"msg_01BWTgasX7BDFvGG5Zp7YLjq","modelId":"claude-opus-4-6","timestamp":"1970-01-01T00:00:00.000Z","metadata":{}},{"type":"reasoning-start","id":"0","metadata":{}},{"type":"reasoning-delta","id":"0","delta":"The user is asking me to recall what we talked about. Based on the summary provided, we discussed","metadata":{}},{"type":"reasoning-delta","id":"0","delta":" how many apples are in a basket, and I told them there are 10 apples in the basket.","metadata":{}},{"type":"reasoning-delta","id":"0","delta":"","metadata":{"anthropic":{"type":"thinking","signature":"EvECClkIDRgCKkASmeuhdK5nBIprAsBq/0ChahRLAcN/Jh26xQdhMZjSsojjx5UoHW21RiuAHCzVLIvt0E/4fNvj7qhOZXzyhNpPMg9jbGF1ZGUtb3B1cy00LTY4ABIMKSjzFmDf3YdferaTGgwKZDXHIy/bxUiq+BQiMHKqTYVUgDcsD1R9OJWF/fKpB2ko0dBkdb/dd5spULoBmqZvFxmOUAvQz+U0OUEToSrFAWa0zySqK5E/R1ZZ0p75Vf28ONof2AMWDCuNT6A35i8ieabC8YHTh3lwgQyaoljpHVkY4uRKqYzUv7t0XBTeAr3Aduq7U+Lmta2+P7Y/oovoOhtfOjADeywq9/PrpCJONwMSU+jctKGfHaln6aoRn1XnIBAiCiUABYCeS9CzXbVTVAOZBQxgmz2Jw5rJfe/EUQfplrcqa3rXDlUjZ6/DTf/YBLIDeCeZ2gpZbnSTIP+7v9mRiAvWlDQfGqM+2KJ/2EorqdD+GAE="}}},{"type":"reasoning-end","id":"0","metadata":{}},{"type":"text-start","id":"1","metadata":{}},{"type":"text-delta","id":"1","delta":"Based","metadata":{}},{"type":"text-delta","id":"1","delta":" on our previous conversation, you asked me how many apples are in a basket, and I told you there are **10 apples** in the basket.","metadata":{}},{"type":"text-delta","id":"1","delta":" That's all we discussed!","metadata":{}},{"type":"text-end","id":"1","metadata":{}},{"type":"finish","reason":"stop","usage":{"inputTokens":98,"outputTokens":103,"totalTokens":201},"metadata":{"anthropic":{"usage":{"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":98,"output_tokens":28,"server_tool_use":null,"service_tier":"standard"}}}}]}]}
@@ -0,0 +1,344 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import type * as AiError from '@effect/ai/AiError';
6
+ import * as LanguageModel from '@effect/ai/LanguageModel';
7
+ import * as Array from 'effect/Array';
8
+ import * as Chunk from 'effect/Chunk';
9
+ import * as Effect from 'effect/Effect';
10
+ import { pipe } from 'effect/Function';
11
+ import * as Option from 'effect/Option';
12
+ import * as Stream from 'effect/Stream';
13
+
14
+ import {
15
+ AiParser,
16
+ AiPreprocessor,
17
+ AiSummarizer,
18
+ type AiToolNotFoundError,
19
+ callTool,
20
+ type OpaqueToolkit,
21
+ type PromptPreprocessingError,
22
+ type ToolExecutionService,
23
+ type ToolResolverService,
24
+ withoutToolCallParising,
25
+ } from '@dxos/ai';
26
+ import { type Blueprint } from '@dxos/compute';
27
+ import { Trace } from '@dxos/compute';
28
+ import { Operation, OperationRegistry } from '@dxos/compute';
29
+ import { Database, Obj } from '@dxos/echo';
30
+ import { log } from '@dxos/log';
31
+ import { ContentBlock, Message } from '@dxos/types';
32
+
33
+ import { type AiAssistantError } from '../errors';
34
+ import { CompleteBlock, PartialBlock } from '../tracing';
35
+ import { formatSystemPrompt, formatUserPrompt } from './format';
36
+ import { GenerationObserver } from './observer';
37
+
38
+ export type AiRequestRunError = AiError.AiError | PromptPreprocessingError | AiToolNotFoundError | AiAssistantError;
39
+
40
+ export type AiRequestRunRequirements =
41
+ | LanguageModel.LanguageModel
42
+ | ToolExecutionService
43
+ | ToolResolverService
44
+ | Database.Service
45
+ | Operation.Service
46
+ | OperationRegistry.Service
47
+ | Trace.TraceService;
48
+
49
+ export type AiRequestOptions = {
50
+ /**
51
+ * Summarize before executing the prompt if the existing history exceeds this threshold.
52
+ */
53
+ summarizationThreshold?: number;
54
+
55
+ // TODO(dmaretskyi): Plan to phase out in favor of TracingService and the return type being a stream.
56
+ observer?: GenerationObserver;
57
+ /**
58
+ * Callback for when a message is received from the user, model, or tool.
59
+ * This is useful for streaming the output to a queue.
60
+ */
61
+ onOutput?: (message: Message.Message) => Effect.Effect<void, never, never>;
62
+ };
63
+
64
+ export type AiRequestRunProps<R = never> = {
65
+ prompt: string | ContentBlock.Any[];
66
+ // TODO(wittjosiah): Rename to systemPrompt.
67
+ system?: string;
68
+ history?: Message.Message[];
69
+ objects?: Obj.Unknown[];
70
+ blueprints?: readonly Blueprint.Blueprint[];
71
+ toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
72
+ };
73
+
74
+ export type AiRequestBeginProps = {
75
+ prompt: string | ContentBlock.Any[];
76
+ system?: string;
77
+ history?: Message.Message[];
78
+ objects?: Obj.Unknown[];
79
+ blueprints?: readonly Blueprint.Blueprint[];
80
+ };
81
+
82
+ export type AiRequestTurnProps<R = never> = {
83
+ system: string;
84
+ toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
85
+ };
86
+
87
+ export type AiRequestTurnResult = {
88
+ messages: Message.Message[];
89
+ done: boolean;
90
+ };
91
+
92
+ /**
93
+ * Contains message history, tools, current context.
94
+ * Current context means the state of the app, time of day, and other contextual information.
95
+ * It makes requests to the model, its a state machine.
96
+ * It keeps track of the current goal.
97
+ * It manages the context window.
98
+ * Tracks the success criteria of reaching the goal, exposing metrics (stretch).
99
+ * Could be run locally in the app or remotely.
100
+ * Could be personal or shared.
101
+ */
102
+ export class AiRequest {
103
+ /** Prevents concurrent execution of session. */
104
+ private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));
105
+
106
+ private readonly _observer: GenerationObserver;
107
+ private readonly _onOutput: (message: Message.Message) => Effect.Effect<void, never, never>;
108
+
109
+ /** Message history from queue. */
110
+ // TODO(burdon): Evolve into supporting a git-like graph of messages.
111
+ private _history: Message.Message[] = [];
112
+
113
+ /** Pending messages for this session (incl. the current prompt). */
114
+ private _pending: Message.Message[] = [];
115
+
116
+ private _started = 0;
117
+ private _ended = 0;
118
+ private _toolCalls = 0;
119
+
120
+ constructor(private readonly _options: AiRequestOptions = {}) {
121
+ this._observer = _options.observer ?? GenerationObserver.noop();
122
+ this._onOutput = _options.onOutput ?? (() => Effect.void);
123
+ }
124
+
125
+ get duration(): number {
126
+ return this._ended - this._started;
127
+ }
128
+
129
+ get toolCalls(): number {
130
+ return this._toolCalls;
131
+ }
132
+
133
+ get pending(): readonly Message.Message[] {
134
+ return this._pending;
135
+ }
136
+
137
+ private _submitMessage = (message: Message.Message): Effect.Effect<Message.Message, never, Trace.TraceService> =>
138
+ Effect.gen(this, function* () {
139
+ this._pending.push(message);
140
+ yield* this._observer.onMessage(message);
141
+ for (const block of message.blocks) {
142
+ yield* Trace.write(CompleteBlock, {
143
+ messageId: message.id,
144
+ role: message.sender.role!,
145
+ block,
146
+ });
147
+ }
148
+ yield* this._onOutput(message);
149
+ return message;
150
+ });
151
+
152
+ getToolCalls = () =>
153
+ pipe(
154
+ [...this._history, ...this._pending],
155
+ Array.reverse,
156
+ Array.takeWhile((_) => _.sender.role === 'assistant'),
157
+ Array.flatMap((_) => _.blocks.filter(ContentBlock.is('toolCall')).map((block) => ({ block, message: _ }))),
158
+ Array.filter((_) => !_.block.providerExecuted),
159
+ Array.reverse,
160
+ );
161
+
162
+ /**
163
+ * Initialize a session: set up history, perform summarization if needed, and submit the user prompt.
164
+ * Must be called before `runTurn()`.
165
+ */
166
+ begin = ({
167
+ prompt,
168
+ system,
169
+ history = [],
170
+ blueprints = [],
171
+ objects = [],
172
+ }: AiRequestBeginProps): Effect.Effect<void, AiRequestRunError, AiRequestRunRequirements> =>
173
+ Effect.gen(this, function* () {
174
+ this._started = Date.now();
175
+ this._history = [...history];
176
+ this._pending = [];
177
+
178
+ const systemPrompt = yield* formatSystemPrompt({ system, blueprints, objects }).pipe(Effect.orDie);
179
+
180
+ if (this._options.summarizationThreshold !== undefined) {
181
+ const tokenCount = yield* AiPreprocessor.estimateTokens(
182
+ yield* AiPreprocessor.preprocessPrompt([...this._history], {
183
+ system: systemPrompt,
184
+ }),
185
+ );
186
+ if (tokenCount > this._options.summarizationThreshold) {
187
+ const summary = yield* AiSummarizer.summarize([...this._history]);
188
+ yield* this._submitMessage(summary);
189
+ }
190
+ }
191
+
192
+ yield* this._submitMessage(yield* formatUserPrompt({ prompt, history }));
193
+ }).pipe(Effect.withSpan('AiRequest.begin'));
194
+
195
+ /**
196
+ * Execute a single turn: one LLM generation followed by tool execution.
197
+ * The toolkit and system prompt can be updated between turns to reflect context changes (e.g. dynamically enabled blueprints).
198
+ */
199
+ runAgentTurn = <const R = never>({
200
+ system,
201
+ toolkit: opaqueToolkit,
202
+ }: AiRequestTurnProps<R>): Effect.Effect<AiRequestTurnResult, AiRequestRunError, AiRequestRunRequirements | R> =>
203
+ Effect.gen(this, function* () {
204
+ log.info('request', {
205
+ system: { snippet: createSnippet(system), length: system.length },
206
+ pending: this._pending.length,
207
+ history: this._history.length,
208
+ });
209
+
210
+ const prompt = yield* AiPreprocessor.preprocessPrompt([...this._history, ...this._pending], {
211
+ system,
212
+ cacheControl: 'ephemeral',
213
+ });
214
+
215
+ const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : undefined;
216
+
217
+ const observer = this._observer;
218
+ let currentMessageId: Obj.ID | null = null;
219
+
220
+ const messages = yield* LanguageModel.streamText({
221
+ prompt,
222
+ toolkit,
223
+ disableToolCallResolution: true,
224
+ }).pipe(
225
+ withoutToolCallParising,
226
+ AiParser.parseResponse({
227
+ emitPartial: true,
228
+ onBegin: () => observer.onBegin(),
229
+ onBlock: (block) => observer.onBlock(block),
230
+ onPart: (part) => observer.onPart(part as any),
231
+ onEnd: (summary) => observer.onEnd(summary),
232
+ }),
233
+ Stream.mapEffect(
234
+ (block) =>
235
+ Effect.gen(this, function* () {
236
+ if (block.pending) {
237
+ currentMessageId ??= Obj.ID.random();
238
+ log('emit ephemeral message', { id: currentMessageId, type: block._tag });
239
+ yield* Trace.write(PartialBlock, {
240
+ messageId: currentMessageId,
241
+ role: 'assistant',
242
+ block,
243
+ });
244
+ return Option.none();
245
+ } else {
246
+ currentMessageId ??= Obj.ID.random();
247
+ const id = currentMessageId;
248
+ currentMessageId = null;
249
+ log('emit complete message', { id, type: block._tag });
250
+ const message = Obj.make(Message.Message, {
251
+ id,
252
+ created: new Date().toISOString(),
253
+ sender: { role: 'assistant' },
254
+ blocks: [block],
255
+ });
256
+ return Option.some(yield* this._submitMessage(message));
257
+ }
258
+ }),
259
+ { concurrency: 1, unordered: false },
260
+ ),
261
+ Stream.filterMap((_) => _),
262
+ Stream.runCollect,
263
+ Effect.map(Chunk.toArray),
264
+ );
265
+ log.info('messages', { messages });
266
+
267
+ const toolCalls = this.getToolCalls();
268
+
269
+ if (toolCalls.length === 0) {
270
+ this._ended = Date.now();
271
+ return { messages, done: true };
272
+ } else if (!toolkit) {
273
+ throw new Error('No toolkit provided');
274
+ }
275
+
276
+ return { messages, done: false };
277
+ }).pipe(Effect.withSpan('AiRequest.runAgentTurn'));
278
+
279
+ runTools = <const R = never>({
280
+ toolkit: opaqueToolkit,
281
+ }: {
282
+ toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
283
+ }): Effect.Effect<void, AiRequestRunError, AiRequestRunRequirements | R> =>
284
+ Effect.gen(this, function* () {
285
+ const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : undefined;
286
+ const toolCalls = this.getToolCalls();
287
+ const toolResults = yield* Effect.forEach(toolCalls, ({ block, message }) => {
288
+ if (!toolkit) {
289
+ throw new Error('No toolkit provided');
290
+ }
291
+ return callTool(toolkit, block);
292
+ });
293
+
294
+ yield* this._submitMessage(
295
+ Obj.make(Message.Message, {
296
+ created: new Date().toISOString(),
297
+ sender: { role: 'tool' },
298
+ blocks: toolResults,
299
+ }),
300
+ );
301
+
302
+ this._toolCalls += toolResults.length;
303
+ }).pipe(Effect.withSpan('AiRequest.runTools'));
304
+
305
+ /**
306
+ * Run a full conversation turn loop. Equivalent to calling `begin()` then `runTurn()` in a loop.
307
+ */
308
+ run = <const R = never>({
309
+ prompt,
310
+ system: systemTemplate,
311
+ history = [],
312
+ objects = [],
313
+ blueprints = [],
314
+ toolkit,
315
+ }: AiRequestRunProps<R>): Effect.Effect<Message.Message[], AiRequestRunError, AiRequestRunRequirements | R> =>
316
+ Effect.gen(this, function* () {
317
+ yield* this.begin({ prompt, system: systemTemplate, history, objects, blueprints });
318
+
319
+ const system = yield* formatSystemPrompt({ system: systemTemplate, blueprints, objects }).pipe(Effect.orDie);
320
+
321
+ do {
322
+ const { done } = yield* this.runAgentTurn({ system, toolkit });
323
+ if (done) {
324
+ break;
325
+ }
326
+ yield* this.runTools({ toolkit });
327
+ } while (true);
328
+
329
+ log('done', { pending: this._pending.length, duration: this.duration, tools: this._toolCalls });
330
+ return this._pending;
331
+ }).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiRequest.run'));
332
+ }
333
+
334
+ const createSnippet = (text: string, len = 32) =>
335
+ text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');
336
+
337
+ // TODO(dmaretskyi): Extract as a general util.
338
+ const logDump = (message: string, data: unknown) => {
339
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
340
+ const { writeFileSync } = require('node:fs');
341
+ const path = `/tmp/log-data-${Date.now()}.json`;
342
+ writeFileSync(path, JSON.stringify(data, null, 2));
343
+ log.info(message, { path });
344
+ };
@@ -0,0 +1,47 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Toolkit from '@effect/ai/Toolkit';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Layer from 'effect/Layer';
8
+
9
+ import { type AiToolNotFoundError, OpaqueToolkit, ToolExecutionService, ToolResolverService } from '@dxos/ai';
10
+ import { type Blueprint } from '@dxos/compute';
11
+ import { isTruthy } from '@dxos/util';
12
+
13
+ export type CreateToolkitProps = {
14
+ toolkit?: OpaqueToolkit.Any;
15
+ blueprints?: readonly Blueprint.Blueprint[];
16
+ /**
17
+ * Self-contained with handlers toolkits.
18
+ */
19
+ opaqueToolkits?: readonly OpaqueToolkit.Any[];
20
+ };
21
+
22
+ /**
23
+ * Build a combined toolkit from the blueprint tools and the provided toolkit.
24
+ */
25
+ export const createToolkit = ({
26
+ toolkit: toolkitProp,
27
+ blueprints = [],
28
+ opaqueToolkits = [],
29
+ }: CreateToolkitProps): Effect.Effect<
30
+ OpaqueToolkit.OpaqueToolkit,
31
+ AiToolNotFoundError,
32
+ ToolResolverService | ToolExecutionService
33
+ > =>
34
+ Effect.gen(function* () {
35
+ const blueprintToolkit = yield* ToolResolverService.resolveToolkit(blueprints.flatMap(({ tools }) => tools));
36
+ const blueprintToolHandler = yield* blueprintToolkit.toContext(ToolExecutionService.handlersFor(blueprintToolkit));
37
+ const opaqueToolkit = OpaqueToolkit.merge(...opaqueToolkits);
38
+
39
+ const toolkitDefs = [toolkitProp?.toolkit, blueprintToolkit, opaqueToolkit.toolkit].filter(isTruthy);
40
+ const mergedToolkit = Toolkit.merge(...toolkitDefs);
41
+ const combinedHandlerLayer = Layer.mergeAll(
42
+ Layer.succeedContext(blueprintToolHandler),
43
+ toolkitProp?.layer ?? OpaqueToolkit.empty.layer,
44
+ opaqueToolkit.layer,
45
+ );
46
+ return OpaqueToolkit.make(mergedToolkit, combinedHandlerLayer as any) as OpaqueToolkit.OpaqueToolkit;
47
+ }) as Effect.Effect<OpaqueToolkit.OpaqueToolkit, AiToolNotFoundError, ToolResolverService | ToolExecutionService>;
@@ -2,12 +2,12 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Schema } from 'effect';
5
+ import * as Schema from 'effect/Schema';
6
6
 
7
- import { type MessageContentBlock } from '@dxos/ai';
8
- import { type ObjectVersion } from '@dxos/echo-db';
9
- import { getVersion } from '@dxos/echo-db';
10
- import { ObjectId, type BaseEchoObject } from '@dxos/echo-schema';
7
+ import { type Obj } from '@dxos/echo';
8
+ import { type ObjectVersion, getVersion } from '@dxos/echo-db';
9
+ import { ObjectId } from '@dxos/keys';
10
+ import { type ContentBlock } from '@dxos/types';
11
11
 
12
12
  // TODO(dmaretskyi): Extract.
13
13
  const ObjectVersionSchema = Schema.Unknown as Schema.Schema<ObjectVersion>;
@@ -15,7 +15,7 @@ const ObjectVersionSchema = Schema.Unknown as Schema.Schema<ObjectVersion>;
15
15
  const VersionPinSchema = Schema.Struct({
16
16
  // TODO(dmaretskyi): Use Ref when those support encoding.
17
17
  objectId: ObjectId,
18
- // TODO(dmaretskyi): Could be opaque
18
+ // TODO(dmaretskyi): Could be opaque.
19
19
  version: ObjectVersionSchema,
20
20
  });
21
21
 
@@ -27,22 +27,22 @@ export interface VersionPin extends Schema.Schema.Type<typeof VersionPinSchema>
27
27
 
28
28
  export const VersionPin: typeof VersionPinSchema & {
29
29
  DISPOSITION: 'version-pin';
30
- fromObject: (object: BaseEchoObject) => VersionPin;
31
- createBlock: (pin: VersionPin) => MessageContentBlock;
30
+ fromObject: (object: Obj.Unknown) => VersionPin;
31
+ createBlock: (pin: VersionPin) => ContentBlock.Any;
32
32
  } = class extends VersionPinSchema {
33
33
  static readonly DISPOSITION = 'version-pin';
34
- static fromObject(object: BaseEchoObject): VersionPin {
34
+ static fromObject(object: Obj.Unknown): VersionPin {
35
35
  return VersionPin.make({
36
36
  objectId: object.id,
37
37
  version: getVersion(object),
38
38
  });
39
39
  }
40
40
 
41
- static createBlock(pin: VersionPin): MessageContentBlock {
41
+ static createBlock(pin: VersionPin): ContentBlock.Any {
42
42
  return {
43
- type: 'json',
43
+ _tag: 'json',
44
44
  disposition: VersionPin.DISPOSITION,
45
- json: JSON.stringify(pin),
45
+ data: JSON.stringify(pin),
46
46
  };
47
47
  }
48
48
  };
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ export * from './system';
@@ -0,0 +1,57 @@
1
+ {{! System Core }}
2
+
3
+ ## Input Formats
4
+
5
+ ### Blueprints
6
+
7
+ You may be provided with Blueprint definitions that include specific instructions and tools for a given set of tasks.
8
+ Blue print instructions will be enclosed in a <blueprint> tag.
9
+
10
+ ### Context objects
11
+
12
+ You may be provided with references to objects that are relevant to the current prompt.
13
+ Objects will be in the form of a <object> tag with a <dxn> element that is the unique key of the object required by many tools.
14
+ The <typename> element is the type of the object.
15
+
16
+ <object>
17
+ <dxn>object-id</dxn>
18
+ <typename>example.com/type/TypeName</typename>
19
+ </object>
20
+
21
+ ## Response Formats
22
+
23
+ It is very important to respond in the correct format.
24
+ You response must be valid Markdown.
25
+ In some cases you should respond with well-formed XML tags along with the content.
26
+ Code snippets should use 2-space indents.
27
+
28
+ {{#if cot}}
29
+ Before responding, explain your reasoning and include your detailed chain-of-thought enclosed in a <cot> tag.
30
+ The <cot> tag should be the first thing in your response.
31
+ {{/if}}
32
+
33
+ ## Block references
34
+
35
+ You can reply with a block reference for objects if you have the DXN. For example:
36
+
37
+ <object>
38
+ <dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M</dxn>
39
+ </object>
40
+ <object>
41
+ <dxn>dxn:echo:@:01K24XPK464FSCKVQJAB2H662M</dxn>
42
+ </object>
43
+
44
+ ### Suggestions
45
+
46
+ Each suggestion must in the form of a proposed action enclosed in a <suggestion> tag.
47
+ Example: <suggestion>Show on a map</suggestion>
48
+ Do not use bullets when listing suggestions.
49
+
50
+ ### Multiple choice questions
51
+
52
+ You may ask multiple choice questions by wrapping consise options inside <option> tags inside a well formed <select> tag.
53
+ Example: <select><option>Yes</option><option>No</option></select>
54
+
55
+ ## Context
56
+
57
+ The current date and time is {{DATETIME}}.
@@ -0,0 +1,85 @@
1
+ {{! System Prompt }}
2
+
3
+ - You are a helpful assistant called Kai.
4
+ - Your name is Kai and you are powered by different language models.
5
+ - You were created by DXOS and operate inside of Composer and on the DXOS EDGE network.
6
+ - In your initial greeting state your name and make some suggestions based on the current context objects.
7
+ - You are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.
8
+ - Your task is to process user commands and questions and decide how best to respond.
9
+ - In general be concise and direct.
10
+ - Follow all instructions carefully.
11
+
12
+ ## Planning
13
+
14
+ - Analyze the structure and type of the content in the user's message.
15
+ - Determine if you complete the task using the available blueprint definitions?
16
+ - If you can't complete the task using the available blueprint definitions, query the list of available blueprint definitions using the appropriate tool.
17
+ - Identify which blueprint definitions are relevant to the user's request.
18
+ - Evaluate the potential benefits of creating an artifact vs. normal processing for each identified element.
19
+ - Make a final decision on whether to create an artifact and explain your reasoning.
20
+ - Are the required blueprint definitions already available?
21
+ - If not, select which blueprint definition(s) will be the most relevant and require them using the require_artifact_definitions tool.
22
+ - The require'd artifact tools will be available for use after require.
23
+ - If creating an artifact, outline how you will structure it within the response.
24
+ - Decide if the artifact needs to be shown to the user.
25
+ - Call the show tool to show the artifact to the user.
26
+ - Your reasoning must include: whether to use artifacts or not, to create one or query, whether to show the artifact to the user, and how to structure the response.
27
+
28
+ ## Blueprints and Artifacts
29
+
30
+ - Determine if the interaction involves an artifact. Prefer artifacts for tables, lists, spreadsheets, kanbans, games, images, and other structured data.
31
+ - Determine if the user is explicitly talking about creating a new artifact, or wants to use an existing artifact.
32
+ - If it is ambiguous, query for existing artifacts first and then decide.
33
+ - If you decide to create an artifact, call the associated tool to create the artifact.
34
+ - Artifacts are stored in the database. Tools are used to create and query artifacts.
35
+ - If you are unsure about creating an artifact ask the user for clarification.
36
+ - Artifacts are mutable objects that can change over the course of the conversation.
37
+ - Always re-query the artifact using the tool (like query or inspect) to get the latest state of the artifact before answering the user.
38
+ - You must never generate the id of the artifact; only recall the ids that are already in the history.
39
+ - Artifacts are created by requiring the specific artifact using the require_artifact tool and creating it by calling the associated tool.
40
+ - You can add suggested actions at the end of your response.
41
+ - Suggested actions should be very concise and start with a verb and be phrased as a command to an agent -- not a question to the user.
42
+ - Suggested actions must be in the form of a user instruction that you can follow.
43
+ - Suggested actions could include actions that create artifacts.
44
+ - After creating an artifact use a tool to add it to the chat context.
45
+
46
+ ## Navigation
47
+
48
+ - When the user asks to open, go to, navigate to, or show a specific document, page, or object, use the navigation tools instead of loading content inline.
49
+ - First, call the Resolve navigation targets tool to find the navigation path for the requested item.
50
+ - Without arguments, it returns available pages that can be navigated to.
51
+ - With a DXN in the query, it resolves that specific object to a navigation path.
52
+ - If you know the object's DXN (e.g. from a database query or context objects), pass it in the query to get the exact navigation path.
53
+ - Then, call the Open tool with the resolved navigation path(s) in the subject array to navigate the user to that item.
54
+ - Do not respond with the document's content when the user asks to open it — open it in the main content area instead.
55
+ - If multiple targets match, present the options to the user and let them choose which to open.
56
+
57
+ ## Response format
58
+
59
+ - When updating the user about the progress of the work you are doing, put the update in a <status> XML tag.
60
+ - Only when you need to show the result to the user or ask a question use a text block without status tags.
61
+
62
+ <example>
63
+ // reasoning...
64
+ <status>Looking for emails from Depot</status>
65
+ // tool call..
66
+ <status>Found 2 emails from Depot.</status>
67
+ <status>Loading email details</status>
68
+ // tool call
69
+ <status>Located mailbox</status>
70
+ I found **2 emails from Depot**:
71
+ </example>
72
+
73
+ Do not do (no status tags):
74
+
75
+ <incorrect_example>
76
+ // reasoning...
77
+ // tool call..
78
+ I found 2 emails from Depot. Let me load their details:
79
+ // tool call
80
+ I found **2 emails from Depot**:
81
+ </incorrect_example>
82
+
83
+ - Avoid using plain text to tell the user what you are about to do; instead, use status blocks.
84
+ - WRONG: Let me get...
85
+ - CORRECT: <status>Getting...</status>