@dxos/assistant 0.8.4-main.fffef41 → 0.8.4-staging.60fe92afc8

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 (174) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +2 -1
  3. package/dist/lib/{browser → neutral}/extraction/index.mjs +42 -59
  4. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  5. package/dist/lib/neutral/index.mjs +1886 -0
  6. package/dist/lib/neutral/index.mjs.map +7 -0
  7. package/dist/lib/neutral/meta.json +1 -0
  8. package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
  9. package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
  10. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  11. package/dist/types/src/extraction/extraction.d.ts +1649 -317
  12. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  13. package/dist/types/src/extraction/index.d.ts +0 -1
  14. package/dist/types/src/extraction/index.d.ts.map +1 -1
  15. package/dist/types/src/extraction/quotes.d.ts +2 -2
  16. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  17. package/dist/types/src/functions/services.d.ts +14 -16
  18. package/dist/types/src/functions/services.d.ts.map +1 -1
  19. package/dist/types/src/index.d.ts +2 -5
  20. package/dist/types/src/index.d.ts.map +1 -1
  21. package/dist/types/src/request/AiRequest.d.ts +308 -0
  22. package/dist/types/src/request/AiRequest.d.ts.map +1 -0
  23. package/dist/types/src/{session → request}/artifact-diff.d.ts +4 -4
  24. package/dist/types/src/request/artifact-diff.d.ts.map +1 -0
  25. package/dist/types/src/request/format.d.ts +15 -0
  26. package/dist/types/src/request/format.d.ts.map +1 -0
  27. package/dist/types/src/request/index.d.ts +4 -0
  28. package/dist/types/src/request/index.d.ts.map +1 -0
  29. package/dist/types/src/{session → request}/observer.d.ts +4 -3
  30. package/dist/types/src/request/observer.d.ts.map +1 -0
  31. package/dist/types/src/{session → request}/version-pin.d.ts +4 -4
  32. package/dist/types/src/request/version-pin.d.ts.map +1 -0
  33. package/dist/types/src/session/AiContext.d.ts +178 -0
  34. package/dist/types/src/session/AiContext.d.ts.map +1 -0
  35. package/dist/types/src/session/AiContext.test.d.ts +2 -0
  36. package/dist/types/src/session/AiContext.test.d.ts.map +1 -0
  37. package/dist/types/src/session/AiSession.d.ts +79 -0
  38. package/dist/types/src/session/AiSession.d.ts.map +1 -0
  39. package/dist/types/src/session/AiSession.test.d.ts +2 -0
  40. package/dist/types/src/session/AiSession.test.d.ts.map +1 -0
  41. package/dist/types/src/session/SessionLink.d.ts +17 -0
  42. package/dist/types/src/session/SessionLink.d.ts.map +1 -0
  43. package/dist/types/src/session/SessionLoader.d.ts +15 -0
  44. package/dist/types/src/session/SessionLoader.d.ts.map +1 -0
  45. package/dist/types/src/session/SessionLoader.test.d.ts +2 -0
  46. package/dist/types/src/session/SessionLoader.test.d.ts.map +1 -0
  47. package/dist/types/src/session/index.d.ts +4 -5
  48. package/dist/types/src/session/index.d.ts.map +1 -1
  49. package/dist/types/src/session/toolkit.d.ts +10 -9
  50. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  51. package/dist/types/src/templates/system.d.ts +12 -3
  52. package/dist/types/src/templates/system.d.ts.map +1 -1
  53. package/dist/types/src/util/artifact.d.ts +18 -0
  54. package/dist/types/src/util/artifact.d.ts.map +1 -0
  55. package/dist/types/src/{diff.d.ts → util/diff.d.ts} +4 -2
  56. package/dist/types/src/util/diff.d.ts.map +1 -0
  57. package/dist/types/src/{diff.test.d.ts.map → util/diff.test.d.ts.map} +1 -1
  58. package/dist/types/src/util/error-handling.d.ts.map +1 -0
  59. package/dist/types/src/{errors.d.ts → util/errors.d.ts} +24 -28
  60. package/dist/types/src/util/errors.d.ts.map +1 -0
  61. package/dist/types/src/{execution-graph.d.ts → util/execution-graph.d.ts} +2 -2
  62. package/dist/types/src/util/execution-graph.d.ts.map +1 -0
  63. package/dist/types/src/util/execution-graph.test.d.ts.map +1 -0
  64. package/dist/types/src/util/index.d.ts +7 -0
  65. package/dist/types/src/util/index.d.ts.map +1 -0
  66. package/dist/types/src/util/tracing.d.ts +296 -0
  67. package/dist/types/src/util/tracing.d.ts.map +1 -0
  68. package/dist/types/tsconfig.tsbuildinfo +1 -1
  69. package/package.json +36 -44
  70. package/src/extraction/extraction-ner-function/index.ts +0 -1
  71. package/src/extraction/extraction.ts +47 -18
  72. package/src/extraction/index.ts +0 -1
  73. package/src/extraction/quotes.test.ts +2 -2
  74. package/src/extraction/quotes.ts +6 -8
  75. package/src/functions/services.ts +129 -63
  76. package/src/index.ts +2 -5
  77. package/src/request/AiRequest.ts +387 -0
  78. package/src/{session → request}/artifact-diff.ts +4 -4
  79. package/src/{session → request}/format.ts +28 -25
  80. package/src/request/index.ts +8 -0
  81. package/src/{session → request}/observer.ts +4 -1
  82. package/src/{session → request}/version-pin.ts +6 -5
  83. package/src/session/AiContext.test.ts +49 -0
  84. package/src/session/AiContext.ts +420 -0
  85. package/src/session/AiSession.test.ts +111 -0
  86. package/src/session/AiSession.ts +328 -0
  87. package/src/session/SessionLink.ts +23 -0
  88. package/src/session/SessionLoader.test.ts +115 -0
  89. package/src/session/SessionLoader.ts +55 -0
  90. package/src/session/index.ts +4 -5
  91. package/src/session/toolkit.ts +27 -28
  92. package/src/templates/instructions/format.tpl +0 -4
  93. package/src/templates/instructions/system.tpl +50 -2
  94. package/src/templates/system.ts +7 -6
  95. package/src/util/artifact.ts +96 -0
  96. package/src/util/diff.test.ts +74 -0
  97. package/src/{diff.ts → util/diff.ts} +14 -5
  98. package/src/{session → util}/error-handling.ts +3 -2
  99. package/src/util/errors.ts +15 -0
  100. package/src/{execution-graph.test.ts → util/execution-graph.test.ts} +4 -4
  101. package/src/{execution-graph.ts → util/execution-graph.ts} +30 -19
  102. package/src/util/index.ts +10 -0
  103. package/src/util/tracing.ts +60 -0
  104. package/dist/lib/browser/extraction/index.mjs.map +0 -7
  105. package/dist/lib/browser/index.mjs +0 -1290
  106. package/dist/lib/browser/index.mjs.map +0 -7
  107. package/dist/lib/browser/meta.json +0 -1
  108. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  109. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  110. package/dist/lib/node-esm/extraction/index.mjs +0 -226
  111. package/dist/lib/node-esm/extraction/index.mjs.map +0 -7
  112. package/dist/lib/node-esm/index.mjs +0 -1291
  113. package/dist/lib/node-esm/index.mjs.map +0 -7
  114. package/dist/lib/node-esm/meta.json +0 -1
  115. package/dist/types/src/conversation/context.d.ts +0 -103
  116. package/dist/types/src/conversation/context.d.ts.map +0 -1
  117. package/dist/types/src/conversation/conversation.d.ts +0 -41
  118. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  119. package/dist/types/src/conversation/index.d.ts +0 -3
  120. package/dist/types/src/conversation/index.d.ts.map +0 -1
  121. package/dist/types/src/diff.d.ts.map +0 -1
  122. package/dist/types/src/errors.d.ts.map +0 -1
  123. package/dist/types/src/execution-graph.d.ts.map +0 -1
  124. package/dist/types/src/execution-graph.test.d.ts.map +0 -1
  125. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
  126. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
  127. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
  128. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
  129. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
  130. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
  131. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -345
  132. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
  133. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
  134. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
  135. package/dist/types/src/session/GenericToolkit.d.ts +0 -84
  136. package/dist/types/src/session/GenericToolkit.d.ts.map +0 -1
  137. package/dist/types/src/session/artifact-diff.d.ts.map +0 -1
  138. package/dist/types/src/session/error-handling.d.ts.map +0 -1
  139. package/dist/types/src/session/format.d.ts +0 -12
  140. package/dist/types/src/session/format.d.ts.map +0 -1
  141. package/dist/types/src/session/format.test.d.ts +0 -2
  142. package/dist/types/src/session/format.test.d.ts.map +0 -1
  143. package/dist/types/src/session/observer.d.ts.map +0 -1
  144. package/dist/types/src/session/session.d.ts +0 -51
  145. package/dist/types/src/session/session.d.ts.map +0 -1
  146. package/dist/types/src/session/session.test.d.ts +0 -2
  147. package/dist/types/src/session/session.test.d.ts.map +0 -1
  148. package/dist/types/src/session/version-pin.d.ts.map +0 -1
  149. package/dist/types/src/types/artifact.d.ts +0 -20
  150. package/dist/types/src/types/artifact.d.ts.map +0 -1
  151. package/dist/types/src/types/index.d.ts +0 -2
  152. package/dist/types/src/types/index.d.ts.map +0 -1
  153. package/src/conversation/context.ts +0 -186
  154. package/src/conversation/conversation.ts +0 -128
  155. package/src/conversation/index.ts +0 -6
  156. package/src/diff.test.ts +0 -43
  157. package/src/errors.ts +0 -15
  158. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -84
  159. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -62
  160. package/src/extraction/extraction-llm-function/index.ts +0 -5
  161. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -116
  162. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -56
  163. package/src/session/GenericToolkit.ts +0 -130
  164. package/src/session/format.test.ts +0 -61
  165. package/src/session/session.conversations.json +0 -1
  166. package/src/session/session.test.ts +0 -149
  167. package/src/session/session.ts +0 -213
  168. package/src/types/artifact.ts +0 -71
  169. package/src/types/index.ts +0 -5
  170. /package/dist/lib/{browser → neutral}/chunk-J5LGTIGS.mjs +0 -0
  171. /package/dist/lib/{browser → neutral}/chunk-J5LGTIGS.mjs.map +0 -0
  172. /package/dist/types/src/{diff.test.d.ts → util/diff.test.d.ts} +0 -0
  173. /package/dist/types/src/{session → util}/error-handling.d.ts +0 -0
  174. /package/dist/types/src/{execution-graph.test.d.ts → util/execution-graph.test.d.ts} +0 -0
