@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
@@ -0,0 +1,2278 @@
1
+ import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
+
3
+ // packages/experimental/assistant/src/ai-service/defs.ts
4
+ var DEFAULT_EDGE_MODEL = "@anthropic/claude-3-5-sonnet-20241022";
5
+ var DEFAULT_EDGE_MODELS = [
6
+ // AI Gateway.
7
+ // https://developers.cloudflare.com/ai-gateway
8
+ "@anthropic/claude-3-5-haiku-20241022",
9
+ "@anthropic/claude-3-5-sonnet-20241022",
10
+ "@anthropic/claude-3-7-sonnet-20250219",
11
+ // Workers AI.
12
+ // https://developers.cloudflare.com/workers-ai/models
13
+ "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b",
14
+ "@hf/nousresearch/hermes-2-pro-mistral-7b",
15
+ "@ollama/llama-3-1-nemotron-70b-instruct",
16
+ "@ollama/llama-3-1-nemotron-mini-4b-instruct",
17
+ "@ollama/llama-3-2-3b"
18
+ ];
19
+ var DEFAULT_OLLAMA_ENDPOINT = "http://localhost:11434";
20
+ var DEFAULT_OLLAMA_MODEL = "llama3.2:1b";
21
+ var DEFAULT_OLLAMA_MODELS = [
22
+ //
23
+ "llama3.2:1b",
24
+ "llama3:70b",
25
+ "deepseek-r1:latest"
26
+ ];
27
+
28
+ // packages/experimental/assistant/src/ai-service/stream.ts
29
+ import { Trigger } from "@dxos/async";
30
+ import { log } from "@dxos/log";
31
+
32
+ // packages/experimental/assistant/src/ai-service/util/sse.ts
33
+ async function* iterSSEMessages(response, controller) {
34
+ if (!response.body) {
35
+ controller.abort();
36
+ throw new Error("Attempted to iterate over a response with no body");
37
+ }
38
+ const sseDecoder = new SSEDecoder();
39
+ const lineDecoder = new LineDecoder();
40
+ const iter = readableStreamAsyncIterable(response.body);
41
+ for await (const sseChunk of iterSSEChunks(iter)) {
42
+ for (const line of lineDecoder.decode(sseChunk)) {
43
+ const sse = sseDecoder.decode(line);
44
+ if (sse) {
45
+ yield sse;
46
+ }
47
+ }
48
+ }
49
+ for (const line of lineDecoder.flush()) {
50
+ const sse = sseDecoder.decode(line);
51
+ if (sse) {
52
+ yield sse;
53
+ }
54
+ }
55
+ }
56
+ async function* iterSSEChunks(iterator) {
57
+ let data = new Uint8Array();
58
+ for await (const chunk of iterator) {
59
+ if (chunk == null) {
60
+ continue;
61
+ }
62
+ const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
63
+ const newData = new Uint8Array(data.length + binaryChunk.length);
64
+ newData.set(data);
65
+ newData.set(binaryChunk, data.length);
66
+ data = newData;
67
+ let patternIndex;
68
+ while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
69
+ yield data.slice(0, patternIndex);
70
+ data = data.slice(patternIndex);
71
+ }
72
+ }
73
+ if (data.length > 0) {
74
+ yield data;
75
+ }
76
+ }
77
+ var findDoubleNewlineIndex = (buffer) => {
78
+ const newline = 10;
79
+ const carriage = 13;
80
+ for (let i = 0; i < buffer.length - 2; i++) {
81
+ if (buffer[i] === newline && buffer[i + 1] === newline) {
82
+ return i + 2;
83
+ }
84
+ if (buffer[i] === carriage && buffer[i + 1] === carriage) {
85
+ return i + 2;
86
+ }
87
+ if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) {
88
+ return i + 4;
89
+ }
90
+ }
91
+ return -1;
92
+ };
93
+ var SSEDecoder = class {
94
+ constructor() {
95
+ this.event = null;
96
+ this.data = [];
97
+ this.chunks = [];
98
+ }
99
+ decode(line) {
100
+ if (line.endsWith("\r")) {
101
+ line = line.substring(0, line.length - 1);
102
+ }
103
+ if (!line) {
104
+ if (!this.event && !this.data.length) {
105
+ return null;
106
+ }
107
+ const sse = {
108
+ event: this.event,
109
+ data: this.data.join("\n"),
110
+ raw: this.chunks
111
+ };
112
+ this.event = null;
113
+ this.data = [];
114
+ this.chunks = [];
115
+ return sse;
116
+ }
117
+ this.chunks.push(line);
118
+ if (line.startsWith(":")) {
119
+ return null;
120
+ }
121
+ let [fieldname, _, value] = partition(line, ":");
122
+ if (value.startsWith(" ")) {
123
+ value = value.substring(1);
124
+ }
125
+ if (fieldname === "event") {
126
+ this.event = value;
127
+ } else if (fieldname === "data") {
128
+ this.data.push(value);
129
+ }
130
+ return null;
131
+ }
132
+ };
133
+ var partition = (str, delimiter) => {
134
+ const index = str.indexOf(delimiter);
135
+ if (index !== -1) {
136
+ return [
137
+ str.substring(0, index),
138
+ delimiter,
139
+ str.substring(index + delimiter.length)
140
+ ];
141
+ }
142
+ return [
143
+ str,
144
+ "",
145
+ ""
146
+ ];
147
+ };
148
+ function readableStreamAsyncIterable(stream) {
149
+ if (stream[Symbol.asyncIterator]) {
150
+ return stream;
151
+ }
152
+ const reader = stream.getReader();
153
+ return {
154
+ next: async () => {
155
+ try {
156
+ const result = await reader.read();
157
+ if (result?.done) {
158
+ reader.releaseLock();
159
+ }
160
+ return result;
161
+ } catch (e) {
162
+ reader.releaseLock();
163
+ throw e;
164
+ }
165
+ },
166
+ return: async () => {
167
+ const cancelPromise = reader.cancel();
168
+ reader.releaseLock();
169
+ await cancelPromise;
170
+ return {
171
+ done: true,
172
+ value: void 0
173
+ };
174
+ },
175
+ [Symbol.asyncIterator]() {
176
+ return this;
177
+ }
178
+ };
179
+ }
180
+ var LineDecoder = class _LineDecoder {
181
+ static {
182
+ // prettier-ignore
183
+ this.NEWLINE_CHARS = /* @__PURE__ */ new Set([
184
+ "\n",
185
+ "\r"
186
+ ]);
187
+ }
188
+ static {
189
+ this.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
190
+ }
191
+ constructor() {
192
+ this.buffer = [];
193
+ this.trailingCR = false;
194
+ }
195
+ decode(chunk) {
196
+ let text = this.decodeText(chunk);
197
+ if (this.trailingCR) {
198
+ text = "\r" + text;
199
+ this.trailingCR = false;
200
+ }
201
+ if (text.endsWith("\r")) {
202
+ this.trailingCR = true;
203
+ text = text.slice(0, -1);
204
+ }
205
+ if (!text) {
206
+ return [];
207
+ }
208
+ const trailingNewline = _LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || "");
209
+ let lines = text.split(_LineDecoder.NEWLINE_REGEXP);
210
+ if (trailingNewline) {
211
+ lines.pop();
212
+ }
213
+ if (lines.length === 1 && !trailingNewline) {
214
+ this.buffer.push(lines[0]);
215
+ return [];
216
+ }
217
+ if (this.buffer.length > 0) {
218
+ lines = [
219
+ this.buffer.join("") + lines[0],
220
+ ...lines.slice(1)
221
+ ];
222
+ this.buffer = [];
223
+ }
224
+ if (!trailingNewline) {
225
+ this.buffer = [
226
+ lines.pop() || ""
227
+ ];
228
+ }
229
+ return lines;
230
+ }
231
+ decodeText(bytes) {
232
+ if (bytes == null) {
233
+ return "";
234
+ }
235
+ if (typeof bytes === "string") {
236
+ return bytes;
237
+ }
238
+ if (typeof Buffer !== "undefined") {
239
+ if (bytes instanceof Buffer) {
240
+ return bytes.toString();
241
+ }
242
+ if (bytes instanceof Uint8Array) {
243
+ return Buffer.from(bytes).toString();
244
+ }
245
+ 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.`);
246
+ }
247
+ if (typeof TextDecoder !== "undefined") {
248
+ if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
249
+ this.textDecoder ??= new TextDecoder("utf8");
250
+ return this.textDecoder.decode(bytes);
251
+ }
252
+ throw new Error(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
253
+ }
254
+ throw new Error("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.");
255
+ }
256
+ flush() {
257
+ if (!this.buffer.length && !this.trailingCR) {
258
+ return [];
259
+ }
260
+ const lines = [
261
+ this.buffer.join("")
262
+ ];
263
+ this.buffer = [];
264
+ this.trailingCR = false;
265
+ return lines;
266
+ }
267
+ };
268
+
269
+ // packages/experimental/assistant/src/ai-service/stream.ts
270
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/stream.ts";
271
+ var createGenerationStream = (response, controller = new AbortController()) => {
272
+ const iterator = async function* () {
273
+ for await (const sse of iterSSEMessages(response, controller)) {
274
+ if (sse.event === "completion") {
275
+ try {
276
+ yield JSON.parse(sse.data);
277
+ } catch (err) {
278
+ log.error("could not parse message into JSON:", {
279
+ data: sse.data,
280
+ raw: sse.raw
281
+ }, {
282
+ F: __dxlog_file,
283
+ L: 22,
284
+ S: this,
285
+ C: (f, a) => f(...a)
286
+ });
287
+ throw err;
288
+ }
289
+ }
290
+ 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") {
291
+ try {
292
+ yield JSON.parse(sse.data);
293
+ } catch (err) {
294
+ log.error("could not parse message into JSON:", {
295
+ data: sse.data,
296
+ raw: sse.raw
297
+ }, {
298
+ F: __dxlog_file,
299
+ L: 38,
300
+ S: this,
301
+ C: (f, a) => f(...a)
302
+ });
303
+ throw err;
304
+ }
305
+ }
306
+ if (sse.event === "ping") {
307
+ continue;
308
+ }
309
+ if (sse.event === "error") {
310
+ throw new Error(`Message generation error: ${sse.data}`);
311
+ }
312
+ }
313
+ };
314
+ return new GenerationStreamImpl(controller, iterator);
315
+ };
316
+ var GenerationStreamImpl = class {
317
+ constructor(_controller, _getIterator) {
318
+ this._controller = _controller;
319
+ this._getIterator = _getIterator;
320
+ this._done = new Trigger();
321
+ this._iterator = void 0;
322
+ }
323
+ /**
324
+ * Returns an iterator over the stream.
325
+ */
326
+ [Symbol.asyncIterator]() {
327
+ return this._createIterator();
328
+ }
329
+ /**
330
+ * Aborts the stream.
331
+ */
332
+ abort() {
333
+ this._controller.abort();
334
+ }
335
+ /**
336
+ * Returns the complete message list generated by the AI service.
337
+ */
338
+ async complete() {
339
+ await this._done.wait();
340
+ }
341
+ /**
342
+ * Creates an iterator over the stream.
343
+ */
344
+ _createIterator() {
345
+ const self = this;
346
+ return this._iterator ??= (() => {
347
+ const generator = async function* () {
348
+ try {
349
+ for await (const event of self._getIterator()) {
350
+ yield event;
351
+ }
352
+ this._done.wake();
353
+ } catch (err) {
354
+ this._done.throw(err);
355
+ throw err;
356
+ }
357
+ };
358
+ return generator.call(this);
359
+ })();
360
+ }
361
+ };
362
+
363
+ // packages/experimental/assistant/src/ai-service/edge-client.ts
364
+ import { Schema as S } from "effect";
365
+ import { Message } from "@dxos/artifact";
366
+ import { invariant } from "@dxos/invariant";
367
+ import { log as log2 } from "@dxos/log";
368
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/edge-client.ts";
369
+ var AIServiceEdgeClient = class {
370
+ constructor({ endpoint }) {
371
+ invariant(endpoint, "endpoint is required", {
372
+ F: __dxlog_file2,
373
+ L: 23,
374
+ S: this,
375
+ A: [
376
+ "endpoint",
377
+ "'endpoint is required'"
378
+ ]
379
+ });
380
+ this._endpoint = endpoint;
381
+ }
382
+ /**
383
+ * @deprecated
384
+ */
385
+ // TODO(burdon): Remove.
386
+ async appendMessages(messages) {
387
+ const url = `${this._endpoint}/message`;
388
+ const res = await fetch(url, {
389
+ method: "POST",
390
+ headers: {
391
+ "Content-Type": "application/json"
392
+ },
393
+ body: JSON.stringify({
394
+ messages: await S.encodePromise(S.Array(Message))(messages)
395
+ })
396
+ });
397
+ if (!res.ok) {
398
+ throw new Error(`${await res.text()} [${url}]`);
399
+ }
400
+ }
401
+ /**
402
+ * Process request and open message stream.
403
+ */
404
+ async exec(request) {
405
+ log2.info("requesting", {
406
+ endpoint: this._endpoint
407
+ }, {
408
+ F: __dxlog_file2,
409
+ L: 50,
410
+ S: this,
411
+ C: (f, a) => f(...a)
412
+ });
413
+ const controller = new AbortController();
414
+ const response = await fetch(`${this._endpoint}/generate`, {
415
+ signal: controller.signal,
416
+ method: "POST",
417
+ headers: {
418
+ "Content-Type": "application/json"
419
+ },
420
+ body: JSON.stringify({
421
+ // TODO(dmaretskyi): Errors if tools are not provided.
422
+ tools: request.tools ?? [],
423
+ ...request
424
+ })
425
+ });
426
+ invariant(response.body instanceof ReadableStream, void 0, {
427
+ F: __dxlog_file2,
428
+ L: 63,
429
+ S: this,
430
+ A: [
431
+ "response.body instanceof ReadableStream",
432
+ ""
433
+ ]
434
+ });
435
+ return createGenerationStream(response, controller);
436
+ }
437
+ };
438
+
439
+ // packages/experimental/assistant/src/ai-service/message-collector.ts
440
+ var MessageCollector = class {
441
+ constructor() {
442
+ this._messages = [];
443
+ this._pendingMessage = void 0;
444
+ }
445
+ get messages() {
446
+ return this._messages;
447
+ }
448
+ get pendingMessage() {
449
+ return this._pendingMessage;
450
+ }
451
+ push(event) {
452
+ switch (event.type) {
453
+ case "message_start":
454
+ this._pendingMessage = event.message;
455
+ break;
456
+ case "message_stop":
457
+ if (this._pendingMessage) {
458
+ this._messages.push(this._pendingMessage);
459
+ this._pendingMessage = void 0;
460
+ }
461
+ break;
462
+ case "content_block_start":
463
+ if (this._pendingMessage) {
464
+ this._pendingMessage.content = this._pendingMessage.content || [];
465
+ this._pendingMessage.content[event.index] = event.content;
466
+ }
467
+ break;
468
+ case "content_block_delta":
469
+ if (this._pendingMessage && this._pendingMessage.content) {
470
+ const block = this._pendingMessage.content[event.index];
471
+ if (block && event.delta.type === "text_delta" && block.type === "text") {
472
+ block.text = (block.text || "") + event.delta.text;
473
+ }
474
+ }
475
+ break;
476
+ case "content_block_stop":
477
+ if (this._pendingMessage && this._pendingMessage.content) {
478
+ const block = this._pendingMessage.content[event.index];
479
+ if (block) {
480
+ block.pending = false;
481
+ }
482
+ }
483
+ break;
484
+ case "message_delta":
485
+ if (this._pendingMessage && event.delta) {
486
+ Object.assign(this._pendingMessage, event.delta);
487
+ }
488
+ break;
489
+ }
490
+ }
491
+ pushMessage(message) {
492
+ this._messages.push(message);
493
+ }
494
+ };
495
+ function* emitMessageAsEvents(message) {
496
+ yield {
497
+ type: "message_start",
498
+ message
499
+ };
500
+ yield {
501
+ type: "message_stop"
502
+ };
503
+ }
504
+
505
+ // packages/experimental/assistant/src/ai-service/types.ts
506
+ import { Schema as S2 } from "effect";
507
+ import { Tool, Message as Message2, SpaceIdSchema } from "@dxos/artifact";
508
+ import { ObjectId } from "@dxos/echo-schema";
509
+ var createArtifactElement = (id) => `<artifact id=${id} />`;
510
+ var LLMModel = S2.Literal(...DEFAULT_EDGE_MODELS);
511
+ var ToolTypes = Object.freeze({
512
+ // TODO(dmaretskyi): Not implemented yet.
513
+ // DatabaseQuery: 'database_query',
514
+ TextToImage: "text_to_image"
515
+ });
516
+ var GenerateRequest = S2.Struct({
517
+ spaceId: S2.optional(SpaceIdSchema),
518
+ threadId: S2.optional(ObjectId),
519
+ /**
520
+ * Preferred model or system default.
521
+ */
522
+ model: S2.optional(LLMModel),
523
+ /**
524
+ * Tools available for the LLM.
525
+ */
526
+ tools: S2.optional(S2.Array(Tool).pipe(S2.mutable)),
527
+ /**
528
+ * System instructions to the LLM.
529
+ */
530
+ systemPrompt: S2.optional(S2.String),
531
+ /**
532
+ * History of messages to include in the context window.
533
+ */
534
+ // TODO(burdon): Rename messages.
535
+ history: S2.optional(S2.Array(Message2)),
536
+ /**
537
+ * Current request.
538
+ */
539
+ prompt: S2.optional(Message2)
540
+ });
541
+
542
+ // packages/experimental/assistant/src/conversation/conversation.ts
543
+ import { ToolResult, Message as Message3 } from "@dxos/artifact";
544
+ import { createStatic, ObjectId as ObjectId2 } from "@dxos/echo-schema";
545
+ import { invariant as invariant2 } from "@dxos/invariant";
546
+ import { log as log3 } from "@dxos/log";
547
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/conversation/conversation.ts";
548
+ var runLLM = async (params) => {
549
+ let conversationResult = null;
550
+ const history = params.history ?? [];
551
+ const generate = async () => {
552
+ log3("llm generate", {
553
+ tools: params.tools
554
+ }, {
555
+ F: __dxlog_file3,
556
+ L: 44,
557
+ S: void 0,
558
+ C: (f, a) => f(...a)
559
+ });
560
+ const beginTs = Date.now();
561
+ const stream = await params.client.exec({
562
+ model: params.model,
563
+ spaceId: params.spaceId,
564
+ threadId: params.threadId,
565
+ history,
566
+ systemPrompt: params.system,
567
+ tools: params.tools
568
+ });
569
+ for await (const event of stream) {
570
+ params.logger?.(event);
571
+ }
572
+ await stream.complete();
573
+ const messages = [];
574
+ const message = messages.at(-1);
575
+ invariant2(message, void 0, {
576
+ F: __dxlog_file3,
577
+ L: 63,
578
+ S: void 0,
579
+ A: [
580
+ "message",
581
+ ""
582
+ ]
583
+ });
584
+ log3("llm result", {
585
+ time: Date.now() - beginTs,
586
+ message
587
+ }, {
588
+ F: __dxlog_file3,
589
+ L: 65,
590
+ S: void 0,
591
+ C: (f, a) => f(...a)
592
+ });
593
+ invariant2(message, void 0, {
594
+ F: __dxlog_file3,
595
+ L: 66,
596
+ S: void 0,
597
+ A: [
598
+ "message",
599
+ ""
600
+ ]
601
+ });
602
+ params.logger?.({
603
+ type: "message",
604
+ message
605
+ });
606
+ history.push(...messages.map((message2) => ({
607
+ ...message2,
608
+ content: message2.content.filter((block) => block.type !== "image")
609
+ })));
610
+ const isToolUse2 = message.content.at(-1)?.type === "tool_use";
611
+ if (isToolUse2) {
612
+ const toolCalls = message.content.filter((block) => block.type === "tool_use");
613
+ invariant2(toolCalls.length === 1, void 0, {
614
+ F: __dxlog_file3,
615
+ L: 77,
616
+ S: void 0,
617
+ A: [
618
+ "toolCalls.length === 1",
619
+ ""
620
+ ]
621
+ });
622
+ const toolCall = toolCalls[0];
623
+ const tool = params.tools.find((tool2) => tool2.name === toolCall.name);
624
+ if (!tool) {
625
+ throw new Error(`Tool not found: ${toolCall.name}`);
626
+ }
627
+ invariant2(tool.execute, void 0, {
628
+ F: __dxlog_file3,
629
+ L: 84,
630
+ S: void 0,
631
+ A: [
632
+ "tool.execute",
633
+ ""
634
+ ]
635
+ });
636
+ const toolResult = await tool.execute(toolCall.input);
637
+ switch (toolResult.kind) {
638
+ case "error": {
639
+ log3.warn("tool error", {
640
+ message: toolResult.message
641
+ }, {
642
+ F: __dxlog_file3,
643
+ L: 88,
644
+ S: void 0,
645
+ C: (f, a) => f(...a)
646
+ });
647
+ const resultMessage = {
648
+ id: ObjectId2.random(),
649
+ spaceId: params.spaceId,
650
+ threadId: params.threadId,
651
+ role: "user",
652
+ content: [
653
+ {
654
+ type: "tool_result",
655
+ toolUseId: toolCall.id,
656
+ content: toolResult.message,
657
+ isError: true
658
+ }
659
+ ]
660
+ };
661
+ params.logger?.({
662
+ type: "message",
663
+ message: resultMessage
664
+ });
665
+ history.push(resultMessage);
666
+ return true;
667
+ }
668
+ case "success": {
669
+ log3("tool success", {
670
+ result: toolResult.result
671
+ }, {
672
+ F: __dxlog_file3,
673
+ L: 110,
674
+ S: void 0,
675
+ C: (f, a) => f(...a)
676
+ });
677
+ const resultMessage = {
678
+ id: ObjectId2.random(),
679
+ spaceId: params.spaceId,
680
+ threadId: params.threadId,
681
+ role: "user",
682
+ content: [
683
+ {
684
+ type: "tool_result",
685
+ toolUseId: toolCall.id,
686
+ content: JSON.stringify(toolResult.result)
687
+ }
688
+ ]
689
+ };
690
+ params.logger?.({
691
+ type: "message",
692
+ message: resultMessage
693
+ });
694
+ history.push(resultMessage);
695
+ return true;
696
+ }
697
+ case "break": {
698
+ log3("tool break", {
699
+ result: toolResult.result
700
+ }, {
701
+ F: __dxlog_file3,
702
+ L: 131,
703
+ S: void 0,
704
+ C: (f, a) => f(...a)
705
+ });
706
+ conversationResult = toolResult.result;
707
+ return false;
708
+ }
709
+ }
710
+ }
711
+ return false;
712
+ };
713
+ while (await generate()) {
714
+ }
715
+ return {
716
+ result: conversationResult,
717
+ history
718
+ };
719
+ };
720
+ var isToolUse = (message, { onlyToolNames } = {}) => {
721
+ const block = message.content.at(-1);
722
+ invariant2(block, void 0, {
723
+ F: __dxlog_file3,
724
+ L: 152,
725
+ S: void 0,
726
+ A: [
727
+ "block",
728
+ ""
729
+ ]
730
+ });
731
+ return block.type === "tool_use" && (!onlyToolNames || onlyToolNames.includes(block.name));
732
+ };
733
+ var runTools = async ({ message, tools, extensions }) => {
734
+ const toolCalls = message.content.filter((block) => block.type === "tool_use");
735
+ invariant2(toolCalls.length === 1, void 0, {
736
+ F: __dxlog_file3,
737
+ L: 174,
738
+ S: void 0,
739
+ A: [
740
+ "toolCalls.length === 1",
741
+ ""
742
+ ]
743
+ });
744
+ const toolCall = toolCalls[0];
745
+ const tool = tools.find((tool2) => tool2.name === toolCall.name);
746
+ if (!tool) {
747
+ throw new Error(`Tool not found: ${toolCall.name}`);
748
+ }
749
+ let toolResult;
750
+ try {
751
+ invariant2(tool.execute, void 0, {
752
+ F: __dxlog_file3,
753
+ L: 183,
754
+ S: void 0,
755
+ A: [
756
+ "tool.execute",
757
+ ""
758
+ ]
759
+ });
760
+ toolResult = await tool.execute(toolCall.input, {
761
+ extensions
762
+ });
763
+ } catch (error) {
764
+ log3("tool error", {
765
+ error
766
+ }, {
767
+ F: __dxlog_file3,
768
+ L: 186,
769
+ S: void 0,
770
+ C: (f, a) => f(...a)
771
+ });
772
+ toolResult = ToolResult.Error(error.message);
773
+ }
774
+ switch (toolResult.kind) {
775
+ case "error": {
776
+ log3("tool error", {
777
+ message: toolResult.message
778
+ }, {
779
+ F: __dxlog_file3,
780
+ L: 192,
781
+ S: void 0,
782
+ C: (f, a) => f(...a)
783
+ });
784
+ const resultMessage = createStatic(Message3, {
785
+ role: "user",
786
+ content: [
787
+ {
788
+ type: "tool_result",
789
+ toolUseId: toolCall.id,
790
+ content: toolResult.message,
791
+ isError: true
792
+ }
793
+ ]
794
+ });
795
+ return {
796
+ type: "continue",
797
+ message: resultMessage
798
+ };
799
+ }
800
+ case "success": {
801
+ log3("tool success", {
802
+ result: toolResult.result
803
+ }, {
804
+ F: __dxlog_file3,
805
+ L: 213,
806
+ S: void 0,
807
+ C: (f, a) => f(...a)
808
+ });
809
+ const resultMessage = createStatic(Message3, {
810
+ role: "user",
811
+ content: [
812
+ {
813
+ type: "tool_result",
814
+ toolUseId: toolCall.id,
815
+ content: typeof toolResult.result === "string" ? toolResult.result : JSON.stringify(toolResult.result) ?? ""
816
+ },
817
+ ...toolResult.extractContentBlocks ?? []
818
+ ]
819
+ });
820
+ return {
821
+ type: "continue",
822
+ message: resultMessage
823
+ };
824
+ }
825
+ case "break": {
826
+ log3("tool break", {
827
+ result: toolResult.result
828
+ }, {
829
+ F: __dxlog_file3,
830
+ L: 234,
831
+ S: void 0,
832
+ C: (f, a) => f(...a)
833
+ });
834
+ return {
835
+ type: "break",
836
+ result: toolResult.result
837
+ };
838
+ }
839
+ }
840
+ };
841
+
842
+ // packages/experimental/assistant/src/ai-service/ollama-client.ts
843
+ import { Schema as S3 } from "effect";
844
+ import { defineTool, ToolResult as ToolResult2 } from "@dxos/artifact";
845
+ import { ObjectId as ObjectId3 } from "@dxos/echo-schema";
846
+ import { invariant as invariant3 } from "@dxos/invariant";
847
+ import { log as log4 } from "@dxos/log";
848
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/ollama-client.ts";
849
+ var OllamaClient = class {
850
+ /**
851
+ * Check if Ollama server is running and accessible.
852
+ * @returns Promise that resolves to true if Ollama is running, false otherwise.
853
+ */
854
+ static async isRunning() {
855
+ try {
856
+ const response = await fetch(`${DEFAULT_OLLAMA_ENDPOINT}/api/version`, {
857
+ method: "GET",
858
+ headers: {
859
+ "Content-Type": "application/json"
860
+ },
861
+ signal: AbortSignal.timeout(100)
862
+ });
863
+ return response.ok;
864
+ } catch (error) {
865
+ return false;
866
+ }
867
+ }
868
+ constructor({ endpoint, tools, overrides, maxToolInvocations } = {}) {
869
+ this._endpoint = endpoint ?? DEFAULT_OLLAMA_ENDPOINT;
870
+ this._tools = tools ?? [];
871
+ this._modelOverride = overrides?.model;
872
+ this._temperatureOverride = overrides?.temperature;
873
+ this._maxToolInvocations = maxToolInvocations ?? 3;
874
+ }
875
+ _getEmbededTools(clientTools) {
876
+ return [
877
+ ...this._tools,
878
+ ...clientTools.filter((tool) => tool.type !== void 0 && WELL_KNOWN_TOOLS[tool.type]).map((tool) => WELL_KNOWN_TOOLS[tool.type])
879
+ ];
880
+ }
881
+ async *_generateStream(request, signal) {
882
+ invariant3(request.prompt === void 0, "Prompt must be in history", {
883
+ F: __dxlog_file4,
884
+ L: 88,
885
+ S: this,
886
+ A: [
887
+ "request.prompt === undefined",
888
+ "'Prompt must be in history'"
889
+ ]
890
+ });
891
+ const ollamaRequest = {
892
+ model: this._modelOverride ?? request.model ?? "llama3",
893
+ messages: [],
894
+ stream: true,
895
+ options: {
896
+ temperature: this._temperatureOverride
897
+ }
898
+ };
899
+ if (request.systemPrompt) {
900
+ ollamaRequest.messages.push({
901
+ role: "system",
902
+ content: request.systemPrompt
903
+ });
904
+ }
905
+ if (request.history?.length) {
906
+ for (const message of request.history) {
907
+ const role = message.role === "assistant" ? "assistant" : "user";
908
+ if (message.content.length === 0) {
909
+ continue;
910
+ }
911
+ for (const content of message.content) {
912
+ switch (content.type) {
913
+ case "text": {
914
+ ollamaRequest.messages.push({
915
+ role,
916
+ content: content.text
917
+ });
918
+ break;
919
+ }
920
+ case "tool_use": {
921
+ ollamaRequest.messages.push({
922
+ role: "assistant",
923
+ content: "",
924
+ tool_calls: [
925
+ {
926
+ function: {
927
+ name: content.name,
928
+ arguments: content.input
929
+ }
930
+ }
931
+ ]
932
+ });
933
+ break;
934
+ }
935
+ case "tool_result": {
936
+ ollamaRequest.messages.push({
937
+ role: "tool",
938
+ content: JSON.stringify({
939
+ type: "tool_result",
940
+ toolUseId: content.toolUseId,
941
+ content: content.content
942
+ })
943
+ });
944
+ break;
945
+ }
946
+ }
947
+ }
948
+ }
949
+ }
950
+ if (request.tools?.length || this._tools.length) {
951
+ const allTools = [
952
+ ...request.tools ?? [],
953
+ ...this._tools
954
+ ];
955
+ const withWellKnownTools = allTools.map((tool) => tool.type !== void 0 && WELL_KNOWN_TOOLS[tool.type] ? WELL_KNOWN_TOOLS[tool.type] : tool);
956
+ if (withWellKnownTools.length > 0) {
957
+ ollamaRequest.tools = withWellKnownTools.map((tool) => ({
958
+ type: "function",
959
+ function: {
960
+ name: tool.name,
961
+ description: tool.description,
962
+ parameters: {
963
+ type: "object",
964
+ properties: tool.parameters?.properties,
965
+ required: tool.parameters?.required
966
+ }
967
+ }
968
+ }));
969
+ }
970
+ }
971
+ log4.info("generate request", {
972
+ history: request.history,
973
+ prompt: request.prompt,
974
+ ollamaRequest
975
+ }, {
976
+ F: __dxlog_file4,
977
+ L: 182,
978
+ S: this,
979
+ C: (f, a) => f(...a)
980
+ });
981
+ const response = await fetch(`${this._endpoint}/api/chat`, {
982
+ method: "POST",
983
+ headers: {
984
+ "Content-Type": "application/json"
985
+ },
986
+ body: JSON.stringify(ollamaRequest),
987
+ signal
988
+ });
989
+ if (!response.ok) {
990
+ throw await parseErrorResponse(response);
991
+ }
992
+ if (!response.body) {
993
+ throw new Error("Ollama API returned no response body");
994
+ }
995
+ const reader = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new OllamaDecoderStream()).getReader();
996
+ try {
997
+ const messageId = ObjectId3.random();
998
+ yield {
999
+ type: "message_start",
1000
+ message: {
1001
+ id: messageId,
1002
+ role: "assistant",
1003
+ content: []
1004
+ }
1005
+ };
1006
+ const textBlock = {
1007
+ type: "text",
1008
+ text: ""
1009
+ };
1010
+ let currentBlockIndex = 0;
1011
+ yield {
1012
+ type: "content_block_start",
1013
+ index: currentBlockIndex,
1014
+ content: textBlock
1015
+ };
1016
+ while (true) {
1017
+ const { done, value: data } = await reader.read();
1018
+ if (done) {
1019
+ break;
1020
+ }
1021
+ log4.info("ollama data", {
1022
+ data
1023
+ }, {
1024
+ F: __dxlog_file4,
1025
+ L: 244,
1026
+ S: this,
1027
+ C: (f, a) => f(...a)
1028
+ });
1029
+ if (data.message?.content) {
1030
+ yield {
1031
+ type: "content_block_delta",
1032
+ index: 0,
1033
+ delta: {
1034
+ type: "text_delta",
1035
+ text: data.message.content
1036
+ }
1037
+ };
1038
+ }
1039
+ if (data.message?.tool_calls && data.message?.tool_calls?.length > 0) {
1040
+ if (data.message.tool_calls.length > 1) {
1041
+ log4.warn("Ollama returned multiple tool calls. Only the first one will be used.", void 0, {
1042
+ F: __dxlog_file4,
1043
+ L: 261,
1044
+ S: this,
1045
+ C: (f, a) => f(...a)
1046
+ });
1047
+ }
1048
+ yield {
1049
+ type: "content_block_stop",
1050
+ index: currentBlockIndex++
1051
+ };
1052
+ yield {
1053
+ type: "content_block_start",
1054
+ index: currentBlockIndex,
1055
+ content: {
1056
+ type: "tool_use",
1057
+ id: ObjectId3.random(),
1058
+ name: data.message.tool_calls[0].function.name,
1059
+ input: sanitizeToolArguments(data.message.tool_calls[0].function.arguments)
1060
+ }
1061
+ };
1062
+ yield {
1063
+ type: "message_delta",
1064
+ delta: {
1065
+ stopReason: "tool_use"
1066
+ }
1067
+ };
1068
+ }
1069
+ }
1070
+ yield {
1071
+ type: "content_block_stop",
1072
+ index: currentBlockIndex
1073
+ };
1074
+ yield {
1075
+ type: "message_stop"
1076
+ };
1077
+ } finally {
1078
+ reader.releaseLock();
1079
+ }
1080
+ }
1081
+ async exec(request) {
1082
+ const controller = new AbortController();
1083
+ try {
1084
+ return new GenerationStreamImpl(controller, async function* () {
1085
+ const collector = new MessageCollector();
1086
+ let toolInvocations = 0;
1087
+ while (true) {
1088
+ for await (const event of this._generateStream({
1089
+ ...request,
1090
+ history: [
1091
+ ...request.history ?? [],
1092
+ ...request.prompt ? [
1093
+ request.prompt
1094
+ ] : [],
1095
+ ...collector.messages
1096
+ ],
1097
+ prompt: void 0
1098
+ }, controller.signal)) {
1099
+ collector.push(event);
1100
+ yield event;
1101
+ }
1102
+ if (collector.messages.length > 0 && !isToolUse(collector.messages.at(-1), {
1103
+ onlyToolNames: this._getEmbededTools(request.tools ?? []).map((tool) => tool.name)
1104
+ })) {
1105
+ break;
1106
+ }
1107
+ if (++toolInvocations > this._maxToolInvocations) {
1108
+ throw new Error("Maximum number of tool invocations reached");
1109
+ }
1110
+ const result = await runTools({
1111
+ message: collector.messages.at(-1),
1112
+ tools: this._getEmbededTools(request.tools ?? [])
1113
+ });
1114
+ switch (result.type) {
1115
+ case "continue": {
1116
+ collector.pushMessage(result.message);
1117
+ yield* emitMessageAsEvents(result.message);
1118
+ break;
1119
+ }
1120
+ case "break": {
1121
+ throw new Error("Tool use breaks not allowed");
1122
+ }
1123
+ }
1124
+ }
1125
+ }.bind(this));
1126
+ } catch (error) {
1127
+ controller.abort();
1128
+ throw error;
1129
+ }
1130
+ }
1131
+ };
1132
+ var sanitizeToolArguments = (args) => {
1133
+ if (args.type === "object" && typeof args.properties === "object" && Array.isArray(args.required)) {
1134
+ return args.properties;
1135
+ }
1136
+ return args;
1137
+ };
1138
+ var SAMPLE_IMAGE_URL = "https://images.nightcafe.studio/jobs/BNmcRhHCM1JRKoUtqSei/BNmcRhHCM1JRKoUtqSei--1--5b9rv.jpg";
1139
+ var WELL_KNOWN_TOOLS = {
1140
+ [ToolTypes.TextToImage]: defineTool("system", {
1141
+ name: "text-to-image",
1142
+ description: "Generate an image from a text prompt",
1143
+ schema: S3.Struct({
1144
+ prompt: S3.String.annotations({
1145
+ description: "The text prompt describing the image to generate"
1146
+ })
1147
+ }),
1148
+ execute: async ({ prompt }) => {
1149
+ const image = await fetch(SAMPLE_IMAGE_URL).then(async (res) => Buffer.from(await res.arrayBuffer()));
1150
+ const imageBase64 = image.toString("base64");
1151
+ const id = ObjectId3.random();
1152
+ return ToolResult2.Success(`The generation was successful. Image ID: ${id} Prompt: ${prompt}`, [
1153
+ {
1154
+ type: "image",
1155
+ id,
1156
+ source: {
1157
+ type: "base64",
1158
+ mediaType: "image/jpeg",
1159
+ data: imageBase64
1160
+ }
1161
+ }
1162
+ ]);
1163
+ }
1164
+ })
1165
+ };
1166
+ var OllamaDecoderStream = class extends TransformStream {
1167
+ constructor() {
1168
+ super({
1169
+ transform: (chunk, controller) => {
1170
+ this._buffer += chunk;
1171
+ const lines = this._buffer.split("\n");
1172
+ this._buffer = lines.pop() || "";
1173
+ for (const line of lines) {
1174
+ controller.enqueue(JSON.parse(line.trim()));
1175
+ }
1176
+ },
1177
+ flush: (controller) => {
1178
+ this._buffer = this._buffer.trim();
1179
+ if (this._buffer.length > 0) {
1180
+ controller.enqueue(JSON.parse(this._buffer));
1181
+ }
1182
+ }
1183
+ });
1184
+ this._buffer = "";
1185
+ }
1186
+ };
1187
+ var ModelDoesNotSupportToolsError = class extends S3.TaggedError()("ModelDoesNotSupportToolsError", {
1188
+ model: S3.String
1189
+ }) {
1190
+ };
1191
+ var ModelNotFoundError = class extends S3.TaggedError()("ModelNotFoundError", {
1192
+ model: S3.String
1193
+ }) {
1194
+ };
1195
+ var parseOllamaError = (error) => {
1196
+ {
1197
+ const match = error.match(/^([^']+) does not support tools$/);
1198
+ if (match) {
1199
+ return new ModelDoesNotSupportToolsError({
1200
+ model: match[1]
1201
+ });
1202
+ }
1203
+ }
1204
+ {
1205
+ const match = error.match(/^model "([^"]+)" not found, try pulling it first$/);
1206
+ if (match) {
1207
+ return new ModelNotFoundError({
1208
+ model: match[1]
1209
+ });
1210
+ }
1211
+ }
1212
+ throw new Error(`Ollama API error: ${error}`);
1213
+ };
1214
+ var parseErrorResponse = async (response) => {
1215
+ if (response.headers.get("content-type")?.includes("application/json")) {
1216
+ const body = await response.json();
1217
+ return parseOllamaError(body.error);
1218
+ }
1219
+ throw new Error(`Ollama API error: ${response.status} ${response.statusText} ${await response.text()}`);
1220
+ };
1221
+
1222
+ // packages/experimental/assistant/src/ai-service/transform.ts
1223
+ import * as P from "parsimmon";
1224
+ var textChunk = P.regexp(/[^<]+/).map((content) => ({
1225
+ type: "text",
1226
+ content
1227
+ }));
1228
+ 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]) => [
1229
+ name,
1230
+ value
1231
+ ]);
1232
+ var tagName = P.regexp(/[a-zA-Z_][a-zA-Z0-9_-]*/);
1233
+ var selfClosingTag = P.seqMap(
1234
+ //
1235
+ P.string("<"),
1236
+ tagName,
1237
+ P.optWhitespace.then(attribute).many(),
1238
+ P.optWhitespace.then(P.string("/>")),
1239
+ P.optWhitespace,
1240
+ (_, tag, attributes, __) => ({
1241
+ type: "tag",
1242
+ tag,
1243
+ attributes: Object.fromEntries(attributes),
1244
+ content: [],
1245
+ selfClosing: true
1246
+ })
1247
+ );
1248
+ var openTag = P.seqMap(
1249
+ //
1250
+ P.string("<"),
1251
+ tagName,
1252
+ P.optWhitespace.then(attribute).many(),
1253
+ P.string(">"),
1254
+ P.regexp(/[^<]*/),
1255
+ (_, tag, attributes, __, content) => ({
1256
+ type: "tag",
1257
+ tag,
1258
+ attributes: Object.fromEntries(attributes),
1259
+ content: content.length ? [
1260
+ {
1261
+ type: "text",
1262
+ content
1263
+ }
1264
+ ] : []
1265
+ })
1266
+ );
1267
+ var closeTag = P.seqMap(
1268
+ //
1269
+ P.string("</"),
1270
+ tagName,
1271
+ P.string(">"),
1272
+ P.optWhitespace,
1273
+ (_, tag) => ({
1274
+ type: "tag",
1275
+ tag,
1276
+ content: [],
1277
+ closing: true
1278
+ })
1279
+ );
1280
+ var mixedChunk = P.alt(selfClosingTag, openTag, closeTag, textChunk);
1281
+ var StreamTransform = class {
1282
+ constructor() {
1283
+ this._buffer = "";
1284
+ }
1285
+ transform(chunk) {
1286
+ this._buffer += chunk;
1287
+ const results = [];
1288
+ const parser = mixedChunk.many().skip(P.optWhitespace);
1289
+ const result = parser.parse(this._buffer);
1290
+ if (result.status) {
1291
+ for (const chunk2 of result.value) {
1292
+ results.push(chunk2);
1293
+ }
1294
+ this._buffer = "";
1295
+ }
1296
+ return results;
1297
+ }
1298
+ // TODO(burdon): Process remaining buffer?
1299
+ flush() {
1300
+ const remaining = this._buffer;
1301
+ this._buffer = "";
1302
+ return remaining.length > 0 ? [
1303
+ {
1304
+ type: "text",
1305
+ content: remaining
1306
+ }
1307
+ ] : [];
1308
+ }
1309
+ };
1310
+
1311
+ // packages/experimental/assistant/src/ai-service/parser.ts
1312
+ import { Message as Message4 } from "@dxos/artifact";
1313
+ import { Event } from "@dxos/async";
1314
+ import { createStatic as createStatic2 } from "@dxos/echo-schema";
1315
+ import { invariant as invariant4 } from "@dxos/invariant";
1316
+ import { log as log5 } from "@dxos/log";
1317
+ import { isNotFalsy, safeParseJson } from "@dxos/util";
1318
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/parser.ts";
1319
+ var MixedStreamParser = class {
1320
+ constructor() {
1321
+ /**
1322
+ * New message.
1323
+ */
1324
+ this.message = new Event();
1325
+ /**
1326
+ * Complete block added to Message.
1327
+ */
1328
+ this.block = new Event();
1329
+ /**
1330
+ * Update partial block (while streaming).
1331
+ */
1332
+ this.update = new Event();
1333
+ this.streamEvent = new Event();
1334
+ }
1335
+ _emitBlock(contentBlock, streamBlock) {
1336
+ const messageBlock = streamBlock ? mergeMessageBlock(contentBlock, streamBlock) : contentBlock;
1337
+ if (messageBlock) {
1338
+ if (messageBlock.type === "text" && messageBlock.text.length === 0) {
1339
+ return;
1340
+ }
1341
+ invariant4(this._message, void 0, {
1342
+ F: __dxlog_file5,
1343
+ L: 49,
1344
+ S: this,
1345
+ A: [
1346
+ "this._message",
1347
+ ""
1348
+ ]
1349
+ });
1350
+ this._message.content.push(messageBlock);
1351
+ this.block.emit(messageBlock);
1352
+ }
1353
+ }
1354
+ _emitUpdate(contentBlock, streamBlock) {
1355
+ const messageBlock = mergeMessageBlock(contentBlock, streamBlock);
1356
+ if (messageBlock) {
1357
+ messageBlock.pending = true;
1358
+ this.update.emit(messageBlock);
1359
+ }
1360
+ }
1361
+ /**
1362
+ * Parse stream until end.
1363
+ */
1364
+ async parse(stream) {
1365
+ const transformer = new StreamTransform();
1366
+ let contentBlock;
1367
+ let streamBlock;
1368
+ const stack = [];
1369
+ const messagesCollected = [];
1370
+ for await (const event of stream) {
1371
+ this.streamEvent.emit(event);
1372
+ switch (event.type) {
1373
+ //
1374
+ // Messages.
1375
+ //
1376
+ case "message_start": {
1377
+ if (this._message) {
1378
+ log5.warn("unexpected message_start", void 0, {
1379
+ F: __dxlog_file5,
1380
+ L: 93,
1381
+ S: this,
1382
+ C: (f, a) => f(...a)
1383
+ });
1384
+ }
1385
+ this._message = createStatic2(Message4, {
1386
+ role: event.message.role,
1387
+ content: [
1388
+ ...event.message.content
1389
+ ]
1390
+ });
1391
+ this.message.emit(this._message);
1392
+ break;
1393
+ }
1394
+ case "message_delta": {
1395
+ if (!this._message) {
1396
+ log5.warn("unexpected message_delta", void 0, {
1397
+ F: __dxlog_file5,
1398
+ L: 103,
1399
+ S: this,
1400
+ C: (f, a) => f(...a)
1401
+ });
1402
+ }
1403
+ break;
1404
+ }
1405
+ case "message_stop": {
1406
+ if (!this._message) {
1407
+ log5.warn("unexpected message_stop", void 0, {
1408
+ F: __dxlog_file5,
1409
+ L: 111,
1410
+ S: this,
1411
+ C: (f, a) => f(...a)
1412
+ });
1413
+ } else {
1414
+ messagesCollected.push(this._message);
1415
+ this._message = void 0;
1416
+ }
1417
+ break;
1418
+ }
1419
+ //
1420
+ // Content blocks.
1421
+ //
1422
+ case "content_block_start": {
1423
+ if (contentBlock) {
1424
+ log5.warn("unexpected content_block_start", {
1425
+ content: contentBlock
1426
+ }, {
1427
+ F: __dxlog_file5,
1428
+ L: 125,
1429
+ S: this,
1430
+ C: (f, a) => f(...a)
1431
+ });
1432
+ }
1433
+ contentBlock = event.content;
1434
+ break;
1435
+ }
1436
+ case "content_block_delta": {
1437
+ if (!contentBlock) {
1438
+ log5.warn("unexpected content_block_delta", void 0, {
1439
+ F: __dxlog_file5,
1440
+ L: 135,
1441
+ S: this,
1442
+ C: (f, a) => f(...a)
1443
+ });
1444
+ break;
1445
+ }
1446
+ switch (event.delta.type) {
1447
+ //
1448
+ // Text
1449
+ //
1450
+ case "text_delta": {
1451
+ const chunks = transformer.transform(event.delta.text);
1452
+ for (const chunk of chunks) {
1453
+ switch (streamBlock?.type) {
1454
+ //
1455
+ // XML Fragment.
1456
+ //
1457
+ case "tag": {
1458
+ if (chunk.type === "tag") {
1459
+ if (chunk.selfClosing) {
1460
+ streamBlock.content.push(chunk);
1461
+ } else if (chunk.closing) {
1462
+ if (stack.length > 0) {
1463
+ const top = stack.pop();
1464
+ invariant4(top && top.type === "tag", void 0, {
1465
+ F: __dxlog_file5,
1466
+ L: 159,
1467
+ S: this,
1468
+ A: [
1469
+ "top && top.type === 'tag'",
1470
+ ""
1471
+ ]
1472
+ });
1473
+ top.content.push(streamBlock);
1474
+ streamBlock = top;
1475
+ } else {
1476
+ this._emitBlock(contentBlock, streamBlock);
1477
+ streamBlock = void 0;
1478
+ }
1479
+ } else {
1480
+ stack.push(streamBlock);
1481
+ streamBlock = chunk;
1482
+ }
1483
+ } else {
1484
+ if (streamBlock.content.length === 0) {
1485
+ streamBlock.content.push(chunk);
1486
+ } else {
1487
+ const last = streamBlock.content.at(-1);
1488
+ invariant4(last, void 0, {
1489
+ F: __dxlog_file5,
1490
+ L: 176,
1491
+ S: this,
1492
+ A: [
1493
+ "last",
1494
+ ""
1495
+ ]
1496
+ });
1497
+ if (last.type === "text") {
1498
+ last.content += chunk.content;
1499
+ } else {
1500
+ streamBlock.content.push(chunk);
1501
+ }
1502
+ }
1503
+ }
1504
+ break;
1505
+ }
1506
+ //
1507
+ // Text Fragment.
1508
+ //
1509
+ case "text": {
1510
+ if (chunk.type === "tag") {
1511
+ this._emitBlock(contentBlock, streamBlock);
1512
+ if (chunk.selfClosing) {
1513
+ this._emitBlock(contentBlock, chunk);
1514
+ streamBlock = void 0;
1515
+ } else {
1516
+ streamBlock = chunk;
1517
+ }
1518
+ } else {
1519
+ streamBlock.content += chunk.content;
1520
+ }
1521
+ break;
1522
+ }
1523
+ //
1524
+ // No current chunk.
1525
+ //
1526
+ default: {
1527
+ if (chunk.type === "tag" && chunk.selfClosing) {
1528
+ this._emitBlock(contentBlock, chunk);
1529
+ } else {
1530
+ streamBlock = chunk;
1531
+ }
1532
+ }
1533
+ }
1534
+ }
1535
+ break;
1536
+ }
1537
+ //
1538
+ // JSON
1539
+ //
1540
+ case "input_json_delta": {
1541
+ if (!contentBlock) {
1542
+ log5.warn("unexpected input_json_delta", {
1543
+ contentBlock
1544
+ }, {
1545
+ F: __dxlog_file5,
1546
+ L: 226,
1547
+ S: this,
1548
+ C: (f, a) => f(...a)
1549
+ });
1550
+ break;
1551
+ }
1552
+ if (streamBlock?.type === "json") {
1553
+ streamBlock.content += event.delta.partial_json;
1554
+ } else {
1555
+ streamBlock = {
1556
+ type: "json",
1557
+ content: event.delta.partial_json
1558
+ };
1559
+ }
1560
+ break;
1561
+ }
1562
+ }
1563
+ break;
1564
+ }
1565
+ case "content_block_stop": {
1566
+ if (!contentBlock) {
1567
+ log5.warn("unexpected content_block_stop", void 0, {
1568
+ F: __dxlog_file5,
1569
+ L: 243,
1570
+ S: this,
1571
+ C: (f, a) => f(...a)
1572
+ });
1573
+ break;
1574
+ }
1575
+ this._emitBlock(contentBlock, streamBlock);
1576
+ contentBlock = void 0;
1577
+ streamBlock = void 0;
1578
+ break;
1579
+ }
1580
+ }
1581
+ if (contentBlock && streamBlock) {
1582
+ this._emitUpdate(contentBlock, streamBlock);
1583
+ }
1584
+ }
1585
+ return messagesCollected;
1586
+ }
1587
+ };
1588
+ var mergeMessageBlock = (contentBlock, streamBlock) => {
1589
+ log5("mergeMessageBlock", {
1590
+ contentBlock,
1591
+ streamBlock
1592
+ }, {
1593
+ F: __dxlog_file5,
1594
+ L: 270,
1595
+ S: void 0,
1596
+ C: (f, a) => f(...a)
1597
+ });
1598
+ switch (streamBlock.type) {
1599
+ //
1600
+ // Text
1601
+ //
1602
+ case "text": {
1603
+ return {
1604
+ ...contentBlock,
1605
+ type: "text",
1606
+ text: streamBlock.content
1607
+ };
1608
+ }
1609
+ //
1610
+ // XML
1611
+ //
1612
+ case "tag": {
1613
+ switch (streamBlock.tag) {
1614
+ case "cot": {
1615
+ const content = streamBlock.content.map((block) => {
1616
+ switch (block.type) {
1617
+ case "text":
1618
+ return block.content;
1619
+ default:
1620
+ return null;
1621
+ }
1622
+ }).filter(isNotFalsy).join("\n");
1623
+ return {
1624
+ ...contentBlock,
1625
+ type: "text",
1626
+ disposition: "cot",
1627
+ text: content
1628
+ };
1629
+ }
1630
+ case "artifact": {
1631
+ const { attributes } = streamBlock;
1632
+ return {
1633
+ type: "json",
1634
+ disposition: "artifact",
1635
+ json: JSON.stringify(attributes)
1636
+ };
1637
+ }
1638
+ case "suggest": {
1639
+ if (streamBlock.content.length === 1 && streamBlock.content[0].type === "text") {
1640
+ return {
1641
+ type: "json",
1642
+ disposition: "suggest",
1643
+ json: JSON.stringify({
1644
+ text: streamBlock.content[0].content
1645
+ })
1646
+ };
1647
+ }
1648
+ break;
1649
+ }
1650
+ case "select": {
1651
+ return {
1652
+ type: "json",
1653
+ disposition: "select",
1654
+ json: JSON.stringify({
1655
+ options: streamBlock.content.flatMap((content) => content.type === "tag" && content.content.length === 1 && content.content[0].type === "text" ? [
1656
+ content.content[0].content
1657
+ ] : [])
1658
+ })
1659
+ };
1660
+ }
1661
+ case "tool-list": {
1662
+ return {
1663
+ type: "json",
1664
+ disposition: "tool_list",
1665
+ json: JSON.stringify({})
1666
+ };
1667
+ }
1668
+ }
1669
+ break;
1670
+ }
1671
+ //
1672
+ // JSON
1673
+ //
1674
+ case "json": {
1675
+ switch (contentBlock.type) {
1676
+ case "tool_use": {
1677
+ return {
1678
+ ...contentBlock,
1679
+ input: safeParseJson(streamBlock.content) ?? {}
1680
+ };
1681
+ }
1682
+ }
1683
+ return {
1684
+ ...contentBlock,
1685
+ type: "json",
1686
+ disposition: "artifact",
1687
+ json: streamBlock.content
1688
+ };
1689
+ }
1690
+ }
1691
+ };
1692
+
1693
+ // packages/experimental/assistant/src/cypher/parjs.ts
1694
+ import { parjsCombinators, parjs } from "#parjs";
1695
+
1696
+ // packages/experimental/assistant/src/cypher/combinators.ts
1697
+ var ws = parjs.whitespace();
1698
+ var nothing = parjs.string("").pipe(parjsCombinators.map(() => null));
1699
+ var optional = (parser) => parser.pipe(parjsCombinators.recover(() => ({
1700
+ kind: "Soft"
1701
+ })), parjsCombinators.or(nothing));
1702
+ var keyword = (word) => parjs.string(word).pipe(parjsCombinators.map(() => word));
1703
+ var identifier = parjs.regexp(/[a-zA-Z_][a-zA-Z0-9_]*/).pipe(parjsCombinators.map((match) => ({
1704
+ astKind: "Identifier",
1705
+ name: match[0]
1706
+ })));
1707
+ var numberLiteral = parjs.regexp(/-?\d+(\.\d+)?/).pipe(parjsCombinators.map(Number));
1708
+ var stringLiteral = parjs.regexp(/"([^"]*)"|'([^']*)'/).pipe(parjsCombinators.map((match) => ({
1709
+ astKind: "StringLiteral",
1710
+ value: match[1] || match[2]
1711
+ })));
1712
+ var variableTag = identifier.pipe(parjsCombinators.map((variable) => variable)).expects("variable tag");
1713
+ var label = identifier.pipe(parjsCombinators.map((name) => name));
1714
+ var property = identifier.pipe(parjsCombinators.then(parjs.string(":"), ws, stringLiteral), parjsCombinators.map(([key, , , value]) => ({
1715
+ key,
1716
+ value
1717
+ })));
1718
+ var properties = property.pipe(parjsCombinators.manySepBy(","), parjsCombinators.between("{", "}"), parjsCombinators.map((properties2) => ({
1719
+ astKind: "Properties",
1720
+ properties: properties2
1721
+ })));
1722
+ var nodePattern = optional(variableTag).pipe(parjsCombinators.then(":"), parjsCombinators.then(ws, label, ws), parjsCombinators.then(optional(properties)), parjsCombinators.between("(", ")"), parjsCombinators.map(([[[variable], _, label2], properties2]) => ({
1723
+ astKind: "NodePattern",
1724
+ variable,
1725
+ label: label2,
1726
+ properties: properties2
1727
+ })));
1728
+ var relationshipPattern = optional(variableTag).pipe(parjsCombinators.then(":"), parjsCombinators.then(ws, label, ws), parjsCombinators.then(optional(properties)), parjsCombinators.between("[", "]"), parjsCombinators.map(([[[variable], _, label2], properties2]) => ({
1729
+ astKind: "RelationshipPattern",
1730
+ variable,
1731
+ label: label2,
1732
+ properties: properties2
1733
+ })));
1734
+ var graphPatternConnector = parjs.string("->").pipe(parjsCombinators.or("<-", "-"), parjsCombinators.map((x) => ({
1735
+ astKind: "GraphPatternConnector",
1736
+ direction: x
1737
+ })));
1738
+ var graphPattern = nodePattern.pipe(parjsCombinators.or(relationshipPattern), parjsCombinators.manySepBy(graphPatternConnector), parjsCombinators.map((segments) => ({
1739
+ astKind: "GraphPattern",
1740
+ segments
1741
+ })));
1742
+ var matchClause = keyword("MATCH").pipe(parjsCombinators.then(ws), parjsCombinators.then(graphPattern), parjsCombinators.map(([, pattern]) => ({
1743
+ astKind: "MatchClause",
1744
+ pattern
1745
+ })));
1746
+ var memberExpression = identifier.pipe(parjsCombinators.manySepBy("."), parjsCombinators.map((path) => ({
1747
+ astKind: "MemberExpression",
1748
+ path
1749
+ })));
1750
+ var equalsPredicate = memberExpression.pipe(parjsCombinators.then(ws, parjs.string("="), ws, stringLiteral), parjsCombinators.map(([left, , , , right]) => ({
1751
+ astKind: "EqualsPredicate",
1752
+ left,
1753
+ right
1754
+ })));
1755
+ var whereClause = keyword("WHERE").pipe(parjsCombinators.then(ws, equalsPredicate.pipe(parjsCombinators.between(ws, ws), parjsCombinators.manySepBy(parjs.string("AND"))), ws), parjsCombinators.map(([, , predicates]) => ({
1756
+ astKind: "WhereClause",
1757
+ predicates
1758
+ })));
1759
+ var returnClause = keyword("RETURN").pipe(parjsCombinators.then(ws, memberExpression.pipe(parjsCombinators.then(optional(parjs.string("AS").pipe(parjsCombinators.between(ws), parjsCombinators.then(identifier))), ws), parjsCombinators.manySepBy(parjs.string(",").pipe(parjsCombinators.then(ws)))), ws), parjsCombinators.map(([, , fields]) => ({
1760
+ astKind: "ReturnClause",
1761
+ fields: fields.map(([f]) => f)
1762
+ })));
1763
+ var cypherQuery = ws.pipe(parjsCombinators.then(matchClause, ws, optional(whereClause), ws, returnClause, ws), parjsCombinators.map(([, matchClause2, , whereClause2, , returnClause2]) => ({
1764
+ astKind: "CypherQuery",
1765
+ matchClause: matchClause2,
1766
+ whereClause: whereClause2,
1767
+ returnClause: returnClause2
1768
+ })));
1769
+
1770
+ // packages/experimental/assistant/src/cypher/parser.ts
1771
+ var parseCypherQuery = (query) => {
1772
+ const parseResult = cypherQuery.parse(query);
1773
+ if (parseResult.isOk) {
1774
+ return {
1775
+ ast: parseResult.value
1776
+ };
1777
+ } else {
1778
+ throw new Error(`Failed to parse query: ${parseResult}`);
1779
+ }
1780
+ };
1781
+
1782
+ // packages/experimental/assistant/src/cypher/query-executor.ts
1783
+ import { log as log7 } from "@dxos/log";
1784
+ import { mapValues } from "@dxos/util";
1785
+
1786
+ // packages/experimental/assistant/src/cypher/execution-plan.ts
1787
+ import { invariant as invariant5 } from "@dxos/invariant";
1788
+ import { log as log6 } from "@dxos/log";
1789
+ var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/cypher/execution-plan.ts";
1790
+ var createExecutionPlan = (query) => {
1791
+ return new ExecutionPlanBuilder().build(query);
1792
+ };
1793
+ var ExecutionPlanBuilder = class {
1794
+ constructor() {
1795
+ this.counter = 0;
1796
+ }
1797
+ newVariable() {
1798
+ return `anon_${this.counter++}`;
1799
+ }
1800
+ build(query) {
1801
+ log6("Creating execution plan for query", {
1802
+ query
1803
+ }, {
1804
+ F: __dxlog_file6,
1805
+ L: 76,
1806
+ S: this,
1807
+ C: (f, a) => f(...a)
1808
+ });
1809
+ return {
1810
+ steps: [
1811
+ ...this.createStepsForMatchClause(query.ast.matchClause),
1812
+ ...query.ast.whereClause ? this.createStepsForWhereClause(query.ast.whereClause) : [],
1813
+ ...this.createStepsForReturnClause(query.ast.returnClause)
1814
+ ],
1815
+ output: {
1816
+ fields: this.getOutputFields(query.ast.returnClause)
1817
+ }
1818
+ };
1819
+ }
1820
+ createStepsForMatchClause(match) {
1821
+ invariant5(match.pattern.segments.length > 0, void 0, {
1822
+ F: __dxlog_file6,
1823
+ L: 90,
1824
+ S: this,
1825
+ A: [
1826
+ "match.pattern.segments.length > 0",
1827
+ ""
1828
+ ]
1829
+ });
1830
+ const firstSegment = match.pattern.segments[0];
1831
+ invariant5(firstSegment.astKind === "NodePattern", void 0, {
1832
+ F: __dxlog_file6,
1833
+ L: 92,
1834
+ S: this,
1835
+ A: [
1836
+ "firstSegment.astKind === 'NodePattern'",
1837
+ ""
1838
+ ]
1839
+ });
1840
+ let lastNodeVariable = firstSegment.variable?.name ?? this.newVariable();
1841
+ const steps = [];
1842
+ steps.push({
1843
+ type: "NodeScan",
1844
+ label: firstSegment.label.name,
1845
+ into: lastNodeVariable
1846
+ });
1847
+ if (firstSegment.properties) {
1848
+ for (const property2 of firstSegment.properties.properties) {
1849
+ steps.push({
1850
+ type: "FilterByProperty",
1851
+ variable: lastNodeVariable,
1852
+ property: property2.key.name,
1853
+ value: property2.value.value
1854
+ });
1855
+ }
1856
+ }
1857
+ for (let i = 1; i < match.pattern.segments.length; i++) {
1858
+ const relationshipSegment = match.pattern.segments[i++];
1859
+ invariant5(relationshipSegment.astKind === "RelationshipPattern", void 0, {
1860
+ F: __dxlog_file6,
1861
+ L: 115,
1862
+ S: this,
1863
+ A: [
1864
+ "relationshipSegment.astKind === 'RelationshipPattern'",
1865
+ ""
1866
+ ]
1867
+ });
1868
+ const nodeSegment = match.pattern.segments[i];
1869
+ invariant5(nodeSegment.astKind === "NodePattern", void 0, {
1870
+ F: __dxlog_file6,
1871
+ L: 117,
1872
+ S: this,
1873
+ A: [
1874
+ "nodeSegment.astKind === 'NodePattern'",
1875
+ ""
1876
+ ]
1877
+ });
1878
+ const leftSeparator = match.pattern.segments.separators[i - 2];
1879
+ const rightSeparator = match.pattern.segments.separators[i - 1];
1880
+ const direction = getDirection(leftSeparator.direction, rightSeparator.direction);
1881
+ const relationshipVariable = relationshipSegment.variable?.name ?? this.newVariable();
1882
+ const nodeVariable = nodeSegment.variable?.name ?? this.newVariable();
1883
+ steps.push({
1884
+ type: "RelationshipScan",
1885
+ label: relationshipSegment.label.name,
1886
+ direction,
1887
+ anchor: lastNodeVariable,
1888
+ relationshipInto: relationshipVariable,
1889
+ nodeInto: nodeVariable
1890
+ });
1891
+ if (relationshipSegment.properties) {
1892
+ for (const property2 of relationshipSegment.properties.properties) {
1893
+ steps.push({
1894
+ type: "FilterByProperty",
1895
+ variable: relationshipVariable,
1896
+ property: property2.key.name,
1897
+ value: property2.value.value
1898
+ });
1899
+ }
1900
+ }
1901
+ if (nodeSegment.label) {
1902
+ steps.push({
1903
+ type: "FilterByLabel",
1904
+ variable: nodeVariable,
1905
+ label: nodeSegment.label.name
1906
+ });
1907
+ }
1908
+ if (nodeSegment.properties) {
1909
+ for (const property2 of nodeSegment.properties.properties) {
1910
+ steps.push({
1911
+ type: "FilterByProperty",
1912
+ variable: nodeVariable,
1913
+ property: property2.key.name,
1914
+ value: property2.value.value
1915
+ });
1916
+ }
1917
+ }
1918
+ lastNodeVariable = nodeVariable;
1919
+ }
1920
+ return steps;
1921
+ }
1922
+ createStepsForWhereClause(where) {
1923
+ return [];
1924
+ }
1925
+ createStepsForReturnClause(returnClause2) {
1926
+ return [
1927
+ {
1928
+ type: "ProduceResults",
1929
+ fields: returnClause2.fields.map((field) => ({
1930
+ name: field.path.map((p) => p.name).join("_"),
1931
+ variable: field.path[0].name,
1932
+ path: field.path.length > 1 ? field.path.slice(1).map((p) => p.name).join(".") : "$"
1933
+ }))
1934
+ }
1935
+ ];
1936
+ }
1937
+ getOutputFields(returnClause2) {
1938
+ return returnClause2.fields.map((field) => field.path.map((p) => p.name).join("_"));
1939
+ }
1940
+ };
1941
+ var getDirection = (left, right) => {
1942
+ if (left === "-" && right === "->") {
1943
+ return "out";
1944
+ } else if (left === "<-" && right === "-") {
1945
+ return "in";
1946
+ } else if (left === "-" && right === "-") {
1947
+ return "both";
1948
+ }
1949
+ throw new Error(`Invalid direction: ()${left}[]${right}()`);
1950
+ };
1951
+
1952
+ // packages/experimental/assistant/src/cypher/query-executor.ts
1953
+ var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/cypher/query-executor.ts";
1954
+ var executeQueryPlan = async (dataSource, plan) => {
1955
+ let buffer = [];
1956
+ const results = [];
1957
+ for (const step of plan.steps) {
1958
+ log7("begin step", {
1959
+ step
1960
+ }, {
1961
+ F: __dxlog_file7,
1962
+ L: 41,
1963
+ S: void 0,
1964
+ C: (f, a) => f(...a)
1965
+ });
1966
+ switch (step.type) {
1967
+ case "NodeScan": {
1968
+ const nodes = await dataSource.getNodes({
1969
+ label: step.label
1970
+ });
1971
+ buffer.push(...nodes.map((node) => ({
1972
+ [step.into]: node
1973
+ })));
1974
+ break;
1975
+ }
1976
+ case "FilterByLabel": {
1977
+ buffer = buffer.filter((item) => {
1978
+ const node = item[step.variable];
1979
+ return node && node.kind === "node" && node.label === step.label;
1980
+ });
1981
+ break;
1982
+ }
1983
+ case "FilterByProperty": {
1984
+ buffer = buffer.filter((item) => {
1985
+ const node = item[step.variable];
1986
+ return node && node.kind === "node" && node.properties[step.property] === step.value;
1987
+ });
1988
+ break;
1989
+ }
1990
+ case "RelationshipScan": {
1991
+ const relationships = await dataSource.getRelationships({
1992
+ label: step.label
1993
+ });
1994
+ for (const tuple of [
1995
+ ...buffer
1996
+ ]) {
1997
+ if (tuple[step.anchor].kind !== "node") {
1998
+ continue;
1999
+ }
2000
+ const filteredRelationships = relationships.filter((relationship) => {
2001
+ switch (step.direction) {
2002
+ case "in":
2003
+ return relationship.target.id === tuple[step.anchor].id;
2004
+ case "out":
2005
+ return relationship.source.id === tuple[step.anchor].id;
2006
+ case "both":
2007
+ return relationship.source.id === tuple[step.anchor].id || relationship.target.id === tuple[step.anchor].id;
2008
+ default:
2009
+ throw new Error(`Unknown direction: ${step.direction}`);
2010
+ }
2011
+ });
2012
+ for (let i = 0; i < filteredRelationships.length; i++) {
2013
+ const relationship = filteredRelationships[i];
2014
+ const newTuple = i === 0 ? tuple : {
2015
+ ...tuple
2016
+ };
2017
+ if (newTuple !== tuple) {
2018
+ buffer.push(newTuple);
2019
+ }
2020
+ newTuple[step.relationshipInto] = relationship;
2021
+ switch (step.direction) {
2022
+ case "in":
2023
+ newTuple[step.nodeInto] = relationship.source;
2024
+ break;
2025
+ case "out":
2026
+ newTuple[step.nodeInto] = relationship.target;
2027
+ break;
2028
+ case "both":
2029
+ newTuple[step.nodeInto] = relationship.source.id === newTuple[step.anchor].id ? relationship.target : relationship.source;
2030
+ break;
2031
+ }
2032
+ }
2033
+ }
2034
+ break;
2035
+ }
2036
+ case "ProduceResults": {
2037
+ for (const tuple of buffer) {
2038
+ const result = {};
2039
+ for (const field of step.fields) {
2040
+ result[field.name] = jsonPathGet(tuple[field.variable].properties, field.path);
2041
+ }
2042
+ results.push(result);
2043
+ }
2044
+ break;
2045
+ }
2046
+ }
2047
+ log7("finish step", {
2048
+ buffer: buffer.map((tuple) => mapValues(tuple, (x) => x.id)),
2049
+ results
2050
+ }, {
2051
+ F: __dxlog_file7,
2052
+ L: 118,
2053
+ S: void 0,
2054
+ C: (f, a) => f(...a)
2055
+ });
2056
+ }
2057
+ return results;
2058
+ };
2059
+ var executeQuery = (dataSource, query) => {
2060
+ const plan = createExecutionPlan(parseCypherQuery(query));
2061
+ return executeQueryPlan(dataSource, plan);
2062
+ };
2063
+ var jsonPathGet = (obj, path) => {
2064
+ if (path === "" || path === "$") {
2065
+ return obj;
2066
+ }
2067
+ const parts = path.split(".");
2068
+ if (parts[0] === "$") {
2069
+ parts.shift();
2070
+ }
2071
+ let result = obj;
2072
+ for (const part of parts) {
2073
+ result = result?.[part];
2074
+ }
2075
+ return result;
2076
+ };
2077
+
2078
+ // packages/experimental/assistant/src/cypher/schema.ts
2079
+ import { raise } from "@dxos/debug";
2080
+ import { JSON_SCHEMA_ECHO_REF_ID } from "@dxos/echo-schema";
2081
+
2082
+ // packages/experimental/assistant/src/util/trim.ts
2083
+ var trim = (strings, ...values) => {
2084
+ const combined = strings.reduce((acc, str, i) => {
2085
+ return acc + str + (values[i] || "");
2086
+ }, "");
2087
+ return combined.replace("/^\n/", "").replace(/\n$/, "");
2088
+ };
2089
+
2090
+ // packages/experimental/assistant/src/cypher/schema.ts
2091
+ var formatJsonSchemaForLLM = (schemaTypes) => {
2092
+ return schemaTypes.flatMap((schema) => [
2093
+ formatNodeSchema(schema),
2094
+ ...formatInferredRelationships(schema, schemaTypes)
2095
+ ]);
2096
+ };
2097
+ var formatNodeSchema = (schema) => {
2098
+ const label2 = formatNodeLabel(schema.typename ?? raise(new Error("Schema must have $id")));
2099
+ const properties2 = Object.entries(schema.properties).filter(([key, prop]) => key !== "id" && !isReference(prop));
2100
+ return trim`
2101
+ <node>
2102
+ (:${label2})
2103
+
2104
+ <description>${schema.description}</description>
2105
+
2106
+ <properties>
2107
+ ${properties2.map(([key, value]) => {
2108
+ return trim`
2109
+ <${key}>
2110
+ <type>${value.type}</type>
2111
+ <description>${value.description}</description>
2112
+ </${key}>
2113
+ `;
2114
+ })}
2115
+ </properties>
2116
+ </node>
2117
+ `;
2118
+ };
2119
+ var formatInferredRelationships = (schema, allSchema) => {
2120
+ const nodeLabel = formatNodeLabel(schema.typename ?? raise(new Error("Schema must have $id")));
2121
+ const relationships = Object.entries(schema.properties).filter(([key, prop]) => isReference(prop));
2122
+ return relationships.map(([key, value]) => {
2123
+ const relationshipLabel = formatInferredRelationshipLabel(schema.typename ?? raise(new Error("Schema must have $id")), key);
2124
+ const targetSchema = allSchema.find((schema2) => `dxn:type/${schema2.typename}` === value.reference?.schema.$ref);
2125
+ const targetLabel = targetSchema ? formatNodeLabel(targetSchema?.typename ?? "") : "";
2126
+ return trim`
2127
+ <relationship>
2128
+ (:${nodeLabel})-[:${relationshipLabel}]->(:${targetLabel})
2129
+
2130
+ <description>${value.description}</description>
2131
+ </relationship>
2132
+ `;
2133
+ });
2134
+ };
2135
+ var formatNodeLabel = (typename) => {
2136
+ return typename.replace(/^example\.com\/type\//g, "");
2137
+ };
2138
+ var formatInferredRelationshipLabel = (typename, property2) => {
2139
+ const nodeLabel = formatNodeLabel(typename);
2140
+ return `${nodeLabel}_${property2}`.toUpperCase();
2141
+ };
2142
+ var isReference = (schema) => schema.$id === JSON_SCHEMA_ECHO_REF_ID || schema.type === "array" && !Array.isArray(schema.items) && typeof schema.items === "object" && "$id" in schema.items && schema.items.$id === JSON_SCHEMA_ECHO_REF_ID;
2143
+
2144
+ // packages/experimental/assistant/src/cypher/echo-data-source.ts
2145
+ import { raise as raise2 } from "@dxos/debug";
2146
+ import { Filter } from "@dxos/echo-db";
2147
+ import { getSchemaTypename, StoredSchema, toJsonSchema } from "@dxos/echo-schema";
2148
+ import { getSchema } from "@dxos/live-object";
2149
+ import { log as log8 } from "@dxos/log";
2150
+ function _ts_decorate(decorators, target, key, desc) {
2151
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2152
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2153
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2154
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2155
+ }
2156
+ var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/cypher/echo-data-source.ts";
2157
+ var EchoDataSource = class {
2158
+ constructor(_db) {
2159
+ this._db = _db;
2160
+ }
2161
+ async getNodes({ label: label2 }) {
2162
+ if (!label2) {
2163
+ const { objects: objects2 } = await this._db.query().run();
2164
+ return objects2.map(this._objectToNode);
2165
+ }
2166
+ const schema = (await this._getAllSchema()).find((s) => getSchemaTypename(s)?.endsWith(label2));
2167
+ if (!schema) {
2168
+ return [];
2169
+ }
2170
+ const { objects } = await this._db.query(Filter.schema(schema)).run();
2171
+ return objects.map(this._objectToNode);
2172
+ }
2173
+ async getRelationships({ label: label2 }) {
2174
+ const syntheticRefRelationships = (await this._getAllSchema()).filter((schema) => getSchemaTypename(schema) !== StoredSchema.typename).flatMap((schema) => {
2175
+ const jsonSchema = toJsonSchema(schema);
2176
+ const relationships = Object.entries(jsonSchema.properties).filter(([key, prop]) => isReference(prop));
2177
+ return relationships.map(([key, value]) => {
2178
+ const relationshipLabel = formatInferredRelationshipLabel(jsonSchema.typename ?? raise2(new Error("Schema must have typename")), key);
2179
+ return {
2180
+ label: relationshipLabel,
2181
+ schema,
2182
+ property: key
2183
+ };
2184
+ });
2185
+ });
2186
+ const relationship = syntheticRefRelationships.find((r) => r.label === label2);
2187
+ if (!relationship) {
2188
+ return [];
2189
+ }
2190
+ const { objects } = await this._db.query(Filter.schema(relationship.schema)).run();
2191
+ return (await Promise.all(objects.map((object) => this._projectRefRelationship(object, relationship.property)))).flat();
2192
+ }
2193
+ async _getAllSchema() {
2194
+ return [
2195
+ ...await this._db.schemaRegistry.query().run(),
2196
+ // TODO(dmaretskyi): Remove once we can serialize recursive schema.
2197
+ ...this._db.graph.schemaRegistry.schemas.filter((s) => getSchemaTypename(s)?.startsWith("example.org"))
2198
+ ].filter((schema) => getSchemaTypename(schema) !== StoredSchema.typename);
2199
+ }
2200
+ _objectToNode(object) {
2201
+ const { id, ...properties2 } = object;
2202
+ return {
2203
+ id,
2204
+ kind: "node",
2205
+ label: formatNodeLabel(getSchemaTypename(getSchema(object))),
2206
+ properties: properties2
2207
+ };
2208
+ }
2209
+ async _projectRefRelationship(object, prop) {
2210
+ if (!object[prop]) {
2211
+ return [];
2212
+ }
2213
+ const value = Array.isArray(object[prop]) ? object[prop] : [
2214
+ object[prop]
2215
+ ];
2216
+ return Promise.all(value.map(async (ref) => {
2217
+ const target = await ref.load();
2218
+ return {
2219
+ id: `${object.id}-${prop}-${target.id}`,
2220
+ kind: "relationship",
2221
+ label: formatInferredRelationshipLabel(getSchemaTypename(getSchema(object)), prop),
2222
+ properties: {},
2223
+ source: this._objectToNode(object),
2224
+ target: this._objectToNode(target)
2225
+ };
2226
+ }));
2227
+ }
2228
+ };
2229
+ _ts_decorate([
2230
+ log8.method(void 0, void 0, {
2231
+ F: __dxlog_file8,
2232
+ L: 17,
2233
+ S: void 0,
2234
+ C: (f, a) => f(...a)
2235
+ })
2236
+ ], EchoDataSource.prototype, "getNodes", null);
2237
+ _ts_decorate([
2238
+ log8.method(void 0, void 0, {
2239
+ F: __dxlog_file8,
2240
+ L: 34,
2241
+ S: void 0,
2242
+ C: (f, a) => f(...a)
2243
+ })
2244
+ ], EchoDataSource.prototype, "getRelationships", null);
2245
+
2246
+ export {
2247
+ DEFAULT_EDGE_MODEL,
2248
+ DEFAULT_EDGE_MODELS,
2249
+ DEFAULT_OLLAMA_ENDPOINT,
2250
+ DEFAULT_OLLAMA_MODEL,
2251
+ DEFAULT_OLLAMA_MODELS,
2252
+ createGenerationStream,
2253
+ GenerationStreamImpl,
2254
+ AIServiceEdgeClient,
2255
+ MessageCollector,
2256
+ emitMessageAsEvents,
2257
+ createArtifactElement,
2258
+ LLMModel,
2259
+ ToolTypes,
2260
+ GenerateRequest,
2261
+ runLLM,
2262
+ isToolUse,
2263
+ runTools,
2264
+ OllamaClient,
2265
+ StreamTransform,
2266
+ MixedStreamParser,
2267
+ mergeMessageBlock,
2268
+ parseCypherQuery,
2269
+ executeQueryPlan,
2270
+ executeQuery,
2271
+ trim,
2272
+ formatJsonSchemaForLLM,
2273
+ formatNodeLabel,
2274
+ formatInferredRelationshipLabel,
2275
+ isReference,
2276
+ EchoDataSource
2277
+ };
2278
+ //# sourceMappingURL=chunk-JUVGBQBL.mjs.map