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

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 (233) hide show
  1. package/README.md +1 -0
  2. package/dist/lib/neutral/chunk-2TBLG3XY.mjs +1793 -0
  3. package/dist/lib/neutral/chunk-2TBLG3XY.mjs.map +7 -0
  4. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
  5. package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +7 -0
  6. package/dist/lib/neutral/extraction/index.mjs +219 -0
  7. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  8. package/dist/lib/neutral/index.mjs +537 -0
  9. package/dist/lib/neutral/index.mjs.map +7 -0
  10. package/dist/lib/neutral/meta.json +1 -0
  11. package/dist/lib/neutral/testing/index.mjs +111 -0
  12. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  13. package/dist/types/src/conversation/context.d.ts +155 -0
  14. package/dist/types/src/conversation/context.d.ts.map +1 -0
  15. package/dist/types/src/conversation/context.test.d.ts +2 -0
  16. package/dist/types/src/conversation/context.test.d.ts.map +1 -0
  17. package/dist/types/src/conversation/index.d.ts +2 -1
  18. package/dist/types/src/conversation/index.d.ts.map +1 -1
  19. package/dist/types/src/conversation/session.d.ts +78 -0
  20. package/dist/types/src/conversation/session.d.ts.map +1 -0
  21. package/dist/types/src/conversation/session.test.d.ts.map +1 -0
  22. package/dist/types/src/diff.d.ts +17 -0
  23. package/dist/types/src/diff.d.ts.map +1 -0
  24. package/dist/types/src/diff.test.d.ts +2 -0
  25. package/dist/types/src/diff.test.d.ts.map +1 -0
  26. package/dist/types/src/errors.d.ts +67 -0
  27. package/dist/types/src/errors.d.ts.map +1 -0
  28. package/dist/types/src/execution-graph.d.ts +85 -0
  29. package/dist/types/src/execution-graph.d.ts.map +1 -0
  30. package/dist/types/src/execution-graph.test.d.ts +2 -0
  31. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  32. package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
  33. package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
  34. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts +1 -1
  35. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  36. package/dist/types/src/extraction/extraction.d.ts +1066 -215
  37. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  38. package/dist/types/src/extraction/index.d.ts +0 -1
  39. package/dist/types/src/extraction/index.d.ts.map +1 -1
  40. package/dist/types/src/extraction/quotes.d.ts +3 -3
  41. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  42. package/dist/types/src/functions/index.d.ts +2 -0
  43. package/dist/types/src/functions/index.d.ts.map +1 -0
  44. package/dist/types/src/functions/services.d.ts +17 -0
  45. package/dist/types/src/functions/services.d.ts.map +1 -0
  46. package/dist/types/src/functions.test.d.ts +2 -0
  47. package/dist/types/src/functions.test.d.ts.map +1 -0
  48. package/dist/types/src/index.d.ts +7 -5
  49. package/dist/types/src/index.d.ts.map +1 -1
  50. package/dist/types/src/service/AgentService.d.ts +75 -0
  51. package/dist/types/src/service/AgentService.d.ts.map +1 -0
  52. package/dist/types/src/service/AgentService.test.d.ts +2 -0
  53. package/dist/types/src/service/AgentService.test.d.ts.map +1 -0
  54. package/dist/types/src/service/agent-process.d.ts +21 -0
  55. package/dist/types/src/service/agent-process.d.ts.map +1 -0
  56. package/dist/types/src/service/index.d.ts +3 -0
  57. package/dist/types/src/service/index.d.ts.map +1 -0
  58. package/dist/types/src/session/artifact-diff.d.ts +27 -0
  59. package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
  60. package/dist/types/src/session/error-handling.d.ts +4 -0
  61. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  62. package/dist/types/src/session/format.d.ts +16 -0
  63. package/dist/types/src/session/format.d.ts.map +1 -0
  64. package/dist/types/src/session/format.test.d.ts +2 -0
  65. package/dist/types/src/session/format.test.d.ts.map +1 -0
  66. package/dist/types/src/session/index.d.ts +5 -1
  67. package/dist/types/src/session/index.d.ts.map +1 -1
  68. package/dist/types/src/session/observer.d.ts +23 -0
  69. package/dist/types/src/session/observer.d.ts.map +1 -0
  70. package/dist/types/src/session/request.d.ts +106 -0
  71. package/dist/types/src/session/request.d.ts.map +1 -0
  72. package/dist/types/src/session/request.test.d.ts +2 -0
  73. package/dist/types/src/session/request.test.d.ts.map +1 -0
  74. package/dist/types/src/session/session-ollama.test.d.ts +2 -0
  75. package/dist/types/src/session/session-ollama.test.d.ts.map +1 -0
  76. package/dist/types/src/session/toolkit.d.ts +16 -0
  77. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  78. package/dist/types/src/session/version-pin.d.ts +5 -5
  79. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  80. package/dist/types/src/templates/index.d.ts +2 -0
  81. package/dist/types/src/templates/index.d.ts.map +1 -0
  82. package/dist/types/src/templates/system.d.ts +17 -0
  83. package/dist/types/src/templates/system.d.ts.map +1 -0
  84. package/dist/types/src/testing/index.d.ts +1 -2
  85. package/dist/types/src/testing/index.d.ts.map +1 -1
  86. package/dist/types/src/testing/layer.d.ts +40 -0
  87. package/dist/types/src/testing/layer.d.ts.map +1 -0
  88. package/dist/types/src/tracing.d.ts +223 -0
  89. package/dist/types/src/tracing.d.ts.map +1 -0
  90. package/dist/types/src/types/artifact.d.ts +28 -0
  91. package/dist/types/src/types/artifact.d.ts.map +1 -0
  92. package/dist/types/src/types/index.d.ts +2 -0
  93. package/dist/types/src/types/index.d.ts.map +1 -0
  94. package/dist/types/tsconfig.tsbuildinfo +1 -1
  95. package/package.json +60 -29
  96. package/src/conversation/context.test.ts +52 -0
  97. package/src/conversation/context.ts +403 -0
  98. package/src/conversation/index.ts +2 -1
  99. package/src/conversation/session.test.ts +58 -0
  100. package/src/conversation/session.ts +300 -0
  101. package/src/diff.test.ts +74 -0
  102. package/src/diff.ts +93 -0
  103. package/src/errors.ts +15 -0
  104. package/src/execution-graph.test.ts +740 -0
  105. package/src/execution-graph.ts +509 -0
  106. package/src/extraction/extraction-ner-function/index.ts +0 -1
  107. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  108. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +3 -1
  109. package/src/extraction/extraction.ts +44 -15
  110. package/src/extraction/index.ts +0 -1
  111. package/src/extraction/quotes.test.ts +3 -3
  112. package/src/extraction/quotes.ts +6 -7
  113. package/src/functions/index.ts +5 -0
  114. package/src/functions/services.ts +214 -0
  115. package/src/functions.conversations.json +1 -0
  116. package/src/functions.test.ts +88 -0
  117. package/src/index.ts +7 -5
  118. package/src/service/AgentService.conversations.json +1 -0
  119. package/src/service/AgentService.test.ts +169 -0
  120. package/src/service/AgentService.ts +184 -0
  121. package/src/service/agent-process.ts +364 -0
  122. package/src/service/index.ts +6 -0
  123. package/src/session/artifact-diff.ts +41 -0
  124. package/src/session/error-handling.ts +41 -0
  125. package/src/session/format.test.ts +132 -0
  126. package/src/session/format.ts +149 -0
  127. package/src/session/index.ts +5 -1
  128. package/src/session/observer.ts +62 -0
  129. package/src/session/request.conversations.json +1 -0
  130. package/src/session/request.test.ts +195 -0
  131. package/src/session/request.ts +344 -0
  132. package/src/session/session-ollama.test.ts +81 -0
  133. package/src/session/toolkit.ts +47 -0
  134. package/src/session/version-pin.ts +12 -12
  135. package/src/templates/index.ts +5 -0
  136. package/src/templates/instructions/format.tpl +57 -0
  137. package/src/templates/instructions/system.tpl +85 -0
  138. package/src/templates/system.ts +42 -0
  139. package/src/testing/index.ts +2 -8
  140. package/src/testing/layer.ts +236 -0
  141. package/src/tracing.ts +43 -0
  142. package/src/types/artifact.ts +89 -0
  143. package/src/types/index.ts +5 -0
  144. package/src/typings.d.ts +5 -0
  145. package/dist/lib/browser/index.mjs +0 -2019
  146. package/dist/lib/browser/index.mjs.map +0 -7
  147. package/dist/lib/browser/meta.json +0 -1
  148. package/dist/lib/node-esm/index.mjs +0 -2021
  149. package/dist/lib/node-esm/index.mjs.map +0 -7
  150. package/dist/lib/node-esm/meta.json +0 -1
  151. package/dist/types/bin/chat.d.ts +0 -2
  152. package/dist/types/bin/chat.d.ts.map +0 -1
  153. package/dist/types/src/blueprint/blueprint.d.ts +0 -41
  154. package/dist/types/src/blueprint/blueprint.d.ts.map +0 -1
  155. package/dist/types/src/blueprint/index.d.ts +0 -3
  156. package/dist/types/src/blueprint/index.d.ts.map +0 -1
  157. package/dist/types/src/blueprint/registry.d.ts +0 -7
  158. package/dist/types/src/blueprint/registry.d.ts.map +0 -1
  159. package/dist/types/src/context/binder.d.ts +0 -34
  160. package/dist/types/src/context/binder.d.ts.map +0 -1
  161. package/dist/types/src/context/binding.d.ts +0 -38
  162. package/dist/types/src/context/binding.d.ts.map +0 -1
  163. package/dist/types/src/context/index.d.ts +0 -3
  164. package/dist/types/src/context/index.d.ts.map +0 -1
  165. package/dist/types/src/conversation/conversation.d.ts +0 -44
  166. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  167. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
  168. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
  169. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
  170. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
  171. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
  172. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
  173. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -208
  174. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
  175. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
  176. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
  177. package/dist/types/src/research/exa.d.ts +0 -7
  178. package/dist/types/src/research/exa.d.ts.map +0 -1
  179. package/dist/types/src/research/graph.d.ts +0 -41
  180. package/dist/types/src/research/graph.d.ts.map +0 -1
  181. package/dist/types/src/research/graph.test.d.ts +0 -2
  182. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  183. package/dist/types/src/research/index.d.ts +0 -4
  184. package/dist/types/src/research/index.d.ts.map +0 -1
  185. package/dist/types/src/research/research.d.ts +0 -10
  186. package/dist/types/src/research/research.d.ts.map +0 -1
  187. package/dist/types/src/research/research.test.d.ts +0 -2
  188. package/dist/types/src/research/research.test.d.ts.map +0 -1
  189. package/dist/types/src/session/session.d.ts +0 -283
  190. package/dist/types/src/session/session.d.ts.map +0 -1
  191. package/dist/types/src/session/session.test.d.ts.map +0 -1
  192. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  193. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  194. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  195. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  196. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  197. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  198. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  199. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  200. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  201. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  202. package/dist/types/src/types.d.ts +0 -3
  203. package/dist/types/src/types.d.ts.map +0 -1
  204. package/src/blueprint/blueprint.ts +0 -75
  205. package/src/blueprint/index.ts +0 -6
  206. package/src/blueprint/registry.ts +0 -15
  207. package/src/context/binder.ts +0 -101
  208. package/src/context/binding.ts +0 -31
  209. package/src/context/index.ts +0 -6
  210. package/src/conversation/conversation.ts +0 -103
  211. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -95
  212. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -66
  213. package/src/extraction/extraction-llm-function/index.ts +0 -5
  214. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -115
  215. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -54
  216. package/src/research/exa.ts +0 -100
  217. package/src/research/graph.test.ts +0 -15
  218. package/src/research/graph.ts +0 -337
  219. package/src/research/index.ts +0 -7
  220. package/src/research/instructions-research.tpl +0 -97
  221. package/src/research/research.test.ts +0 -190
  222. package/src/research/research.ts +0 -90
  223. package/src/session/session.test.ts +0 -275
  224. package/src/session/session.ts +0 -582
  225. package/src/session/version-pin.test.ts +0 -26
  226. package/src/summarization/summarization.test.ts +0 -221
  227. package/src/testing/exa-search-1748337321991.ts +0 -131
  228. package/src/testing/exa-search-1748337331526.ts +0 -144
  229. package/src/testing/exa-search-1748337344119.ts +0 -133
  230. package/src/typedefs.d.ts +0 -8
  231. package/src/types.ts +0 -8
  232. /package/dist/types/src/{session → conversation}/session.test.d.ts +0 -0
  233. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -1,582 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { Array, Option, pipe, 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
- type ToolId,
23
- type ToolResolver,
24
- } from '@dxos/ai';
25
- import { type ArtifactDefinition } from '@dxos/artifact';
26
- import { Event, synchronized } from '@dxos/async';
27
- import { Obj } from '@dxos/echo';
28
- import { ObjectVersion } from '@dxos/echo-db';
29
- import { create, type ObjectId } from '@dxos/echo-schema';
30
- import { invariant } from '@dxos/invariant';
31
- import { log } from '@dxos/log';
32
-
33
- import { VersionPin } from './version-pin';
34
-
35
- /**
36
- * Contains message history, tools, current context.
37
- * Current context means the state of the app, time of day, and other contextual information.
38
- * It makes requests to the model, its a state machine.
39
- * It keeps track of the current goal.
40
- * It manages the context window.
41
- * Tracks the success criteria of reaching the goal, exposing metrics (stretch)
42
- * Could be run locally in the app or remotely.
43
- * Could be personal or shared.
44
- */
45
-
46
- /**
47
- * Resolves artifact ids to their versions.
48
- * Used to give the model a sense of the changes to the artifacts made by users during the conversation.
49
- * The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,
50
- * a diff is inserted into the conversation.
51
- */
52
- export type ArtifactDiffResolver = (artifacts: { id: ObjectId; lastVersion: ObjectVersion }[]) => Promise<
53
- Map<
54
- ObjectId,
55
- {
56
- version: ObjectVersion;
57
- diff?: string;
58
- }
59
- >
60
- >;
61
-
62
- export type SessionRunOptions = {
63
- artifacts: ArtifactDefinition[];
64
-
65
- /**
66
- * Non-artifact specific tools.
67
- */
68
- tools: ToolId[];
69
-
70
- history: Message[];
71
-
72
- prompt: string;
73
-
74
- generationOptions?: Pick<GenerateRequest, 'model'>;
75
-
76
- extensions?: ToolContextExtensions;
77
-
78
- systemPrompt?: string;
79
-
80
- /**
81
- * Pre-require artifacts.
82
- */
83
- requiredArtifactIds?: string[];
84
-
85
- client: AiServiceClient;
86
- toolResolver: ToolResolver;
87
-
88
- /**
89
- * Executable tools that do not go through the tool resolver.
90
- */
91
- executableTools?: ExecutableTool[];
92
-
93
- /**
94
- * @see ArtifactDiffResolver
95
- */
96
- artifactDiffResolver?: ArtifactDiffResolver;
97
- };
98
-
99
- type OperationModel = 'planning' | 'importing' | 'configured';
100
-
101
- export type AiSessionOptions = {
102
- /**
103
- * Determines the agent's handling of the artifacts definitions:
104
- *
105
- * - `planning`: The model will create a plan with required artifacts for each step.
106
- * - `importing`: The model can query registry and only pull in the artifacts that are required to complete the task.
107
- * - `configured`: The available artifacts are pre-selected and the model cannot select additional artifacts.
108
- */
109
- operationModel: OperationModel;
110
- };
111
-
112
- export class AISession {
113
- /** SSE stream parser. */
114
- private readonly _parser = new MixedStreamParser();
115
-
116
- /** Pending messages (incl. the current user request). */
117
- private _pending: Message[] = [];
118
-
119
- /** Current streaming response. */
120
- private _stream: GenerationStream | undefined;
121
-
122
- /** Prior history from queue. */
123
- private _history: Message[] = [];
124
-
125
- /**
126
- * New message.
127
- */
128
- public readonly message = this._parser.message;
129
-
130
- /**
131
- * Complete block added to Message.
132
- */
133
- public readonly block = this._parser.block;
134
-
135
- /**
136
- * Update partial block (while streaming).
137
- */
138
- public readonly update = this._parser.update;
139
-
140
- /**
141
- * Unparsed events from the underlying generation stream.
142
- */
143
- public readonly streamEvent = this._parser.streamEvent;
144
-
145
- /**
146
- * User prompt or tool result.
147
- */
148
- public readonly userMessage = new Event<Message>();
149
-
150
- /**
151
- * Agent self-reporting its status.
152
- * Triggered by the model.
153
- */
154
- public readonly statusReport = new Event<AgentStatus>();
155
-
156
- /**
157
- * Emits when the session is done.
158
- */
159
- public readonly done = new Event<void>();
160
-
161
- /**
162
- * Emits when the tool reports its status.
163
- * Triggered by the tool execution function.
164
- */
165
- public readonly toolStatusReport = new Event<{ message: Message; status: AgentStatus }>();
166
-
167
- constructor(private readonly _options: AiSessionOptions) {
168
- // Message complete.
169
- this._parser.message.on((message) => {
170
- this._pending.push(message);
171
- });
172
- this._parser.block.on((block) => {
173
- if (block.type === 'text' && block.disposition === 'status') {
174
- this.statusReport.emit(create(AgentStatusReport, { message: block.text }));
175
- }
176
- });
177
- }
178
-
179
- /**
180
- * Runs the AI model loop interacting with tools and artifacts.
181
- * @param options - The session options.
182
- * @returns The messages generated by the session, including the user's prompt.
183
- */
184
- @synchronized
185
- async run(options: SessionRunOptions): Promise<Message[]> {
186
- const systemTools: ExecutableTool[] = [];
187
- switch (this._options.operationModel) {
188
- case 'planning':
189
- systemTools.push(this._createQueryArtifactsTool(options.artifacts), this._createPlanningTool(options));
190
- break;
191
- case 'importing':
192
- systemTools.push(
193
- this._createQueryArtifactsTool(options.artifacts),
194
- this._createRequireTool(options.artifacts, (artifactDefinitionIds) => {
195
- for (const artifactDefinitionId of artifactDefinitionIds) {
196
- requiredArtifactIds.add(artifactDefinitionId);
197
- }
198
- }),
199
- );
200
- break;
201
- case 'configured':
202
- // no system tools
203
- break;
204
- default:
205
- throw new TypeError(`Invalid operation model: ${this._options.operationModel}`);
206
- }
207
-
208
- this._history = [...options.history];
209
- this._pending = [await this._formatUserPrompt(options.artifactDiffResolver, options.prompt, options.history)];
210
- this.userMessage.emit(this._pending.at(-1)!);
211
- this._stream = undefined;
212
-
213
- let error: Error | undefined;
214
-
215
- const requiredArtifactIds = new Set<string>(options.requiredArtifactIds ?? []);
216
- try {
217
- let more = false;
218
- do {
219
- const tools: ExecutableTool[] = pipe(
220
- [
221
- ...systemTools,
222
- ...(await Promise.all(options.tools.map((toolId) => options.toolResolver.resolve(toolId)))),
223
- ...(options.executableTools ?? []),
224
- ...options.artifacts
225
- .filter((artifact) => requiredArtifactIds.has(artifact.id))
226
- .flatMap((artifact) => artifact.tools),
227
- ],
228
- Array.dedupeWith((a, b) => a.id === b.id),
229
- );
230
-
231
- log('request', {
232
- pending: this._pending.length,
233
- history: this._history.length,
234
- tools: tools.map((tool) => tool.name),
235
- });
236
-
237
- // Open request stream.
238
- this._stream = await options.client.execStream({
239
- ...(options.generationOptions ?? {}),
240
- // TODO(burdon): Rename messages or separate history/message.
241
- history: [...this._history, ...this._pending],
242
- tools,
243
- systemPrompt:
244
- options.systemPrompt ??
245
- createBaseInstructions({
246
- availableArtifacts: [...requiredArtifactIds],
247
- operationModel: this._options.operationModel,
248
- }),
249
- });
250
-
251
- // Wait until complete.
252
- await this._parser.parse(this._stream);
253
- await this._stream.complete();
254
-
255
- // Add messages.
256
- log('response', { pending: this._pending });
257
-
258
- // Resolve tool use locally.
259
- more = false;
260
- const message = this._pending.at(-1);
261
- invariant(message);
262
- if (isToolUse(message)) {
263
- log('tool request...');
264
- const response = await runTools({
265
- message: this._pending.at(-1)!,
266
- tools,
267
- extensions: options.extensions ?? {},
268
- reportStatus: (status) => this._onToolStatusReport(message, status),
269
- });
270
-
271
- log('tool response', { response });
272
- switch (response.type) {
273
- case 'continue': {
274
- this._pending = [...this._pending, response.message];
275
- this.userMessage.emit(response.message);
276
- more = true;
277
- break;
278
- }
279
- }
280
- }
281
- } while (more);
282
- } catch (err) {
283
- log.catch(err);
284
- if (err instanceof Error && err.message.includes('Overloaded')) {
285
- error = new AIServiecOverloadedError('AI service overloaded', { cause: err } as any); // TODO(dmaretskyi): Schema errors cant have cause
286
- } else {
287
- error = new Error('AI service error', { cause: err });
288
- }
289
- } finally {
290
- this._stream = undefined;
291
- this.done.emit();
292
- }
293
-
294
- if (error) {
295
- throw error;
296
- }
297
-
298
- return this._pending;
299
- }
300
-
301
- async runStructured<S extends Schema.Schema.AnyNoContext>(
302
- schema: S,
303
- options: SessionRunOptions,
304
- ): Promise<Schema.Schema.Type<S>> {
305
- const parser = structuredOutputParser(schema);
306
- const result = await this.run({
307
- ...options,
308
- executableTools: [...(options.executableTools ?? []), parser.tool],
309
- });
310
- return parser.getResult(result);
311
- }
312
-
313
- private async _formatUserPrompt(
314
- artifactDiffResolver: ArtifactDiffResolver | undefined,
315
- prompt: string,
316
- history: Message[],
317
- ) {
318
- const prelude: MessageContentBlock[] = [];
319
-
320
- if (artifactDiffResolver) {
321
- const versions = gatherObjectVersions(history);
322
-
323
- const artifactDiff = await artifactDiffResolver(
324
- [...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),
325
- );
326
-
327
- log.info('vision', {
328
- artifactDiff,
329
- versions,
330
- });
331
-
332
- for (const [id, { version }] of [...artifactDiff.entries()]) {
333
- if (ObjectVersion.equals(version, versions.get(id)!)) {
334
- artifactDiff.delete(id);
335
- continue;
336
- }
337
-
338
- prelude.push(VersionPin.createBlock(VersionPin.make({ objectId: id, version })));
339
- }
340
- if (artifactDiff.size > 0) {
341
- prelude.push(createArtifactUpdateBlock(artifactDiff));
342
- }
343
- }
344
-
345
- return Obj.make(Message, {
346
- role: 'user',
347
- content: [...prelude, { type: 'text', text: prompt }],
348
- });
349
- }
350
-
351
- private _createQueryArtifactsTool(artifacts: ArtifactDefinition[]): ExecutableTool {
352
- return createTool('system', {
353
- name: 'query_artifact_definitions',
354
- description: 'Query the available artifact definitions',
355
- schema: Schema.Struct({}),
356
- execute: async () => {
357
- return ToolResult.Success({
358
- artifactDefinitions: artifacts.map((artifact) => ({
359
- id: artifact.id,
360
- name: artifact.name,
361
- description: artifact.description,
362
- })),
363
- });
364
- },
365
- });
366
- }
367
-
368
- private _createRequireTool(
369
- artifacts: ArtifactDefinition[],
370
- onRequire: (artifactDefinitionIds: readonly string[]) => void,
371
- ): ExecutableTool {
372
- return createTool('system', {
373
- name: 'require_artifact_definitions',
374
- description:
375
- 'Require the use of specific artifact definitions. This will allow the model to interact with artifact definitions and use their tools.',
376
- schema: Schema.Struct({
377
- artifactDefinitionIds: Schema.Array(Schema.String).annotations({
378
- description: 'The ids of the artifact definitions to require',
379
- examples: [['artifact:dxos.org/example/Test']],
380
- }),
381
- }),
382
- execute: async ({ artifactDefinitionIds }) => {
383
- const missingArtifactDefinitionIds = artifactDefinitionIds.filter(
384
- (artifactId) => !artifacts.some((artifact) => artifact.id === artifactId),
385
- );
386
- if (missingArtifactDefinitionIds.length > 0) {
387
- return ToolResult.Error(
388
- `One or more artifact definition ids are invalid: ${missingArtifactDefinitionIds.join(', ')}`,
389
- );
390
- }
391
-
392
- onRequire(artifactDefinitionIds);
393
-
394
- return ToolResult.Success({});
395
- },
396
- });
397
- }
398
-
399
- private _createPlanningTool(options: SessionRunOptions): ExecutableTool {
400
- return createTool('system', {
401
- name: 'create_plan',
402
- description:
403
- '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.',
404
- schema: Schema.Struct({
405
- goal: Schema.String.annotations({ description: 'The goal that the plan will achieve.' }),
406
- steps: Schema.Array(
407
- Schema.Struct({
408
- action: Schema.String.annotations({
409
- description: 'Complete, detailed action to perform.',
410
- }),
411
- input: Schema.String.annotations({
412
- description: 'The required input data for this step. First step must not require any data.',
413
- }),
414
- output: Schema.String.annotations({
415
- description: 'The output data from this step. This is passed to the next step as input.',
416
- }),
417
- requiredArtifactIds: Schema.Array(Schema.String).annotations({
418
- description: 'The ids of the artifacts required to perform this step.',
419
- examples: [['artifact:dxos.org/example/Test']],
420
- }),
421
- }),
422
- ).annotations({ description: 'Steps' }),
423
- }),
424
- execute: async ({ goal, steps }) => {
425
- const missingArtifactIds = steps
426
- .flatMap((step) => step.requiredArtifactIds)
427
- .filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
428
- if (missingArtifactIds.length > 0) {
429
- return ToolResult.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(', ')}`);
430
- }
431
-
432
- const stepResults: any[] = [];
433
- for (const step of steps) {
434
- log('executing step', { action: step.action });
435
- const session = new AISession({ operationModel: 'importing' });
436
- session.message.on((ev) => this.message.emit(ev));
437
- session.block.on((ev) => this.block.emit(ev));
438
- session.update.on((ev) => this.update.emit(ev));
439
- session.streamEvent.on((ev) => this.streamEvent.emit(ev));
440
- session.userMessage.on((ev) => this.userMessage.emit(ev));
441
-
442
- const messages = await session.run({
443
- artifacts: options.artifacts,
444
- tools: options.tools,
445
- history: options.history,
446
- extensions: options.extensions,
447
- requiredArtifactIds: step.requiredArtifactIds.slice(),
448
- prompt: `
449
- You are an agent that executes the subtask in a plan.
450
-
451
- While you know the plan's goal only focus on your subtask
452
- Use the data from the previous step to complete your task.
453
- Return all of the data from "output" in your last message.
454
-
455
- Current step (that you need to complete):
456
- ${JSON.stringify(
457
- {
458
- goal,
459
- input: step.input,
460
- output: step.output,
461
- yourTask: step.action,
462
- },
463
- null,
464
- 2,
465
- )}
466
-
467
- Previous step results:
468
- ${JSON.stringify(stepResults.at(-1))}.
469
- `,
470
-
471
- generationOptions: options.generationOptions,
472
- client: options.client,
473
- toolResolver: options.toolResolver,
474
- artifactDiffResolver: options.artifactDiffResolver,
475
- });
476
- const result = messages.at(-1);
477
- stepResults.push(result);
478
- }
479
-
480
- return ToolResult.Success({ stepResults });
481
- },
482
- });
483
- }
484
-
485
- private _onToolStatusReport(message: Message, status: AgentStatus): void {
486
- this.toolStatusReport.emit({ message, status });
487
- }
488
-
489
- abort(): void {
490
- this._stream?.abort();
491
- }
492
- }
493
-
494
- // TODO(burdon): Use handlebars template with effect-schema input.
495
- const createBaseInstructions = ({
496
- availableArtifacts,
497
- operationModel,
498
- }: {
499
- availableArtifacts: string[];
500
- operationModel: OperationModel;
501
- }) => `
502
- You are a friendly, advanced AI assistant capable of creating and managing artifacts from available data and tools.
503
- Your task is to process user commands and questions and decide how best to respond.
504
- In some cases, you will need to create or reference data objects called artifacts.
505
-
506
- Follow these guidelines carefully:
507
-
508
- Decision-making:
509
-
510
- - Analyze the structure and type of the content in the user's message.
511
-
512
-
513
- ${
514
- operationModel === 'planning'
515
- ? `
516
- - Can you complete the task using the available artifacts?
517
- - If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
518
- - Identify which artifacts are relevant to the user's request.
519
- - 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.
520
- `
521
- : ''
522
- }
523
- ${
524
- operationModel === 'importing'
525
- ? `
526
- - Can you complete the task using the available artifacts?
527
- - If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
528
- - Identify which artifacts are relevant to the user's request.
529
- - Are the required artifacts already available?
530
- - If not, select which artifact(s) will be the most relevant and require them using the require_artifacts tool.
531
- - The require'd artifact tools will be available for use after require.
532
- `
533
- : ''
534
- }
535
- ${
536
- operationModel === 'configured'
537
- ? `
538
- - Select the most relevant artifact(s) to complete the task.
539
- - Call the appropriate tool to use the artifact(s).
540
- `
541
- : ''
542
- }
543
-
544
- ${availableArtifacts.length > 0 ? `Artifacts already in context: ${availableArtifacts.join('\n')}` : ''}
545
- `;
546
-
547
- export class AIServiecOverloadedError extends Schema.TaggedError<AIServiecOverloadedError>()(
548
- 'AIServiecOverloadedError',
549
- {},
550
- ) {}
551
-
552
- const gatherObjectVersions = (messages: Message[]): Map<ObjectId, ObjectVersion> => {
553
- const artifactIds = new Map<ObjectId, ObjectVersion>();
554
- for (const message of messages) {
555
- for (const block of message.content) {
556
- if (block.type === 'json' && block.disposition === VersionPin.DISPOSITION) {
557
- const pin = VersionPin.pipe(Schema.decodeOption)(JSON.parse(block.json)).pipe(Option.getOrUndefined);
558
- if (!pin) {
559
- continue;
560
- }
561
- artifactIds.set(pin.objectId, pin.version);
562
- }
563
- }
564
- }
565
-
566
- return artifactIds;
567
- };
568
-
569
- const createArtifactUpdateBlock = (
570
- artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,
571
- ): MessageContentBlock => {
572
- return {
573
- type: 'text',
574
- disposition: 'artifact-update',
575
- text: `
576
- The following artifacts have been updated since the last message:
577
- ${[...artifactDiff.entries()]
578
- .map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `\n${diff}` : ''}</changed-artifact>`)
579
- .join('\n')}
580
- `,
581
- };
582
- };
@@ -1,26 +0,0 @@
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
- });