@dxos/assistant 0.8.2-staging.7ac8446 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (277) hide show
  1. package/dist/lib/browser/index.mjs +1830 -228
  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 +1825 -229
  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 +1831 -228
  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/blueprint/machine.d.ts +113 -0
  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 -3
  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 +2 -0
  60. package/dist/types/src/research/research.test.d.ts.map +1 -0
  61. package/dist/types/src/session/index.d.ts +1 -0
  62. package/dist/types/src/session/index.d.ts.map +1 -1
  63. package/dist/types/src/session/session.d.ts +80 -35
  64. package/dist/types/src/session/session.d.ts.map +1 -1
  65. package/dist/types/src/session/version-pin.d.ts +21 -0
  66. package/dist/types/src/session/version-pin.d.ts.map +1 -0
  67. package/dist/types/src/session/version-pin.test.d.ts +2 -0
  68. package/dist/types/src/session/version-pin.test.d.ts.map +1 -0
  69. package/dist/types/src/summarization/summarization.test.d.ts +2 -0
  70. package/dist/types/src/summarization/summarization.test.d.ts.map +1 -0
  71. package/dist/types/src/testing/exa-search-1748337321991.d.ts +38 -0
  72. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +1 -0
  73. package/dist/types/src/testing/exa-search-1748337331526.d.ts +37 -0
  74. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +1 -0
  75. package/dist/types/src/testing/exa-search-1748337344119.d.ts +58 -0
  76. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +1 -0
  77. package/dist/types/src/testing/index.d.ts +2 -6
  78. package/dist/types/src/testing/index.d.ts.map +1 -1
  79. package/dist/types/src/types.d.ts +3 -0
  80. package/dist/types/src/types.d.ts.map +1 -0
  81. package/dist/types/tsconfig.tsbuildinfo +1 -1
  82. package/package.json +25 -35
  83. package/src/blueprint/blueprint.test.ts +142 -0
  84. package/src/blueprint/blueprint.ts +95 -0
  85. package/src/blueprint/index.ts +7 -0
  86. package/src/blueprint/logger.ts +66 -0
  87. package/src/blueprint/machine.ts +208 -0
  88. package/src/blueprint/test-data.ts +55 -0
  89. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +95 -0
  90. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +64 -0
  91. package/src/extraction/extraction-llm-function/index.ts +5 -0
  92. package/src/extraction/extraction-llm-function/instructions.tpl +28 -0
  93. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +115 -0
  94. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +54 -0
  95. package/src/extraction/extraction-ner-function/index.ts +6 -0
  96. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +94 -0
  97. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +97 -0
  98. package/src/extraction/extraction.ts +75 -0
  99. package/src/extraction/index.ts +8 -0
  100. package/src/extraction/quotes.test.ts +27 -0
  101. package/src/extraction/quotes.ts +57 -0
  102. package/src/index.ts +4 -3
  103. package/src/research/exa.ts +100 -0
  104. package/src/research/graph.test.ts +15 -0
  105. package/src/research/graph.ts +291 -0
  106. package/src/research/index.ts +7 -0
  107. package/src/research/instructions-research.tpl +97 -0
  108. package/src/research/research.test.ts +189 -0
  109. package/src/research/research.ts +89 -0
  110. package/src/session/index.ts +1 -0
  111. package/src/session/session.test.ts +39 -67
  112. package/src/session/session.ts +328 -155
  113. package/src/session/version-pin.test.ts +26 -0
  114. package/src/session/version-pin.ts +48 -0
  115. package/src/summarization/summarization.test.ts +216 -0
  116. package/src/testing/exa-search-1748337321991.ts +131 -0
  117. package/src/testing/exa-search-1748337331526.ts +144 -0
  118. package/src/testing/exa-search-1748337344119.ts +133 -0
  119. package/src/testing/index.ts +8 -7
  120. package/src/typedefs.d.ts +8 -0
  121. package/src/types.ts +8 -0
  122. package/src/typings.d.ts +8 -0
  123. package/dist/lib/browser/chunk-PND5VR6D.mjs +0 -2315
  124. package/dist/lib/browser/chunk-PND5VR6D.mjs.map +0 -7
  125. package/dist/lib/browser/testing/index.mjs +0 -621
  126. package/dist/lib/browser/testing/index.mjs.map +0 -7
  127. package/dist/lib/node/chunk-IBOBRBDF.cjs +0 -2326
  128. package/dist/lib/node/chunk-IBOBRBDF.cjs.map +0 -7
  129. package/dist/lib/node/testing/index.cjs +0 -637
  130. package/dist/lib/node/testing/index.cjs.map +0 -7
  131. package/dist/lib/node-esm/chunk-DCQJOLSR.mjs +0 -2317
  132. package/dist/lib/node-esm/chunk-DCQJOLSR.mjs.map +0 -7
  133. package/dist/lib/node-esm/testing/index.mjs +0 -622
  134. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  135. package/dist/types/src/ai-service/client.test.d.ts +0 -2
  136. package/dist/types/src/ai-service/client.test.d.ts.map +0 -1
  137. package/dist/types/src/ai-service/defs.d.ts +0 -9
  138. package/dist/types/src/ai-service/defs.d.ts.map +0 -1
  139. package/dist/types/src/ai-service/edge-client.d.ts +0 -19
  140. package/dist/types/src/ai-service/edge-client.d.ts.map +0 -1
  141. package/dist/types/src/ai-service/index.d.ts +0 -10
  142. package/dist/types/src/ai-service/index.d.ts.map +0 -1
  143. package/dist/types/src/ai-service/message-collector.d.ts +0 -88
  144. package/dist/types/src/ai-service/message-collector.d.ts.map +0 -1
  145. package/dist/types/src/ai-service/ollama-client.d.ts +0 -39
  146. package/dist/types/src/ai-service/ollama-client.d.ts.map +0 -1
  147. package/dist/types/src/ai-service/parser.d.ts +0 -138
  148. package/dist/types/src/ai-service/parser.d.ts.map +0 -1
  149. package/dist/types/src/ai-service/service.d.ts +0 -9
  150. package/dist/types/src/ai-service/service.d.ts.map +0 -1
  151. package/dist/types/src/ai-service/stream.d.ts +0 -40
  152. package/dist/types/src/ai-service/stream.d.ts.map +0 -1
  153. package/dist/types/src/ai-service/stream.test.d.ts +0 -2
  154. package/dist/types/src/ai-service/stream.test.d.ts.map +0 -1
  155. package/dist/types/src/ai-service/testing/index.d.ts +0 -3
  156. package/dist/types/src/ai-service/testing/index.d.ts.map +0 -1
  157. package/dist/types/src/ai-service/testing/mock.d.ts +0 -7
  158. package/dist/types/src/ai-service/testing/mock.d.ts.map +0 -1
  159. package/dist/types/src/ai-service/testing/test-stream.d.ts +0 -7
  160. package/dist/types/src/ai-service/testing/test-stream.d.ts.map +0 -1
  161. package/dist/types/src/ai-service/transform.d.ts +0 -27
  162. package/dist/types/src/ai-service/transform.d.ts.map +0 -1
  163. package/dist/types/src/ai-service/types.d.ts +0 -167
  164. package/dist/types/src/ai-service/types.d.ts.map +0 -1
  165. package/dist/types/src/ai-service/util/index.d.ts +0 -2
  166. package/dist/types/src/ai-service/util/index.d.ts.map +0 -1
  167. package/dist/types/src/ai-service/util/sse.d.ts +0 -39
  168. package/dist/types/src/ai-service/util/sse.d.ts.map +0 -1
  169. package/dist/types/src/conversation/conversation.d.ts +0 -80
  170. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  171. package/dist/types/src/conversation/conversation.test.d.ts +0 -2
  172. package/dist/types/src/conversation/conversation.test.d.ts.map +0 -1
  173. package/dist/types/src/conversation/index.d.ts +0 -2
  174. package/dist/types/src/conversation/index.d.ts.map +0 -1
  175. package/dist/types/src/conversation/types.d.ts +0 -79
  176. package/dist/types/src/conversation/types.d.ts.map +0 -1
  177. package/dist/types/src/cypher/ast.d.ts +0 -56
  178. package/dist/types/src/cypher/ast.d.ts.map +0 -1
  179. package/dist/types/src/cypher/combinators.d.ts +0 -14
  180. package/dist/types/src/cypher/combinators.d.ts.map +0 -1
  181. package/dist/types/src/cypher/combinators.test.d.ts +0 -2
  182. package/dist/types/src/cypher/combinators.test.d.ts.map +0 -1
  183. package/dist/types/src/cypher/echo-data-source.d.ts +0 -16
  184. package/dist/types/src/cypher/echo-data-source.d.ts.map +0 -1
  185. package/dist/types/src/cypher/execution-plan.d.ts +0 -49
  186. package/dist/types/src/cypher/execution-plan.d.ts.map +0 -1
  187. package/dist/types/src/cypher/execution-plan.test.d.ts +0 -2
  188. package/dist/types/src/cypher/execution-plan.test.d.ts.map +0 -1
  189. package/dist/types/src/cypher/index.d.ts +0 -5
  190. package/dist/types/src/cypher/index.d.ts.map +0 -1
  191. package/dist/types/src/cypher/parjs.d.ts +0 -4
  192. package/dist/types/src/cypher/parjs.d.ts.map +0 -1
  193. package/dist/types/src/cypher/parser.d.ts +0 -6
  194. package/dist/types/src/cypher/parser.d.ts.map +0 -1
  195. package/dist/types/src/cypher/query-executor.d.ts +0 -26
  196. package/dist/types/src/cypher/query-executor.d.ts.map +0 -1
  197. package/dist/types/src/cypher/query-executor.test.d.ts +0 -2
  198. package/dist/types/src/cypher/query-executor.test.d.ts.map +0 -1
  199. package/dist/types/src/cypher/schema.d.ts +0 -12
  200. package/dist/types/src/cypher/schema.d.ts.map +0 -1
  201. package/dist/types/src/cypher/schema.test.d.ts +0 -2
  202. package/dist/types/src/cypher/schema.test.d.ts.map +0 -1
  203. package/dist/types/src/testing/artifacts.test.d.ts +0 -1
  204. package/dist/types/src/testing/artifacts.test.d.ts.map +0 -1
  205. package/dist/types/src/testing/data.d.ts +0 -2
  206. package/dist/types/src/testing/data.d.ts.map +0 -1
  207. package/dist/types/src/testing/defs.d.ts +0 -5
  208. package/dist/types/src/testing/defs.d.ts.map +0 -1
  209. package/dist/types/src/testing/logger.d.ts +0 -12
  210. package/dist/types/src/testing/logger.d.ts.map +0 -1
  211. package/dist/types/src/testing/object-extraction.test.d.ts +0 -1
  212. package/dist/types/src/testing/object-extraction.test.d.ts.map +0 -1
  213. package/dist/types/src/testing/ollama.d.ts +0 -6
  214. package/dist/types/src/testing/ollama.d.ts.map +0 -1
  215. package/dist/types/src/testing/query-promts.d.ts +0 -5
  216. package/dist/types/src/testing/query-promts.d.ts.map +0 -1
  217. package/dist/types/src/testing/query.test.d.ts +0 -2
  218. package/dist/types/src/testing/query.test.d.ts.map +0 -1
  219. package/dist/types/src/testing/test-data.d.ts +0 -29
  220. package/dist/types/src/testing/test-data.d.ts.map +0 -1
  221. package/dist/types/src/testing/test-schema.d.ts +0 -50
  222. package/dist/types/src/testing/test-schema.d.ts.map +0 -1
  223. package/dist/types/src/util/index.d.ts +0 -2
  224. package/dist/types/src/util/index.d.ts.map +0 -1
  225. package/dist/types/src/util/trim.d.ts +0 -5
  226. package/dist/types/src/util/trim.d.ts.map +0 -1
  227. package/src/ai-service/client.test.ts +0 -265
  228. package/src/ai-service/defs.ts +0 -39
  229. package/src/ai-service/edge-client.ts +0 -67
  230. package/src/ai-service/index.ts +0 -13
  231. package/src/ai-service/message-collector.ts +0 -84
  232. package/src/ai-service/ollama-client.ts +0 -499
  233. package/src/ai-service/parser.ts +0 -358
  234. package/src/ai-service/service.ts +0 -15
  235. package/src/ai-service/stream.test.ts +0 -125
  236. package/src/ai-service/stream.ts +0 -118
  237. package/src/ai-service/testing/index.ts +0 -6
  238. package/src/ai-service/testing/mock.ts +0 -22
  239. package/src/ai-service/testing/test-stream.ts +0 -93
  240. package/src/ai-service/transform.ts +0 -121
  241. package/src/ai-service/types.ts +0 -103
  242. package/src/ai-service/util/index.ts +0 -5
  243. package/src/ai-service/util/sse.ts +0 -341
  244. package/src/bin/chat.ts +0 -79
  245. package/src/conversation/conversation.test.ts +0 -73
  246. package/src/conversation/conversation.ts +0 -257
  247. package/src/conversation/index.ts +0 -5
  248. package/src/conversation/types.ts +0 -129
  249. package/src/cypher/ast.ts +0 -75
  250. package/src/cypher/combinators.test.ts +0 -137
  251. package/src/cypher/combinators.ts +0 -148
  252. package/src/cypher/echo-data-source.ts +0 -105
  253. package/src/cypher/execution-plan.test.ts +0 -44
  254. package/src/cypher/execution-plan.ts +0 -208
  255. package/src/cypher/index.ts +0 -8
  256. package/src/cypher/parjs-shims.d.ts +0 -10
  257. package/src/cypher/parjs.ts +0 -10
  258. package/src/cypher/parser.ts +0 -19
  259. package/src/cypher/query-executor.test.ts +0 -47
  260. package/src/cypher/query-executor.ts +0 -145
  261. package/src/cypher/schema.test.ts +0 -17
  262. package/src/cypher/schema.ts +0 -86
  263. package/src/testing/artifacts.test.ts +0 -182
  264. package/src/testing/data.ts +0 -13
  265. package/src/testing/defs.ts +0 -9
  266. package/src/testing/logger.ts +0 -129
  267. package/src/testing/object-extraction.test.ts +0 -71
  268. package/src/testing/ollama.ts +0 -15
  269. package/src/testing/query-promts.ts +0 -75
  270. package/src/testing/query.test.ts +0 -91
  271. package/src/testing/test-data.ts +0 -372
  272. package/src/testing/test-schema.ts +0 -80
  273. package/src/util/index.ts +0 -5
  274. package/src/util/trim.ts +0 -15
  275. package/vendor/parjs-browser.mjs +0 -4
  276. package/vendor/parjs-default.mjs +0 -8
  277. /package/dist/types/{src/bin → bin}/chat.d.ts +0 -0
