@dxos/assistant 0.8.4-main.72ec0f3 → 0.8.4-main.765dc60934

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 (160) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +2 -1
  3. package/dist/lib/{browser → neutral}/extraction/index.mjs +33 -54
  4. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  5. package/dist/lib/neutral/index.mjs +1755 -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 +1065 -313
  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 +13 -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 +104 -0
  22. package/dist/types/src/request/AiRequest.d.ts.map +1 -0
  23. package/dist/types/src/{session → request}/artifact-diff.d.ts +1 -1
  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 +2 -2
  32. package/dist/types/src/request/version-pin.d.ts.map +1 -0
  33. package/dist/types/src/session/AiContext.d.ts +154 -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 +73 -0
  38. package/dist/types/src/session/AiSession.d.ts.map +1 -0
  39. package/dist/types/src/session/index.d.ts +2 -5
  40. package/dist/types/src/session/index.d.ts.map +1 -1
  41. package/dist/types/src/session/toolkit.d.ts +10 -9
  42. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  43. package/dist/types/src/templates/system.d.ts +1 -2
  44. package/dist/types/src/templates/system.d.ts.map +1 -1
  45. package/dist/types/src/util/artifact.d.ts +27 -0
  46. package/dist/types/src/util/artifact.d.ts.map +1 -0
  47. package/dist/types/src/{diff.d.ts → util/diff.d.ts} +3 -1
  48. package/dist/types/src/util/diff.d.ts.map +1 -0
  49. package/dist/types/src/{diff.test.d.ts.map → util/diff.test.d.ts.map} +1 -1
  50. package/dist/types/src/util/error-handling.d.ts.map +1 -0
  51. package/dist/types/src/{errors.d.ts → util/errors.d.ts} +24 -28
  52. package/dist/types/src/util/errors.d.ts.map +1 -0
  53. package/dist/types/src/{execution-graph.d.ts → util/execution-graph.d.ts} +2 -2
  54. package/dist/types/src/util/execution-graph.d.ts.map +1 -0
  55. package/dist/types/src/util/execution-graph.test.d.ts.map +1 -0
  56. package/dist/types/src/util/index.d.ts +7 -0
  57. package/dist/types/src/util/index.d.ts.map +1 -0
  58. package/dist/types/src/util/tracing.d.ts +233 -0
  59. package/dist/types/src/util/tracing.d.ts.map +1 -0
  60. package/dist/types/tsconfig.tsbuildinfo +1 -1
  61. package/package.json +36 -44
  62. package/src/extraction/extraction-ner-function/index.ts +0 -1
  63. package/src/extraction/extraction.ts +40 -12
  64. package/src/extraction/index.ts +0 -1
  65. package/src/extraction/quotes.ts +4 -5
  66. package/src/functions/services.ts +115 -63
  67. package/src/index.ts +2 -5
  68. package/src/request/AiRequest.ts +348 -0
  69. package/src/{session → request}/artifact-diff.ts +1 -1
  70. package/src/{session → request}/format.ts +24 -21
  71. package/src/request/index.ts +8 -0
  72. package/src/{session → request}/observer.ts +4 -1
  73. package/src/{session → request}/version-pin.ts +4 -3
  74. package/src/session/AiContext.test.ts +53 -0
  75. package/src/session/AiContext.ts +403 -0
  76. package/src/session/AiSession.ts +324 -0
  77. package/src/session/index.ts +2 -5
  78. package/src/session/toolkit.ts +27 -28
  79. package/src/templates/instructions/format.tpl +0 -4
  80. package/src/templates/instructions/system.tpl +50 -2
  81. package/src/templates/system.ts +7 -6
  82. package/src/{types → util}/artifact.ts +29 -12
  83. package/src/util/diff.test.ts +74 -0
  84. package/src/{diff.ts → util/diff.ts} +13 -4
  85. package/src/{session → util}/error-handling.ts +3 -2
  86. package/src/util/errors.ts +15 -0
  87. package/src/{execution-graph.test.ts → util/execution-graph.test.ts} +3 -3
  88. package/src/{execution-graph.ts → util/execution-graph.ts} +22 -12
  89. package/src/util/index.ts +10 -0
  90. package/src/util/tracing.ts +57 -0
  91. package/dist/lib/browser/extraction/index.mjs.map +0 -7
  92. package/dist/lib/browser/index.mjs +0 -1290
  93. package/dist/lib/browser/index.mjs.map +0 -7
  94. package/dist/lib/browser/meta.json +0 -1
  95. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  96. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  97. package/dist/lib/node-esm/extraction/index.mjs +0 -226
  98. package/dist/lib/node-esm/extraction/index.mjs.map +0 -7
  99. package/dist/lib/node-esm/index.mjs +0 -1291
  100. package/dist/lib/node-esm/index.mjs.map +0 -7
  101. package/dist/lib/node-esm/meta.json +0 -1
  102. package/dist/types/src/conversation/context.d.ts +0 -103
  103. package/dist/types/src/conversation/context.d.ts.map +0 -1
  104. package/dist/types/src/conversation/conversation.d.ts +0 -41
  105. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  106. package/dist/types/src/conversation/index.d.ts +0 -3
  107. package/dist/types/src/conversation/index.d.ts.map +0 -1
  108. package/dist/types/src/diff.d.ts.map +0 -1
  109. package/dist/types/src/errors.d.ts.map +0 -1
  110. package/dist/types/src/execution-graph.d.ts.map +0 -1
  111. package/dist/types/src/execution-graph.test.d.ts.map +0 -1
  112. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
  113. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
  114. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
  115. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
  116. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
  117. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
  118. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -345
  119. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
  120. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
  121. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
  122. package/dist/types/src/session/GenericToolkit.d.ts +0 -84
  123. package/dist/types/src/session/GenericToolkit.d.ts.map +0 -1
  124. package/dist/types/src/session/artifact-diff.d.ts.map +0 -1
  125. package/dist/types/src/session/error-handling.d.ts.map +0 -1
  126. package/dist/types/src/session/format.d.ts +0 -12
  127. package/dist/types/src/session/format.d.ts.map +0 -1
  128. package/dist/types/src/session/format.test.d.ts +0 -2
  129. package/dist/types/src/session/format.test.d.ts.map +0 -1
  130. package/dist/types/src/session/observer.d.ts.map +0 -1
  131. package/dist/types/src/session/session.d.ts +0 -51
  132. package/dist/types/src/session/session.d.ts.map +0 -1
  133. package/dist/types/src/session/session.test.d.ts +0 -2
  134. package/dist/types/src/session/session.test.d.ts.map +0 -1
  135. package/dist/types/src/session/version-pin.d.ts.map +0 -1
  136. package/dist/types/src/types/artifact.d.ts +0 -20
  137. package/dist/types/src/types/artifact.d.ts.map +0 -1
  138. package/dist/types/src/types/index.d.ts +0 -2
  139. package/dist/types/src/types/index.d.ts.map +0 -1
  140. package/src/conversation/context.ts +0 -186
  141. package/src/conversation/conversation.ts +0 -128
  142. package/src/conversation/index.ts +0 -6
  143. package/src/diff.test.ts +0 -43
  144. package/src/errors.ts +0 -15
  145. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -84
  146. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -62
  147. package/src/extraction/extraction-llm-function/index.ts +0 -5
  148. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -116
  149. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -56
  150. package/src/session/GenericToolkit.ts +0 -130
  151. package/src/session/format.test.ts +0 -61
  152. package/src/session/session.conversations.json +0 -1
  153. package/src/session/session.test.ts +0 -149
  154. package/src/session/session.ts +0 -213
  155. package/src/types/index.ts +0 -5
  156. /package/dist/lib/{browser → neutral}/chunk-J5LGTIGS.mjs +0 -0
  157. /package/dist/lib/{browser → neutral}/chunk-J5LGTIGS.mjs.map +0 -0
  158. /package/dist/types/src/{diff.test.d.ts → util/diff.test.d.ts} +0 -0
  159. /package/dist/types/src/{session → util}/error-handling.d.ts +0 -0
  160. /package/dist/types/src/{execution-graph.test.d.ts → util/execution-graph.test.d.ts} +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,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, type OperationRegistry, Template } from '@dxos/compute';
10
+ import { type Database, Obj } from '@dxos/echo';
11
+ import { ObjectVersion } from '@dxos/echo-db';
12
+ import { type ObjectNotFoundError } from '@dxos/echo/Err';
13
+ import { type ObjectId } 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 | ObjectNotFoundError,
33
+ Database.Service | OperationRegistry.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) =>
@@ -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,9 +113,9 @@ 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
120
  const gatherObjectVersions = (messages: Message.Message[]): Map<ObjectId, ObjectVersion> => {
118
121
  const artifactIds = new Map<ObjectId, ObjectVersion>();
@@ -133,7 +136,7 @@ const createArtifactUpdateBlock = (
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';
7
+ import { type Obj } from '@dxos/echo';
8
8
  import { type ObjectVersion, getVersion } from '@dxos/echo-db';
9
+ import { ObjectId } from '@dxos/keys';
9
10
  import { type ContentBlock } from '@dxos/types';
10
11
 
11
12
  // TODO(dmaretskyi): Extract.
@@ -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,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
+ });