@dxos/assistant 0.8.0 → 0.8.1-main.013e445

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