@dxos/assistant 0.8.1-main.ba2dec9 → 0.8.1-staging.5be625a

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