@dxos/assistant 0.8.0 → 0.8.1-main.81238a8

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 (87) hide show
  1. package/dist/lib/browser/chunk-RFTY3OMK.mjs +2276 -0
  2. package/dist/lib/browser/chunk-RFTY3OMK.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +33 -1236
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing/index.mjs +17 -3
  7. package/dist/lib/browser/testing/index.mjs.map +4 -4
  8. package/dist/lib/node/chunk-4ZDZUCAS.cjs +2287 -0
  9. package/dist/lib/node/chunk-4ZDZUCAS.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +40 -1236
  11. package/dist/lib/node/index.cjs.map +4 -4
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/testing/index.cjs +40 -29
  14. package/dist/lib/node/testing/index.cjs.map +4 -4
  15. package/dist/lib/node-esm/chunk-JUVGBQBL.mjs +2278 -0
  16. package/dist/lib/node-esm/chunk-JUVGBQBL.mjs.map +7 -0
  17. package/dist/lib/node-esm/index.mjs +33 -1236
  18. package/dist/lib/node-esm/index.mjs.map +4 -4
  19. package/dist/lib/node-esm/meta.json +1 -1
  20. package/dist/lib/node-esm/testing/index.mjs +17 -3
  21. package/dist/lib/node-esm/testing/index.mjs.map +4 -4
  22. package/dist/types/src/ai-service/defs.d.ts +8 -2
  23. package/dist/types/src/ai-service/defs.d.ts.map +1 -1
  24. package/dist/types/src/ai-service/edge-client.d.ts +19 -0
  25. package/dist/types/src/ai-service/edge-client.d.ts.map +1 -0
  26. package/dist/types/src/ai-service/index.d.ts +4 -1
  27. package/dist/types/src/ai-service/index.d.ts.map +1 -1
  28. package/dist/types/src/ai-service/message-collector.d.ts +88 -0
  29. package/dist/types/src/ai-service/message-collector.d.ts.map +1 -0
  30. package/dist/types/src/ai-service/ollama-client.d.ts +39 -0
  31. package/dist/types/src/ai-service/ollama-client.d.ts.map +1 -0
  32. package/dist/types/src/ai-service/parser.d.ts +11 -9
  33. package/dist/types/src/ai-service/parser.d.ts.map +1 -1
  34. package/dist/types/src/ai-service/service.d.ts +9 -0
  35. package/dist/types/src/ai-service/service.d.ts.map +1 -0
  36. package/dist/types/src/ai-service/stream.d.ts +2 -1
  37. package/dist/types/src/ai-service/stream.d.ts.map +1 -1
  38. package/dist/types/src/ai-service/testing/mock.d.ts +2 -2
  39. package/dist/types/src/ai-service/testing/mock.d.ts.map +1 -1
  40. package/dist/types/src/ai-service/types.d.ts +91 -157
  41. package/dist/types/src/ai-service/types.d.ts.map +1 -1
  42. package/dist/types/src/conversation/conversation.d.ts +11 -9
  43. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  44. package/dist/types/src/conversation/types.d.ts +1 -1
  45. package/dist/types/src/conversation/types.d.ts.map +1 -1
  46. package/dist/types/src/testing/index.d.ts +1 -0
  47. package/dist/types/src/testing/index.d.ts.map +1 -1
  48. package/dist/types/src/testing/ollama.d.ts +6 -0
  49. package/dist/types/src/testing/ollama.d.ts.map +1 -0
  50. package/dist/types/src/testing/query-promts.d.ts +1 -1
  51. package/dist/types/src/testing/query-promts.d.ts.map +1 -1
  52. package/dist/types/src/testing/test-data.d.ts +1 -1
  53. package/dist/types/src/testing/test-data.d.ts.map +1 -1
  54. package/dist/types/src/testing/test-schema.d.ts +1 -1
  55. package/dist/types/src/testing/test-schema.d.ts.map +1 -1
  56. package/package.json +17 -14
  57. package/src/ai-service/client.test.ts +100 -13
  58. package/src/ai-service/defs.ts +17 -2
  59. package/src/ai-service/{client.ts → edge-client.ts} +15 -24
  60. package/src/ai-service/index.ts +4 -1
  61. package/src/ai-service/message-collector.ts +84 -0
  62. package/src/ai-service/ollama-client.ts +499 -0
  63. package/src/ai-service/parser.ts +7 -2
  64. package/src/ai-service/service.ts +15 -0
  65. package/src/ai-service/stream.ts +5 -3
  66. package/src/ai-service/testing/mock.ts +7 -2
  67. package/src/ai-service/types.ts +3 -3
  68. package/src/bin/chat.ts +3 -3
  69. package/src/conversation/conversation.test.ts +5 -5
  70. package/src/conversation/conversation.ts +3 -2
  71. package/src/conversation/types.ts +1 -1
  72. package/src/testing/artifacts.test.ts +4 -4
  73. package/src/testing/index.ts +1 -0
  74. package/src/testing/object-extraction.test.ts +1 -1
  75. package/src/testing/ollama.ts +15 -0
  76. package/src/testing/query-promts.ts +1 -1
  77. package/src/testing/query.test.ts +4 -4
  78. package/src/testing/test-data.ts +1 -1
  79. package/src/testing/test-schema.ts +1 -1
  80. package/dist/lib/browser/chunk-AXUUNA7O.mjs +0 -565
  81. package/dist/lib/browser/chunk-AXUUNA7O.mjs.map +0 -7
  82. package/dist/lib/node/chunk-QPHGQINW.cjs +0 -577
  83. package/dist/lib/node/chunk-QPHGQINW.cjs.map +0 -7
  84. package/dist/lib/node-esm/chunk-GOVFOBIB.mjs +0 -567
  85. package/dist/lib/node-esm/chunk-GOVFOBIB.mjs.map +0 -7
  86. package/dist/types/src/ai-service/client.d.ts +0 -25
  87. package/dist/types/src/ai-service/client.d.ts.map +0 -1
