@dxos/assistant 0.8.4-main.84f28bd → 0.8.4-main.ae835ea

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 (179) hide show
  1. package/dist/lib/browser/chunk-4VIJTKPM.mjs +354 -0
  2. package/dist/lib/browser/chunk-4VIJTKPM.mjs.map +7 -0
  3. package/dist/lib/browser/chunk-UB26N5UF.mjs +89 -0
  4. package/dist/lib/browser/chunk-UB26N5UF.mjs.map +7 -0
  5. package/dist/lib/browser/extraction/index.mjs +272 -0
  6. package/dist/lib/browser/extraction/index.mjs.map +7 -0
  7. package/dist/lib/browser/index.mjs +754 -1873
  8. package/dist/lib/browser/index.mjs.map +4 -4
  9. package/dist/lib/browser/meta.json +1 -1
  10. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs +13 -0
  11. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs.map +7 -0
  12. package/dist/lib/node-esm/chunk-AUUC7II4.mjs +356 -0
  13. package/dist/lib/node-esm/chunk-AUUC7II4.mjs.map +7 -0
  14. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs +91 -0
  15. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs.map +7 -0
  16. package/dist/lib/node-esm/extraction/index.mjs +273 -0
  17. package/dist/lib/node-esm/extraction/index.mjs.map +7 -0
  18. package/dist/lib/node-esm/index.mjs +754 -1874
  19. package/dist/lib/node-esm/index.mjs.map +4 -4
  20. package/dist/lib/node-esm/meta.json +1 -1
  21. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs +14 -0
  22. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs.map +7 -0
  23. package/dist/types/src/conversation/context.d.ts +103 -0
  24. package/dist/types/src/conversation/context.d.ts.map +1 -0
  25. package/dist/types/src/conversation/conversation.d.ts +29 -32
  26. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  27. package/dist/types/src/conversation/index.d.ts +1 -0
  28. package/dist/types/src/conversation/index.d.ts.map +1 -1
  29. package/dist/types/src/diff.d.ts +15 -0
  30. package/dist/types/src/diff.d.ts.map +1 -0
  31. package/dist/types/src/diff.test.d.ts +2 -0
  32. package/dist/types/src/diff.test.d.ts.map +1 -0
  33. package/dist/types/src/errors.d.ts +75 -0
  34. package/dist/types/src/errors.d.ts.map +1 -0
  35. package/dist/types/src/execution-graph.d.ts +82 -0
  36. package/dist/types/src/execution-graph.d.ts.map +1 -0
  37. package/dist/types/src/execution-graph.test.d.ts +2 -0
  38. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  39. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +1 -1
  40. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  41. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +210 -73
  42. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  43. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts +1 -1
  44. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  45. package/dist/types/src/extraction/extraction.d.ts +264 -166
  46. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  47. package/dist/types/src/extraction/quotes.d.ts +1 -1
  48. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  49. package/dist/types/src/functions/index.d.ts +2 -0
  50. package/dist/types/src/functions/index.d.ts.map +1 -0
  51. package/dist/types/src/functions/services.d.ts +19 -0
  52. package/dist/types/src/functions/services.d.ts.map +1 -0
  53. package/dist/types/src/index.d.ts +5 -5
  54. package/dist/types/src/index.d.ts.map +1 -1
  55. package/dist/types/src/session/artifact-diff.d.ts +27 -0
  56. package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
  57. package/dist/types/src/session/error-handling.d.ts +4 -0
  58. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  59. package/dist/types/src/session/format.d.ts +186 -0
  60. package/dist/types/src/session/format.d.ts.map +1 -0
  61. package/dist/types/src/session/format.test.d.ts +2 -0
  62. package/dist/types/src/session/format.test.d.ts.map +1 -0
  63. package/dist/types/src/session/index.d.ts +3 -0
  64. package/dist/types/src/session/index.d.ts.map +1 -1
  65. package/dist/types/src/session/observer.d.ts +22 -0
  66. package/dist/types/src/session/observer.d.ts.map +1 -0
  67. package/dist/types/src/session/session.d.ts +36 -268
  68. package/dist/types/src/session/session.d.ts.map +1 -1
  69. package/dist/types/src/session/toolkit.d.ts +15 -0
  70. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  71. package/dist/types/src/session/version-pin.d.ts +5 -5
  72. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  73. package/dist/types/src/templates/index.d.ts +2 -0
  74. package/dist/types/src/templates/index.d.ts.map +1 -0
  75. package/dist/types/src/templates/system.d.ts +18 -0
  76. package/dist/types/src/templates/system.d.ts.map +1 -0
  77. package/dist/types/src/types/artifact.d.ts +16 -0
  78. package/dist/types/src/types/artifact.d.ts.map +1 -0
  79. package/dist/types/src/types/index.d.ts +2 -0
  80. package/dist/types/src/types/index.d.ts.map +1 -0
  81. package/dist/types/tsconfig.tsbuildinfo +1 -1
  82. package/package.json +46 -26
  83. package/src/conversation/context.ts +186 -0
  84. package/src/conversation/conversation.ts +101 -76
  85. package/src/conversation/index.ts +1 -0
  86. package/src/diff.test.ts +43 -0
  87. package/src/diff.ts +84 -0
  88. package/src/errors.ts +15 -0
  89. package/src/execution-graph.test.ts +738 -0
  90. package/src/execution-graph.ts +500 -0
  91. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +13 -24
  92. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +28 -22
  93. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +9 -9
  94. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +18 -8
  95. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +4 -3
  96. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +3 -1
  97. package/src/extraction/extraction.ts +2 -2
  98. package/src/extraction/quotes.test.ts +3 -3
  99. package/src/extraction/quotes.ts +4 -4
  100. package/src/functions/index.ts +5 -0
  101. package/src/functions/services.ts +158 -0
  102. package/src/index.ts +5 -5
  103. package/src/session/artifact-diff.ts +41 -0
  104. package/src/session/error-handling.ts +41 -0
  105. package/src/session/format.test.ts +60 -0
  106. package/src/session/format.ts +142 -0
  107. package/src/session/index.ts +3 -0
  108. package/src/session/observer.ts +59 -0
  109. package/src/session/session.conversations.json +1 -0
  110. package/src/session/session.test.ts +88 -214
  111. package/src/session/session.ts +170 -539
  112. package/src/session/toolkit.ts +48 -0
  113. package/src/session/version-pin.ts +10 -10
  114. package/src/summarization/summarization.test.ts +87 -106
  115. package/src/templates/format.tpl +60 -0
  116. package/src/templates/index.ts +5 -0
  117. package/src/templates/system.tpl +48 -0
  118. package/src/templates/system.ts +41 -0
  119. package/src/types/artifact.ts +52 -0
  120. package/src/types/index.ts +5 -0
  121. package/src/typings.d.ts +5 -0
  122. package/dist/types/bin/chat.d.ts +0 -2
  123. package/dist/types/bin/chat.d.ts.map +0 -1
  124. package/dist/types/src/blueprint/blueprint.d.ts +0 -41
  125. package/dist/types/src/blueprint/blueprint.d.ts.map +0 -1
  126. package/dist/types/src/blueprint/index.d.ts +0 -3
  127. package/dist/types/src/blueprint/index.d.ts.map +0 -1
  128. package/dist/types/src/blueprint/registry.d.ts +0 -7
  129. package/dist/types/src/blueprint/registry.d.ts.map +0 -1
  130. package/dist/types/src/context/binder.d.ts +0 -34
  131. package/dist/types/src/context/binder.d.ts.map +0 -1
  132. package/dist/types/src/context/binding.d.ts +0 -38
  133. package/dist/types/src/context/binding.d.ts.map +0 -1
  134. package/dist/types/src/context/index.d.ts +0 -3
  135. package/dist/types/src/context/index.d.ts.map +0 -1
  136. package/dist/types/src/research/exa.d.ts +0 -7
  137. package/dist/types/src/research/exa.d.ts.map +0 -1
  138. package/dist/types/src/research/graph.d.ts +0 -41
  139. package/dist/types/src/research/graph.d.ts.map +0 -1
  140. package/dist/types/src/research/graph.test.d.ts +0 -2
  141. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  142. package/dist/types/src/research/index.d.ts +0 -4
  143. package/dist/types/src/research/index.d.ts.map +0 -1
  144. package/dist/types/src/research/research.d.ts +0 -10
  145. package/dist/types/src/research/research.d.ts.map +0 -1
  146. package/dist/types/src/research/research.test.d.ts +0 -2
  147. package/dist/types/src/research/research.test.d.ts.map +0 -1
  148. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  149. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  150. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  151. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  152. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  153. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  154. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  155. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  156. package/dist/types/src/testing/index.d.ts +0 -3
  157. package/dist/types/src/testing/index.d.ts.map +0 -1
  158. package/dist/types/src/types.d.ts +0 -3
  159. package/dist/types/src/types.d.ts.map +0 -1
  160. package/src/blueprint/blueprint.ts +0 -75
  161. package/src/blueprint/index.ts +0 -6
  162. package/src/blueprint/registry.ts +0 -15
  163. package/src/context/binder.ts +0 -101
  164. package/src/context/binding.ts +0 -31
  165. package/src/context/index.ts +0 -6
  166. package/src/research/exa.ts +0 -100
  167. package/src/research/graph.test.ts +0 -15
  168. package/src/research/graph.ts +0 -337
  169. package/src/research/index.ts +0 -7
  170. package/src/research/instructions-research.tpl +0 -97
  171. package/src/research/research.test.ts +0 -190
  172. package/src/research/research.ts +0 -90
  173. package/src/session/version-pin.test.ts +0 -26
  174. package/src/testing/exa-search-1748337321991.ts +0 -131
  175. package/src/testing/exa-search-1748337331526.ts +0 -144
  176. package/src/testing/exa-search-1748337344119.ts +0 -133
  177. package/src/testing/index.ts +0 -11
  178. package/src/typedefs.d.ts +0 -8
  179. package/src/types.ts +0 -8
