@dxos/assistant 0.8.1-main.ba2dec9 → 0.8.1-staging.31c3ee1

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