@@ -1,1256 +1,53 @@
1
1
  import {
2
+ AIServiceEdgeClient,
3
+ DEFAULT_EDGE_MODEL,
4
+ DEFAULT_EDGE_MODELS,
5
+ DEFAULT_OLLAMA_ENDPOINT,
6
+ DEFAULT_OLLAMA_MODEL,
7
+ DEFAULT_OLLAMA_MODELS,
2
8
  EchoDataSource,
9
+ GenerateRequest,
10
+ GenerationStreamImpl,
11
+ LLMModel,
12
+ MessageCollector,
13
+ MixedStreamParser,
14
+ OllamaClient,
15
+ StreamTransform,
16
+ ToolTypes,
17
+ createArtifactElement,
18
+ createGenerationStream,
19
+ emitMessageAsEvents,
3
20
  executeQuery,
4
21
  executeQueryPlan,
5
22
  formatInferredRelationshipLabel,
6
23
  formatJsonSchemaForLLM,
7
24
  formatNodeLabel,
8
25
  isReference,
9
- parseCypherQuery
10
- } from "./chunk-AXUUNA7O.mjs";
11
-
12
- // packages/experimental/assistant/src/ai-service/client.ts
13
- import { Schema as S } from "@effect/schema";
14
- import { Message } from "@dxos/artifact";
15
- import { invariant } from "@dxos/invariant";
16
- import { log as log2 } from "@dxos/log";
17
-
18
- // packages/experimental/assistant/src/ai-service/stream.ts
19
- import { Trigger } from "@dxos/async";
20
- import { log } from "@dxos/log";
21
-
22
- // packages/experimental/assistant/src/ai-service/util/sse.ts
23
- async function* iterSSEMessages(response, controller) {
24
- if (!response.body) {
25
- controller.abort();
26
- throw new Error("Attempted to iterate over a response with no body");
27
- }
28
- const sseDecoder = new SSEDecoder();
29
- const lineDecoder = new LineDecoder();
30
- const iter = readableStreamAsyncIterable(response.body);
31
- for await (const sseChunk of iterSSEChunks(iter)) {
32
- for (const line of lineDecoder.decode(sseChunk)) {
33
- const sse = sseDecoder.decode(line);
34
- if (sse) {
35
- yield sse;
36
- }
37
- }
38
- }
39
- for (const line of lineDecoder.flush()) {
40
- const sse = sseDecoder.decode(line);
41
- if (sse) {
42
- yield sse;
43
- }
44
- }
45
- }
46
- async function* iterSSEChunks(iterator) {
47
- let data = new Uint8Array();
48
- for await (const chunk of iterator) {
49
- if (chunk == null) {
50
- continue;
51
- }
52
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
53
- const newData = new Uint8Array(data.length + binaryChunk.length);
54
- newData.set(data);
55
- newData.set(binaryChunk, data.length);
56
- data = newData;
57
- let patternIndex;
58
- while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
59
- yield data.slice(0, patternIndex);
60
- data = data.slice(patternIndex);
61
- }
62
- }
63
- if (data.length > 0) {
64
- yield data;
65
- }
66
- }
67
- var findDoubleNewlineIndex = (buffer) => {
68
- const newline = 10;
69
- const carriage = 13;
70
- for (let i = 0; i < buffer.length - 2; i++) {
71
- if (buffer[i] === newline && buffer[i + 1] === newline) {
72
- return i + 2;
73
- }
74
- if (buffer[i] === carriage && buffer[i + 1] === carriage) {
75
- return i + 2;
76
- }
77
- if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) {
78
- return i + 4;
79
- }
80
- }
81
- return -1;
82
- };
83
- var SSEDecoder = class {
84
- constructor() {
85
- this.event = null;
86
- this.data = [];
87
- this.chunks = [];
88
- }
89
- decode(line) {
90
- if (line.endsWith("\r")) {
91
- line = line.substring(0, line.length - 1);
92
- }
93
- if (!line) {
94
- if (!this.event && !this.data.length) {
95
- return null;
96
- }
97
- const sse = {
98
- event: this.event,
99
- data: this.data.join("\n"),
100
- raw: this.chunks
101
- };
102
- this.event = null;
103
- this.data = [];
104
- this.chunks = [];
105
- return sse;
106
- }
107
- this.chunks.push(line);
108
- if (line.startsWith(":")) {
109
- return null;
110
- }
111
- let [fieldname, _, value] = partition(line, ":");
112
- if (value.startsWith(" ")) {
113
- value = value.substring(1);
114
- }
115
- if (fieldname === "event") {
116
- this.event = value;
117
- } else if (fieldname === "data") {
118
- this.data.push(value);
119
- }
120
- return null;
121
- }
122
- };
123
- var partition = (str, delimiter) => {
124
- const index = str.indexOf(delimiter);
125
- if (index !== -1) {
126
- return [
127
- str.substring(0, index),
128
- delimiter,
129
- str.substring(index + delimiter.length)
130
- ];
131
- }
132
- return [
133
- str,
134
- "",
135
- ""
136
- ];
137
- };
138
- function readableStreamAsyncIterable(stream) {
139
- if (stream[Symbol.asyncIterator]) {
140
- return stream;
141
- }
142
- const reader = stream.getReader();
143
- return {
144
- next: async () => {
145
- try {
146
- const result = await reader.read();
147
- if (result?.done) {
148
- reader.releaseLock();
149
- }
150
- return result;
151
- } catch (e) {
152
- reader.releaseLock();
153
- throw e;
154
- }
155
- },
156
- return: async () => {
157
- const cancelPromise = reader.cancel();
158
- reader.releaseLock();
159
- await cancelPromise;
160
- return {
161
- done: true,
162
- value: void 0
163
- };
164
- },
165
- [Symbol.asyncIterator]() {
166
- return this;
167
- }
168
- };
169
- }
170
- var LineDecoder = class _LineDecoder {
171
- static {
172
- // prettier-ignore
173
- this.NEWLINE_CHARS = /* @__PURE__ */ new Set([
174
- "\n",
175
- "\r"
176
- ]);
177
- }
178
- static {
179
- this.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
180
- }
181
- constructor() {
182
- this.buffer = [];
183
- this.trailingCR = false;
184
- }
185
- decode(chunk) {
186
- let text = this.decodeText(chunk);
187
- if (this.trailingCR) {
188
- text = "\r" + text;
189
- this.trailingCR = false;
190
- }
191
- if (text.endsWith("\r")) {
192
- this.trailingCR = true;
193
- text = text.slice(0, -1);
194
- }
195
- if (!text) {
196
- return [];
197
- }
198
- const trailingNewline = _LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || "");
199
- let lines = text.split(_LineDecoder.NEWLINE_REGEXP);
200
- if (trailingNewline) {
201
- lines.pop();
202
- }
203
- if (lines.length === 1 && !trailingNewline) {
204
- this.buffer.push(lines[0]);
205
- return [];
206
- }
207
- if (this.buffer.length > 0) {
208
- lines = [
209
- this.buffer.join("") + lines[0],
210
- ...lines.slice(1)
211
- ];
212
- this.buffer = [];
213
- }
214
- if (!trailingNewline) {
215
- this.buffer = [
216
- lines.pop() || ""
217
- ];
218
- }
219
- return lines;
220
- }
221
- decodeText(bytes) {
222
- if (bytes == null) {
223
- return "";
224
- }
225
- if (typeof bytes === "string") {
226
- return bytes;
227
- }
228
- if (typeof Buffer !== "undefined") {
229
- if (bytes instanceof Buffer) {
230
- return bytes.toString();
231
- }
232
- if (bytes instanceof Uint8Array) {
233
- return Buffer.from(bytes).toString();
234
- }
235
- throw new Error(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`);
236
- }
237
- if (typeof TextDecoder !== "undefined") {
238
- if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
239
- this.textDecoder ??= new TextDecoder("utf8");
240
- return this.textDecoder.decode(bytes);
241
- }
242
- throw new Error(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
243
- }
244
- throw new Error("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.");
245
- }
246
- flush() {
247
- if (!this.buffer.length && !this.trailingCR) {
248
- return [];
249
- }
250
- const lines = [
251
- this.buffer.join("")
252
- ];
253
- this.buffer = [];
254
- this.trailingCR = false;
255
- return lines;
256
- }
257
- };
258
-
259
- // packages/experimental/assistant/src/ai-service/stream.ts
260
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/stream.ts";
261
- var createGenerationStream = (response, controller = new AbortController()) => {
262
- const iterator = async function* () {
263
- for await (const sse of iterSSEMessages(response, controller)) {
264
- if (sse.event === "completion") {
265
- try {
266
- yield JSON.parse(sse.data);
267
- } catch (err) {
268
- log.error("could not parse message into JSON:", {
269
- data: sse.data,
270
- raw: sse.raw
271
- }, {
272
- F: __dxlog_file,
273
- L: 21,
274
- S: this,
275
- C: (f, a) => f(...a)
276
- });
277
- throw err;
278
- }
279
- }
280
- if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop") {
281
- try {
282
- yield JSON.parse(sse.data);
283
- } catch (err) {
284
- log.error("could not parse message into JSON:", {
285
- data: sse.data,
286
- raw: sse.raw
287
- }, {
288
- F: __dxlog_file,
289
- L: 37,
290
- S: this,
291
- C: (f, a) => f(...a)
292
- });
293
- throw err;
294
- }
295
- }
296
- if (sse.event === "ping") {
297
- continue;
298
- }
299
- if (sse.event === "error") {
300
- throw new Error(`Message generation error: ${sse.data}`);
301
- }
302
- }
303
- };
304
- return new GenerationStream(controller, iterator);
305
- };
306
- var GenerationStream = class {
307
- constructor(_controller, _getIterator) {
308
- this._controller = _controller;
309
- this._getIterator = _getIterator;
310
- this._done = new Trigger();
311
- this._iterator = void 0;
312
- }
313
- /**
314
- * Returns an iterator over the stream.
315
- */
316
- [Symbol.asyncIterator]() {
317
- return this._createIterator();
318
- }
319
- /**
320
- * Aborts the stream.
321
- */
322
- abort() {
323
- this._controller.abort();
324
- }
325
- /**
326
- * Returns the complete message list generated by the AI service.
327
- */
328
- async complete() {
329
- await this._done.wait();
330
- }
331
- /**
332
- * Creates an iterator over the stream.
333
- */
334
- _createIterator() {
335
- const self = this;
336
- return this._iterator ??= (() => {
337
- const generator = async function* () {
338
- try {
339
- for await (const event of self._getIterator()) {
340
- yield event;
341
- }
342
- this._done.wake();
343
- } catch (err) {
344
- this._done.throw(err);
345
- }
346
- };
347
- return generator.call(this);
348
- })();
349
- }
350
- };
351
-
352
- // packages/experimental/assistant/src/ai-service/client.ts
353
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/client.ts";
354
- var AIServiceClientImpl = class {
355
- constructor({ endpoint }) {
356
- invariant(endpoint, "endpoint is required", {
357
- F: __dxlog_file2,
358
- L: 34,
359
- S: this,
360
- A: [
361
- "endpoint",
362
- "'endpoint is required'"
363
- ]
364
- });
365
- this._endpoint = endpoint;
366
- }
367
- async appendMessages(messages) {
368
- const url = `${this._endpoint}/message`;
369
- const res = await fetch(url, {
370
- method: "POST",
371
- headers: {
372
- "Content-Type": "application/json"
373
- },
374
- body: JSON.stringify({
375
- messages: await S.encodePromise(S.Array(Message))(messages)
376
- })
377
- });
378
- if (!res.ok) {
379
- throw new Error(`${await res.text()} [${url}]`);
380
- }
381
- }
382
- /**
383
- * Process request and open message stream.
384
- */
385
- async exec(request) {
386
- request = {
387
- tools: request.tools ?? [],
388
- ...request
389
- };
390
- log2.info("requesting", {
391
- endpoint: this._endpoint
392
- }, {
393
- F: __dxlog_file2,
394
- L: 63,
395
- S: this,
396
- C: (f, a) => f(...a)
397
- });
398
- const controller = new AbortController();
399
- const response = await fetch(`${this._endpoint}/generate`, {
400
- signal: controller.signal,
401
- method: "POST",
402
- headers: {
403
- "Content-Type": "application/json"
404
- },
405
- body: JSON.stringify(request)
406
- });
407
- invariant(response.body instanceof ReadableStream, void 0, {
408
- F: __dxlog_file2,
409
- L: 72,
410
- S: this,
411
- A: [
412
- "response.body instanceof ReadableStream",
413
- ""
414
- ]
415
- });
416
- return createGenerationStream(response, controller);
417
- }
418
- };
419
-
420
- // packages/experimental/assistant/src/ai-service/defs.ts
421
- var DEFAULT_LLM_MODEL = "@anthropic/claude-3-5-sonnet-20241022";
422
- var DEFAULT_LLM_MODELS = [
423
- // AI Gateway.
424
- // https://developers.cloudflare.com/ai-gateway
425
- "@anthropic/claude-3-5-haiku-20241022",
426
- "@anthropic/claude-3-5-sonnet-20241022",
427
- "@anthropic/claude-3-7-sonnet-20250219",
428
- // Workers AI.
429
- // https://developers.cloudflare.com/workers-ai/models
430
- "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b",
431
- "@hf/nousresearch/hermes-2-pro-mistral-7b",
432
- "@ollama/llama-3-1-nemotron-70b-instruct",
433
- "@ollama/llama-3-1-nemotron-mini-4b-instruct",
434
- "@ollama/llama-3-2-3b"
435
- ];
436
-
437
- // packages/experimental/assistant/src/ai-service/parser.ts
438
- import { Message as Message2 } from "@dxos/artifact";
439
- import { Event } from "@dxos/async";
440
- import { createStatic } from "@dxos/echo-schema";
441
- import { invariant as invariant2 } from "@dxos/invariant";
442
- import { log as log3 } from "@dxos/log";
443
- import { isNotFalsy, safeParseJson } from "@dxos/util";
444
-
445
- // packages/experimental/assistant/src/ai-service/transform.ts
446
- import * as P from "parsimmon";
447
- var textChunk = P.regexp(/[^<]+/).map((content) => ({
448
- type: "text",
449
- content
450
- }));
451
- var attribute = P.seq(P.regexp(/[a-zA-Z_][a-zA-Z0-9_-]*/), P.string("=").trim(P.optWhitespace), P.alt(P.regexp(/"[^"]*"/).map((s) => s.slice(1, -1)), P.regexp(/'[^']*'/).map((s) => s.slice(1, -1)))).map(([name, _, value]) => [
452
- name,
453
- value
454
- ]);
455
- var tagName = P.regexp(/[a-zA-Z_][a-zA-Z0-9_-]*/);
456
- var selfClosingTag = P.seqMap(
457
- //
458
- P.string("<"),
459
- tagName,
460
- P.optWhitespace.then(attribute).many(),
461
- P.optWhitespace.then(P.string("/>")),
462
- P.optWhitespace,
463
- (_, tag, attributes, __) => ({
464
- type: "tag",
465
- tag,
466
- attributes: Object.fromEntries(attributes),
467
- content: [],
468
- selfClosing: true
469
- })
470
- );
471
- var openTag = P.seqMap(
472
- //
473
- P.string("<"),
474
- tagName,
475
- P.optWhitespace.then(attribute).many(),
476
- P.string(">"),
477
- P.regexp(/[^<]*/),
478
- (_, tag, attributes, __, content) => ({
479
- type: "tag",
480
- tag,
481
- attributes: Object.fromEntries(attributes),
482
- content: content.length ? [
483
- {
484
- type: "text",
485
- content
486
- }
487
- ] : []
488
- })
489
- );
490
- var closeTag = P.seqMap(
491
- //
492
- P.string("</"),
493
- tagName,
494
- P.string(">"),
495
- P.optWhitespace,
496
- (_, tag) => ({
497
- type: "tag",
498
- tag,
499
- content: [],
500
- closing: true
501
- })
502
- );
503
- var mixedChunk = P.alt(selfClosingTag, openTag, closeTag, textChunk);
504
- var StreamTransform = class {
505
- constructor() {
506
- this._buffer = "";
507
- }
508
- transform(chunk) {
509
- this._buffer += chunk;
510
- const results = [];
511
- const parser = mixedChunk.many().skip(P.optWhitespace);
512
- const result = parser.parse(this._buffer);
513
- if (result.status) {
514
- for (const chunk2 of result.value) {
515
- results.push(chunk2);
516
- }
517
- this._buffer = "";
518
- }
519
- return results;
520
- }
521
- // TODO(burdon): Process remaining buffer?
522
- flush() {
523
- const remaining = this._buffer;
524
- this._buffer = "";
525
- return remaining.length > 0 ? [
526
- {
527
- type: "text",
528
- content: remaining
529
- }
530
- ] : [];
531
- }
532
- };
533
-
534
- // packages/experimental/assistant/src/ai-service/parser.ts
535
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/parser.ts";
536
- var MixedStreamParser = class {
537
- constructor() {
538
- /**
539
- * New message.
540
- */
541
- this.message = new Event();
542
- /**
543
- * Complete block added to Message.
544
- */
545
- this.block = new Event();
546
- /**
547
- * Update partial block (while streaming).
548
- */
549
- this.update = new Event();
550
- }
551
- _emitBlock(contentBlock, streamBlock) {
552
- const messageBlock = streamBlock ? mergeMessageBlock(contentBlock, streamBlock) : contentBlock;
553
- if (messageBlock) {
554
- if (messageBlock.type === "text" && messageBlock.text.length === 0) {
555
- return;
556
- }
557
- invariant2(this._message, void 0, {
558
- F: __dxlog_file3,
559
- L: 46,
560
- S: this,
561
- A: [
562
- "this._message",
563
- ""
564
- ]
565
- });
566
- this._message.content.push(messageBlock);
567
- this.block.emit(messageBlock);
568
- }
569
- }
570
- _emitUpdate(contentBlock, streamBlock) {
571
- const messageBlock = mergeMessageBlock(contentBlock, streamBlock);
572
- if (messageBlock) {
573
- messageBlock.pending = true;
574
- this.update.emit(messageBlock);
575
- }
576
- }
577
- /**
578
- * Parse stream until end.
579
- */
580
- async parse(stream) {
581
- const transformer = new StreamTransform();
582
- let contentBlock;
583
- let streamBlock;
584
- const stack = [];
585
- const messagesCollected = [];
586
- for await (const event of stream) {
587
- switch (event.type) {
588
- //
589
- // Messages.
590
- //
591
- case "message_start": {
592
- if (this._message) {
593
- log3.warn("unexpected message_start", void 0, {
594
- F: __dxlog_file3,
595
- L: 88,
596
- S: this,
597
- C: (f, a) => f(...a)
598
- });
599
- }
600
- this._message = createStatic(Message2, {
601
- role: "assistant",
602
- content: []
603
- });
604
- this.message.emit(this._message);
605
- break;
606
- }
607
- case "message_delta": {
608
- if (!this._message) {
609
- log3.warn("unexpected message_delta", void 0, {
610
- F: __dxlog_file3,
611
- L: 98,
612
- S: this,
613
- C: (f, a) => f(...a)
614
- });
615
- }
616
- break;
617
- }
618
- case "message_stop": {
619
- if (!this._message) {
620
- log3.warn("unexpected message_stop", void 0, {
621
- F: __dxlog_file3,
622
- L: 106,
623
- S: this,
624
- C: (f, a) => f(...a)
625
- });
626
- } else {
627
- messagesCollected.push(this._message);
628
- this._message = void 0;
629
- }
630
- break;
631
- }
632
- //
633
- // Content blocks.
634
- //
635
- case "content_block_start": {
636
- if (contentBlock) {
637
- log3.warn("unexpected content_block_start", {
638
- content: contentBlock
639
- }, {
640
- F: __dxlog_file3,
641
- L: 120,
642
- S: this,
643
- C: (f, a) => f(...a)
644
- });
645
- }
646
- contentBlock = event.content;
647
- break;
648
- }
649
- case "content_block_delta": {
650
- if (!contentBlock) {
651
- log3.warn("unexpected content_block_delta", void 0, {
652
- F: __dxlog_file3,
653
- L: 130,
654
- S: this,
655
- C: (f, a) => f(...a)
656
- });
657
- break;
658
- }
659
- switch (event.delta.type) {
660
- //
661
- // Text
662
- //
663
- case "text_delta": {
664
- const chunks = transformer.transform(event.delta.text);
665
- for (const chunk of chunks) {
666
- switch (streamBlock?.type) {
667
- //
668
- // XML Fragment.
669
- //
670
- case "tag": {
671
- if (chunk.type === "tag") {
672
- if (chunk.selfClosing) {
673
- streamBlock.content.push(chunk);
674
- } else if (chunk.closing) {
675
- if (stack.length > 0) {
676
- const top = stack.pop();
677
- invariant2(top && top.type === "tag", void 0, {
678
- F: __dxlog_file3,
679
- L: 154,
680
- S: this,
681
- A: [
682
- "top && top.type === 'tag'",
683
- ""
684
- ]
685
- });
686
- top.content.push(streamBlock);
687
- streamBlock = top;
688
- } else {
689
- this._emitBlock(contentBlock, streamBlock);
690
- streamBlock = void 0;
691
- }
692
- } else {
693
- stack.push(streamBlock);
694
- streamBlock = chunk;
695
- }
696
- } else {
697
- if (streamBlock.content.length === 0) {
698
- streamBlock.content.push(chunk);
699
- } else {
700
- const last = streamBlock.content.at(-1);
701
- invariant2(last, void 0, {
702
- F: __dxlog_file3,
703
- L: 171,
704
- S: this,
705
- A: [
706
- "last",
707
- ""
708
- ]
709
- });
710
- if (last.type === "text") {
711
- last.content += chunk.content;
712
- } else {
713
- streamBlock.content.push(chunk);
714
- }
715
- }
716
- }
717
- break;
718
- }
719
- //
720
- // Text Fragment.
721
- //
722
- case "text": {
723
- if (chunk.type === "tag") {
724
- this._emitBlock(contentBlock, streamBlock);
725
- if (chunk.selfClosing) {
726
- this._emitBlock(contentBlock, chunk);
727
- streamBlock = void 0;
728
- } else {
729
- streamBlock = chunk;
730
- }
731
- } else {
732
- streamBlock.content += chunk.content;
733
- }
734
- break;
735
- }
736
- //
737
- // No current chunk.
738
- //
739
- default: {
740
- if (chunk.type === "tag" && chunk.selfClosing) {
741
- this._emitBlock(contentBlock, chunk);
742
- } else {
743
- streamBlock = chunk;
744
- }
745
- }
746
- }
747
- }
748
- break;
749
- }
750
- //
751
- // JSON
752
- //
753
- case "input_json_delta": {
754
- if (!contentBlock) {
755
- log3.warn("unexpected input_json_delta", {
756
- contentBlock
757
- }, {
758
- F: __dxlog_file3,
759
- L: 221,
760
- S: this,
761
- C: (f, a) => f(...a)
762
- });
763
- break;
764
- }
765
- if (streamBlock?.type === "json") {
766
- streamBlock.content += event.delta.partial_json;
767
- } else {
768
- streamBlock = {
769
- type: "json",
770
- content: event.delta.partial_json
771
- };
772
- }
773
- break;
774
- }
775
- }
776
- break;
777
- }
778
- case "content_block_stop": {
779
- if (!contentBlock) {
780
- log3.warn("unexpected content_block_stop", void 0, {
781
- F: __dxlog_file3,
782
- L: 238,
783
- S: this,
784
- C: (f, a) => f(...a)
785
- });
786
- break;
787
- }
788
- this._emitBlock(contentBlock, streamBlock);
789
- contentBlock = void 0;
790
- streamBlock = void 0;
791
- break;
792
- }
793
- }
794
- if (contentBlock && streamBlock) {
795
- this._emitUpdate(contentBlock, streamBlock);
796
- }
797
- }
798
- return messagesCollected;
799
- }
800
- };
801
- var mergeMessageBlock = (contentBlock, streamBlock) => {
802
- log3("mergeMessageBlock", {
803
- contentBlock,
804
- streamBlock
805
- }, {
806
- F: __dxlog_file3,
807
- L: 265,
808
- S: void 0,
809
- C: (f, a) => f(...a)
810
- });
811
- switch (streamBlock.type) {
812
- //
813
- // Text
814
- //
815
- case "text": {
816
- return {
817
- ...contentBlock,
818
- type: "text",
819
- text: streamBlock.content
820
- };
821
- }
822
- //
823
- // XML
824
- //
825
- case "tag": {
826
- switch (streamBlock.tag) {
827
- case "cot": {
828
- const content = streamBlock.content.map((block) => {
829
- switch (block.type) {
830
- case "text":
831
- return block.content;
832
- default:
833
- return null;
834
- }
835
- }).filter(isNotFalsy).join("\n");
836
- return {
837
- ...contentBlock,
838
- type: "text",
839
- disposition: "cot",
840
- text: content
841
- };
842
- }
843
- case "artifact": {
844
- const { attributes } = streamBlock;
845
- return {
846
- type: "json",
847
- disposition: "artifact",
848
- json: JSON.stringify(attributes)
849
- };
850
- }
851
- case "suggest": {
852
- if (streamBlock.content.length === 1 && streamBlock.content[0].type === "text") {
853
- return {
854
- type: "json",
855
- disposition: "suggest",
856
- json: JSON.stringify({
857
- text: streamBlock.content[0].content
858
- })
859
- };
860
- }
861
- break;
862
- }
863
- case "select": {
864
- return {
865
- type: "json",
866
- disposition: "select",
867
- json: JSON.stringify({
868
- options: streamBlock.content.flatMap((content) => content.type === "tag" && content.content.length === 1 && content.content[0].type === "text" ? [
869
- content.content[0].content
870
- ] : [])
871
- })
872
- };
873
- }
874
- case "tool-list": {
875
- return {
876
- type: "json",
877
- disposition: "tool_list",
878
- json: JSON.stringify({})
879
- };
880
- }
881
- }
882
- break;
883
- }
884
- //
885
- // JSON
886
- //
887
- case "json": {
888
- switch (contentBlock.type) {
889
- case "tool_use": {
890
- return {
891
- ...contentBlock,
892
- input: safeParseJson(streamBlock.content) ?? {}
893
- };
894
- }
895
- }
896
- return {
897
- ...contentBlock,
898
- type: "json",
899
- disposition: "artifact",
900
- json: streamBlock.content
901
- };
902
- }
903
- }
904
- };
905
-
906
- // packages/experimental/assistant/src/ai-service/types.ts
907
- import { Schema as S2 } from "@effect/schema";
908
- import { Tool, Message as Message3, SpaceIdSchema } from "@dxos/artifact";
909
- import { ObjectId } from "@dxos/echo-schema";
910
- var createArtifactElement = (id) => `<artifact id=${id} />`;
911
- var LLMModel = S2.Literal(...DEFAULT_LLM_MODELS);
912
- var ToolTypes = Object.freeze({
913
- // TODO(dmaretskyi): Not implemented yet.
914
- // DatabaseQuery: 'database_query',
915
- TextToImage: "text_to_image"
916
- });
917
- var GenerateRequest = S2.Struct({
918
- spaceId: S2.optional(SpaceIdSchema),
919
- threadId: S2.optional(ObjectId),
920
- /**
921
- * Preferred model or system default.
922
- */
923
- model: S2.optional(LLMModel),
924
- /**
925
- * Tools available for the LLM.
926
- */
927
- tools: S2.optional(S2.Array(Tool).pipe(S2.mutable)),
928
- /**
929
- * System instructions to the LLM.
930
- */
931
- systemPrompt: S2.optional(S2.String),
932
- /**
933
- * History of messages to include in the context window.
934
- */
935
- // TODO(burdon): Rename messages.
936
- history: S2.optional(S2.Array(Message3)),
937
- /**
938
- * Current request.
939
- */
940
- prompt: S2.optional(Message3)
941
- });
942
-
943
- // packages/experimental/assistant/src/conversation/conversation.ts
944
- import { ToolResult, Message as Message4 } from "@dxos/artifact";
945
- import { createStatic as createStatic2, ObjectId as ObjectId2 } from "@dxos/echo-schema";
946
- import { invariant as invariant3 } from "@dxos/invariant";
947
- import { log as log4 } from "@dxos/log";
948
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/conversation/conversation.ts";
949
- var runLLM = async (params) => {
950
- let conversationResult = null;
951
- const history = params.history ?? [];
952
- const generate = async () => {
953
- log4("llm generate", {
954
- tools: params.tools
955
- }, {
956
- F: __dxlog_file4,
957
- L: 44,
958
- S: void 0,
959
- C: (f, a) => f(...a)
960
- });
961
- const beginTs = Date.now();
962
- const stream = await params.client.exec({
963
- model: params.model,
964
- spaceId: params.spaceId,
965
- threadId: params.threadId,
966
- history,
967
- systemPrompt: params.system,
968
- tools: params.tools
969
- });
970
- for await (const event of stream) {
971
- params.logger?.(event);
972
- }
973
- await stream.complete();
974
- const messages = [];
975
- const message = messages.at(-1);
976
- invariant3(message, void 0, {
977
- F: __dxlog_file4,
978
- L: 63,
979
- S: void 0,
980
- A: [
981
- "message",
982
- ""
983
- ]
984
- });
985
- log4("llm result", {
986
- time: Date.now() - beginTs,
987
- message
988
- }, {
989
- F: __dxlog_file4,
990
- L: 65,
991
- S: void 0,
992
- C: (f, a) => f(...a)
993
- });
994
- invariant3(message, void 0, {
995
- F: __dxlog_file4,
996
- L: 66,
997
- S: void 0,
998
- A: [
999
- "message",
1000
- ""
1001
- ]
1002
- });
1003
- params.logger?.({
1004
- type: "message",
1005
- message
1006
- });
1007
- history.push(...messages.map((message2) => ({
1008
- ...message2,
1009
- content: message2.content.filter((block) => block.type !== "image")
1010
- })));
1011
- const isToolUse2 = message.content.at(-1)?.type === "tool_use";
1012
- if (isToolUse2) {
1013
- const toolCalls = message.content.filter((block) => block.type === "tool_use");
1014
- invariant3(toolCalls.length === 1, void 0, {
1015
- F: __dxlog_file4,
1016
- L: 77,
1017
- S: void 0,
1018
- A: [
1019
- "toolCalls.length === 1",
1020
- ""
1021
- ]
1022
- });
1023
- const toolCall = toolCalls[0];
1024
- const tool = params.tools.find((tool2) => tool2.name === toolCall.name);
1025
- if (!tool) {
1026
- throw new Error(`Tool not found: ${toolCall.name}`);
1027
- }
1028
- invariant3(tool.execute, void 0, {
1029
- F: __dxlog_file4,
1030
- L: 84,
1031
- S: void 0,
1032
- A: [
1033
- "tool.execute",
1034
- ""
1035
- ]
1036
- });
1037
- const toolResult = await tool.execute(toolCall.input);
1038
- switch (toolResult.kind) {
1039
- case "error": {
1040
- log4.warn("tool error", {
1041
- message: toolResult.message
1042
- }, {
1043
- F: __dxlog_file4,
1044
- L: 88,
1045
- S: void 0,
1046
- C: (f, a) => f(...a)
1047
- });
1048
- const resultMessage = {
1049
- id: ObjectId2.random(),
1050
- spaceId: params.spaceId,
1051
- threadId: params.threadId,
1052
- role: "user",
1053
- content: [
1054
- {
1055
- type: "tool_result",
1056
- toolUseId: toolCall.id,
1057
- content: toolResult.message,
1058
- isError: true
1059
- }
1060
- ]
1061
- };
1062
- params.logger?.({
1063
- type: "message",
1064
- message: resultMessage
1065
- });
1066
- history.push(resultMessage);
1067
- return true;
1068
- }
1069
- case "success": {
1070
- log4("tool success", {
1071
- result: toolResult.result
1072
- }, {
1073
- F: __dxlog_file4,
1074
- L: 110,
1075
- S: void 0,
1076
- C: (f, a) => f(...a)
1077
- });
1078
- const resultMessage = {
1079
- id: ObjectId2.random(),
1080
- spaceId: params.spaceId,
1081
- threadId: params.threadId,
1082
- role: "user",
1083
- content: [
1084
- {
1085
- type: "tool_result",
1086
- toolUseId: toolCall.id,
1087
- content: JSON.stringify(toolResult.result)
1088
- }
1089
- ]
1090
- };
1091
- params.logger?.({
1092
- type: "message",
1093
- message: resultMessage
1094
- });
1095
- history.push(resultMessage);
1096
- return true;
1097
- }
1098
- case "break": {
1099
- log4("tool break", {
1100
- result: toolResult.result
1101
- }, {
1102
- F: __dxlog_file4,
1103
- L: 131,
1104
- S: void 0,
1105
- C: (f, a) => f(...a)
1106
- });
1107
- conversationResult = toolResult.result;
1108
- return false;
1109
- }
1110
- }
1111
- }
1112
- return false;
1113
- };
1114
- while (await generate()) {
1115
- }
1116
- return {
1117
- result: conversationResult,
1118
- history
1119
- };
1120
- };
1121
- var isToolUse = (message) => {
1122
- const block = message.content.at(-1);
1123
- invariant3(block, void 0, {
1124
- F: __dxlog_file4,
1125
- L: 152,
1126
- S: void 0,
1127
- A: [
1128
- "block",
1129
- ""
1130
- ]
1131
- });
1132
- return block.type === "tool_use";
1133
- };
1134
- var runTools = async ({ message, tools, extensions }) => {
1135
- const toolCalls = message.content.filter((block) => block.type === "tool_use");
1136
- invariant3(toolCalls.length === 1, void 0, {
1137
- F: __dxlog_file4,
1138
- L: 174,
1139
- S: void 0,
1140
- A: [
1141
- "toolCalls.length === 1",
1142
- ""
1143
- ]
1144
- });
1145
- const toolCall = toolCalls[0];
1146
- const tool = tools.find((tool2) => tool2.name === toolCall.name);
1147
- if (!tool) {
1148
- throw new Error(`Tool not found: ${toolCall.name}`);
1149
- }
1150
- let toolResult;
1151
- try {
1152
- invariant3(tool.execute, void 0, {
1153
- F: __dxlog_file4,
1154
- L: 183,
1155
- S: void 0,
1156
- A: [
1157
- "tool.execute",
1158
- ""
1159
- ]
1160
- });
1161
- toolResult = await tool.execute(toolCall.input, {
1162
- extensions
1163
- });
1164
- } catch (error) {
1165
- log4("tool error", {
1166
- error
1167
- }, {
1168
- F: __dxlog_file4,
1169
- L: 186,
1170
- S: void 0,
1171
- C: (f, a) => f(...a)
1172
- });
1173
- toolResult = ToolResult.Error(error.message);
1174
- }
1175
- switch (toolResult.kind) {
1176
- case "error": {
1177
- log4("tool error", {
1178
- message: toolResult.message
1179
- }, {
1180
- F: __dxlog_file4,
1181
- L: 192,
1182
- S: void 0,
1183
- C: (f, a) => f(...a)
1184
- });
1185
- const resultMessage = createStatic2(Message4, {
1186
- role: "user",
1187
- content: [
1188
- {
1189
- type: "tool_result",
1190
- toolUseId: toolCall.id,
1191
- content: toolResult.message,
1192
- isError: true
1193
- }
1194
- ]
1195
- });
1196
- return {
1197
- type: "continue",
1198
- message: resultMessage
1199
- };
1200
- }
1201
- case "success": {
1202
- log4("tool success", {
1203
- result: toolResult.result
1204
- }, {
1205
- F: __dxlog_file4,
1206
- L: 213,
1207
- S: void 0,
1208
- C: (f, a) => f(...a)
1209
- });
1210
- const resultMessage = createStatic2(Message4, {
1211
- role: "user",
1212
- content: [
1213
- {
1214
- type: "tool_result",
1215
- toolUseId: toolCall.id,
1216
- content: typeof toolResult.result === "string" ? toolResult.result : JSON.stringify(toolResult.result) ?? ""
1217
- }
1218
- ]
1219
- });
1220
- return {
1221
- type: "continue",
1222
- message: resultMessage
1223
- };
1224
- }
1225
- case "break": {
1226
- log4("tool break", {
1227
- result: toolResult.result
1228
- }, {
1229
- F: __dxlog_file4,
1230
- L: 233,
1231
- S: void 0,
1232
- C: (f, a) => f(...a)
1233
- });
1234
- return {
1235
- type: "break",
1236
- result: toolResult.result
1237
- };
1238
- }
1239
- }
1240
- };
26
+ isToolUse,
27
+ mergeMessageBlock,
28
+ parseCypherQuery,
29
+ runLLM,
30
+ runTools
31
+ } from "./chunk-RFTY3OMK.mjs";
1241
32
  export {
1242
- AIServiceClientImpl,
1243
- DEFAULT_LLM_MODEL,
1244
- DEFAULT_LLM_MODELS,
33
+ AIServiceEdgeClient,
34
+ DEFAULT_EDGE_MODEL,
35
+ DEFAULT_EDGE_MODELS,
36
+ DEFAULT_OLLAMA_ENDPOINT,
37
+ DEFAULT_OLLAMA_MODEL,
38
+ DEFAULT_OLLAMA_MODELS,
1245
39
  EchoDataSource,
1246
40
  GenerateRequest,
1247
- GenerationStream,
41
+ GenerationStreamImpl,
1248
42
  LLMModel,
43
+ MessageCollector,
1249
44
  MixedStreamParser,
45
+ OllamaClient,
1250
46
  StreamTransform,
1251
47
  ToolTypes,
1252
48
  createArtifactElement,
1253
49
  createGenerationStream,
50
+ emitMessageAsEvents,
1254
51
  executeQuery,
1255
52
  executeQueryPlan,
1256
53
  formatInferredRelationshipLabel,