@@ -2,35 +2,57 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Array, Option, pipe, Schema } from 'effect';
5
+ import type * as AiError from '@effect/ai/AiError';
6
+ import * as LanguageModel from '@effect/ai/LanguageModel';
7
+ import type * as Tool from '@effect/ai/Tool';
8
+ import type * as Toolkit from '@effect/ai/Toolkit';
9
+ import * as Chunk from 'effect/Chunk';
10
+ import * as Effect from 'effect/Effect';
11
+ import type * as Schema from 'effect/Schema';
12
+ import * as Stream from 'effect/Stream';
6
13
 
7
14
  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,
15
+ AiParser,
16
+ AiPreprocessor,
17
+ type AiToolNotFoundError,
18
+ type PromptPreprocessingError,
19
+ type ToolExecutionService,
20
+ type ToolResolverService,
21
+ callTool,
22
+ getToolCalls,
24
23
  } from '@dxos/ai';
25
- import { type ArtifactDefinition } from '@dxos/artifact';
26
- import { Event, synchronized } from '@dxos/async';
24
+ import { type Blueprint } from '@dxos/blueprints';
25
+ import { todo } from '@dxos/debug';
27
26
  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';
27
+ import { TracingService } from '@dxos/functions';
31
28
  import { log } from '@dxos/log';