@@ -0,0 +1,387 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import type * as AiError from '@effect/ai/AiError';
8
+ import * as LanguageModel from '@effect/ai/LanguageModel';
9
+ import type * as Toolkit from '@effect/ai/Toolkit';
10
+ import * as Array from 'effect/Array';
11
+ import * as Chunk from 'effect/Chunk';
12
+ import * as Effect from 'effect/Effect';
13
+ import { pipe } from 'effect/Function';
14
+ import * as Option from 'effect/Option';
15
+ import * as Stream from 'effect/Stream';
16
+
17
+ import {
18
+ AiParser,
19
+ AiPreprocessor,
20
+ AiSummarizer,
21
+ type AiToolNotFoundError,
22
+ callTool,
23
+ type OpaqueToolkit,
24
+ type PromptPreprocessingError,
25
+ type ToolExecutionService,
26
+ type ToolResolverService,
27
+ withoutToolCallParising,
28
+ } from '@dxos/ai';
29
+ import { type Blueprint, Trace, Operation } from '@dxos/compute';
30
+ import { Database, Obj, Registry } from '@dxos/echo';
31
+ import { log } from '@dxos/log';
32
+ import { ContentBlock, Message } from '@dxos/types';
33
+
34
+ import { getOperationFromTool } from '../functions/services';
35
+ import { type AiAssistantError, CompleteBlock, PartialBlock } from '../util';
36
+ import { formatSystemPrompt, formatUserPrompt } from './format';
37
+ import { GenerationObserver } from './observer';
38
+
39
+ export type RunError = AiError.AiError | PromptPreprocessingError | AiToolNotFoundError | AiAssistantError;
40
+
41
+ export type RunRequirements =
42
+ | LanguageModel.LanguageModel
43
+ | ToolExecutionService
44
+ | ToolResolverService
45
+ | Database.Service
46
+ | Operation.Service
47
+ | Registry.Service
48
+ | Trace.TraceService;
49
+
50
+ export type Options = {
51
+ /**
52
+ * Summarize before executing the prompt if the existing history exceeds this threshold.
53
+ */
54
+ summarizationThreshold?: number;
55
+
56
+ // TODO(dmaretskyi): Plan to phase out in favor of TracingService and the return type being a stream.
57
+ observer?: GenerationObserver;
58
+ /**
59
+ * Callback for when a message is received from the user, model, or tool.
60
+ * This is useful for streaming the output to a queue.
61
+ */
62
+ onOutput?: (message: Message.Message) => Effect.Effect<void, never, never>;
63
+ };
64
+
65
+ export type RunProps<R = never> = {
66
+ prompt: string | ContentBlock.Any[];
67
+ // TODO(wittjosiah): Rename to systemPrompt.
68
+ system?: string;
69
+ history?: Message.Message[];
70
+ objects?: Obj.Unknown[];
71
+ blueprints?: readonly Blueprint.Blueprint[];
72
+ toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
73
+ };
74
+
75
+ export type BeginProps = {
76
+ prompt: string | ContentBlock.Any[];
77
+ system?: string;
78
+ history?: Message.Message[];
79
+ objects?: Obj.Unknown[];
80
+ blueprints?: readonly Blueprint.Blueprint[];
81
+ };
82
+
83
+ export type TurnProps<R = never> = {
84
+ system: string;
85
+ toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
86
+ };
87
+
88
+ export type TurnResult = {
89
+ messages: Message.Message[];
90
+ done: boolean;
91
+ };
92
+
93
+ /**
94
+ * Contains message history, tools, current context.
95
+ * Current context means the state of the app, time of day, and other contextual information.
96
+ * It makes requests to the model, its a state machine.
97
+ * It keeps track of the current goal.
98
+ * It manages the context window.
99
+ * Tracks the success criteria of reaching the goal, exposing metrics (stretch).
100
+ * Could be run locally in the app or remotely.
101
+ * Could be personal or shared.
102
+ */
103
+ export class Request {
104
+ /** Prevents concurrent execution of session. */
105
+ private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));
106
+
107
+ private readonly _observer: GenerationObserver;
108
+ private readonly _onOutput: (message: Message.Message) => Effect.Effect<void, never, never>;
109
+
110
+ /** Message history from queue. */
111
+ // TODO(burdon): Evolve into supporting a git-like graph of messages.
112
+ private _history: Message.Message[] = [];
113
+
114
+ /** Pending messages for this session (incl. the current prompt). */
115
+ private _pending: Message.Message[] = [];
116
+
117
+ private _started = 0;
118
+ private _ended = 0;
119
+ private _toolCalls = 0;
120
+
121
+ constructor(private readonly _options: Options = {}) {
122
+ this._observer = _options.observer ?? GenerationObserver.noop();
123
+ this._onOutput = _options.onOutput ?? (() => Effect.void);
124
+ }
125
+
126
+ get duration(): number {
127
+ return this._ended - this._started;
128
+ }
129
+
130
+ get toolCalls(): number {
131
+ return this._toolCalls;
132
+ }
133
+
134
+ get pending(): readonly Message.Message[] {
135
+ return this._pending;
136
+ }
137
+
138
+ private _submitMessage = (message: Message.Message): Effect.Effect<Message.Message, never, Trace.TraceService> =>
139
+ Effect.gen(this, function* () {
140
+ this._pending.push(message);
141
+ yield* this._observer.onMessage(message);
142
+ for (const block of message.blocks) {
143
+ log('write complete block', {
144
+ messageId: message.id,
145
+ role: message.sender.role!,
146
+ block: JSON.stringify(block),
147
+ });
148
+ yield* Trace.write(CompleteBlock, {
149
+ messageId: message.id,
150
+ role: message.sender.role!,
151
+ block,
152
+ });
153
+ }
154
+ yield* this._onOutput(message);
155
+ return message;
156
+ });
157
+
158
+ getToolCalls = () =>
159
+ pipe(
160
+ [...this._history, ...this._pending],
161
+ Array.reverse,
162
+ Array.takeWhile((_) => _.sender.role === 'assistant'),
163
+ Array.flatMap((_) => _.blocks.filter(ContentBlock.is('toolCall')).map((block) => ({ block, message: _ }))),
164
+ Array.filter((_) => !_.block.providerExecuted),
165
+ Array.reverse,
166
+ );
167
+
168
+ /**
169
+ * Initialize a session: set up history, perform summarization if needed, and submit the user prompt.
170
+ * Must be called before `runTurn()`.
171
+ */
172
+ begin = ({
173
+ prompt,
174
+ system,
175
+ history = [],
176
+ blueprints = [],
177
+ objects = [],
178
+ }: BeginProps): Effect.Effect<void, RunError, RunRequirements> =>
179
+ Effect.gen(this, function* () {
180
+ this._started = Date.now();
181
+ this._history = [...history];
182
+ this._pending = [];
183
+
184
+ const systemPrompt = yield* formatSystemPrompt({ system, blueprints, objects }).pipe(Effect.orDie);
185
+
186
+ if (this._options.summarizationThreshold !== undefined) {
187
+ const tokenCount = yield* AiPreprocessor.estimateTokens(
188
+ yield* AiPreprocessor.preprocessPrompt([...this._history], {
189
+ system: systemPrompt,
190
+ }),
191
+ );
192
+ if (tokenCount > this._options.summarizationThreshold) {
193
+ const summary = yield* AiSummarizer.summarize([...this._history]);
194
+ yield* this._submitMessage(summary);
195
+ }
196
+ }
197
+
198
+ yield* this._submitMessage(yield* formatUserPrompt({ prompt, history }));
199
+ }).pipe(Effect.withSpan('AiRequest.begin'));
200
+
201
+ /**
202
+ * Execute a single turn: one LLM generation followed by tool execution.
203
+ * The toolkit and system prompt can be updated between turns to reflect context changes (e.g. dynamically enabled blueprints).
204
+ */
205
+ runAgentTurn = <const R = never>({
206
+ system,
207
+ toolkit: opaqueToolkit,
208
+ }: TurnProps<R>): Effect.Effect<TurnResult, RunError, RunRequirements | R> =>
209
+ Effect.gen(this, function* () {
210
+ log('request', {
211
+ system: { snippet: createSnippet(system), length: system.length },
212
+ pending: this._pending.length,
213
+ history: this._history.length,
214
+ });
215
+
216
+ const prompt = yield* AiPreprocessor.preprocessPrompt([...this._history, ...this._pending], {
217
+ system,
218
+ cacheControl: 'ephemeral',
219
+ });
220
+
221
+ const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : undefined;
222
+
223
+ const observer = this._observer;
224
+ let currentMessageId: Obj.ID | null = null;
225
+
226
+ const messages = yield* LanguageModel.streamText({
227
+ prompt,
228
+ toolkit,
229
+ disableToolCallResolution: true,
230
+ }).pipe(
231
+ withoutToolCallParising,
232
+ AiParser.parseResponse({
233
+ emitPartial: true,
234
+ onBegin: () => observer.onBegin(),
235
+ onBlock: (block) => observer.onBlock(block),
236
+ onPart: (part) => observer.onPart(part as any),
237
+ onEnd: (summary) => observer.onEnd(summary),
238
+ }),
239
+ Stream.map((block) => enrichToolCallBlock(block, toolkit)),
240
+ Stream.mapEffect(
241
+ (block) =>
242
+ Effect.gen(this, function* () {
243
+ if (block.pending) {
244
+ currentMessageId ??= Obj.ID.random();
245
+ log('emit ephemeral message', { id: currentMessageId, type: block._tag });
246
+ yield* Trace.write(PartialBlock, {
247
+ messageId: currentMessageId,
248
+ role: 'assistant',
249
+ block,
250
+ });
251
+ return Option.none();
252
+ } else {
253
+ currentMessageId ??= Obj.ID.random();
254
+ const id = currentMessageId;
255
+ currentMessageId = null;
256
+ log('emit complete message', { id, type: block._tag });
257
+ const message = Obj.make(Message.Message, {
258
+ id,
259
+ created: new Date().toISOString(),
260
+ sender: { role: 'assistant' },
261
+ blocks: [block],
262
+ });
263
+ return Option.some(yield* this._submitMessage(message));
264
+ }
265
+ }),
266
+ { concurrency: 1, unordered: false },
267
+ ),
268
+ Stream.filterMap((_) => _),
269
+ Stream.runCollect,
270
+ Effect.map(Chunk.toArray),
271
+ );
272
+ log('messages', { messages });
273
+
274
+ const toolCalls = this.getToolCalls();
275
+
276
+ if (toolCalls.length === 0) {
277
+ this._ended = Date.now();
278
+ return { messages, done: true };
279
+ } else if (!toolkit) {
280
+ throw new Error('No toolkit provided');
281
+ }
282
+
283
+ return { messages, done: false };
284
+ }).pipe(Effect.withSpan('AiRequest.runAgentTurn'));
285
+
286
+ runTools = <const R = never>({
287
+ toolkit: opaqueToolkit,
288
+ }: {
289
+ toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
290
+ }): Effect.Effect<void, RunError, RunRequirements | R> =>
291
+ Effect.gen(this, function* () {
292
+ const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : undefined;
293
+ const toolCalls = this.getToolCalls();
294
+ const toolResults = yield* Effect.forEach(toolCalls, ({ block, message }) => {
295
+ if (!toolkit) {
296
+ throw new Error('No toolkit provided');
297
+ }
298
+ return callTool(toolkit, block);
299
+ });
300
+
301
+ yield* this._submitMessage(
302
+ Obj.make(Message.Message, {
303
+ created: new Date().toISOString(),
304
+ sender: { role: 'tool' },
305
+ blocks: toolResults,
306
+ }),
307
+ );
308
+
309
+ this._toolCalls += toolResults.length;
310
+ }).pipe(Effect.withSpan('AiRequest.runTools'));
311
+
312
+ /**
313
+ * Run a full conversation turn loop. Equivalent to calling `begin()` then `runTurn()` in a loop.
314
+ */
315
+ run = <const R = never>({
316
+ prompt,
317
+ system: systemTemplate,
318
+ history = [],
319
+ objects = [],
320
+ blueprints = [],
321
+ toolkit,
322
+ }: RunProps<R>): Effect.Effect<Message.Message[], RunError, RunRequirements | R> =>
323
+ Effect.gen(this, function* () {
324
+ yield* this.begin({ prompt, system: systemTemplate, history, objects, blueprints });
325
+
326
+ const system = yield* formatSystemPrompt({ system: systemTemplate, blueprints, objects }).pipe(Effect.orDie);
327
+
328
+ do {
329
+ const { done } = yield* this.runAgentTurn({ system, toolkit });
330
+ if (done) {
331
+ break;
332
+ }
333
+ yield* this.runTools({ toolkit });
334
+ } while (true);
335
+
336
+ log('done', { pending: this._pending.length, duration: this.duration, tools: this._toolCalls });
337
+ return this._pending;
338
+ }).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiRequest.run'));
339
+ }
340
+
341
+ /**
342
+ * Annotates `toolCall` blocks with metadata about the backing Operation, when one exists.
343
+ * Tool calls that resolve to a toolkit handler (no Operation) are left unchanged so callers can
344
+ * distinguish operation invocations from inline tool calls.
345
+ */
346
+ const enrichToolCallBlock = (
347
+ block: ContentBlock.Any,
348
+ toolkit: Toolkit.WithHandler<any> | undefined,
349
+ ): ContentBlock.Any => {
350
+ if (block._tag !== 'toolCall' || !toolkit) {
351
+ return block;
352
+ }
353
+ const tool = toolkit.tools[block.name];
354
+ if (!tool) {
355
+ return block;
356
+ }
357
+ // Some tools (provider-defined, raw MCP) don't carry an Effect `Context` for annotations and
358
+ // `getOperationFromTool` throws. Be defensive: treat any failure as "no operation".
359
+ let operationOpt: Option.Option<Operation.Definition.Any>;
360
+ try {
361
+ operationOpt = getOperationFromTool(tool);
362
+ } catch {
363
+ return block;
364
+ }
365
+ if (Option.isNone(operationOpt)) {
366
+ return block;
367
+ }
368
+ const { meta } = operationOpt.value;
369
+ return {
370
+ ...block,
371
+ operationKey: meta.key,
372
+ operationName: meta.name,
373
+ operationIcon: meta.icon,
374
+ } satisfies ContentBlock.ToolCall;
375
+ };
376
+
377
+ const createSnippet = (text: string, len = 32) =>
378
+ text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');
379
+
380
+ // TODO(dmaretskyi): Extract as a general util.
381
+ const logDump = (message: string, data: unknown) => {
382
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
383
+ const { writeFileSync } = require('node:fs');
384
+ const path = `/tmp/log-data-${Date.now()}.json`;
385
+ writeFileSync(path, JSON.stringify(data, null, 2));
386
+ log.info(message, { path });
387
+ };
@@ -4,8 +4,8 @@
4
4
 
