@dxos/assistant 0.8.4-main.ae835ea → 0.8.4-main.bc2380dfbc

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