29
+ import { DataType } from '@dxos/schema';
32
30
 
33
- import { VersionPin } from './version-pin';
31
+ import { type AiAssistantError } from '../errors';
32
+
33
+ import { formatSystemPrompt, formatUserPrompt } from './format';
34
+ import { GenerationObserver } from './observer';
35
+
36
+ export type AiSessionRunError = AiError.AiError | PromptPreprocessingError | AiToolNotFoundError | AiAssistantError;
37
+
38
+ export type AiSessionRunRequirements =
39
+ | LanguageModel.LanguageModel
40
+ | ToolExecutionService
41
+ | ToolResolverService
42
+ | TracingService;
43
+
44
+ export type AiSessionRunParams<Tools extends Record<string, Tool.Any>> = {
45
+ prompt: string;
46
+ // TODO(wittjosiah): Rename to systemPrompt.
47
+ system?: string;
48
+ history?: DataType.Message[];
49
+ objects?: Obj.Any[];
50
+ blueprints?: Blueprint.Blueprint[];
51
+ toolkit?: Toolkit.WithHandler<Tools>;
52
+ observer?: GenerationObserver;
53
+ };
54
+
55
+ export type AiSessionOptions = {};
34
56
 
35
57
  /**
36
58
  * Contains message history, tools, current context.
@@ -38,545 +60,154 @@ import { VersionPin } from './version-pin';
38
60
  * It makes requests to the model, its a state machine.
39
61
  * It keeps track of the current goal.
40
62
  * It manages the context window.
41
- * Tracks the success criteria of reaching the goal, exposing metrics (stretch)
63
+ * Tracks the success criteria of reaching the goal, exposing metrics (stretch).
42
64
  * Could be run locally in the app or remotely.
43
65
  * Could be personal or shared.
44
66
  */