5
5
  import * as Context from 'effect/Context';
6
6
 
7
- import { type ObjectId } from '@dxos/echo/internal';
8
- import { type ObjectVersion } from '@dxos/echo-db';
7
+ import { type ObjectVersion } from '@dxos/echo-client';
8
+ import { type EntityId } from '@dxos/keys';
9
9
 
10
10
  /**
11
11
  * Resolves artifact ids to their versions.
@@ -25,12 +25,12 @@ export namespace ArtifactDiffResolver {
25
25
  export type Service = {
26
26
  resolve: (
27
27
  artifacts: {
28
- id: ObjectId;
28
+ id: EntityId;
29
29
  lastVersion: ObjectVersion;
30
30
  }[],
31
31
  ) => Promise<
32
32
  Map<
33
- ObjectId,
33
+ EntityId,
34
34
  {
35
35
  version: ObjectVersion;
36
36
  diff?: string;
@@ -2,23 +2,22 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import * as Array from 'effect/Array';
6
5
  import * as Effect from 'effect/Effect';
7
6
  import * as Function from 'effect/Function';
8
7
  import * as Option from 'effect/Option';
9
8
 
10
- import { Template } from '@dxos/blueprints';
11
- import { Obj } from '@dxos/echo';
12
- import { type ObjectId } from '@dxos/echo/internal';
13
- import { DatabaseService, ObjectVersion } from '@dxos/echo-db';
9
+ import { type FunctionNotFoundError, type Operation, Template } from '@dxos/compute';
10
+ import { type Database, Obj, type Registry } from '@dxos/echo';
11
+ import { ObjectVersion } from '@dxos/echo-client';
12
+ import { type EntityNotFoundError } from '@dxos/echo/Err';
13
+ import { type EntityId } from '@dxos/keys';
14
14
  import { log } from '@dxos/log';
15
15
  import { type ContentBlock, Message } from '@dxos/types';
16
16
  import { trim } from '@dxos/util';
17
17
 
18
- import { AiAssistantError } from '../errors';
19
-
18
+ import { AiAssistantError } from '../util';
19
+ import type * as AiRequest from './AiRequest';
20
20
  import { ArtifactDiffResolver } from './artifact-diff';
21
- import { type AiSessionRunError, type AiSessionRunParams } from './session';
22
21
 
23
22
  /**
24
23
  * Formats the system prompt.
@@ -28,20 +27,24 @@ export const formatSystemPrompt = ({
28
27
  system,
29
28
  blueprints = [],
30
29
  objects = [],
31
- }: Pick<AiSessionRunParams<any>, 'system' | 'blueprints' | 'objects'>) =>
30
+ }: Pick<AiRequest.RunProps, 'system' | 'blueprints' | 'objects'>): Effect.Effect<
31
+ string,
32
+ FunctionNotFoundError | EntityNotFoundError,
33
+ Database.Service | Registry.Service | Operation.Service
34
+ > =>
32
35
  Effect.gen(function* () {
33
36
  const blueprintDefs = yield* Function.pipe(
34
37
  blueprints,
35
38
  Effect.forEach((blueprint) => Effect.succeed(blueprint.instructions)),
36
- Effect.flatMap(Effect.forEach((template) => DatabaseService.loadOption(template.source))),
37
- Effect.map(Array.filter(Option.isSome)),
38
- Effect.map(
39
- Array.map(
40
- (template) => trim`
39
+ Effect.flatMap(
40
+ Effect.forEach((template) =>
41
+ Effect.gen(function* () {
42
+ return trim`
41
43
  <blueprint>
42
- ${Template.process(template.value.content)}
44
+ ${yield* Template.processTemplate(template)}
43
45
  </blueprint>
44
- `,
46
+ `;
47
+ }),
45
48
  ),
46
49
  ),
47
50
  Effect.map((blueprints) =>
@@ -54,7 +57,7 @@ export const formatSystemPrompt = ({
54
57
  Effect.forEach((object) =>
55
58
  Effect.succeed(trim`
56
59
  <object>
57
- <dxn>${Obj.getDXN(object)}</dxn>
60
+ <dxn>${Obj.getURI(object)}</dxn>
58
61
  <typename>${Obj.getTypename(object)}</typename>
59
62
  </object>
60
63
  `),
@@ -66,7 +69,7 @@ export const formatSystemPrompt = ({
66
69
  Effect.succeed([system, blueprintDefs, objectDefs].filter((def): def is string => def !== undefined)),
67
70
  Effect.map((parts) => parts.join('\n\n')),
68
71
  );
69
- });
72
+ }).pipe(Effect.withSpan('formatSystemPrompt'));
70
73
 
71
74
  /**
72
75
  * Formats the user prompt.
@@ -76,7 +79,7 @@ export const formatSystemPrompt = ({
76
79
  export const formatUserPrompt = ({
77
80
  prompt,
78
81
  history = [],
79
- }: Pick<AiSessionRunParams<any>, 'prompt' | 'history'>): Effect.Effect<Message.Message, AiSessionRunError> =>
82
+ }: Pick<AiRequest.RunProps, 'prompt' | 'history'>): Effect.Effect<Message.Message, AiRequest.RunError> =>
80
83
  Effect.gen(function* () {
81
84
  const blocks: ContentBlock.Any[] = [];
82
85
 
@@ -110,12 +113,12 @@ export const formatUserPrompt = ({
110
113
  return Obj.make(Message.Message, {
111
114
  created: new Date().toISOString(),
112
115
  sender: { role: 'user' },
113
- blocks: [...blocks, { _tag: 'text', text: prompt }],
116
+ blocks: typeof prompt === 'string' ? [...blocks, { _tag: 'text', text: prompt }] : [...blocks, ...prompt],
114
117
  });
115
- });
118
+ }).pipe(Effect.withSpan('formatUserPrompt'));
116
119
 
117
- const gatherObjectVersions = (messages: Message.Message[]): Map<ObjectId, ObjectVersion> => {
118
- const artifactIds = new Map<ObjectId, ObjectVersion>();
120
+ const gatherObjectVersions = (messages: Message.Message[]): Map<EntityId, ObjectVersion> => {
121
+ const artifactIds = new Map<EntityId, ObjectVersion>();
119
122
  for (const message of messages) {
120
123
  for (const block of message.blocks) {
121
124
  if (block._tag === 'anchor') {
@@ -128,12 +131,12 @@ const gatherObjectVersions = (messages: Message.Message[]): Map<ObjectId, Object
128
131
  };
129
132
 
130
133
  const createArtifactUpdateBlock = (
131
- artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,
134
+ artifactDiff: Map<EntityId, { version: ObjectVersion; diff?: string }>,
132
135
  ): ContentBlock.Any => {
133
136
  return {
134
137
  _tag: 'text',
135
138
  // TODO(dmaretskyi): Does this need to be a special content-block?
136
- disposition: 'artifact-update',
139
+ disposition: 'synthetic',
137
140
  text: trim`
138
141
  The following artifacts have been updated since the last message:
139
142
  ${[...artifactDiff.entries()]
@@ -0,0 +1,8 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ export * from './format';
6
+ export * from './observer';
7
+
8
+ export * as AiRequest from './AiRequest';
@@ -2,6 +2,7 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ import type * as Tool from '@effect/ai/Tool';
5
6
  import * as Effect from 'effect/Effect';
6
7
  import * as Function from 'effect/Function';
7
8
 
@@ -11,7 +12,9 @@ import { type Message } from '@dxos/types';
11
12
  /**
12
13
  * Live observer of the generation process.
13
14
  */
