@dxos/assistant 0.8.2-main.fbd8ed0 → 0.8.2-staging.4d6ad0f

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 (289) hide show
  1. package/dist/lib/browser/index.mjs +1983 -64
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node/index.cjs +1976 -63
  5. package/dist/lib/node/index.cjs.map +4 -4
  6. package/dist/lib/node/meta.json +1 -1
  7. package/dist/lib/node-esm/index.mjs +1984 -64
  8. package/dist/lib/node-esm/index.mjs.map +4 -4
  9. package/dist/lib/node-esm/meta.json +1 -1
  10. package/dist/types/{src/bin → bin}/chat.d.ts.map +1 -1
  11. package/dist/types/src/blueprint/blueprint.d.ts +79 -0
  12. package/dist/types/src/blueprint/blueprint.d.ts.map +1 -0
  13. package/dist/types/src/blueprint/blueprint.test.d.ts +2 -0
  14. package/dist/types/src/blueprint/blueprint.test.d.ts.map +1 -0
  15. package/dist/types/src/blueprint/index.d.ts +4 -0
  16. package/dist/types/src/blueprint/index.d.ts.map +1 -0
  17. package/dist/types/src/blueprint/logger.d.ts +3 -0
  18. package/dist/types/src/blueprint/logger.d.ts.map +1 -0
  19. package/dist/types/src/{ai-service/parser.d.ts → blueprint/machine.d.ts} +46 -68
  20. package/dist/types/src/blueprint/machine.d.ts.map +1 -0
  21. package/dist/types/src/blueprint/test-data.d.ts +3 -0
  22. package/dist/types/src/blueprint/test-data.d.ts.map +1 -0
  23. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +4 -0
  24. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -0
  25. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +2 -0
  26. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +1 -0
  27. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +2 -0
  28. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +1 -0
  29. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +210 -0
  30. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -0
  31. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +2 -0
  32. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +1 -0
  33. package/dist/types/src/extraction/extraction-ner-function/index.d.ts +3 -0
  34. package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -0
  35. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts +14 -0
  36. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -0
  37. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.test.d.ts +2 -0
  38. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.test.d.ts.map +1 -0
  39. package/dist/types/src/extraction/extraction.d.ts +242 -0
  40. package/dist/types/src/extraction/extraction.d.ts.map +1 -0
  41. package/dist/types/src/extraction/index.d.ts +5 -0
  42. package/dist/types/src/extraction/index.d.ts.map +1 -0
  43. package/dist/types/src/extraction/quotes.d.ts +15 -0
  44. package/dist/types/src/extraction/quotes.d.ts.map +1 -0
  45. package/dist/types/src/extraction/quotes.test.d.ts +2 -0
  46. package/dist/types/src/extraction/quotes.test.d.ts.map +1 -0
  47. package/dist/types/src/index.d.ts +4 -2
  48. package/dist/types/src/index.d.ts.map +1 -1
  49. package/dist/types/src/research/exa.d.ts +7 -0
  50. package/dist/types/src/research/exa.d.ts.map +1 -0
  51. package/dist/types/src/research/graph.d.ts +39 -0
  52. package/dist/types/src/research/graph.d.ts.map +1 -0
  53. package/dist/types/src/research/graph.test.d.ts +2 -0
  54. package/dist/types/src/research/graph.test.d.ts.map +1 -0
  55. package/dist/types/src/research/index.d.ts +4 -0
  56. package/dist/types/src/research/index.d.ts.map +1 -0
  57. package/dist/types/src/research/research.d.ts +10 -0
  58. package/dist/types/src/research/research.d.ts.map +1 -0
  59. package/dist/types/src/research/research.test.d.ts.map +1 -0
  60. package/dist/types/src/session/index.d.ts +0 -1
  61. package/dist/types/src/session/index.d.ts.map +1 -1
  62. package/dist/types/src/session/session.d.ts +47 -22
  63. package/dist/types/src/session/session.d.ts.map +1 -1
  64. package/dist/types/src/session/version-pin.d.ts +3 -4
  65. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  66. package/dist/types/src/summarization/summarization.test.d.ts +2 -0
  67. package/dist/types/src/summarization/summarization.test.d.ts.map +1 -0
  68. package/dist/types/src/testing/exa-search-1748337321991.d.ts +38 -0
  69. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +1 -0
  70. package/dist/types/src/testing/exa-search-1748337331526.d.ts +37 -0
  71. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +1 -0
  72. package/dist/types/src/testing/exa-search-1748337344119.d.ts +58 -0
  73. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +1 -0
  74. package/dist/types/src/testing/index.d.ts +2 -7
  75. package/dist/types/src/testing/index.d.ts.map +1 -1
  76. package/dist/types/src/types.d.ts +3 -0
  77. package/dist/types/src/types.d.ts.map +1 -0
  78. package/package.json +22 -38
  79. package/src/blueprint/blueprint.test.ts +142 -0
  80. package/src/blueprint/blueprint.ts +95 -0
  81. package/src/blueprint/index.ts +7 -0
  82. package/src/blueprint/logger.ts +66 -0
  83. package/src/blueprint/machine.ts +208 -0
  84. package/src/blueprint/test-data.ts +55 -0
  85. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +95 -0
  86. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +64 -0
  87. package/src/extraction/extraction-llm-function/index.ts +5 -0
  88. package/src/extraction/extraction-llm-function/instructions.tpl +28 -0
  89. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +115 -0
  90. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +54 -0
  91. package/src/extraction/extraction-ner-function/index.ts +6 -0
  92. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +94 -0
  93. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +97 -0
  94. package/src/extraction/extraction.ts +75 -0
  95. package/src/extraction/index.ts +8 -0
  96. package/src/extraction/quotes.test.ts +27 -0
  97. package/src/extraction/quotes.ts +57 -0
  98. package/src/index.ts +4 -4
  99. package/src/research/exa.ts +100 -0
  100. package/src/research/graph.test.ts +15 -0
  101. package/src/research/graph.ts +291 -0
  102. package/src/research/index.ts +7 -0
  103. package/src/research/instructions-research.tpl +97 -0
  104. package/src/research/research.test.ts +189 -0
  105. package/src/research/research.ts +89 -0
  106. package/src/session/index.ts +0 -1
  107. package/src/session/session.test.ts +7 -7
  108. package/src/session/session.ts +46 -19
  109. package/src/session/version-pin.ts +2 -3
  110. package/src/summarization/summarization.test.ts +216 -0
  111. package/src/testing/exa-search-1748337321991.ts +131 -0
  112. package/src/testing/exa-search-1748337331526.ts +144 -0
  113. package/src/testing/exa-search-1748337344119.ts +133 -0
  114. package/src/testing/index.ts +8 -8
  115. package/src/types.ts +8 -0
  116. package/src/typings.d.ts +8 -0
  117. package/dist/lib/browser/chunk-B4HAWUFW.mjs +0 -2786
  118. package/dist/lib/browser/chunk-B4HAWUFW.mjs.map +0 -7
  119. package/dist/lib/browser/testing/index.mjs +0 -658
  120. package/dist/lib/browser/testing/index.mjs.map +0 -7
  121. package/dist/lib/node/chunk-NOB7CIIC.cjs +0 -2791
  122. package/dist/lib/node/chunk-NOB7CIIC.cjs.map +0 -7
  123. package/dist/lib/node/testing/index.cjs +0 -672
  124. package/dist/lib/node/testing/index.cjs.map +0 -7
  125. package/dist/lib/node-esm/chunk-SAWYU3V5.mjs +0 -2788
  126. package/dist/lib/node-esm/chunk-SAWYU3V5.mjs.map +0 -7
  127. package/dist/lib/node-esm/testing/index.mjs +0 -659
  128. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  129. package/dist/types/src/ai-service/client.test.d.ts +0 -2
  130. package/dist/types/src/ai-service/client.test.d.ts.map +0 -1
  131. package/dist/types/src/ai-service/defs.d.ts +0 -9
  132. package/dist/types/src/ai-service/defs.d.ts.map +0 -1
  133. package/dist/types/src/ai-service/edge-client.d.ts +0 -18
  134. package/dist/types/src/ai-service/edge-client.d.ts.map +0 -1
  135. package/dist/types/src/ai-service/index.d.ts +0 -10
  136. package/dist/types/src/ai-service/index.d.ts.map +0 -1
  137. package/dist/types/src/ai-service/message-collector.d.ts +0 -82
  138. package/dist/types/src/ai-service/message-collector.d.ts.map +0 -1
  139. package/dist/types/src/ai-service/ollama-client.d.ts +0 -43
  140. package/dist/types/src/ai-service/ollama-client.d.ts.map +0 -1
  141. package/dist/types/src/ai-service/parser.d.ts.map +0 -1
  142. package/dist/types/src/ai-service/service.d.ts +0 -25
  143. package/dist/types/src/ai-service/service.d.ts.map +0 -1
  144. package/dist/types/src/ai-service/stream.d.ts +0 -40
  145. package/dist/types/src/ai-service/stream.d.ts.map +0 -1
  146. package/dist/types/src/ai-service/stream.test.d.ts +0 -2
  147. package/dist/types/src/ai-service/stream.test.d.ts.map +0 -1
  148. package/dist/types/src/ai-service/testing/index.d.ts +0 -3
  149. package/dist/types/src/ai-service/testing/index.d.ts.map +0 -1
  150. package/dist/types/src/ai-service/testing/mock.d.ts +0 -11
  151. package/dist/types/src/ai-service/testing/mock.d.ts.map +0 -1
  152. package/dist/types/src/ai-service/testing/test-stream.d.ts +0 -7
  153. package/dist/types/src/ai-service/testing/test-stream.d.ts.map +0 -1
  154. package/dist/types/src/ai-service/transform.d.ts +0 -27
  155. package/dist/types/src/ai-service/transform.d.ts.map +0 -1
  156. package/dist/types/src/ai-service/types.d.ts +0 -210
  157. package/dist/types/src/ai-service/types.d.ts.map +0 -1
  158. package/dist/types/src/ai-service/util/index.d.ts +0 -2
  159. package/dist/types/src/ai-service/util/index.d.ts.map +0 -1
  160. package/dist/types/src/ai-service/util/sse.d.ts +0 -39
  161. package/dist/types/src/ai-service/util/sse.d.ts.map +0 -1
  162. package/dist/types/src/experimental/conversation/conversation.d.ts +0 -61
  163. package/dist/types/src/experimental/conversation/conversation.d.ts.map +0 -1
  164. package/dist/types/src/experimental/conversation/conversation.test.d.ts +0 -2
  165. package/dist/types/src/experimental/conversation/conversation.test.d.ts.map +0 -1
  166. package/dist/types/src/experimental/conversation/index.d.ts +0 -2
  167. package/dist/types/src/experimental/conversation/index.d.ts.map +0 -1
  168. package/dist/types/src/experimental/conversation/types.d.ts +0 -78
  169. package/dist/types/src/experimental/conversation/types.d.ts.map +0 -1
  170. package/dist/types/src/experimental/cypher/ast.d.ts +0 -56
  171. package/dist/types/src/experimental/cypher/ast.d.ts.map +0 -1
  172. package/dist/types/src/experimental/cypher/combinators.d.ts +0 -14
  173. package/dist/types/src/experimental/cypher/combinators.d.ts.map +0 -1
  174. package/dist/types/src/experimental/cypher/combinators.test.d.ts +0 -2
  175. package/dist/types/src/experimental/cypher/combinators.test.d.ts.map +0 -1
  176. package/dist/types/src/experimental/cypher/echo-data-source.d.ts +0 -16
  177. package/dist/types/src/experimental/cypher/echo-data-source.d.ts.map +0 -1
  178. package/dist/types/src/experimental/cypher/execution-plan.d.ts +0 -49
  179. package/dist/types/src/experimental/cypher/execution-plan.d.ts.map +0 -1
  180. package/dist/types/src/experimental/cypher/execution-plan.test.d.ts +0 -2
  181. package/dist/types/src/experimental/cypher/execution-plan.test.d.ts.map +0 -1
  182. package/dist/types/src/experimental/cypher/index.d.ts +0 -5
  183. package/dist/types/src/experimental/cypher/index.d.ts.map +0 -1
  184. package/dist/types/src/experimental/cypher/parjs.d.ts +0 -4
  185. package/dist/types/src/experimental/cypher/parjs.d.ts.map +0 -1
  186. package/dist/types/src/experimental/cypher/parser.d.ts +0 -6
  187. package/dist/types/src/experimental/cypher/parser.d.ts.map +0 -1
  188. package/dist/types/src/experimental/cypher/query-executor.d.ts +0 -26
  189. package/dist/types/src/experimental/cypher/query-executor.d.ts.map +0 -1
  190. package/dist/types/src/experimental/cypher/query-executor.test.d.ts +0 -2
  191. package/dist/types/src/experimental/cypher/query-executor.test.d.ts.map +0 -1
  192. package/dist/types/src/experimental/cypher/schema.d.ts +0 -12
  193. package/dist/types/src/experimental/cypher/schema.d.ts.map +0 -1
  194. package/dist/types/src/experimental/cypher/schema.test.d.ts +0 -2
  195. package/dist/types/src/experimental/cypher/schema.test.d.ts.map +0 -1
  196. package/dist/types/src/experimental/index.d.ts +0 -3
  197. package/dist/types/src/experimental/index.d.ts.map +0 -1
  198. package/dist/types/src/experimental/ner/ner.test.d.ts +0 -2
  199. package/dist/types/src/experimental/ner/ner.test.d.ts.map +0 -1
  200. package/dist/types/src/experimental/research/exa.d.ts +0 -6
  201. package/dist/types/src/experimental/research/exa.d.ts.map +0 -1
  202. package/dist/types/src/experimental/research/research.test.d.ts.map +0 -1
  203. package/dist/types/src/session/tools.d.ts +0 -18
  204. package/dist/types/src/session/tools.d.ts.map +0 -1
  205. package/dist/types/src/testing/artifacts.test.d.ts +0 -1
  206. package/dist/types/src/testing/artifacts.test.d.ts.map +0 -1
  207. package/dist/types/src/testing/data.d.ts +0 -2
  208. package/dist/types/src/testing/data.d.ts.map +0 -1
  209. package/dist/types/src/testing/defs.d.ts +0 -5
  210. package/dist/types/src/testing/defs.d.ts.map +0 -1
  211. package/dist/types/src/testing/logger.d.ts +0 -12
  212. package/dist/types/src/testing/logger.d.ts.map +0 -1
  213. package/dist/types/src/testing/object-extraction.test.d.ts +0 -1
  214. package/dist/types/src/testing/object-extraction.test.d.ts.map +0 -1
  215. package/dist/types/src/testing/ollama.d.ts +0 -6
  216. package/dist/types/src/testing/ollama.d.ts.map +0 -1
  217. package/dist/types/src/testing/printer.d.ts +0 -6
  218. package/dist/types/src/testing/printer.d.ts.map +0 -1
  219. package/dist/types/src/testing/query-promts.d.ts +0 -5
  220. package/dist/types/src/testing/query-promts.d.ts.map +0 -1
  221. package/dist/types/src/testing/query.test.d.ts +0 -2
  222. package/dist/types/src/testing/query.test.d.ts.map +0 -1
  223. package/dist/types/src/testing/test-data.d.ts +0 -29
  224. package/dist/types/src/testing/test-data.d.ts.map +0 -1
  225. package/dist/types/src/testing/test-schema.d.ts +0 -52
  226. package/dist/types/src/testing/test-schema.d.ts.map +0 -1
  227. package/dist/types/src/util/index.d.ts +0 -2
  228. package/dist/types/src/util/index.d.ts.map +0 -1
  229. package/dist/types/src/util/trim.d.ts +0 -5
  230. package/dist/types/src/util/trim.d.ts.map +0 -1
  231. package/src/ai-service/client.test.ts +0 -247
  232. package/src/ai-service/defs.ts +0 -39
  233. package/src/ai-service/edge-client.ts +0 -60
  234. package/src/ai-service/index.ts +0 -13
  235. package/src/ai-service/message-collector.ts +0 -84
  236. package/src/ai-service/ollama-client.ts +0 -506
  237. package/src/ai-service/parser.ts +0 -369
  238. package/src/ai-service/service.ts +0 -31
  239. package/src/ai-service/stream.test.ts +0 -125
  240. package/src/ai-service/stream.ts +0 -118
  241. package/src/ai-service/testing/index.ts +0 -6
  242. package/src/ai-service/testing/mock.ts +0 -30
  243. package/src/ai-service/testing/test-stream.ts +0 -93
  244. package/src/ai-service/transform.ts +0 -121
  245. package/src/ai-service/types.ts +0 -112
  246. package/src/ai-service/util/index.ts +0 -5
  247. package/src/ai-service/util/sse.ts +0 -341
  248. package/src/bin/chat.ts +0 -79
  249. package/src/experimental/conversation/conversation.test.ts +0 -73
  250. package/src/experimental/conversation/conversation.ts +0 -142
  251. package/src/experimental/conversation/index.ts +0 -5
  252. package/src/experimental/conversation/types.ts +0 -126
  253. package/src/experimental/cypher/ast.ts +0 -75
  254. package/src/experimental/cypher/combinators.test.ts +0 -137
  255. package/src/experimental/cypher/combinators.ts +0 -148
  256. package/src/experimental/cypher/echo-data-source.ts +0 -105
  257. package/src/experimental/cypher/execution-plan.test.ts +0 -44
  258. package/src/experimental/cypher/execution-plan.ts +0 -208
  259. package/src/experimental/cypher/index.ts +0 -8
  260. package/src/experimental/cypher/parjs-shims.d.ts +0 -10
  261. package/src/experimental/cypher/parjs.ts +0 -10
  262. package/src/experimental/cypher/parser.ts +0 -19
  263. package/src/experimental/cypher/query-executor.test.ts +0 -47
  264. package/src/experimental/cypher/query-executor.ts +0 -145
  265. package/src/experimental/cypher/schema.test.ts +0 -17
  266. package/src/experimental/cypher/schema.ts +0 -86
  267. package/src/experimental/index.ts +0 -6
  268. package/src/experimental/ner/ner.test.ts +0 -163
  269. package/src/experimental/research/exa.ts +0 -38
  270. package/src/experimental/research/instructions.tpl +0 -64
  271. package/src/experimental/research/research.test.ts +0 -263
  272. package/src/session/tools.ts +0 -117
  273. package/src/testing/artifacts.test.ts +0 -182
  274. package/src/testing/data.ts +0 -13
  275. package/src/testing/defs.ts +0 -9
  276. package/src/testing/logger.ts +0 -129
  277. package/src/testing/object-extraction.test.ts +0 -71
  278. package/src/testing/ollama.ts +0 -15
  279. package/src/testing/printer.ts +0 -41
  280. package/src/testing/query-promts.ts +0 -75
  281. package/src/testing/query.test.ts +0 -88
  282. package/src/testing/test-data.ts +0 -379
  283. package/src/testing/test-schema.ts +0 -79
  284. package/src/util/index.ts +0 -5
  285. package/src/util/trim.ts +0 -15
  286. package/vendor/parjs-browser.mjs +0 -4
  287. package/vendor/parjs-default.mjs +0 -8
  288. /package/dist/types/{src/bin → bin}/chat.d.ts +0 -0
  289. /package/dist/types/src/{experimental/research → research}/research.test.d.ts +0 -0