67
+ export class AiSession {
68
+ /** Prevents concurrent execution of session. */
69
+ private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));
70
+
71
+ /** Message history from queue. */
72
+ // TODO(burdon): Evolve into supporting a git-like graph of messages.
73
+ private _history: DataType.Message[] = [];
74
+
75
+ /** Pending messages for this session (incl. the current prompt). */
76
+ private _pending: DataType.Message[] = [];
77
+
78
+ constructor(private readonly _options: AiSessionOptions = {}) {}
79
+
80
+ run = <Tools extends Record<string, Tool.Any>>({
81
+ prompt,
82
+ system: systemTemplate,
83
+ history = [],
84
+ objects = [],
85
+ blueprints = [],
86
+ toolkit,
87
+ observer = GenerationObserver.noop(),
88
+ }: AiSessionRunParams<Tools>): Effect.Effect<DataType.Message[], AiSessionRunError, AiSessionRunRequirements> =>
89
+ Effect.gen(this, function* () {
90
+ this._history = [...history];
91
+ this._pending = [];
92
+ const pending = this._pending;
93
+
94
+ const submitMessage = Effect.fnUntraced(function* (message: DataType.Message) {
95
+ pending.push(message);
96
+ yield* observer.onMessage(message);
97
+ yield* TracingService.emitConverationMessage(message);
98
+ return message;
99
+ });
45
100
 
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;
101
+ // Submit the prompt.
102
+ // TODO(burdon): Remove if cancelled?
103
+ const promptMessage = yield* submitMessage(yield* formatUserPrompt({ prompt, history }));
212
104
 
213
- let error: Error | undefined;
105
+ // Generate system and prompt messages.
106
+ const system = yield* formatSystemPrompt({ system: systemTemplate, blueprints, objects });
214
107
 
215
- const requiredArtifactIds = new Set<string>(options.requiredArtifactIds ?? []);
216
- try {
217
- let more = false;
108
+ // Tool call loop.
218
109
  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
110
  log('request', {
111
+ prompt: promptMessage,
112
+ system: { snippet: createSnippet(system), length: system.length },
232
113
  pending: this._pending.length,
233
114
  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
- }),
115
+ objects: objects?.length ?? 0,
249
116
  });
250
117
 
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
- );
118
+ const prompt = yield* AiPreprocessor.preprocessPrompt([...this._history, ...this._pending], { system });
119
+
120
+ // Execute the stream request.
121
+ // logDump('prompt', Prompt.Prompt.pipe(Schema.encodeSync)(prompt));
122
+ const blocks = yield* LanguageModel.streamText({
123
+ prompt,
124
+ toolkit,
125
+ disableToolCallResolution: true,
126
+ }).pipe(
127
+ // TOOD(dmaretskyi): Error mapping.
128
+ AiParser.parseResponse({
129
+ onBegin: () => observer.onBegin(),
130
+ onBlock: (block) => observer.onBlock(block),
131
+ onPart: (part) => observer.onPart(part),
132
+ onEnd: (summary) => observer.onEnd(summary),
133
+ }),
134
+ Stream.runCollect,
135
+ Effect.map(Chunk.toArray),
136
+ );
326
137
 