14
- export interface GenerationObserver extends AiParser.ParseResponseCallbacks {
15
+ export interface GenerationObserver<
16
+ Tools extends Record<string, Tool.Any> = any,
17
+ > extends AiParser.ParseResponseCallbacks<Tools> {
15
18
  /**
16
19
  * Complete messages fired during the session, both from the model and from the user.
17
20
  * This message will contain all message blocks emitted through the `onBlock` callback.
@@ -4,8 +4,9 @@
4
4
 
5
5
  import * as Schema from 'effect/Schema';
6
6
 
7
- import { type AnyEchoObject, ObjectId } from '@dxos/echo/internal';
8
- import { type ObjectVersion, getVersion } from '@dxos/echo-db';
7
+ import { type Obj } from '@dxos/echo';
8
+ import { type ObjectVersion, getVersion } from '@dxos/echo-client';
9
+ import { EntityId } from '@dxos/keys';
9
10
  import { type ContentBlock } from '@dxos/types';
10
11
 
11
12
  // TODO(dmaretskyi): Extract.
@@ -13,7 +14,7 @@ const ObjectVersionSchema = Schema.Unknown as Schema.Schema<ObjectVersion>;
13
14
 
14
15
  const VersionPinSchema = Schema.Struct({
15
16
  // TODO(dmaretskyi): Use Ref when those support encoding.
16
- objectId: ObjectId,
17
+ objectId: EntityId,
17
18
  // TODO(dmaretskyi): Could be opaque.
18
19
  version: ObjectVersionSchema,
19
20
  });
@@ -26,11 +27,11 @@ export interface VersionPin extends Schema.Schema.Type<typeof VersionPinSchema>
26
27
 
27
28
  export const VersionPin: typeof VersionPinSchema & {
28
29
  DISPOSITION: 'version-pin';
29
- fromObject: (object: AnyEchoObject) => VersionPin;
30
+ fromObject: (object: Obj.Unknown) => VersionPin;
30
31
  createBlock: (pin: VersionPin) => ContentBlock.Any;
31
32
  } = class extends VersionPinSchema {
32
33
  static readonly DISPOSITION = 'version-pin';
33
- static fromObject(object: AnyEchoObject): VersionPin {
34
+ static fromObject(object: Obj.Unknown): VersionPin {
34
35
  return VersionPin.make({
35
36
  objectId: object.id,
36
37
  version: getVersion(object),
@@ -0,0 +1,49 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Context from 'effect/Context';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Layer from 'effect/Layer';
8
+ import * as Runtime from 'effect/Runtime';
9
+ import * as Schema from 'effect/Schema';
10
+ import { describe, it } from 'vitest';
11
+
12
+ import { DXN, Feed, Obj, Ref, Type } from '@dxos/echo';
13
+
14
+ import * as AiContext from './AiContext';
15
+
16
+ const createMockFeedRuntime = (): Runtime.Runtime<Feed.FeedService> => {
17
+ const mockFeedService: Context.Tag.Service<Feed.FeedService> = {
18
+ append: async () => {},
19
+ remove: async () => {},
20
+ query: () =>
21
+ ({
22
+ subscribe: () => () => {},
23
+ results: [],
24
+ run: async () => [],
25
+ }) as any,
26
+ sync: async () => {},
27
+ getSyncState: async () => ({ blocksToPull: 0, blocksToPush: 0, totalBlocks: 0 }),
28
+ };
29
+ const layer = Layer.succeed(Feed.FeedService, mockFeedService);
30
+ return Effect.runSync(Effect.runtime<Feed.FeedService>().pipe(Effect.provide(layer)));
31
+ };
32
+
33
+ describe('AiContext.Binder', () => {
34
+ it('should handle bind with Ref', async () => {
35
+ const feed = Feed.make();
36
+ const runtime = createMockFeedRuntime();
37
+ const binder = new AiContext.Binder({ feed, runtime });
38
+
39
+ const TestSchema = Schema.Struct({}).pipe(Type.makeObject(DXN.make('org.dxos.type.example', '0.1.0')));
40
+
41
+ const obj = Obj.make(TestSchema, {});
42
+ const ref = Ref.make(obj);
43
+
44
+ await binder.bind({
45
+ blueprints: [],
46
+ objects: [ref],
47
+ });
48
+ });
49
+ });