@@ -2,16 +2,33 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Schema as S } from 'effect';
6
-
7
- import { defineTool, Message, ToolResult, type ArtifactDefinition, type Tool } from '@dxos/artifact';
5
+ import { Option, Schema } from 'effect';
6
+
7
+ import {
8
+ AgentStatusReport,
9
+ isToolUse,
10
+ runTools,
11
+ type AgentStatus,
12
+ structuredOutputParser,
13
+ type AIServiceClient,
14
+ type GenerationStream,
15
+ type GenerateRequest,
16
+ Message,
17
+ type MessageContentBlock,
18
+ MixedStreamParser,
19
+ ToolResult,
20
+ createTool,
21
+ type ExecutableTool,
22
+ } from '@dxos/ai';
23
+ import { type ArtifactDefinition } from '@dxos/artifact';
8
24
  import { Event, synchronized } from '@dxos/async';
9
- import { createStatic } from '@dxos/echo-schema';
25
+ import { ObjectVersion } from '@dxos/echo-db';
26
+ import { create, type ObjectId } from '@dxos/echo-schema';
10
27
  import { invariant } from '@dxos/invariant';
11
28
  import { log } from '@dxos/log';
12
29
 
13
- import { MixedStreamParser, type AIServiceClient, type GenerateRequest, type GenerationStream } from '../ai-service';
14
- import { isToolUse, runTools } from '../conversation';
30
+ import { VersionPin } from './version-pin';
31
+
15
32
  /**
16
33
  * Contains message history, tools, current context.
17
34
  * Current context means the state of the app, time of day, and other contextual information.
@@ -23,6 +40,22 @@ import { isToolUse, runTools } from '../conversation';
23
40
  * Could be personal or shared.
24
41
  */