327
- log.info('vision', {
328
- artifactDiff,
329
- versions,
330
- });
138
+ // Create the response message.
139
+ const response = yield* submitMessage(
140
+ Obj.make(DataType.Message, {
141
+ created: new Date().toISOString(),
142
+ sender: { role: 'assistant' },
143
+ blocks,
144
+ }),
145
+ );
331
146
 
332
- for (const [id, { version }] of [...artifactDiff.entries()]) {
333
- if (ObjectVersion.equals(version, versions.get(id)!)) {
334
- artifactDiff.delete(id);
335
- continue;
147
+ // Parse the response for tool calls.
148
+ const toolCalls = getToolCalls(response);
149
+ if (toolCalls.length === 0) {
150
+ break;
151
+ } else if (!toolkit) {
152
+ throw new Error('No toolkit provided'); // TODO(burdon): Throw user error?
336
153
  }
337
154
 
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(', ')}`,
155
+ // Execute the tool calls.
156
+ // TODO(burdon): Retry errors? Write result when each completes individually?
157
+ const toolResults = yield* Effect.forEach(toolCalls, (toolCall) => {
158
+ return callTool(toolkit, toolCall).pipe(
159
+ Effect.provide(
160
+ TracingService.layerSubframe((context) => ({
161
+ ...context,
162
+ parentMessage: response.id,
163
+ toolCallId: toolCall.toolCallId,
164
+ })),
165
+ ),
389
166
  );
390
- }
391
-
392
- onRequire(artifactDefinitionIds);
393
-
394
- return ToolResult.Success({});
395
- },
396
- });
397
- }
167
+ });
398
168
 
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
- }),
169
+ // Add to queue and continue loop.
170
+ // TODO(wittjosiah): Sometimes tool error results are added to the queue before the tool agent statuses.
171
+ // This results in a broken execution graph.
172
+ yield* submitMessage(
173
+ Obj.make(DataType.Message, {
174
+ created: new Date().toISOString(),
175
+ sender: { role: 'tool' },
176
+ blocks: toolResults,
421
177
  }),
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
- }
178
+ );
179
+ } while (true);
484
180
 
485
- private _onToolStatusReport(message: Message, status: AgentStatus): void {
486
- this.toolStatusReport.emit({ message, status });
487
- }
181
+ log('done', { pending: this._pending.length });
182
+ return this._pending;
183
+ }).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiSession.run'));
488
184
 
489
- abort(): void {
490
- this._stream?.abort();
185
+ /**
186
+ * @deprecated
187
+ */
188
+ // TODO(burdon): Implement or remove.
189
+ async runStructured<S extends Schema.Schema.AnyNoContext>(
190
+ _schema: S,
191
+ _options: AiSessionRunParams<any>,
192
+ ): Promise<Schema.Schema.Type<S>> {
193
+ return todo();
194
+ // const parser = structuredOutputParser(schema);
195
+ // const result = await this.run({
196
+ // ...options,
197
+ // executableTools: [...(options.executableTools ?? []), parser.tool],
198
+ // });
199
+ // return parser.getResult(result);
491
200
  }
492
201
  }
493
202
 
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
- };
203
+ const createSnippet = (text: string, len = 32) =>
204
+ text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');
568
205
 
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
- };
206
+ // TODO(dmaretskyi): Extract as a general util.
207
+ const logDump = (message: string, data: unknown) => {
208
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
209
+ const { writeFileSync } = require('node:fs');
210
+ const path = `/tmp/log-data-${Date.now()}.json`;
211
+ writeFileSync(path, JSON.stringify(data, null, 2));
212
+ log.info(message, { path });
582
213
  };