@@ -1,2791 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var chunk_NOB7CIIC_exports = {};
30
- __export(chunk_NOB7CIIC_exports, {
31
- AIServiceEdgeClient: () => AIServiceEdgeClient,
32
- AIServiecOverloadedError: () => AIServiecOverloadedError,
33
- AISession: () => AISession,
34
- DEFAULT_EDGE_MODEL: () => DEFAULT_EDGE_MODEL,
35
- DEFAULT_EDGE_MODELS: () => DEFAULT_EDGE_MODELS,
36
- DEFAULT_OLLAMA_ENDPOINT: () => DEFAULT_OLLAMA_ENDPOINT,
37
- DEFAULT_OLLAMA_MODEL: () => DEFAULT_OLLAMA_MODEL,
38
- DEFAULT_OLLAMA_MODELS: () => DEFAULT_OLLAMA_MODELS,
39
- EchoDataSource: () => EchoDataSource,
40
- GenerateRequest: () => GenerateRequest,
41
- GenerateResponse: () => GenerateResponse,
42
- GenerationStreamImpl: () => GenerationStreamImpl,
43
- LLMModel: () => LLMModel,
44
- MessageCollector: () => MessageCollector,
45
- MixedStreamParser: () => MixedStreamParser,
46
- OllamaClient: () => OllamaClient,
47
- StreamTransform: () => StreamTransform,
48
- ToolTypes: () => ToolTypes,
49
- VersionPin: () => VersionPin,
50
- createArtifactElement: () => createArtifactElement,
51
- createGenerationStream: () => createGenerationStream,
52
- emitMessageAsEvents: () => emitMessageAsEvents,
53
- executeQuery: () => executeQuery,
54
- executeQueryPlan: () => executeQueryPlan,
55
- formatInferredRelationshipLabel: () => formatInferredRelationshipLabel,
56
- formatJsonSchemaForLLM: () => formatJsonSchemaForLLM,
57
- formatNodeLabel: () => formatNodeLabel,
58
- isReference: () => isReference,
59
- isToolUse: () => isToolUse,
60
- mergeMessageBlock: () => mergeMessageBlock,
61
- parseCypherQuery: () => parseCypherQuery,
62
- runLLM: () => runLLM,
63
- runTools: () => runTools,
64
- trim: () => trim
65
- });
66
- module.exports = __toCommonJS(chunk_NOB7CIIC_exports);
67
- var import_async = require("@dxos/async");
68
- var import_log = require("@dxos/log");
69
- var import_invariant = require("@dxos/invariant");
70
- var import_log2 = require("@dxos/log");
71
- var import_effect = require("effect");
72
- var import_artifact = require("@dxos/artifact");
73
- var import_artifact2 = require("@dxos/artifact");
74
- var import_echo_schema = require("@dxos/echo-schema");
75
- var import_invariant2 = require("@dxos/invariant");
76
- var import_log3 = require("@dxos/log");
77
- var import_effect2 = require("effect");
78
- var import_echo_db = require("@dxos/echo-db");
79
- var import_echo_schema2 = require("@dxos/echo-schema");
80
- var import_effect3 = require("effect");
81
- var import_artifact3 = require("@dxos/artifact");
82
- var import_async2 = require("@dxos/async");
83
- var import_echo_db2 = require("@dxos/echo-db");
84
- var import_echo_schema3 = require("@dxos/echo-schema");
85
- var import_invariant3 = require("@dxos/invariant");
86
- var import_log4 = require("@dxos/log");
87
- var import_effect4 = require("effect");
88
- var import_artifact4 = require("@dxos/artifact");
89
- var import_echo_schema4 = require("@dxos/echo-schema");
90
- var import_invariant4 = require("@dxos/invariant");
91
- var import_log5 = require("@dxos/log");
92
- var import_artifact5 = require("@dxos/artifact");
93
- var import_async3 = require("@dxos/async");
94
- var import_echo_schema5 = require("@dxos/echo-schema");
95
- var import_invariant5 = require("@dxos/invariant");
96
- var import_log6 = require("@dxos/log");
97
- var import_util = require("@dxos/util");
98
- var P = __toESM(require("parsimmon"));
99
- var import_echo_schema6 = require("@dxos/echo-schema");
100
- var import_invariant6 = require("@dxos/invariant");
101
- var import_log7 = require("@dxos/log");
102
- var import_parjs = require("#parjs");
103
- var import_log8 = require("@dxos/log");
104
- var import_util2 = require("@dxos/util");
105
- var import_invariant7 = require("@dxos/invariant");
106
- var import_log9 = require("@dxos/log");
107
- var import_debug = require("@dxos/debug");
108
- var import_echo_schema7 = require("@dxos/echo-schema");
109
- var import_debug2 = require("@dxos/debug");
110
- var import_echo_db3 = require("@dxos/echo-db");
111
- var import_echo_schema8 = require("@dxos/echo-schema");
112
- var import_log10 = require("@dxos/log");
113
- var DEFAULT_EDGE_MODEL = "@anthropic/claude-3-5-sonnet-20241022";
114
- var DEFAULT_EDGE_MODELS = [
115
- // AI Gateway.
116
- // https://developers.cloudflare.com/ai-gateway
117
- "@anthropic/claude-3-5-haiku-20241022",
118
- "@anthropic/claude-3-5-sonnet-20241022",
119
- "@anthropic/claude-3-7-sonnet-20250219",
120
- // Workers AI.
121
- // https://developers.cloudflare.com/workers-ai/models
122
- "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b",
123
- "@hf/nousresearch/hermes-2-pro-mistral-7b",
124
- "@ollama/llama-3-1-nemotron-70b-instruct",
125
- "@ollama/llama-3-1-nemotron-mini-4b-instruct",
126
- "@ollama/llama-3-2-3b"
127
- ];
128
- var DEFAULT_OLLAMA_ENDPOINT = "http://localhost:11434";
129
- var DEFAULT_OLLAMA_MODEL = "llama3.2:1b";
130
- var DEFAULT_OLLAMA_MODELS = [
131
- //
132
- "llama3.2:1b",
133
- "llama3:70b",
134
- "deepseek-r1:latest"
135
- ];
136
- async function* iterSSEMessages(response, controller) {
137
- if (!response.body) {
138
- controller.abort();
139
- throw new Error("Attempted to iterate over a response with no body");
140
- }
141
- const sseDecoder = new SSEDecoder();
142
- const lineDecoder = new LineDecoder();
143
- const iter = readableStreamAsyncIterable(response.body);
144
- for await (const sseChunk of iterSSEChunks(iter)) {
145
- for (const line of lineDecoder.decode(sseChunk)) {
146
- const sse = sseDecoder.decode(line);
147
- if (sse) {
148
- yield sse;
149
- }
150
- }
151
- }
152
- for (const line of lineDecoder.flush()) {
153
- const sse = sseDecoder.decode(line);
154
- if (sse) {
155
- yield sse;
156
- }
157
- }
158
- }
159
- async function* iterSSEChunks(iterator) {
160
- let data = new Uint8Array();
161
- for await (const chunk of iterator) {
162
- if (chunk == null) {
163
- continue;
164
- }
165
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
166
- const newData = new Uint8Array(data.length + binaryChunk.length);
167
- newData.set(data);
168
- newData.set(binaryChunk, data.length);
169
- data = newData;
170
- let patternIndex;
171
- while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
172
- yield data.slice(0, patternIndex);
173
- data = data.slice(patternIndex);
174
- }
175
- }
176
- if (data.length > 0) {
177
- yield data;
178
- }
179
- }
180
- var findDoubleNewlineIndex = (buffer) => {
181
- const newline = 10;
182
- const carriage = 13;
183
- for (let i = 0; i < buffer.length - 2; i++) {
184
- if (buffer[i] === newline && buffer[i + 1] === newline) {
185
- return i + 2;
186
- }
187
- if (buffer[i] === carriage && buffer[i + 1] === carriage) {
188
- return i + 2;
189
- }
190
- if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) {
191
- return i + 4;
192
- }
193
- }
194
- return -1;
195
- };
196
- var SSEDecoder = class {
197
- constructor() {
198
- this.event = null;
199
- this.data = [];
200
- this.chunks = [];
201
- }
202
- decode(line) {
203
- if (line.endsWith("\r")) {
204
- line = line.substring(0, line.length - 1);
205
- }
206
- if (!line) {
207
- if (!this.event && !this.data.length) {
208
- return null;
209
- }
210
- const sse = {
211
- event: this.event,
212
- data: this.data.join("\n"),
213
- raw: this.chunks
214
- };
215
- this.event = null;
216
- this.data = [];
217
- this.chunks = [];
218
- return sse;
219
- }
220
- this.chunks.push(line);
221
- if (line.startsWith(":")) {
222
- return null;
223
- }
224
- let [fieldname, _, value] = partition(line, ":");
225
- if (value.startsWith(" ")) {
226
- value = value.substring(1);
227
- }
228
- if (fieldname === "event") {
229
- this.event = value;
230
- } else if (fieldname === "data") {
231
- this.data.push(value);
232
- }
233
- return null;
234
- }
235
- };
236
- var partition = (str, delimiter) => {
237
- const index = str.indexOf(delimiter);
238
- if (index !== -1) {
239
- return [
240
- str.substring(0, index),
241
- delimiter,
242
- str.substring(index + delimiter.length)
243
- ];
244
- }
245
- return [
246
- str,
247
- "",
248
- ""
249
- ];
250
- };
251
- function readableStreamAsyncIterable(stream) {
252
- if (stream[Symbol.asyncIterator]) {
253
- return stream;
254
- }
255
- const reader = stream.getReader();
256
- return {
257
- next: async () => {
258
- try {
259
- const result = await reader.read();
260
- if (result?.done) {
261
- reader.releaseLock();
262
- }
263
- return result;
264
- } catch (e) {
265
- reader.releaseLock();
266
- throw e;
267
- }
268
- },
269
- return: async () => {
270
- const cancelPromise = reader.cancel();
271
- reader.releaseLock();
272
- await cancelPromise;
273
- return {
274
- done: true,
275
- value: void 0
276
- };
277
- },
278
- [Symbol.asyncIterator]() {
279
- return this;
280
- }
281
- };
282
- }
283
- var LineDecoder = class _LineDecoder {
284
- static {
285
- this.NEWLINE_CHARS = /* @__PURE__ */ new Set([
286
- "\n",
287
- "\r"
288
- ]);
289
- }
290
- static {
291
- this.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
292
- }
293
- constructor() {
294
- this.buffer = [];
295
- this.trailingCR = false;
296
- }
297
- decode(chunk) {
298
- let text = this.decodeText(chunk);
299
- if (this.trailingCR) {
300
- text = "\r" + text;
301
- this.trailingCR = false;
302
- }
303
- if (text.endsWith("\r")) {
304
- this.trailingCR = true;
305
- text = text.slice(0, -1);
306
- }
307
- if (!text) {
308
- return [];
309
- }
310
- const trailingNewline = _LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || "");
311
- let lines = text.split(_LineDecoder.NEWLINE_REGEXP);
312
- if (trailingNewline) {
313
- lines.pop();
314
- }
315
- if (lines.length === 1 && !trailingNewline) {
316
- this.buffer.push(lines[0]);
317
- return [];
318
- }
319
- if (this.buffer.length > 0) {
320
- lines = [
321
- this.buffer.join("") + lines[0],
322
- ...lines.slice(1)
323
- ];
324
- this.buffer = [];
325
- }
326
- if (!trailingNewline) {
327
- this.buffer = [
328
- lines.pop() || ""
329
- ];
330
- }
331
- return lines;
332
- }
333
- decodeText(bytes) {
334
- if (bytes == null) {
335
- return "";
336
- }
337
- if (typeof bytes === "string") {
338
- return bytes;
339
- }
340
- if (typeof Buffer !== "undefined") {
341
- if (bytes instanceof Buffer) {
342
- return bytes.toString();
343
- }
344
- if (bytes instanceof Uint8Array) {
345
- return Buffer.from(bytes).toString();
346
- }
347
- throw new Error(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`);
348
- }
349
- if (typeof TextDecoder !== "undefined") {
350
- if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
351
- this.textDecoder ??= new TextDecoder("utf8");
352
- return this.textDecoder.decode(bytes);
353
- }
354
- throw new Error(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
355
- }
356
- throw new Error("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.");
357
- }
358
- flush() {
359
- if (!this.buffer.length && !this.trailingCR) {
360
- return [];
361
- }
362
- const lines = [
363
- this.buffer.join("")
364
- ];
365
- this.buffer = [];
366
- this.trailingCR = false;
367
- return lines;
368
- }
369
- };
370
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/stream.ts";
371
- var createGenerationStream = (response, controller = new AbortController()) => {
372
- const iterator = async function* () {
373
- for await (const sse of iterSSEMessages(response, controller)) {
374
- if (sse.event === "completion") {
375
- try {
376
- yield JSON.parse(sse.data);
377
- } catch (err) {
378
- import_log.log.error("could not parse message into JSON:", {
379
- data: sse.data,
380
- raw: sse.raw
381
- }, {
382
- F: __dxlog_file,
383
- L: 22,
384
- S: this,
385
- C: (f, a) => f(...a)
386
- });
387
- throw err;
388
- }
389
- }
390
- if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop") {
391
- try {
392
- yield JSON.parse(sse.data);
393
- } catch (err) {
394
- import_log.log.error("could not parse message into JSON:", {
395
- data: sse.data,
396
- raw: sse.raw
397
- }, {
398
- F: __dxlog_file,
399
- L: 38,
400
- S: this,
401
- C: (f, a) => f(...a)
402
- });
403
- throw err;
404
- }
405
- }
406
- if (sse.event === "ping") {
407
- continue;
408
- }
409
- if (sse.event === "error") {
410
- throw new Error(`Message generation error: ${sse.data}`);
411
- }
412
- }
413
- };
414
- return new GenerationStreamImpl(controller, iterator);
415
- };
416
- var GenerationStreamImpl = class {
417
- constructor(_controller, _getIterator) {
418
- this._controller = _controller;
419
- this._getIterator = _getIterator;
420
- this._done = new import_async.Trigger();
421
- this._iterator = void 0;
422
- }
423
- /**
424
- * Returns an iterator over the stream.
425
- */
426
- [Symbol.asyncIterator]() {
427
- return this._createIterator();
428
- }
429
- /**
430
- * Aborts the stream.
431
- */
432
- abort() {
433
- this._controller.abort();
434
- }
435
- /**
436
- * Returns the complete message list generated by the AI service.
437
- */
438
- async complete() {
439
- await this._done.wait();
440
- }
441
- /**
442
- * Creates an iterator over the stream.
443
- */
444
- _createIterator() {
445
- const self = this;
446
- return this._iterator ??= (() => {
447
- const generator = async function* () {
448
- try {
449
- for await (const event of self._getIterator()) {
450
- yield event;
451
- }
452
- this._done.wake();
453
- } catch (err) {
454
- this._done.throw(err);
455
- throw err;
456
- }
457
- };
458
- return generator.call(this);
459
- })();
460
- }
461
- };
462
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/edge-client.ts";
463
- var AIServiceEdgeClient = class {
464
- constructor({ endpoint }) {
465
- (0, import_invariant.invariant)(endpoint, "endpoint is required", {
466
- F: __dxlog_file2,
467
- L: 20,
468
- S: this,
469
- A: [
470
- "endpoint",
471
- "'endpoint is required'"
472
- ]
473
- });
474
- this._endpoint = endpoint;
475
- }
476
- /**
477
- * Generate non-streaming response.
478
- */
479
- async exec(request) {
480
- throw new Error("Not implemented");
481
- }
482
- /**
483
- * Process request and open message stream.
484
- */
485
- async execStream(request) {
486
- (0, import_invariant.assertArgument)(typeof request.model === "string", "model is required");
487
- (0, import_log2.log)("requesting", {
488
- endpoint: this._endpoint
489
- }, {
490
- F: __dxlog_file2,
491
- L: 36,
492
- S: this,
493
- C: (f, a) => f(...a)
494
- });
495
- const controller = new AbortController();
496
- const response = await fetch(`${this._endpoint}/generate`, {
497
- signal: controller.signal,
498
- method: "POST",
499
- headers: {
500
- "Content-Type": "application/json"
501
- },
502
- body: JSON.stringify({
503
- // TODO(dmaretskyi): Errors if tools are not provided.
504
- tools: request.tools ?? [],
505
- ...request
506
- })
507
- });
508
- if (!response.ok) {
509
- throw await parseErrorResponse(response);
510
- }
511
- (0, import_invariant.invariant)(response.body instanceof ReadableStream, void 0, {
512
- F: __dxlog_file2,
513
- L: 53,
514
- S: this,
515
- A: [
516
- "response.body instanceof ReadableStream",
517
- ""
518
- ]
519
- });
520
- return createGenerationStream(response, controller);
521
- }
522
- };
523
- var parseErrorResponse = async (response) => {
524
- throw new Error(`AI Service error: ${response.status} ${response.statusText} ${await response.text()}`);
525
- };
526
- var MessageCollector = class {
527
- constructor() {
528
- this._messages = [];
529
- this._pendingMessage = void 0;
530
- }
531
- get messages() {
532
- return this._messages;
533
- }
534
- get pendingMessage() {
535
- return this._pendingMessage;
536
- }
537
- push(event) {
538
- switch (event.type) {
539
- case "message_start":
540
- this._pendingMessage = event.message;
541
- break;
542
- case "message_stop":
543
- if (this._pendingMessage) {
544
- this._messages.push(this._pendingMessage);
545
- this._pendingMessage = void 0;
546
- }
547
- break;
548
- case "content_block_start":
549
- if (this._pendingMessage) {
550
- this._pendingMessage.content = this._pendingMessage.content || [];
551
- this._pendingMessage.content[event.index] = event.content;
552
- }
553
- break;
554
- case "content_block_delta":
555
- if (this._pendingMessage && this._pendingMessage.content) {
556
- const block = this._pendingMessage.content[event.index];
557
- if (block && event.delta.type === "text_delta" && block.type === "text") {
558
- block.text = (block.text || "") + event.delta.text;
559
- }
560
- }
561
- break;
562
- case "content_block_stop":
563
- if (this._pendingMessage && this._pendingMessage.content) {
564
- const block = this._pendingMessage.content[event.index];
565
- if (block) {
566
- block.pending = false;
567
- }
568
- }
569
- break;
570
- case "message_delta":
571
- if (this._pendingMessage && event.delta) {
572
- Object.assign(this._pendingMessage, event.delta);
573
- }
574
- break;
575
- }
576
- }
577
- pushMessage(message) {
578
- this._messages.push(message);
579
- }
580
- };
581
- function* emitMessageAsEvents(message) {
582
- yield {
583
- type: "message_start",
584
- message
585
- };
586
- yield {
587
- type: "message_stop"
588
- };
589
- }
590
- var createArtifactElement = (id) => `<artifact id=${id} />`;
591
- var LLMModel = import_effect.Schema.Literal(...DEFAULT_EDGE_MODELS, ...DEFAULT_OLLAMA_MODELS);
592
- var ToolTypes = Object.freeze({
593
- // TODO(dmaretskyi): Not implemented yet.
594
- // DatabaseQuery: 'database_query',
595
- TextToImage: "text_to_image"
596
- });
597
- var GenerateRequest = import_effect.Schema.Struct({
598
- /**
599
- * Preferred model or system default.
600
- */
601
- model: import_effect.Schema.optional(LLMModel),
602
- /**
603
- * Tools available for the LLM.
604
- */
605
- tools: import_effect.Schema.optional(import_effect.Schema.Array(import_artifact.Tool).pipe(import_effect.Schema.mutable)),
606
- /**
607
- * System instructions to the LLM.
608
- */
609
- systemPrompt: import_effect.Schema.optional(import_effect.Schema.String),
610
- /**
611
- * History of messages to include in the context window.
612
- */
613
- // TODO(burdon): Rename messages.
614
- history: import_effect.Schema.optional(import_effect.Schema.Array(import_artifact.Message)),
615
- /**
616
- * Current request.
617
- */
618
- prompt: import_effect.Schema.optional(import_artifact.Message)
619
- });
620
- var GenerateResponse = import_effect.Schema.Struct({
621
- messages: import_effect.Schema.Array(import_artifact.Message),
622
- /**
623
- * Number of tokens used in the response.
624
- */
625
- tokenCount: import_effect.Schema.optional(import_effect.Schema.Number)
626
- });
627
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/session/tools.ts";
628
- var isToolUse = (message, { onlyToolNames } = {}) => {
629
- const block = message.content.at(-1);
630
- (0, import_invariant2.invariant)(block, void 0, {
631
- F: __dxlog_file3,
632
- L: 12,
633
- S: void 0,
634
- A: [
635
- "block",
636
- ""
637
- ]
638
- });
639
- return block.type === "tool_use" && (!onlyToolNames || onlyToolNames.includes(block.name));
640
- };
641
- var runTools = async ({ message, tools, extensions }) => {
642
- const toolCalls = message.content.filter((block) => block.type === "tool_use");
643
- (0, import_invariant2.invariant)(toolCalls.length === 1, void 0, {
644
- F: __dxlog_file3,
645
- L: 34,
646
- S: void 0,
647
- A: [
648
- "toolCalls.length === 1",
649
- ""
650
- ]
651
- });
652
- const toolCall = toolCalls[0];
653
- const tool = tools.find((tool2) => tool2.name === toolCall.name);
654
- if (!tool) {
655
- const resultMessage = (0, import_echo_schema.create)(import_artifact2.Message, {
656
- role: "user",
657
- content: [
658
- {
659
- type: "tool_result",
660
- toolUseId: toolCall.id,
661
- content: `Tool not found: ${toolCall.name}`,
662
- isError: true
663
- }
664
- ]
665
- });
666
- return {
667
- type: "continue",
668
- message: resultMessage
669
- };
670
- }
671
- let toolResult;
672
- try {
673
- (0, import_invariant2.invariant)(tool.execute, void 0, {
674
- F: __dxlog_file3,
675
- L: 59,
676
- S: void 0,
677
- A: [
678
- "tool.execute",
679
- ""
680
- ]
681
- });
682
- toolResult = await tool.execute(toolCall.input, {
683
- extensions
684
- });
685
- } catch (error) {
686
- (0, import_log3.log)("tool error", {
687
- error
688
- }, {
689
- F: __dxlog_file3,
690
- L: 62,
691
- S: void 0,
692
- C: (f, a) => f(...a)
693
- });
694
- toolResult = import_artifact2.ToolResult.Error(error.message);
695
- }
696
- switch (toolResult.kind) {
697
- case "error": {
698
- (0, import_log3.log)("tool error", {
699
- message: toolResult.message
700
- }, {
701
- F: __dxlog_file3,
702
- L: 68,
703
- S: void 0,
704
- C: (f, a) => f(...a)
705
- });
706
- const resultMessage = (0, import_echo_schema.create)(import_artifact2.Message, {
707
- role: "user",
708
- content: [
709
- {
710
- type: "tool_result",
711
- toolUseId: toolCall.id,
712
- content: toolResult.message,
713
- isError: true
714
- }
715
- ]
716
- });
717
- return {
718
- type: "continue",
719
- message: resultMessage
720
- };
721
- }
722
- case "success": {
723
- (0, import_log3.log)("tool success", {
724
- result: toolResult.result
725
- }, {
726
- F: __dxlog_file3,
727
- L: 89,
728
- S: void 0,
729
- C: (f, a) => f(...a)
730
- });
731
- const resultMessage = (0, import_echo_schema.create)(import_artifact2.Message, {
732
- role: "user",
733
- content: [
734
- {
735
- type: "tool_result",
736
- toolUseId: toolCall.id,
737
- content: typeof toolResult.result === "string" ? toolResult.result : JSON.stringify(toolResult.result) ?? ""
738
- },
739
- ...toolResult.extractContentBlocks ?? []
740
- ]
741
- });
742
- return {
743
- type: "continue",
744
- message: resultMessage
745
- };
746
- }
747
- case "break": {
748
- (0, import_log3.log)("tool break", {
749
- result: toolResult.result
750
- }, {
751
- F: __dxlog_file3,
752
- L: 110,
753
- S: void 0,
754
- C: (f, a) => f(...a)
755
- });
756
- return {
757
- type: "break",
758
- result: toolResult.result
759
- };
760
- }
761
- }
762
- };
763
- var ObjectVersionSchema = import_effect2.Schema.Unknown;
764
- var VersionPinSchema = import_effect2.Schema.Struct({
765
- // TODO(dmaretskyi): Use Ref when those support encoding.
766
- objectId: import_echo_schema2.ObjectId,
767
- // TODO(dmaretskyi): Could be opaque
768
- version: ObjectVersionSchema
769
- });
770
- var VersionPin = class extends VersionPinSchema {
771
- static {
772
- this.DISPOSITION = "version-pin";
773
- }
774
- static fromObject(object) {
775
- return VersionPin.make({
776
- objectId: object.id,
777
- version: (0, import_echo_db.getVersion)(object)
778
- });
779
- }
780
- static createBlock(pin) {
781
- return {
782
- type: "json",
783
- disposition: VersionPin.DISPOSITION,
784
- json: JSON.stringify(pin)
785
- };
786
- }
787
- };
788
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/ollama-client.ts";
789
- var OllamaClient = class {
790
- /**
791
- * Check if Ollama server is running and accessible.
792
- * @returns Promise that resolves to true if Ollama is running, false otherwise.
793
- */
794
- static async isRunning() {
795
- try {
796
- const response = await fetch(`${DEFAULT_OLLAMA_ENDPOINT}/api/version`, {
797
- method: "GET",
798
- headers: {
799
- "Content-Type": "application/json"
800
- },
801
- signal: AbortSignal.timeout(100)
802
- });
803
- return response.ok;
804
- } catch (error) {
805
- return false;
806
- }
807
- }
808
- constructor({ endpoint, tools, overrides, maxToolInvocations } = {}) {
809
- this._endpoint = endpoint ?? DEFAULT_OLLAMA_ENDPOINT;
810
- this._tools = tools ?? [];
811
- this._modelOverride = overrides?.model;
812
- this._temperatureOverride = overrides?.temperature;
813
- this._maxToolInvocations = maxToolInvocations ?? 3;
814
- }
815
- _getEmbededTools(clientTools) {
816
- return [
817
- ...this._tools,
818
- ...clientTools.filter((tool) => tool.type !== void 0 && WELL_KNOWN_TOOLS[tool.type]).map((tool) => WELL_KNOWN_TOOLS[tool.type])
819
- ];
820
- }
821
- async *_generateStream(request, signal) {
822
- (0, import_invariant4.invariant)(request.prompt === void 0, "Prompt must be in history", {
823
- F: __dxlog_file4,
824
- L: 88,
825
- S: this,
826
- A: [
827
- "request.prompt === undefined",
828
- "'Prompt must be in history'"
829
- ]
830
- });
831
- const ollamaRequest = {
832
- model: this._modelOverride ?? request.model ?? "llama3",
833
- messages: [],
834
- stream: true,
835
- options: {
836
- temperature: this._temperatureOverride
837
- }
838
- };
839
- if (request.systemPrompt) {
840
- ollamaRequest.messages.push({
841
- role: "system",
842
- content: request.systemPrompt
843
- });
844
- }
845
- if (request.history?.length) {
846
- for (const message of request.history) {
847
- const role = message.role === "assistant" ? "assistant" : "user";
848
- if (message.content.length === 0) {
849
- continue;
850
- }
851
- for (const content of message.content) {
852
- switch (content.type) {
853
- case "text": {
854
- ollamaRequest.messages.push({
855
- role,
856
- content: content.text
857
- });
858
- break;
859
- }
860
- case "tool_use": {
861
- ollamaRequest.messages.push({
862
- role: "assistant",
863
- content: "",
864
- tool_calls: [
865
- {
866
- function: {
867
- name: content.name,
868
- arguments: content.input
869
- }
870
- }
871
- ]
872
- });
873
- break;
874
- }
875
- case "tool_result": {
876
- ollamaRequest.messages.push({
877
- role: "tool",
878
- content: JSON.stringify({
879
- type: "tool_result",
880
- toolUseId: content.toolUseId,
881
- content: content.content
882
- })
883
- });
884
- break;
885
- }
886
- }
887
- }
888
- }
889
- }
890
- if (request.tools?.length || this._tools.length) {
891
- const allTools = [
892
- ...request.tools ?? [],
893
- ...this._tools
894
- ];
895
- const withWellKnownTools = allTools.map((tool) => tool.type !== void 0 && WELL_KNOWN_TOOLS[tool.type] ? WELL_KNOWN_TOOLS[tool.type] : tool);
896
- if (withWellKnownTools.length > 0) {
897
- ollamaRequest.tools = withWellKnownTools.map((tool) => ({
898
- type: "function",
899
- function: {
900
- name: tool.name,
901
- description: tool.description,
902
- parameters: {
903
- type: "object",
904
- properties: tool.parameters?.properties,
905
- required: tool.parameters?.required
906
- }
907
- }
908
- }));
909
- }
910
- }
911
- (0, import_log5.log)("generate request", {
912
- history: request.history,
913
- prompt: request.prompt,
914
- ollamaRequest
915
- }, {
916
- F: __dxlog_file4,
917
- L: 182,
918
- S: this,
919
- C: (f, a) => f(...a)
920
- });
921
- const response = await fetch(`${this._endpoint}/api/chat`, {
922
- method: "POST",
923
- headers: {
924
- "Content-Type": "application/json"
925
- },
926
- body: JSON.stringify(ollamaRequest),
927
- signal
928
- });
929
- if (!response.ok) {
930
- throw await parseErrorResponse2(response);
931
- }
932
- if (!response.body) {
933
- throw new Error("Ollama API returned no response body");
934
- }
935
- const reader = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new OllamaDecoderStream()).getReader();
936
- try {
937
- const messageId = import_echo_schema4.ObjectId.random();
938
- yield {
939
- type: "message_start",
940
- message: {
941
- id: messageId,
942
- role: "assistant",
943
- content: []
944
- }
945
- };
946
- const textBlock = {
947
- type: "text",
948
- text: ""
949
- };
950
- let currentBlockIndex = 0;
951
- yield {
952
- type: "content_block_start",
953
- index: currentBlockIndex,
954
- content: textBlock
955
- };
956
- while (true) {
957
- const { done, value: data } = await reader.read();
958
- if (done) {
959
- break;
960
- }
961
- (0, import_log5.log)("ollama data", {
962
- data
963
- }, {
964
- F: __dxlog_file4,
965
- L: 244,
966
- S: this,
967
- C: (f, a) => f(...a)
968
- });
969
- if (data.message?.content) {
970
- yield {
971
- type: "content_block_delta",
972
- index: 0,
973
- delta: {
974
- type: "text_delta",
975
- text: data.message.content
976
- }
977
- };
978
- }
979
- if (data.message?.tool_calls && data.message?.tool_calls?.length > 0) {
980
- if (data.message.tool_calls.length > 1) {
981
- import_log5.log.warn("Ollama returned multiple tool calls. Only the first one will be used.", void 0, {
982
- F: __dxlog_file4,
983
- L: 261,
984
- S: this,
985
- C: (f, a) => f(...a)
986
- });
987
- }
988
- yield {
989
- type: "content_block_stop",
990
- index: currentBlockIndex++
991
- };
992
- yield {
993
- type: "content_block_start",
994
- index: currentBlockIndex,
995
- content: {
996
- type: "tool_use",
997
- id: import_echo_schema4.ObjectId.random(),
998
- name: data.message.tool_calls[0].function.name,
999
- input: sanitizeToolArguments(data.message.tool_calls[0].function.arguments)
1000
- }
1001
- };
1002
- yield {
1003
- type: "message_delta",
1004
- delta: {
1005
- stopReason: "tool_use"
1006
- }
1007
- };
1008
- }
1009
- }
1010
- yield {
1011
- type: "content_block_stop",
1012
- index: currentBlockIndex
1013
- };
1014
- yield {
1015
- type: "message_stop"
1016
- };
1017
- } finally {
1018
- reader.releaseLock();
1019
- }
1020
- }
1021
- /**
1022
- * Generate non-streaming response.
1023
- */
1024
- async exec(request) {
1025
- throw new Error("Not implemented");
1026
- }
1027
- async execStream(request) {
1028
- const controller = new AbortController();
1029
- try {
1030
- return new GenerationStreamImpl(controller, async function* () {
1031
- const collector = new MessageCollector();
1032
- let toolInvocations = 0;
1033
- while (true) {
1034
- for await (const event of this._generateStream({
1035
- ...request,
1036
- history: [
1037
- ...request.history ?? [],
1038
- ...request.prompt ? [
1039
- request.prompt
1040
- ] : [],
1041
- ...collector.messages
1042
- ],
1043
- prompt: void 0
1044
- }, controller.signal)) {
1045
- collector.push(event);
1046
- yield event;
1047
- }
1048
- if (collector.messages.length > 0 && !isToolUse(collector.messages.at(-1), {
1049
- onlyToolNames: this._getEmbededTools(request.tools ?? []).map((tool) => tool.name)
1050
- })) {
1051
- break;
1052
- }
1053
- if (++toolInvocations > this._maxToolInvocations) {
1054
- throw new Error("Maximum number of tool invocations reached");
1055
- }
1056
- const result = await runTools({
1057
- message: collector.messages.at(-1),
1058
- tools: this._getEmbededTools(request.tools ?? [])
1059
- });
1060
- switch (result.type) {
1061
- case "continue": {
1062
- collector.pushMessage(result.message);
1063
- yield* emitMessageAsEvents(result.message);
1064
- break;
1065
- }
1066
- case "break": {
1067
- throw new Error("Tool use breaks not allowed");
1068
- }
1069
- }
1070
- }
1071
- }.bind(this));
1072
- } catch (error) {
1073
- controller.abort();
1074
- throw error;
1075
- }
1076
- }
1077
- };
1078
- var sanitizeToolArguments = (args) => {
1079
- if (args.type === "object" && typeof args.properties === "object" && Array.isArray(args.required)) {
1080
- return args.properties;
1081
- }
1082
- return args;
1083
- };
1084
- var SAMPLE_IMAGE_URL = "https://images.nightcafe.studio/jobs/BNmcRhHCM1JRKoUtqSei/BNmcRhHCM1JRKoUtqSei--1--5b9rv.jpg";
1085
- var WELL_KNOWN_TOOLS = {
1086
- [ToolTypes.TextToImage]: (0, import_artifact4.defineTool)("system", {
1087
- name: "text-to-image",
1088
- description: "Generate an image from a text prompt",
1089
- schema: import_effect4.Schema.Struct({
1090
- prompt: import_effect4.Schema.String.annotations({
1091
- description: "The text prompt describing the image to generate"
1092
- })
1093
- }),
1094
- execute: async ({ prompt }) => {
1095
- const image = await fetch(SAMPLE_IMAGE_URL).then(async (res) => Buffer.from(await res.arrayBuffer()));
1096
- const imageBase64 = image.toString("base64");
1097
- const id = import_echo_schema4.ObjectId.random();
1098
- return import_artifact4.ToolResult.Success(`The generation was successful. Image ID: ${id} Prompt: ${prompt}`, [
1099
- {
1100
- type: "image",
1101
- id,
1102
- source: {
1103
- type: "base64",
1104
- mediaType: "image/jpeg",
1105
- data: imageBase64
1106
- }
1107
- }
1108
- ]);
1109
- }
1110
- })
1111
- };
1112
- var OllamaDecoderStream = class extends TransformStream {
1113
- constructor() {
1114
- super({
1115
- transform: (chunk, controller) => {
1116
- this._buffer += chunk;
1117
- const lines = this._buffer.split("\n");
1118
- this._buffer = lines.pop() || "";
1119
- for (const line of lines) {
1120
- controller.enqueue(JSON.parse(line.trim()));
1121
- }
1122
- },
1123
- flush: (controller) => {
1124
- this._buffer = this._buffer.trim();
1125
- if (this._buffer.length > 0) {
1126
- controller.enqueue(JSON.parse(this._buffer));
1127
- }
1128
- }
1129
- });
1130
- this._buffer = "";
1131
- }
1132
- };
1133
- var ModelDoesNotSupportToolsError = class extends import_effect4.Schema.TaggedError()("ModelDoesNotSupportToolsError", {
1134
- model: import_effect4.Schema.String
1135
- }) {
1136
- };
1137
- var ModelNotFoundError = class extends import_effect4.Schema.TaggedError()("ModelNotFoundError", {
1138
- model: import_effect4.Schema.String
1139
- }) {
1140
- };
1141
- var parseOllamaError = (error) => {
1142
- {
1143
- const match = error.match(/^([^']+) does not support tools$/);
1144
- if (match) {
1145
- return new ModelDoesNotSupportToolsError({
1146
- model: match[1]
1147
- });
1148
- }
1149
- }
1150
- {
1151
- const match = error.match(/^model "([^"]+)" not found, try pulling it first$/);
1152
- if (match) {
1153
- return new ModelNotFoundError({
1154
- model: match[1]
1155
- });
1156
- }
1157
- }
1158
- throw new Error(`Ollama API error: ${error}`);
1159
- };
1160
- var parseErrorResponse2 = async (response) => {
1161
- if (response.headers.get("content-type")?.includes("application/json")) {
1162
- const body = await response.json();
1163
- return parseOllamaError(body.error);
1164
- }
1165
- throw new Error(`Ollama API error: ${response.status} ${response.statusText} ${await response.text()}`);
1166
- };
1167
- var textChunk = P.regexp(/[^<]+/).map((content) => ({
1168
- type: "text",
1169
- content
1170
- }));
1171
- var attribute = P.seq(P.regexp(/[a-zA-Z_][a-zA-Z0-9_-]*/), P.string("=").trim(P.optWhitespace), P.alt(P.regexp(/"[^"]*"/).map((s) => s.slice(1, -1)), P.regexp(/'[^']*'/).map((s) => s.slice(1, -1)))).map(([name, _, value]) => [
1172
- name,
1173
- value
1174
- ]);
1175
- var tagName = P.regexp(/[a-zA-Z_][a-zA-Z0-9_-]*/);
1176
- var selfClosingTag = P.seqMap(
1177
- //
1178
- P.string("<"),
1179
- tagName,
1180
- P.optWhitespace.then(attribute).many(),
1181
- P.optWhitespace.then(P.string("/>")),
1182
- P.optWhitespace,
1183
- (_, tag, attributes, __) => ({
1184
- type: "tag",
1185
- tag,
1186
- attributes: Object.fromEntries(attributes),
1187
- content: [],
1188
- selfClosing: true
1189
- })
1190
- );
1191
- var openTag = P.seqMap(
1192
- //
1193
- P.string("<"),
1194
- tagName,
1195
- P.optWhitespace.then(attribute).many(),
1196
- P.string(">"),
1197
- P.regexp(/[^<]*/),
1198
- (_, tag, attributes, __, content) => ({
1199
- type: "tag",
1200
- tag,
1201
- attributes: Object.fromEntries(attributes),
1202
- content: content.length ? [
1203
- {
1204
- type: "text",
1205
- content
1206
- }
1207
- ] : []
1208
- })
1209
- );
1210
- var closeTag = P.seqMap(
1211
- //
1212
- P.string("</"),
1213
- tagName,
1214
- P.string(">"),
1215
- P.optWhitespace,
1216
- (_, tag) => ({
1217
- type: "tag",
1218
- tag,
1219
- content: [],
1220
- closing: true
1221
- })
1222
- );
1223
- var mixedChunk = P.alt(selfClosingTag, openTag, closeTag, textChunk);
1224
- var StreamTransform = class {
1225
- constructor() {
1226
- this._buffer = "";
1227
- }
1228
- transform(chunk) {
1229
- this._buffer += chunk;
1230
- const results = [];
1231
- const parser = mixedChunk.many().skip(P.optWhitespace);
1232
- const result = parser.parse(this._buffer);
1233
- if (result.status) {
1234
- for (const chunk2 of result.value) {
1235
- results.push(chunk2);
1236
- }
1237
- this._buffer = "";
1238
- }
1239
- return results;
1240
- }
1241
- // TODO(burdon): Process remaining buffer?
1242
- flush() {
1243
- const remaining = this._buffer;
1244
- this._buffer = "";
1245
- return remaining.length > 0 ? [
1246
- {
1247
- type: "text",
1248
- content: remaining
1249
- }
1250
- ] : [];
1251
- }
1252
- };
1253
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/parser.ts";
1254
- var MixedStreamParser = class {
1255
- constructor() {
1256
- this.message = new import_async3.Event();
1257
- this.block = new import_async3.Event();
1258
- this.update = new import_async3.Event();
1259
- this.streamEvent = new import_async3.Event();
1260
- }
1261
- _emitBlock(contentBlock, streamBlock) {
1262
- const messageBlock = streamBlock ? mergeMessageBlock(contentBlock, streamBlock) : contentBlock;
1263
- if (messageBlock) {
1264
- if (messageBlock.type === "text" && messageBlock.text.length === 0) {
1265
- return;
1266
- }
1267
- (0, import_invariant5.invariant)(this._message, void 0, {
1268
- F: __dxlog_file5,
1269
- L: 49,
1270
- S: this,
1271
- A: [
1272
- "this._message",
1273
- ""
1274
- ]
1275
- });
1276
- this._message.content.push(messageBlock);
1277
- this.block.emit(messageBlock);
1278
- }
1279
- }
1280
- _emitUpdate(contentBlock, streamBlock) {
1281
- const messageBlock = mergeMessageBlock(contentBlock, streamBlock);
1282
- if (messageBlock) {
1283
- messageBlock.pending = true;
1284
- this.update.emit(messageBlock);
1285
- }
1286
- }
1287
- /**
1288
- * Parse stream until end.
1289
- */
1290
- async parse(stream) {
1291
- const transformer = new StreamTransform();
1292
- let contentBlock;
1293
- let streamBlock;
1294
- const stack = [];
1295
- const messagesCollected = [];
1296
- for await (const event of stream) {
1297
- (0, import_log6.log)("streamEvent", {
1298
- event
1299
- }, {
1300
- F: __dxlog_file5,
1301
- L: 83,
1302
- S: this,
1303
- C: (f, a) => f(...a)
1304
- });
1305
- this.streamEvent.emit(event);
1306
- switch (event.type) {
1307
- //
1308
- // Messages.
1309
- //
1310
- case "message_start": {
1311
- if (this._message) {
1312
- import_log6.log.warn("unexpected message_start", void 0, {
1313
- F: __dxlog_file5,
1314
- L: 94,
1315
- S: this,
1316
- C: (f, a) => f(...a)
1317
- });
1318
- }
1319
- this._message = (0, import_echo_schema5.create)(import_artifact5.Message, {
1320
- role: event.message.role,
1321
- content: [
1322
- ...event.message.content
1323
- ]
1324
- });
1325
- this.message.emit(this._message);
1326
- break;
1327
- }
1328
- case "message_delta": {
1329
- if (!this._message) {
1330
- import_log6.log.warn("unexpected message_delta", void 0, {
1331
- F: __dxlog_file5,
1332
- L: 104,
1333
- S: this,
1334
- C: (f, a) => f(...a)
1335
- });
1336
- }
1337
- break;
1338
- }
1339
- case "message_stop": {
1340
- if (!this._message) {
1341
- import_log6.log.warn("unexpected message_stop", void 0, {
1342
- F: __dxlog_file5,
1343
- L: 112,
1344
- S: this,
1345
- C: (f, a) => f(...a)
1346
- });
1347
- } else {
1348
- messagesCollected.push(this._message);
1349
- this._message = void 0;
1350
- }
1351
- break;
1352
- }
1353
- //
1354
- // Content blocks.
1355
- //
1356
- case "content_block_start": {
1357
- if (contentBlock) {
1358
- import_log6.log.warn("unexpected content_block_start", {
1359
- content: contentBlock
1360
- }, {
1361
- F: __dxlog_file5,
1362
- L: 126,
1363
- S: this,
1364
- C: (f, a) => f(...a)
1365
- });
1366
- }
1367
- contentBlock = event.content;
1368
- break;
1369
- }
1370
- case "content_block_delta": {
1371
- if (!contentBlock) {
1372
- import_log6.log.warn("unexpected content_block_delta", void 0, {
1373
- F: __dxlog_file5,
1374
- L: 136,
1375
- S: this,
1376
- C: (f, a) => f(...a)
1377
- });
1378
- break;
1379
- }
1380
- switch (event.delta.type) {
1381
- //
1382
- // Text
1383
- //
1384
- case "text_delta": {
1385
- const chunks = transformer.transform(event.delta.text);
1386
- for (const chunk of chunks) {
1387
- (0, import_log6.log)("text_delta", {
1388
- chunk
1389
- }, {
1390
- F: __dxlog_file5,
1391
- L: 147,
1392
- S: this,
1393
- C: (f, a) => f(...a)
1394
- });
1395
- switch (streamBlock?.type) {
1396
- //
1397
- // XML Fragment.
1398
- //
1399
- case "tag": {
1400
- if (chunk.type === "tag") {
1401
- if (chunk.selfClosing) {
1402
- streamBlock.content.push(chunk);
1403
- } else if (chunk.closing) {
1404
- if (stack.length > 0) {
1405
- const top = stack.pop();
1406
- (0, import_invariant5.invariant)(top && top.type === "tag", void 0, {
1407
- F: __dxlog_file5,
1408
- L: 160,
1409
- S: this,
1410
- A: [
1411
- "top && top.type === 'tag'",
1412
- ""
1413
- ]
1414
- });
1415
- (0, import_log6.log)("pop", {
1416
- top
1417
- }, {
1418
- F: __dxlog_file5,
1419
- L: 161,
1420
- S: this,
1421
- C: (f, a) => f(...a)
1422
- });
1423
- top.content.push(streamBlock);
1424
- streamBlock = top;
1425
- } else {
1426
- this._emitBlock(contentBlock, streamBlock);
1427
- streamBlock = void 0;
1428
- }
1429
- } else {
1430
- stack.push(streamBlock);
1431
- streamBlock = chunk;
1432
- }
1433
- } else {
1434
- if (streamBlock.content.length === 0) {
1435
- streamBlock.content.push(chunk);
1436
- } else {
1437
- const last = streamBlock.content.at(-1);
1438
- (0, import_invariant5.invariant)(last, void 0, {
1439
- F: __dxlog_file5,
1440
- L: 178,
1441
- S: this,
1442
- A: [
1443
- "last",
1444
- ""
1445
- ]
1446
- });
1447
- if (last.type === "text") {
1448
- last.content += chunk.content;
1449
- } else {
1450
- streamBlock.content.push(chunk);
1451
- }
1452
- }
1453
- }
1454
- break;
1455
- }
1456
- //
1457
- // Text Fragment.
1458
- //
1459
- case "text": {
1460
- if (chunk.type === "tag") {
1461
- this._emitBlock(contentBlock, streamBlock);
1462
- if (chunk.selfClosing) {
1463
- this._emitBlock(contentBlock, chunk);
1464
- streamBlock = void 0;
1465
- } else {
1466
- streamBlock = chunk;
1467
- }
1468
- } else {
1469
- streamBlock.content += chunk.content;
1470
- }
1471
- break;
1472
- }
1473
- //
1474
- // No current chunk.
1475
- //
1476
- default: {
1477
- if (chunk.type === "tag" && chunk.selfClosing) {
1478
- this._emitBlock(contentBlock, chunk);
1479
- } else {
1480
- streamBlock = chunk;
1481
- }
1482
- }
1483
- }
1484
- }
1485
- break;
1486
- }
1487
- //
1488
- // JSON
1489
- //
1490
- case "input_json_delta": {
1491
- if (!contentBlock) {
1492
- import_log6.log.warn("unexpected input_json_delta", {
1493
- contentBlock
1494
- }, {
1495
- F: __dxlog_file5,
1496
- L: 228,
1497
- S: this,
1498
- C: (f, a) => f(...a)
1499
- });
1500
- break;
1501
- }
1502
- if (streamBlock?.type === "json") {
1503
- streamBlock.content += event.delta.partial_json;
1504
- } else {
1505
- streamBlock = {
1506
- type: "json",
1507
- content: event.delta.partial_json
1508
- };
1509
- }
1510
- break;
1511
- }
1512
- }
1513
- break;
1514
- }
1515
- case "content_block_stop": {
1516
- if (!contentBlock) {
1517
- import_log6.log.warn("unexpected content_block_stop", void 0, {
1518
- F: __dxlog_file5,
1519
- L: 245,
1520
- S: this,
1521
- C: (f, a) => f(...a)
1522
- });
1523
- break;
1524
- }
1525
- this._emitBlock(contentBlock, streamBlock);
1526
- contentBlock = void 0;
1527
- streamBlock = void 0;
1528
- break;
1529
- }
1530
- }
1531
- if (contentBlock && streamBlock) {
1532
- this._emitUpdate(contentBlock, streamBlock);
1533
- }
1534
- }
1535
- return messagesCollected;
1536
- }
1537
- };
1538
- var mergeMessageBlock = (contentBlock, streamBlock) => {
1539
- (0, import_log6.log)("mergeMessageBlock", {
1540
- contentBlock,
1541
- streamBlock
1542
- }, {
1543
- F: __dxlog_file5,
1544
- L: 272,
1545
- S: void 0,
1546
- C: (f, a) => f(...a)
1547
- });
1548
- switch (streamBlock.type) {
1549
- //
1550
- // Text
1551
- //
1552
- case "text": {
1553
- return {
1554
- ...contentBlock,
1555
- type: "text",
1556
- text: streamBlock.content
1557
- };
1558
- }
1559
- //
1560
- // XML
1561
- //
1562
- case "tag": {
1563
- switch (streamBlock.tag) {
1564
- case "cot": {
1565
- const content = streamBlock.content.map((block) => {
1566
- switch (block.type) {
1567
- case "text":
1568
- return block.content;
1569
- default:
1570
- return null;
1571
- }
1572
- }).filter(import_util.isNotFalsy).join("\n");
1573
- return {
1574
- ...contentBlock,
1575
- type: "text",
1576
- disposition: "cot",
1577
- text: content
1578
- };
1579
- }
1580
- case "artifact": {
1581
- const { attributes } = streamBlock;
1582
- return {
1583
- type: "json",
1584
- disposition: "artifact",
1585
- json: JSON.stringify(attributes)
1586
- };
1587
- }
1588
- case "suggest": {
1589
- if (streamBlock.content.length === 1 && streamBlock.content[0].type === "text") {
1590
- return {
1591
- type: "json",
1592
- disposition: "suggest",
1593
- json: JSON.stringify({
1594
- text: streamBlock.content[0].content
1595
- })
1596
- };
1597
- }
1598
- break;
1599
- }
1600
- case "proposal": {
1601
- if (streamBlock.content.length === 1 && streamBlock.content[0].type === "text") {
1602
- return {
1603
- type: "json",
1604
- disposition: "proposal",
1605
- json: JSON.stringify({
1606
- text: streamBlock.content[0].content
1607
- })
1608
- };
1609
- }
1610
- break;
1611
- }
1612
- case "select": {
1613
- return {
1614
- type: "json",
1615
- disposition: "select",
1616
- json: JSON.stringify({
1617
- options: streamBlock.content.flatMap((content) => content.type === "tag" && content.content.length === 1 && content.content[0].type === "text" ? [
1618
- content.content[0].content
1619
- ] : [])
1620
- })
1621
- };
1622
- }
1623
- case "tool-list": {
1624
- return {
1625
- type: "json",
1626
- disposition: "tool_list",
1627
- json: JSON.stringify({})
1628
- };
1629
- }
1630
- }
1631
- break;
1632
- }
1633
- //
1634
- // JSON
1635
- //
1636
- case "json": {
1637
- switch (contentBlock.type) {
1638
- case "tool_use": {
1639
- return {
1640
- ...contentBlock,
1641
- input: (0, import_util.safeParseJson)(streamBlock.content) ?? {}
1642
- };
1643
- }
1644
- }
1645
- return {
1646
- ...contentBlock,
1647
- type: "json",
1648
- disposition: "artifact",
1649
- json: streamBlock.content
1650
- };
1651
- }
1652
- }
1653
- };
1654
- function _ts_decorate(decorators, target, key, desc) {
1655
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1656
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1657
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1658
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1659
- }
1660
- var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/session/session.ts";
1661
- var AISession = class _AISession {
1662
- constructor(_options) {
1663
- this._options = _options;
1664
- this._parser = new MixedStreamParser();
1665
- this._pending = [];
1666
- this._history = [];
1667
- this.message = this._parser.message;
1668
- this.block = this._parser.block;
1669
- this.update = this._parser.update;
1670
- this.streamEvent = this._parser.streamEvent;
1671
- this.userMessage = new import_async2.Event();
1672
- this._parser.message.on((message) => {
1673
- this._pending.push(message);
1674
- });
1675
- }
1676
- async run(options) {
1677
- const systemTools = [];
1678
- switch (this._options.operationModel) {
1679
- case "planning":
1680
- systemTools.push(this._createQueryArtifactsTool(options.artifacts), this._createPlanningTool(options));
1681
- break;
1682
- case "importing":
1683
- systemTools.push(this._createQueryArtifactsTool(options.artifacts), this._createRequireTool(options.artifacts, (artifactDefinitionIds) => {
1684
- for (const artifactDefinitionId of artifactDefinitionIds) {
1685
- requiredArtifactIds.add(artifactDefinitionId);
1686
- }
1687
- }));
1688
- break;
1689
- case "configured":
1690
- break;
1691
- default:
1692
- throw new TypeError(`Invalid operation model: ${this._options.operationModel}`);
1693
- }
1694
- this._history = [
1695
- ...options.history
1696
- ];
1697
- this._pending = [
1698
- await this._formatUserPrompt(options.artifactDiffResolver, options.prompt, options.history)
1699
- ];
1700
- this.userMessage.emit(this._pending.at(-1));
1701
- this._stream = void 0;
1702
- let error;
1703
- const requiredArtifactIds = new Set(options.requiredArtifactIds ?? []);
1704
- try {
1705
- let more = false;
1706
- do {
1707
- const tools = [
1708
- ...systemTools,
1709
- ...options.tools,
1710
- ...options.artifacts.filter((artifact) => requiredArtifactIds.has(artifact.id)).flatMap((artifact) => artifact.tools)
1711
- ];
1712
- (0, import_log4.log)("request", {
1713
- pending: this._pending.length,
1714
- history: this._history.length,
1715
- tools: tools.map((tool) => tool.name)
1716
- }, {
1717
- F: __dxlog_file6,
1718
- L: 181,
1719
- S: this,
1720
- C: (f, a) => f(...a)
1721
- });
1722
- this._stream = await options.client.execStream({
1723
- ...options.generationOptions ?? {},
1724
- // TODO(burdon): Rename messages or separate history/message.
1725
- history: [
1726
- ...this._history,
1727
- ...this._pending
1728
- ],
1729
- tools,
1730
- systemPrompt: options.systemPrompt ?? createBaseInstructions({
1731
- availableArtifacts: Array.from(requiredArtifactIds),
1732
- operationModel: this._options.operationModel
1733
- })
1734
- });
1735
- await this._parser.parse(this._stream);
1736
- await this._stream.complete();
1737
- (0, import_log4.log)("response", {
1738
- pending: this._pending
1739
- }, {
1740
- F: __dxlog_file6,
1741
- L: 206,
1742
- S: this,
1743
- C: (f, a) => f(...a)
1744
- });
1745
- more = false;
1746
- const message = this._pending.at(-1);
1747
- (0, import_invariant3.invariant)(message, void 0, {
1748
- F: __dxlog_file6,
1749
- L: 211,
1750
- S: this,
1751
- A: [
1752
- "message",
1753
- ""
1754
- ]
1755
- });
1756
- if (isToolUse(message)) {
1757
- (0, import_log4.log)("tool request...", void 0, {
1758
- F: __dxlog_file6,
1759
- L: 213,
1760
- S: this,
1761
- C: (f, a) => f(...a)
1762
- });
1763
- const response = await runTools({
1764
- message: this._pending.at(-1),
1765
- tools,
1766
- extensions: options.extensions ?? {}
1767
- });
1768
- (0, import_log4.log)("tool response", {
1769
- response
1770
- }, {
1771
- F: __dxlog_file6,
1772
- L: 220,
1773
- S: this,
1774
- C: (f, a) => f(...a)
1775
- });
1776
- switch (response.type) {
1777
- case "continue": {
1778
- this._pending = [
1779
- ...this._pending,
1780
- response.message
1781
- ];
1782
- this.userMessage.emit(response.message);
1783
- more = true;
1784
- break;
1785
- }
1786
- }
1787
- }
1788
- } while (more);
1789
- } catch (err) {
1790
- import_log4.log.catch(err, void 0, {
1791
- F: __dxlog_file6,
1792
- L: 232,
1793
- S: this,
1794
- C: (f, a) => f(...a)
1795
- });
1796
- if (err instanceof Error && err.message.includes("Overloaded")) {
1797
- error = new AIServiecOverloadedError("AI service overloaded", {
1798
- cause: err
1799
- });
1800
- } else {
1801
- error = new Error("AI service error", {
1802
- cause: err
1803
- });
1804
- }
1805
- } finally {
1806
- this._stream = void 0;
1807
- }
1808
- if (error) {
1809
- throw error;
1810
- }
1811
- return this._pending;
1812
- }
1813
- async runStructured(schema, options) {
1814
- const parser = (0, import_artifact3.structuredOutputParser)(schema);
1815
- const result = await this.run({
1816
- ...options,
1817
- tools: [
1818
- ...options.tools,
1819
- parser.tool
1820
- ]
1821
- });
1822
- return parser.getResult(result);
1823
- }
1824
- async _formatUserPrompt(artifactDiffResolver, prompt, history) {
1825
- const prelude = [];
1826
- if (artifactDiffResolver) {
1827
- const versions = gatherObjectVersions(history);
1828
- const artifactDiff = await artifactDiffResolver(Array.from(versions.entries()).map(([id, version]) => ({
1829
- id,
1830
- lastVersion: version
1831
- })));
1832
- import_log4.log.info("vision", {
1833
- artifactDiff,
1834
- versions
1835
- }, {
1836
- F: __dxlog_file6,
1837
- L: 272,
1838
- S: this,
1839
- C: (f, a) => f(...a)
1840
- });
1841
- for (const [id, { version }] of [
1842
- ...artifactDiff.entries()
1843
- ]) {
1844
- if (import_echo_db2.ObjectVersion.equals(version, versions.get(id))) {
1845
- artifactDiff.delete(id);
1846
- continue;
1847
- }
1848
- prelude.push(VersionPin.createBlock(VersionPin.make({
1849
- objectId: id,
1850
- version
1851
- })));
1852
- }
1853
- if (artifactDiff.size > 0) {
1854
- prelude.push(createArtifactUpdateBlock(artifactDiff));
1855
- }
1856
- }
1857
- return (0, import_echo_schema3.create)(import_artifact3.Message, {
1858
- role: "user",
1859
- content: [
1860
- ...prelude,
1861
- {
1862
- type: "text",
1863
- text: prompt
1864
- }
1865
- ]
1866
- });
1867
- }
1868
- _createQueryArtifactsTool(artifacts) {
1869
- return (0, import_artifact3.defineTool)("system", {
1870
- name: "query_artifact_definitions",
1871
- description: "Query the available artifact definitions",
1872
- schema: import_effect3.Schema.Struct({}),
1873
- execute: async () => {
1874
- return import_artifact3.ToolResult.Success({
1875
- artifactDefinitions: artifacts.map((artifact) => ({
1876
- id: artifact.id,
1877
- name: artifact.name,
1878
- description: artifact.description
1879
- }))
1880
- });
1881
- }
1882
- });
1883
- }
1884
- _createRequireTool(artifacts, onRequire) {
1885
- return (0, import_artifact3.defineTool)("system", {
1886
- name: "require_artifact_definitions",
1887
- description: "Require the use of specific artifact definitions. This will allow the model to interact with artifact definitions and use their tools.",
1888
- schema: import_effect3.Schema.Struct({
1889
- artifactDefinitionIds: import_effect3.Schema.Array(import_effect3.Schema.String).annotations({
1890
- description: "The ids of the artifact definitions to require",
1891
- examples: [
1892
- [
1893
- "artifact:dxos.org/example/Test"
1894
- ]
1895
- ]
1896
- })
1897
- }),
1898
- execute: async ({ artifactDefinitionIds }) => {
1899
- const missingArtifactDefinitionIds = artifactDefinitionIds.filter((artifactId) => !artifacts.some((artifact) => artifact.id === artifactId));
1900
- if (missingArtifactDefinitionIds.length > 0) {
1901
- return import_artifact3.ToolResult.Error(`One or more artifact definition ids are invalid: ${missingArtifactDefinitionIds.join(", ")}`);
1902
- }
1903
- onRequire(artifactDefinitionIds);
1904
- return import_artifact3.ToolResult.Success({});
1905
- }
1906
- });
1907
- }
1908
- _createPlanningTool(options) {
1909
- return (0, import_artifact3.defineTool)("system", {
1910
- name: "create_plan",
1911
- description: "Create a plan. Make sure that each step is independent and can be executed solely on the data returned by the previous step. The steps only share the data that is specified in the plan.",
1912
- schema: import_effect3.Schema.Struct({
1913
- goal: import_effect3.Schema.String.annotations({
1914
- description: "The goal that the plan will achieve."
1915
- }),
1916
- steps: import_effect3.Schema.Array(import_effect3.Schema.Struct({
1917
- action: import_effect3.Schema.String.annotations({
1918
- description: "Complete, detailed action to perform."
1919
- }),
1920
- input: import_effect3.Schema.String.annotations({
1921
- description: "The required input data for this step. First step must not require any data."
1922
- }),
1923
- output: import_effect3.Schema.String.annotations({
1924
- description: "The output data from this step. This is passed to the next step as input."
1925
- }),
1926
- requiredArtifactIds: import_effect3.Schema.Array(import_effect3.Schema.String).annotations({
1927
- description: "The ids of the artifacts required to perform this step.",
1928
- examples: [
1929
- [
1930
- "artifact:dxos.org/example/Test"
1931
- ]
1932
- ]
1933
- })
1934
- })).annotations({
1935
- description: "Steps"
1936
- })
1937
- }),
1938
- execute: async ({ goal, steps }) => {
1939
- const missingArtifactIds = steps.flatMap((step) => step.requiredArtifactIds).filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
1940
- if (missingArtifactIds.length > 0) {
1941
- return import_artifact3.ToolResult.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(", ")}`);
1942
- }
1943
- const stepResults = [];
1944
- for (const step of steps) {
1945
- (0, import_log4.log)("executing step", {
1946
- action: step.action
1947
- }, {
1948
- F: __dxlog_file6,
1949
- L: 379,
1950
- S: this,
1951
- C: (f, a) => f(...a)
1952
- });
1953
- const session = new _AISession({
1954
- operationModel: "importing"
1955
- });
1956
- session.message.on((ev) => this.message.emit(ev));
1957
- session.block.on((ev) => this.block.emit(ev));
1958
- session.update.on((ev) => this.update.emit(ev));
1959
- session.streamEvent.on((ev) => this.streamEvent.emit(ev));
1960
- session.userMessage.on((ev) => this.userMessage.emit(ev));
1961
- const messages = await session.run({
1962
- client: options.client,
1963
- artifacts: options.artifacts,
1964
- tools: options.tools,
1965
- history: options.history,
1966
- extensions: options.extensions,
1967
- generationOptions: options.generationOptions,
1968
- requiredArtifactIds: step.requiredArtifactIds.slice(),
1969
- artifactDiffResolver: options.artifactDiffResolver,
1970
- prompt: `
1971
- You are an agent that executes the subtask in a plan.
1972
-
1973
- While you know the plan's goal only focus on your subtask
1974
- Use the data from the previous step to complete your task.
1975
- Return all of the data from "output" in your last message.
1976
-
1977
- Current step (that you need to complete):
1978
- ${JSON.stringify({
1979
- goal,
1980
- input: step.input,
1981
- output: step.output,
1982
- yourTask: step.action
1983
- }, null, 2)}
1984
-
1985
- Previous step results:
1986
- ${JSON.stringify(stepResults.at(-1))}.
1987
- `
1988
- });
1989
- const result = messages.at(-1);
1990
- stepResults.push(result);
1991
- }
1992
- return import_artifact3.ToolResult.Success({
1993
- stepResults
1994
- });
1995
- }
1996
- });
1997
- }
1998
- abort() {
1999
- this._stream?.abort();
2000
- }
2001
- };
2002
- _ts_decorate([
2003
- import_async2.synchronized
2004
- ], AISession.prototype, "run", null);
2005
- var createBaseInstructions = ({ availableArtifacts, operationModel }) => `
2006
- You are a friendly, advanced AI assistant capable of creating and managing artifacts from available data and tools.
2007
- Your task is to process user commands and questions and decide how best to respond.
2008
- In some cases, you will need to create or reference data objects called artifacts.
2009
-
2010
- Follow these guidelines carefully:
2011
-
2012
- Decision-making:
2013
-
2014
- - Analyze the structure and type of the content in the user's message.
2015
-
2016
-
2017
- ${operationModel === "planning" ? `
2018
- - Can you complete the task using the available artifacts?
2019
- - If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
2020
- - Identify which artifacts are relevant to the user's request.
2021
- - Break down the user's request into a step-by-step plan that you will use to execute the user's request, the plan items should include artifacts which will be used to perform the actions.
2022
- ` : ""}
2023
- ${operationModel === "importing" ? `
2024
- - Can you complete the task using the available artifacts?
2025
- - If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
2026
- - Identify which artifacts are relevant to the user's request.
2027
- - Are the required artifacts already available?
2028
- - If not, select which artifact(s) will be the most relevant and require them using the require_artifacts tool.
2029
- - The require'd artifact tools will be available for use after require.
2030
- ` : ""}
2031
- ${operationModel === "configured" ? `
2032
- - Select the most relevant artifact(s) to complete the task.
2033
- - Call the appropriate tool to use the artifact(s).
2034
- ` : ""}
2035
-
2036
- ${availableArtifacts.length > 0 ? `Artifacts already in context: ${availableArtifacts.join("\n")}` : ""}
2037
- `;
2038
- var AIServiecOverloadedError = class extends import_effect3.Schema.TaggedError()("AIServiecOverloadedError", {}) {
2039
- };
2040
- var gatherObjectVersions = (messages) => {
2041
- const artifactIds = /* @__PURE__ */ new Map();
2042
- for (const message of messages) {
2043
- for (const block of message.content) {
2044
- if (block.type === "json" && block.disposition === VersionPin.DISPOSITION) {
2045
- const pin = VersionPin.pipe(import_effect3.Schema.decodeOption)(JSON.parse(block.json)).pipe(import_effect3.Option.getOrUndefined);
2046
- if (!pin) {
2047
- continue;
2048
- }
2049
- artifactIds.set(pin.objectId, pin.version);
2050
- }
2051
- }
2052
- }
2053
- return artifactIds;
2054
- };
2055
- var createArtifactUpdateBlock = (artifactDiff) => {
2056
- return {
2057
- type: "text",
2058
- disposition: "artifact-update",
2059
- text: `
2060
- The following artifacts have been updated since the last message:
2061
- ${Array.from(artifactDiff.entries()).map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `
2062
- ${diff}` : ""}</changed-artifact>`).join("\n")}
2063
- `
2064
- };
2065
- };
2066
- var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/experimental/conversation/conversation.ts";
2067
- var runLLM = async (params) => {
2068
- let conversationResult = null;
2069
- const history = params.history ?? [];
2070
- const generate = async () => {
2071
- (0, import_log7.log)("llm generate", {
2072
- tools: params.tools
2073
- }, {
2074
- F: __dxlog_file7,
2075
- L: 44,
2076
- S: void 0,
2077
- C: (f, a) => f(...a)
2078
- });
2079
- const beginTs = Date.now();
2080
- const stream = await params.client.execStream({
2081
- model: params.model,
2082
- history,
2083
- systemPrompt: params.system,
2084
- tools: params.tools
2085
- });
2086
- for await (const event of stream) {
2087
- params.logger?.(event);
2088
- }
2089
- await stream.complete();
2090
- const messages = [];
2091
- const message = messages.at(-1);
2092
- (0, import_invariant6.invariant)(message, void 0, {
2093
- F: __dxlog_file7,
2094
- L: 61,
2095
- S: void 0,
2096
- A: [
2097
- "message",
2098
- ""
2099
- ]
2100
- });
2101
- (0, import_log7.log)("llm result", {
2102
- time: Date.now() - beginTs,
2103
- message
2104
- }, {
2105
- F: __dxlog_file7,
2106
- L: 63,
2107
- S: void 0,
2108
- C: (f, a) => f(...a)
2109
- });
2110
- (0, import_invariant6.invariant)(message, void 0, {
2111
- F: __dxlog_file7,
2112
- L: 64,
2113
- S: void 0,
2114
- A: [
2115
- "message",
2116
- ""
2117
- ]
2118
- });
2119
- params.logger?.({
2120
- type: "message",
2121
- message
2122
- });
2123
- history.push(...messages.map((message2) => ({
2124
- ...message2,
2125
- content: message2.content.filter((block) => block.type !== "image")
2126
- })));
2127
- const isToolUse2 = message.content.at(-1)?.type === "tool_use";
2128
- if (isToolUse2) {
2129
- const toolCalls = message.content.filter((block) => block.type === "tool_use");
2130
- (0, import_invariant6.invariant)(toolCalls.length === 1, void 0, {
2131
- F: __dxlog_file7,
2132
- L: 75,
2133
- S: void 0,
2134
- A: [
2135
- "toolCalls.length === 1",
2136
- ""
2137
- ]
2138
- });
2139
- const toolCall = toolCalls[0];
2140
- const tool = params.tools.find((tool2) => tool2.name === toolCall.name);
2141
- if (!tool) {
2142
- throw new Error(`Tool not found: ${toolCall.name}`);
2143
- }
2144
- (0, import_invariant6.invariant)(tool.execute, void 0, {
2145
- F: __dxlog_file7,
2146
- L: 82,
2147
- S: void 0,
2148
- A: [
2149
- "tool.execute",
2150
- ""
2151
- ]
2152
- });
2153
- const toolResult = await tool.execute(toolCall.input);
2154
- switch (toolResult.kind) {
2155
- case "error": {
2156
- import_log7.log.warn("tool error", {
2157
- message: toolResult.message
2158
- }, {
2159
- F: __dxlog_file7,
2160
- L: 86,
2161
- S: void 0,
2162
- C: (f, a) => f(...a)
2163
- });
2164
- const resultMessage = {
2165
- id: import_echo_schema6.ObjectId.random(),
2166
- role: "user",
2167
- content: [
2168
- {
2169
- type: "tool_result",
2170
- toolUseId: toolCall.id,
2171
- content: toolResult.message,
2172
- isError: true
2173
- }
2174
- ]
2175
- };
2176
- params.logger?.({
2177
- type: "message",
2178
- message: resultMessage
2179
- });
2180
- history.push(resultMessage);
2181
- return true;
2182
- }
2183
- case "success": {
2184
- (0, import_log7.log)("tool success", {
2185
- result: toolResult.result
2186
- }, {
2187
- F: __dxlog_file7,
2188
- L: 106,
2189
- S: void 0,
2190
- C: (f, a) => f(...a)
2191
- });
2192
- const resultMessage = {
2193
- id: import_echo_schema6.ObjectId.random(),
2194
- role: "user",
2195
- content: [
2196
- {
2197
- type: "tool_result",
2198
- toolUseId: toolCall.id,
2199
- content: JSON.stringify(toolResult.result)
2200
- }
2201
- ]
2202
- };
2203
- params.logger?.({
2204
- type: "message",
2205
- message: resultMessage
2206
- });
2207
- history.push(resultMessage);
2208
- return true;
2209
- }
2210
- case "break": {
2211
- (0, import_log7.log)("tool break", {
2212
- result: toolResult.result
2213
- }, {
2214
- F: __dxlog_file7,
2215
- L: 125,
2216
- S: void 0,
2217
- C: (f, a) => f(...a)
2218
- });
2219
- conversationResult = toolResult.result;
2220
- return false;
2221
- }
2222
- }
2223
- }
2224
- return false;
2225
- };
2226
- while (await generate()) {
2227
- }
2228
- return {
2229
- result: conversationResult,
2230
- history
2231
- };
2232
- };
2233
- var ws = import_parjs.parjs.whitespace();
2234
- var nothing = import_parjs.parjs.string("").pipe(import_parjs.parjsCombinators.map(() => null));
2235
- var optional = (parser) => parser.pipe(import_parjs.parjsCombinators.recover(() => ({
2236
- kind: "Soft"
2237
- })), import_parjs.parjsCombinators.or(nothing));
2238
- var keyword = (word) => import_parjs.parjs.string(word).pipe(import_parjs.parjsCombinators.map(() => word));
2239
- var identifier = import_parjs.parjs.regexp(/[a-zA-Z_][a-zA-Z0-9_]*/).pipe(import_parjs.parjsCombinators.map((match) => ({
2240
- astKind: "Identifier",
2241
- name: match[0]
2242
- })));
2243
- var numberLiteral = import_parjs.parjs.regexp(/-?\d+(\.\d+)?/).pipe(import_parjs.parjsCombinators.map(Number));
2244
- var stringLiteral = import_parjs.parjs.regexp(/"([^"]*)"|'([^']*)'/).pipe(import_parjs.parjsCombinators.map((match) => ({
2245
- astKind: "StringLiteral",
2246
- value: match[1] || match[2]
2247
- })));
2248
- var variableTag = identifier.pipe(import_parjs.parjsCombinators.map((variable) => variable)).expects("variable tag");
2249
- var label = identifier.pipe(import_parjs.parjsCombinators.map((name) => name));
2250
- var property = identifier.pipe(import_parjs.parjsCombinators.then(import_parjs.parjs.string(":"), ws, stringLiteral), import_parjs.parjsCombinators.map(([key, , , value]) => ({
2251
- key,
2252
- value
2253
- })));
2254
- var properties = property.pipe(import_parjs.parjsCombinators.manySepBy(","), import_parjs.parjsCombinators.between("{", "}"), import_parjs.parjsCombinators.map((properties2) => ({
2255
- astKind: "Properties",
2256
- properties: properties2
2257
- })));
2258
- var nodePattern = optional(variableTag).pipe(import_parjs.parjsCombinators.then(":"), import_parjs.parjsCombinators.then(ws, label, ws), import_parjs.parjsCombinators.then(optional(properties)), import_parjs.parjsCombinators.between("(", ")"), import_parjs.parjsCombinators.map(([[[variable], _, label2], properties2]) => ({
2259
- astKind: "NodePattern",
2260
- variable,
2261
- label: label2,
2262
- properties: properties2
2263
- })));
2264
- var relationshipPattern = optional(variableTag).pipe(import_parjs.parjsCombinators.then(":"), import_parjs.parjsCombinators.then(ws, label, ws), import_parjs.parjsCombinators.then(optional(properties)), import_parjs.parjsCombinators.between("[", "]"), import_parjs.parjsCombinators.map(([[[variable], _, label2], properties2]) => ({
2265
- astKind: "RelationshipPattern",
2266
- variable,
2267
- label: label2,
2268
- properties: properties2
2269
- })));
2270
- var graphPatternConnector = import_parjs.parjs.string("->").pipe(import_parjs.parjsCombinators.or("<-", "-"), import_parjs.parjsCombinators.map((x) => ({
2271
- astKind: "GraphPatternConnector",
2272
- direction: x
2273
- })));
2274
- var graphPattern = nodePattern.pipe(import_parjs.parjsCombinators.or(relationshipPattern), import_parjs.parjsCombinators.manySepBy(graphPatternConnector), import_parjs.parjsCombinators.map((segments) => ({
2275
- astKind: "GraphPattern",
2276
- segments
2277
- })));
2278
- var matchClause = keyword("MATCH").pipe(import_parjs.parjsCombinators.then(ws), import_parjs.parjsCombinators.then(graphPattern), import_parjs.parjsCombinators.map(([, pattern]) => ({
2279
- astKind: "MatchClause",
2280
- pattern
2281
- })));
2282
- var memberExpression = identifier.pipe(import_parjs.parjsCombinators.manySepBy("."), import_parjs.parjsCombinators.map((path) => ({
2283
- astKind: "MemberExpression",
2284
- path
2285
- })));
2286
- var equalsPredicate = memberExpression.pipe(import_parjs.parjsCombinators.then(ws, import_parjs.parjs.string("="), ws, stringLiteral), import_parjs.parjsCombinators.map(([left, , , , right]) => ({
2287
- astKind: "EqualsPredicate",
2288
- left,
2289
- right
2290
- })));
2291
- var whereClause = keyword("WHERE").pipe(import_parjs.parjsCombinators.then(ws, equalsPredicate.pipe(import_parjs.parjsCombinators.between(ws, ws), import_parjs.parjsCombinators.manySepBy(import_parjs.parjs.string("AND"))), ws), import_parjs.parjsCombinators.map(([, , predicates]) => ({
2292
- astKind: "WhereClause",
2293
- predicates
2294
- })));
2295
- var returnClause = keyword("RETURN").pipe(import_parjs.parjsCombinators.then(ws, memberExpression.pipe(import_parjs.parjsCombinators.then(optional(import_parjs.parjs.string("AS").pipe(import_parjs.parjsCombinators.between(ws), import_parjs.parjsCombinators.then(identifier))), ws), import_parjs.parjsCombinators.manySepBy(import_parjs.parjs.string(",").pipe(import_parjs.parjsCombinators.then(ws)))), ws), import_parjs.parjsCombinators.map(([, , fields]) => ({
2296
- astKind: "ReturnClause",
2297
- fields: fields.map(([f]) => f)
2298
- })));
2299
- var cypherQuery = ws.pipe(import_parjs.parjsCombinators.then(matchClause, ws, optional(whereClause), ws, returnClause, ws), import_parjs.parjsCombinators.map(([, matchClause2, , whereClause2, , returnClause2]) => ({
2300
- astKind: "CypherQuery",
2301
- matchClause: matchClause2,
2302
- whereClause: whereClause2,
2303
- returnClause: returnClause2
2304
- })));
2305
- var parseCypherQuery = (query) => {
2306
- const parseResult = cypherQuery.parse(query);
2307
- if (parseResult.isOk) {
2308
- return {
2309
- ast: parseResult.value
2310
- };
2311
- } else {
2312
- throw new Error(`Failed to parse query: ${parseResult}`);
2313
- }
2314
- };
2315
- var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/experimental/cypher/execution-plan.ts";
2316
- var createExecutionPlan = (query) => {
2317
- return new ExecutionPlanBuilder().build(query);
2318
- };
2319
- var ExecutionPlanBuilder = class {
2320
- constructor() {
2321
- this.counter = 0;
2322
- }
2323
- newVariable() {
2324
- return `anon_${this.counter++}`;
2325
- }
2326
- build(query) {
2327
- (0, import_log9.log)("Creating execution plan for query", {
2328
- query
2329
- }, {
2330
- F: __dxlog_file8,
2331
- L: 76,
2332
- S: this,
2333
- C: (f, a) => f(...a)
2334
- });
2335
- return {
2336
- steps: [
2337
- ...this.createStepsForMatchClause(query.ast.matchClause),
2338
- ...query.ast.whereClause ? this.createStepsForWhereClause(query.ast.whereClause) : [],
2339
- ...this.createStepsForReturnClause(query.ast.returnClause)
2340
- ],
2341
- output: {
2342
- fields: this.getOutputFields(query.ast.returnClause)
2343
- }
2344
- };
2345
- }
2346
- createStepsForMatchClause(match) {
2347
- (0, import_invariant7.invariant)(match.pattern.segments.length > 0, void 0, {
2348
- F: __dxlog_file8,
2349
- L: 90,
2350
- S: this,
2351
- A: [
2352
- "match.pattern.segments.length > 0",
2353
- ""
2354
- ]
2355
- });
2356
- const firstSegment = match.pattern.segments[0];
2357
- (0, import_invariant7.invariant)(firstSegment.astKind === "NodePattern", void 0, {
2358
- F: __dxlog_file8,
2359
- L: 92,
2360
- S: this,
2361
- A: [
2362
- "firstSegment.astKind === 'NodePattern'",
2363
- ""
2364
- ]
2365
- });
2366
- let lastNodeVariable = firstSegment.variable?.name ?? this.newVariable();
2367
- const steps = [];
2368
- steps.push({
2369
- type: "NodeScan",
2370
- label: firstSegment.label.name,
2371
- into: lastNodeVariable
2372
- });
2373
- if (firstSegment.properties) {
2374
- for (const property2 of firstSegment.properties.properties) {
2375
- steps.push({
2376
- type: "FilterByProperty",
2377
- variable: lastNodeVariable,
2378
- property: property2.key.name,
2379
- value: property2.value.value
2380
- });
2381
- }
2382
- }
2383
- for (let i = 1; i < match.pattern.segments.length; i++) {
2384
- const relationshipSegment = match.pattern.segments[i++];
2385
- (0, import_invariant7.invariant)(relationshipSegment.astKind === "RelationshipPattern", void 0, {
2386
- F: __dxlog_file8,
2387
- L: 115,
2388
- S: this,
2389
- A: [
2390
- "relationshipSegment.astKind === 'RelationshipPattern'",
2391
- ""
2392
- ]
2393
- });
2394
- const nodeSegment = match.pattern.segments[i];
2395
- (0, import_invariant7.invariant)(nodeSegment.astKind === "NodePattern", void 0, {
2396
- F: __dxlog_file8,
2397
- L: 117,
2398
- S: this,
2399
- A: [
2400
- "nodeSegment.astKind === 'NodePattern'",
2401
- ""
2402
- ]
2403
- });
2404
- const leftSeparator = match.pattern.segments.separators[i - 2];
2405
- const rightSeparator = match.pattern.segments.separators[i - 1];
2406
- const direction = getDirection(leftSeparator.direction, rightSeparator.direction);
2407
- const relationshipVariable = relationshipSegment.variable?.name ?? this.newVariable();
2408
- const nodeVariable = nodeSegment.variable?.name ?? this.newVariable();
2409
- steps.push({
2410
- type: "RelationshipScan",
2411
- label: relationshipSegment.label.name,
2412
- direction,
2413
- anchor: lastNodeVariable,
2414
- relationshipInto: relationshipVariable,
2415
- nodeInto: nodeVariable
2416
- });
2417
- if (relationshipSegment.properties) {
2418
- for (const property2 of relationshipSegment.properties.properties) {
2419
- steps.push({
2420
- type: "FilterByProperty",
2421
- variable: relationshipVariable,
2422
- property: property2.key.name,
2423
- value: property2.value.value
2424
- });
2425
- }
2426
- }
2427
- if (nodeSegment.label) {
2428
- steps.push({
2429
- type: "FilterByLabel",
2430
- variable: nodeVariable,
2431
- label: nodeSegment.label.name
2432
- });
2433
- }
2434
- if (nodeSegment.properties) {
2435
- for (const property2 of nodeSegment.properties.properties) {
2436
- steps.push({
2437
- type: "FilterByProperty",
2438
- variable: nodeVariable,
2439
- property: property2.key.name,
2440
- value: property2.value.value
2441
- });
2442
- }
2443
- }
2444
- lastNodeVariable = nodeVariable;
2445
- }
2446
- return steps;
2447
- }
2448
- createStepsForWhereClause(where) {
2449
- return [];
2450
- }
2451
- createStepsForReturnClause(returnClause2) {
2452
- return [
2453
- {
2454
- type: "ProduceResults",
2455
- fields: returnClause2.fields.map((field) => ({
2456
- name: field.path.map((p) => p.name).join("_"),
2457
- variable: field.path[0].name,
2458
- path: field.path.length > 1 ? field.path.slice(1).map((p) => p.name).join(".") : "$"
2459
- }))
2460
- }
2461
- ];
2462
- }
2463
- getOutputFields(returnClause2) {
2464
- return returnClause2.fields.map((field) => field.path.map((p) => p.name).join("_"));
2465
- }
2466
- };
2467
- var getDirection = (left, right) => {
2468
- if (left === "-" && right === "->") {
2469
- return "out";
2470
- } else if (left === "<-" && right === "-") {
2471
- return "in";
2472
- } else if (left === "-" && right === "-") {
2473
- return "both";
2474
- }
2475
- throw new Error(`Invalid direction: ()${left}[]${right}()`);
2476
- };
2477
- var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/experimental/cypher/query-executor.ts";
2478
- var executeQueryPlan = async (dataSource, plan) => {
2479
- let buffer = [];
2480
- const results = [];
2481
- for (const step of plan.steps) {
2482
- (0, import_log8.log)("begin step", {
2483
- step
2484
- }, {
2485
- F: __dxlog_file9,
2486
- L: 41,
2487
- S: void 0,
2488
- C: (f, a) => f(...a)
2489
- });
2490
- switch (step.type) {
2491
- case "NodeScan": {
2492
- const nodes = await dataSource.getNodes({
2493
- label: step.label
2494
- });
2495
- buffer.push(...nodes.map((node) => ({
2496
- [step.into]: node
2497
- })));
2498
- break;
2499
- }
2500
- case "FilterByLabel": {
2501
- buffer = buffer.filter((item) => {
2502
- const node = item[step.variable];
2503
- return node && node.kind === "node" && node.label === step.label;
2504
- });
2505
- break;
2506
- }
2507
- case "FilterByProperty": {
2508
- buffer = buffer.filter((item) => {
2509
- const node = item[step.variable];
2510
- return node && node.kind === "node" && node.properties[step.property] === step.value;
2511
- });
2512
- break;
2513
- }
2514
- case "RelationshipScan": {
2515
- const relationships = await dataSource.getRelationships({
2516
- label: step.label
2517
- });
2518
- for (const tuple of [
2519
- ...buffer
2520
- ]) {
2521
- if (tuple[step.anchor].kind !== "node") {
2522
- continue;
2523
- }
2524
- const filteredRelationships = relationships.filter((relationship) => {
2525
- switch (step.direction) {
2526
- case "in":
2527
- return relationship.target.id === tuple[step.anchor].id;
2528
- case "out":
2529
- return relationship.source.id === tuple[step.anchor].id;
2530
- case "both":
2531
- return relationship.source.id === tuple[step.anchor].id || relationship.target.id === tuple[step.anchor].id;
2532
- default:
2533
- throw new Error(`Unknown direction: ${step.direction}`);
2534
- }
2535
- });
2536
- for (let i = 0; i < filteredRelationships.length; i++) {
2537
- const relationship = filteredRelationships[i];
2538
- const newTuple = i === 0 ? tuple : {
2539
- ...tuple
2540
- };
2541
- if (newTuple !== tuple) {
2542
- buffer.push(newTuple);
2543
- }
2544
- newTuple[step.relationshipInto] = relationship;
2545
- switch (step.direction) {
2546
- case "in":
2547
- newTuple[step.nodeInto] = relationship.source;
2548
- break;
2549
- case "out":
2550
- newTuple[step.nodeInto] = relationship.target;
2551
- break;
2552
- case "both":
2553
- newTuple[step.nodeInto] = relationship.source.id === newTuple[step.anchor].id ? relationship.target : relationship.source;
2554
- break;
2555
- }
2556
- }
2557
- }
2558
- break;
2559
- }
2560
- case "ProduceResults": {
2561
- for (const tuple of buffer) {
2562
- const result = {};
2563
- for (const field of step.fields) {
2564
- result[field.name] = jsonPathGet(tuple[field.variable].properties, field.path);
2565
- }
2566
- results.push(result);
2567
- }
2568
- break;
2569
- }
2570
- }
2571
- (0, import_log8.log)("finish step", {
2572
- buffer: buffer.map((tuple) => (0, import_util2.mapValues)(tuple, (x) => x.id)),
2573
- results
2574
- }, {
2575
- F: __dxlog_file9,
2576
- L: 118,
2577
- S: void 0,
2578
- C: (f, a) => f(...a)
2579
- });
2580
- }
2581
- return results;
2582
- };
2583
- var executeQuery = (dataSource, query) => {
2584
- const plan = createExecutionPlan(parseCypherQuery(query));
2585
- return executeQueryPlan(dataSource, plan);
2586
- };
2587
- var jsonPathGet = (obj, path) => {
2588
- if (path === "" || path === "$") {
2589
- return obj;
2590
- }
2591
- const parts = path.split(".");
2592
- if (parts[0] === "$") {
2593
- parts.shift();
2594
- }
2595
- let result = obj;
2596
- for (const part of parts) {
2597
- result = result?.[part];
2598
- }
2599
- return result;
2600
- };
2601
- var trim = (strings, ...values) => {
2602
- const combined = strings.reduce((acc, str, i) => {
2603
- return acc + str + (values[i] || "");
2604
- }, "");
2605
- return combined.replace("/^\n/", "").replace(/\n$/, "");
2606
- };
2607
- var formatJsonSchemaForLLM = (schemaTypes) => {
2608
- return schemaTypes.flatMap((schema) => [
2609
- formatNodeSchema(schema),
2610
- ...formatInferredRelationships(schema, schemaTypes)
2611
- ]);
2612
- };
2613
- var formatNodeSchema = (schema) => {
2614
- const label2 = formatNodeLabel(schema.typename ?? (0, import_debug.raise)(new Error("Schema must have $id")));
2615
- const properties2 = Object.entries(schema.properties).filter(([key, prop]) => key !== "id" && !isReference(prop));
2616
- return trim`
2617
- <node>
2618
- (:${label2})
2619
-
2620
- <description>${schema.description}</description>
2621
-
2622
- <properties>
2623
- ${properties2.map(([key, value]) => {
2624
- return trim`
2625
- <${key}>
2626
- <type>${value.type}</type>
2627
- <description>${value.description}</description>
2628
- </${key}>
2629
- `;
2630
- })}
2631
- </properties>
2632
- </node>
2633
- `;
2634
- };
2635
- var formatInferredRelationships = (schema, allSchema) => {
2636
- const nodeLabel = formatNodeLabel(schema.typename ?? (0, import_debug.raise)(new Error("Schema must have $id")));
2637
- const relationships = Object.entries(schema.properties).filter(([key, prop]) => isReference(prop));
2638
- return relationships.map(([key, value]) => {
2639
- const relationshipLabel = formatInferredRelationshipLabel(schema.typename ?? (0, import_debug.raise)(new Error("Schema must have $id")), key);
2640
- const targetSchema = allSchema.find((schema2) => `dxn:type/${schema2.typename}` === value.reference?.schema.$ref);
2641
- const targetLabel = targetSchema ? formatNodeLabel(targetSchema?.typename ?? "") : "";
2642
- return trim`
2643
- <relationship>
2644
- (:${nodeLabel})-[:${relationshipLabel}]->(:${targetLabel})
2645
-
2646
- <description>${value.description}</description>
2647
- </relationship>
2648
- `;
2649
- });
2650
- };
2651
- var formatNodeLabel = (typename) => {
2652
- return typename.replace(/^example\.com\/type\//g, "");
2653
- };
2654
- var formatInferredRelationshipLabel = (typename, property2) => {
2655
- const nodeLabel = formatNodeLabel(typename);
2656
- return `${nodeLabel}_${property2}`.toUpperCase();
2657
- };
2658
- var isReference = (schema) => schema.$id === import_echo_schema7.JSON_SCHEMA_ECHO_REF_ID || schema.type === "array" && !Array.isArray(schema.items) && typeof schema.items === "object" && "$id" in schema.items && schema.items.$id === import_echo_schema7.JSON_SCHEMA_ECHO_REF_ID;
2659
- function _ts_decorate2(decorators, target, key, desc) {
2660
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2661
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2662
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2663
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2664
- }
2665
- var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/experimental/cypher/echo-data-source.ts";
2666
- var EchoDataSource = class {
2667
- constructor(_db) {
2668
- this._db = _db;
2669
- }
2670
- async getNodes({ label: label2 }) {
2671
- if (!label2) {
2672
- const { objects: objects2 } = await this._db.query().run();
2673
- return objects2.map(this._objectToNode);
2674
- }
2675
- const schema = (await this._getAllSchema()).find((schema2) => (0, import_echo_schema8.getSchemaTypename)(schema2)?.endsWith(label2));
2676
- if (!schema) {
2677
- return [];
2678
- }
2679
- const { objects } = await this._db.query(import_echo_db3.Filter.type(schema)).run();
2680
- return objects.map(this._objectToNode);
2681
- }
2682
- async getRelationships({ label: label2 }) {
2683
- const syntheticRefRelationships = (await this._getAllSchema()).filter((schema) => (0, import_echo_schema8.getSchemaTypename)(schema) !== import_echo_schema8.StoredSchema.typename).flatMap((schema) => {
2684
- const jsonSchema = (0, import_echo_schema8.toJsonSchema)(schema);
2685
- const relationships = Object.entries(jsonSchema.properties).filter(([key, prop]) => isReference(prop));
2686
- return relationships.map(([key, value]) => {
2687
- const relationshipLabel = formatInferredRelationshipLabel(jsonSchema.typename ?? (0, import_debug2.raise)(new Error("Schema must have typename")), key);
2688
- return {
2689
- label: relationshipLabel,
2690
- schema,
2691
- property: key
2692
- };
2693
- });
2694
- });
2695
- const relationship = syntheticRefRelationships.find((r) => r.label === label2);
2696
- if (!relationship) {
2697
- return [];
2698
- }
2699
- const { objects } = await this._db.query(import_echo_db3.Filter.type(relationship.schema)).run();
2700
- return (await Promise.all(objects.map((object) => this._projectRefRelationship(object, relationship.property)))).flat();
2701
- }
2702
- async _getAllSchema() {
2703
- return [
2704
- ...await this._db.schemaRegistry.query().run(),
2705
- // TODO(dmaretskyi): Remove once we can serialize recursive schema.
2706
- ...this._db.graph.schemaRegistry.schemas.filter((schema) => (0, import_echo_schema8.getSchemaTypename)(schema)?.startsWith("example.org"))
2707
- ].filter((schema) => (0, import_echo_schema8.getSchemaTypename)(schema) !== import_echo_schema8.StoredSchema.typename);
2708
- }
2709
- _objectToNode(object) {
2710
- const { id, ...properties2 } = object;
2711
- return {
2712
- id,
2713
- kind: "node",
2714
- label: formatNodeLabel((0, import_echo_schema8.getSchemaTypename)((0, import_echo_schema8.getSchema)(object))),
2715
- properties: properties2
2716
- };
2717
- }
2718
- async _projectRefRelationship(object, prop) {
2719
- if (!object[prop]) {
2720
- return [];
2721
- }
2722
- const value = Array.isArray(object[prop]) ? object[prop] : [
2723
- object[prop]
2724
- ];
2725
- return Promise.all(value.map(async (ref) => {
2726
- const target = await ref.load();
2727
- return {
2728
- id: `${object.id}-${prop}-${target.id}`,
2729
- kind: "relationship",
2730
- label: formatInferredRelationshipLabel((0, import_echo_schema8.getSchemaTypename)((0, import_echo_schema8.getSchema)(object)), prop),
2731
- properties: {},
2732
- source: this._objectToNode(object),
2733
- target: this._objectToNode(target)
2734
- };
2735
- }));
2736
- }
2737
- };
2738
- _ts_decorate2([
2739
- import_log10.log.method(void 0, void 0, {
2740
- F: __dxlog_file10,
2741
- L: 18,
2742
- S: void 0,
2743
- C: (f, a) => f(...a)
2744
- })
2745
- ], EchoDataSource.prototype, "getNodes", null);
2746
- _ts_decorate2([
2747
- import_log10.log.method(void 0, void 0, {
2748
- F: __dxlog_file10,
2749
- L: 34,
2750
- S: void 0,
2751
- C: (f, a) => f(...a)
2752
- })
2753
- ], EchoDataSource.prototype, "getRelationships", null);
2754
- // Annotate the CommonJS export names for ESM import in node:
2755
- 0 && (module.exports = {
2756
- AIServiceEdgeClient,
2757
- AIServiecOverloadedError,
2758
- AISession,
2759
- DEFAULT_EDGE_MODEL,
2760
- DEFAULT_EDGE_MODELS,
2761
- DEFAULT_OLLAMA_ENDPOINT,
2762
- DEFAULT_OLLAMA_MODEL,
2763
- DEFAULT_OLLAMA_MODELS,
2764
- EchoDataSource,
2765
- GenerateRequest,
2766
- GenerateResponse,
2767
- GenerationStreamImpl,
2768
- LLMModel,
2769
- MessageCollector,
2770
- MixedStreamParser,
2771
- OllamaClient,
2772
- StreamTransform,
2773
- ToolTypes,
2774
- VersionPin,
2775
- createArtifactElement,
2776
- createGenerationStream,
2777
- emitMessageAsEvents,
2778
- executeQuery,
2779
- executeQueryPlan,
2780
- formatInferredRelationshipLabel,
2781
- formatJsonSchemaForLLM,
2782
- formatNodeLabel,
2783
- isReference,
2784
- isToolUse,
2785
- mergeMessageBlock,
2786
- parseCypherQuery,
2787
- runLLM,
2788
- runTools,
2789
- trim
2790
- });
2791
- //# sourceMappingURL=chunk-NOB7CIIC.cjs.map