25
42
 
43
+ /**
44
+ * Resolves artifact ids to their versions.
45
+ * Used to give the model a sense of the changes to the artifacts made by users during the conversation.
46
+ * The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,
47
+ * a diff is inserted into the conversation.
48
+ */
49
+ export type ArtifactDiffResolver = (artifacts: { id: ObjectId; lastVersion: ObjectVersion }[]) => Promise<
50
+ Map<
51
+ ObjectId,
52
+ {
53
+ version: ObjectVersion;
54
+ diff?: string;
55
+ }
56
+ >
57
+ >;
58
+
26
59
  export type SessionRunOptions = {
27
60
  client: AIServiceClient;
28
61
 
@@ -31,7 +64,7 @@ export type SessionRunOptions = {
31
64
  /**
32
65
  * Non-artifact specific tools.
33
66
  */
34
- tools: Tool[];
67
+ tools: ExecutableTool[];
35
68
 
36
69
  history: Message[];
37
70
 
@@ -47,15 +80,22 @@ export type SessionRunOptions = {
47
80
  * Pre-require artifacts.
48
81
  */
49
82
  requiredArtifactIds?: string[];
83
+
84
+ /**
85
+ * @see ArtifactDiffResolver
86
+ */
87
+ artifactDiffResolver?: ArtifactDiffResolver;
50
88
  };
51
89
 
52
- type OperationModel = 'planning' | 'immediate';
90
+ type OperationModel = 'planning' | 'importing' | 'configured';
53
91
 
54
92
  export type AiSessionOptions = {
55
93
  /**
56
- * In planning mode, the model will create a plan before executing the user's request.
57
- * The plan will determine the artifacts that will be used to perform the actions.
58
- * In require mode, the model will select the artifacts that will be used to perform the actions.
94
+ * Determines the agent's handling of the artifacts definitions:
95
+ *
96
+ * - `planning`: The model will create a plan with required artifacts for each step.
97
+ * - `importing`: The model can query registry and only pull in the artifacts that are required to complete the task.
98
+ * - `configured`: The available artifacts are pre-selected and the model cannot select additional artifacts.
59
99
  */
60
100
  operationModel: OperationModel;
61
101
  };
@@ -95,165 +135,61 @@ export class AISession {
95
135
  */
96
136
  public readonly userMessage = new Event<Message>();
97
137
 
138
+ /**
139
+ * Agent self-reporting its status.
140
+ */
141
+ public readonly statusReport = new Event<AgentStatus>();
142
+
143
+ public readonly toolStatusReport = new Event<{ message: Message; status: AgentStatus }>();
144
+
98
145
  constructor(private readonly _options: AiSessionOptions) {
99
146
  // Message complete.
100
147
  this._parser.message.on((message) => {
101
148
  this._pending.push(message);
102
149
  });
150
+ this._parser.block.on((block) => {
151
+ if (block.type === 'text' && block.disposition === 'status') {
152
+ this.statusReport.emit(create(AgentStatusReport, { message: block.text }));
153
+ }
154
+ });
103
155
  }
104
156
 
105
157
  @synchronized
106
158
  async run(options: SessionRunOptions): Promise<Message[]> {
107
- const systemTools: Tool[] = [
108
- defineTool('system', {
109
- name: 'query_artifact_definitions',
110
- description: 'Query the available artifact definitions',
111
- schema: S.Struct({}),
112
- execute: async () => {
113
- return ToolResult.Success({
114
- artifactDefinitions: options.artifacts.map((artifact) => ({
115
- id: artifact.id,
116
- name: artifact.name,
117
- description: artifact.description,
118
- })),
119
- });
120
- },
121
- }),
122
- ];
159
+ const systemTools: ExecutableTool[] = [];
123
160
  switch (this._options.operationModel) {
124
161
  case 'planning':
125
- systemTools.push(
126
- defineTool('system', {
127
- name: 'create_plan',
128
- description:
129
- '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.',
130
- schema: S.Struct({
131
- goal: S.String.annotations({ description: 'The goal that the plan will achieve.' }),
132
- steps: S.Array(
133
- S.Struct({
134
- action: S.String.annotations({
135
- description: 'Complete, detailed action to perform.',
136
- }),
137
- input: S.String.annotations({
138
- description: 'The required input data for this step. First step must not require any data.',
139
- }),
140
- output: S.String.annotations({
141
- description: 'The output data from this step. This is passed to the next step as input.',
142
- }),
143
- requiredArtifactIds: S.Array(S.String).annotations({
144
- description: 'The ids of the artifacts required to perform this step.',
145
- examples: [['artifact:dxos.org/example/Test']],
146
- }),
147
- }),
148
- ).annotations({ description: 'Steps' }),
149
- }),
150
- execute: async ({ goal, steps }) => {
151
- const missingArtifactIds = steps
152
- .flatMap((step) => step.requiredArtifactIds)
153
- .filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
154
- if (missingArtifactIds.length > 0) {
155
- return ToolResult.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(', ')}`);
156
- }
157
-
158
- const stepResults: any[] = [];
159
- for (const step of steps) {
160
- log('executing step', { action: step.action });
161
- const session = new AISession({ operationModel: 'immediate' });
162
- session.message.on((ev) => this.message.emit(ev));
163
- session.block.on((ev) => this.block.emit(ev));
164
- session.update.on((ev) => this.update.emit(ev));
165
- session.streamEvent.on((ev) => this.streamEvent.emit(ev));
166
- session.userMessage.on((ev) => this.userMessage.emit(ev));
167
-
168
- const messages = await session.run({
169
- client: options.client,
170
- artifacts: options.artifacts,
171
- tools: options.tools,
172
- history: options.history,
173
- extensions: options.extensions,
174
- generationOptions: options.generationOptions,
175
- requiredArtifactIds: step.requiredArtifactIds.slice(),
176
- prompt: `
177
- You are an agent that executes the subtask in a plan.
178
-
179
- While you know the plan's goal only focus on your subtask
180
- Use the data from the previous step to complete your task.
181
- Return all of the data from "output" in your last message.
182
-
183
- Current step (that you need to complete):
184
- ${JSON.stringify(
185
- {
186
- goal,
187
- input: step.input,
188
- output: step.output,
189
- yourTask: step.action,
190
- },
191
- null,
192
- 2,
193
- )}
194
-
195
- Previous step results:
196
- ${JSON.stringify(stepResults.at(-1))}.
197
- `,
198
- });
199
- const result = messages.at(-1);
200
- stepResults.push(result);
201
- }
202
-
203
- return ToolResult.Success({ stepResults });
204
- },
205
- }),
206
- );
162
+ systemTools.push(this._createQueryArtifactsTool(options.artifacts), this._createPlanningTool(options));
207
163
  break;
208
- case 'immediate':
164
+ case 'importing':
209
165
  systemTools.push(
210
- defineTool('system', {
211
- name: 'require_artifact_definitions',
212
- description:
213
- 'Require the use of specific artifact definitions. This will allow the model to interact with artifact definitions and use their tools.',
214
- schema: S.Struct({
215
- artifactDefinitionIds: S.Array(S.String).annotations({
216
- description: 'The ids of the artifact definitions to require',
217
- examples: [['artifact:dxos.org/example/Test']],
218
- }),
219
- }),
220
- execute: async ({ artifactDefinitionIds }) => {
221
- const missingArtifactDefinitionIds = artifactDefinitionIds.filter(
222
- (artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId),
223
- );
224
- if (missingArtifactDefinitionIds.length > 0) {
225
- return ToolResult.Error(
226
- `One or more artifact definition ids are invalid: ${missingArtifactDefinitionIds.join(', ')}`,
227
- );
228
- }
229
-
230
- for (const artifactDefinitionId of artifactDefinitionIds) {
231
- requiredArtifactIds.add(artifactDefinitionId);
232
- }
233
-
234
- return ToolResult.Success({});
235
- },
166
+ this._createQueryArtifactsTool(options.artifacts),
167
+ this._createRequireTool(options.artifacts, (artifactDefinitionIds) => {
168
+ for (const artifactDefinitionId of artifactDefinitionIds) {
169
+ requiredArtifactIds.add(artifactDefinitionId);
170
+ }
236
171
  }),
237
172
  );
238
173
  break;
174
+ case 'configured':
175
+ // no system tools
176
+ break;
177
+ default:
178
+ throw new TypeError(`Invalid operation model: ${this._options.operationModel}`);
239
179
  }
240
180
 
241
181
  this._history = [...options.history];
242
- this._pending = [
243
- createStatic(Message, {
244
- role: 'user',
245
- content: [{ type: 'text', text: options.prompt }],
246
- }),
247
- ];
182
+ this._pending = [await this._formatUserPrompt(options.artifactDiffResolver, options.prompt, options.history)];
248
183
  this.userMessage.emit(this._pending.at(-1)!);
249
184
  this._stream = undefined;
185
+
250
186
  let error: Error | undefined;
251
187
 
252
188
  const requiredArtifactIds = new Set<string>(options.requiredArtifactIds ?? []);
253
189
  try {
254
190
  let more = false;
255
191
  do {
256
- const tools = [
192
+ const tools: ExecutableTool[] = [
257
193
  ...systemTools,
258
194
  ...options.tools,
259
195
  ...options.artifacts
@@ -268,7 +204,7 @@ export class AISession {
268
204
  });
269
205
 
270
206
  // Open request stream.
271
- this._stream = await options.client.exec({
207
+ this._stream = await options.client.execStream({
272
208
  ...(options.generationOptions ?? {}),
273
209
  // TODO(burdon): Rename messages or separate history/message.
274
210
  history: [...this._history, ...this._pending],
@@ -298,6 +234,7 @@ export class AISession {
298
234
  message: this._pending.at(-1)!,
299
235
  tools,
300
236
  extensions: options.extensions ?? {},
237
+ reportStatus: (status) => this._onToolStatusReport(message, status),
301
238
  });
302
239
 
303
240
  log('tool response', { response });
@@ -314,7 +251,7 @@ export class AISession {
314
251
  } catch (err) {
315
252
  log.catch(err);
316
253
  if (err instanceof Error && err.message.includes('Overloaded')) {
317
- error = new AIServiecOverloadedError('AI service overloaded', { cause: err });
254
+ error = new AIServiecOverloadedError('AI service overloaded', { cause: err } as any); // TODO(dmaretskyi): Schema errors cant have cause
318
255
  } else {
319
256
  error = new Error('AI service error', { cause: err });
320
257
  }
@@ -329,7 +266,193 @@ export class AISession {
329
266
  return this._pending;
330
267
  }
331
268
 
332
- abort() {
269
+ async runStructured<S extends Schema.Schema.AnyNoContext>(
270
+ schema: S,
271
+ options: SessionRunOptions,
272
+ ): Promise<Schema.Schema.Type<S>> {
273
+ const parser = structuredOutputParser(schema);
274
+ const result = await this.run({
275
+ ...options,
276
+ tools: [...options.tools, parser.tool],
277
+ });
278
+ return parser.getResult(result);
279
+ }
280
+
281
+ private async _formatUserPrompt(
282
+ artifactDiffResolver: ArtifactDiffResolver | undefined,
283
+ prompt: string,
284
+ history: Message[],
285
+ ) {
286
+ const prelude: MessageContentBlock[] = [];
287
+
288
+ if (artifactDiffResolver) {
289
+ const versions = gatherObjectVersions(history);
290
+
291
+ const artifactDiff = await artifactDiffResolver(
292
+ Array.from(versions.entries()).map(([id, version]) => ({ id, lastVersion: version })),
293
+ );
294
+
295
+ log.info('vision', {
296
+ artifactDiff,
297
+ versions,
298
+ });
299
+
300
+ for (const [id, { version }] of [...artifactDiff.entries()]) {
301
+ if (ObjectVersion.equals(version, versions.get(id)!)) {
302
+ artifactDiff.delete(id);
303
+ continue;
304
+ }
305
+
306
+ prelude.push(VersionPin.createBlock(VersionPin.make({ objectId: id, version })));
307
+ }
308
+ if (artifactDiff.size > 0) {
309
+ prelude.push(createArtifactUpdateBlock(artifactDiff));
310
+ }
311
+ }
312
+
313
+ return create(Message, {
314
+ role: 'user',
315
+ content: [...prelude, { type: 'text', text: prompt }],
316
+ });
317
+ }
318
+
319
+ private _createQueryArtifactsTool(artifacts: ArtifactDefinition[]): ExecutableTool {
320
+ return createTool('system', {
321
+ name: 'query_artifact_definitions',
322
+ description: 'Query the available artifact definitions',
323
+ schema: Schema.Struct({}),
324
+ execute: async () => {
325
+ return ToolResult.Success({
326
+ artifactDefinitions: artifacts.map((artifact) => ({
327
+ id: artifact.id,
328
+ name: artifact.name,
329
+ description: artifact.description,
330
+ })),
331
+ });
332
+ },
333
+ });
334
+ }
335
+
336
+ private _createRequireTool(
337
+ artifacts: ArtifactDefinition[],
338
+ onRequire: (artifactDefinitionIds: readonly string[]) => void,
339
+ ): ExecutableTool {
340
+ return createTool('system', {
341
+ name: 'require_artifact_definitions',
342
+ description:
343
+ 'Require the use of specific artifact definitions. This will allow the model to interact with artifact definitions and use their tools.',
344
+ schema: Schema.Struct({
345
+ artifactDefinitionIds: Schema.Array(Schema.String).annotations({
346
+ description: 'The ids of the artifact definitions to require',
347
+ examples: [['artifact:dxos.org/example/Test']],
348
+ }),
349
+ }),
350
+ execute: async ({ artifactDefinitionIds }) => {
351
+ const missingArtifactDefinitionIds = artifactDefinitionIds.filter(
352
+ (artifactId) => !artifacts.some((artifact) => artifact.id === artifactId),
353
+ );
354
+ if (missingArtifactDefinitionIds.length > 0) {
355
+ return ToolResult.Error(
356
+ `One or more artifact definition ids are invalid: ${missingArtifactDefinitionIds.join(', ')}`,
357
+ );
358
+ }
359
+
360
+ onRequire(artifactDefinitionIds);
361
+
362
+ return ToolResult.Success({});
363
+ },
364
+ });
365
+ }
366
+
367
+ private _createPlanningTool(options: SessionRunOptions): ExecutableTool {
368
+ return createTool('system', {
369
+ name: 'create_plan',
370
+ description:
371
+ '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.',
372
+ schema: Schema.Struct({
373
+ goal: Schema.String.annotations({ description: 'The goal that the plan will achieve.' }),
374
+ steps: Schema.Array(
375
+ Schema.Struct({
376
+ action: Schema.String.annotations({
377
+ description: 'Complete, detailed action to perform.',
378
+ }),
379
+ input: Schema.String.annotations({
380
+ description: 'The required input data for this step. First step must not require any data.',
381
+ }),
382
+ output: Schema.String.annotations({
383
+ description: 'The output data from this step. This is passed to the next step as input.',
384
+ }),
385
+ requiredArtifactIds: Schema.Array(Schema.String).annotations({
386
+ description: 'The ids of the artifacts required to perform this step.',
387
+ examples: [['artifact:dxos.org/example/Test']],
388
+ }),
389
+ }),
390
+ ).annotations({ description: 'Steps' }),
391
+ }),
392
+ execute: async ({ goal, steps }) => {
393
+ const missingArtifactIds = steps
394
+ .flatMap((step) => step.requiredArtifactIds)
395
+ .filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
396
+ if (missingArtifactIds.length > 0) {
397
+ return ToolResult.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(', ')}`);
398
+ }
399
+
400
+ const stepResults: any[] = [];
401
+ for (const step of steps) {
402
+ log('executing step', { action: step.action });
403
+ const session = new AISession({ operationModel: 'importing' });
404
+ session.message.on((ev) => this.message.emit(ev));
405
+ session.block.on((ev) => this.block.emit(ev));
406
+ session.update.on((ev) => this.update.emit(ev));
407
+ session.streamEvent.on((ev) => this.streamEvent.emit(ev));
408
+ session.userMessage.on((ev) => this.userMessage.emit(ev));
409
+
410
+ const messages = await session.run({
411
+ client: options.client,
412
+ artifacts: options.artifacts,
413
+ tools: options.tools,
414
+ history: options.history,
415
+ extensions: options.extensions,
416
+ generationOptions: options.generationOptions,
417
+ requiredArtifactIds: step.requiredArtifactIds.slice(),
418
+ artifactDiffResolver: options.artifactDiffResolver,
419
+ prompt: `
420
+ You are an agent that executes the subtask in a plan.
421
+
422
+ While you know the plan's goal only focus on your subtask
423
+ Use the data from the previous step to complete your task.
424
+ Return all of the data from "output" in your last message.
425
+
426
+ Current step (that you need to complete):
427
+ ${JSON.stringify(
428
+ {
429
+ goal,
430
+ input: step.input,
431
+ output: step.output,
432
+ yourTask: step.action,
433
+ },
434
+ null,
435
+ 2,
436
+ )}
437
+
438
+ Previous step results:
439
+ ${JSON.stringify(stepResults.at(-1))}.
440
+ `,
441
+ });
442
+ const result = messages.at(-1);
443
+ stepResults.push(result);
444
+ }
445
+
446
+ return ToolResult.Success({ stepResults });
447
+ },
448
+ });
449
+ }
450
+
451
+ private _onToolStatusReport(message: Message, status: AgentStatus): void {
452
+ this.toolStatusReport.emit({ message, status });
453
+ }
454
+
455
+ abort(): void {
333
456
  this._stream?.abort();
334
457
  }
335
458
  }
@@ -351,25 +474,75 @@ const createBaseInstructions = ({
351
474
  Decision-making:
352
475
 
353
476
  - Analyze the structure and type of the content in the user's message.
354
- - Can you complete the task using the available artifacts?
355
- - If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
356
- - Identify which artifacts are relevant to the user's request.
477
+
478
+
357
479
  ${
358
480
  operationModel === 'planning'
359
481
  ? `
482
+ - Can you complete the task using the available artifacts?
483
+ - If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
484
+ - Identify which artifacts are relevant to the user's request.
360
485
  - 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.
361
486
  `
362
- : `
363
- - Are the required artifacts already available?
364
- - If not, select which artifact(s) will be the most relevant and require them using the require_artifacts tool.
365
- - The require'd artifact tools will be available for use after require.
366
- `
487
+ : ''
488
+ }
489
+ ${
490
+ operationModel === 'importing'
491
+ ? `
492
+ - Can you complete the task using the available artifacts?
493
+ - If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
494
+ - Identify which artifacts are relevant to the user's request.
495
+ - Are the required artifacts already available?
496
+ - If not, select which artifact(s) will be the most relevant and require them using the require_artifacts tool.
497
+ - The require'd artifact tools will be available for use after require.
498
+ `
499
+ : ''
500
+ }
501
+ ${
502
+ operationModel === 'configured'
503
+ ? `
504
+ - Select the most relevant artifact(s) to complete the task.
505
+ - Call the appropriate tool to use the artifact(s).
506
+ `
507
+ : ''
367
508
  }
368
509
 
369
510
  ${availableArtifacts.length > 0 ? `Artifacts already in context: ${availableArtifacts.join('\n')}` : ''}
370
511
  `;
371
512
 
372
- export class AIServiecOverloadedError extends S.TaggedError<AIServiecOverloadedError>()(
513
+ export class AIServiecOverloadedError extends Schema.TaggedError<AIServiecOverloadedError>()(
373
514
  'AIServiecOverloadedError',
374
515
  {},
375
516
  ) {}
517
+
518
+ const gatherObjectVersions = (messages: Message[]): Map<ObjectId, ObjectVersion> => {
519
+ const artifactIds = new Map<ObjectId, ObjectVersion>();
520
+ for (const message of messages) {
521
+ for (const block of message.content) {
522
+ if (block.type === 'json' && block.disposition === VersionPin.DISPOSITION) {
523
+ const pin = VersionPin.pipe(Schema.decodeOption)(JSON.parse(block.json)).pipe(Option.getOrUndefined);
524
+ if (!pin) {
525
+ continue;
526
+ }
527
+ artifactIds.set(pin.objectId, pin.version);
528
+ }
529
+ }
530
+ }
531
+
532
+ return artifactIds;
533
+ };
534
+
535
+ const createArtifactUpdateBlock = (
536
+ artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,
537
+ ): MessageContentBlock => {
538
+ return {
539
+ type: 'text',
540
+ disposition: 'artifact-update',
541
+ text: `
542
+ The following artifacts have been updated since the last message:
543
+ ${Array.from(artifactDiff.entries())
544
+ .map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `\n${diff}` : ''}</changed-artifact>`)
545
+ .join('\n')}
546
+ `,
547
+ };
548
+ };
@@ -0,0 +1,26 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { pipe, Schema } from 'effect';
6
+ import { describe, expect, test } from 'vitest';
7
+
8
+ import { Expando } from '@dxos/echo-schema';
9
+ import { invariant } from '@dxos/invariant';
10
+ import { live } from '@dxos/live-object';
11
+
12
+ import { VersionPin } from './version-pin';
13
+
14
+ describe('VersionPin', () => {
15
+ test('serialization', () => {
16
+ const obj = live(Expando, {
17
+ name: 'John Doe',
18
+ });
19
+ const block = VersionPin.createBlock(VersionPin.make({ objectId: obj.id, version: obj.version }));
20
+ invariant(block.type === 'json' && block.disposition === VersionPin.DISPOSITION);
21
+ const pin = pipe(JSON.parse(block.json), VersionPin.pipe(Schema.decodeSync));
22
+ expect(pin).toBeDefined();
23
+ expect(pin?.objectId).toBe(obj.id);
24
+ expect(pin?.version).toBe(obj.version);
25
+ });
26
+ });
@@ -0,0 +1,48 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Schema } from 'effect';
6
+
7
+ import { type MessageContentBlock } from '@dxos/ai';
8
+ import { type ObjectVersion } from '@dxos/echo-db';
9
+ import { getVersion } from '@dxos/echo-db';
10
+ import { ObjectId, type BaseEchoObject } from '@dxos/echo-schema';
11
+
12
+ // TODO(dmaretskyi): Extract.
13
+ const ObjectVersionSchema = Schema.Unknown as Schema.Schema<ObjectVersion>;
14
+
15
+ const VersionPinSchema = Schema.Struct({
16
+ // TODO(dmaretskyi): Use Ref when those support encoding.
17
+ objectId: ObjectId,
18
+ // TODO(dmaretskyi): Could be opaque
19
+ version: ObjectVersionSchema,
20
+ });
21
+
22
+ /**
23
+ * Used to pin a specific version of an object during the course of a conversation.
24
+ * This allows us to detect when the object changes during the course of the conversation.
25
+ */
26
+ export interface VersionPin extends Schema.Schema.Type<typeof VersionPinSchema> {}
27
+
28
+ export const VersionPin: typeof VersionPinSchema & {
29
+ DISPOSITION: 'version-pin';
30
+ fromObject: (object: BaseEchoObject) => VersionPin;
31
+ createBlock: (pin: VersionPin) => MessageContentBlock;
32
+ } = class extends VersionPinSchema {
33
+ static readonly DISPOSITION = 'version-pin';
34
+ static fromObject(object: BaseEchoObject): VersionPin {
35
+ return VersionPin.make({
36
+ objectId: object.id,
37
+ version: getVersion(object),
38
+ });
39
+ }
40
+
41
+ static createBlock(pin: VersionPin): MessageContentBlock {
42
+ return {
43
+ type: 'json',
44
+ disposition: VersionPin.DISPOSITION,
45
+ json: JSON.stringify(pin),
46
+ };
47
+ }
48
+ };