@dxos/assistant 0.7.4 → 0.7.5-labs.5f04cf6

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 (109) hide show
  1. package/dist/lib/browser/chunk-37SDA65J.mjs +565 -0
  2. package/dist/lib/browser/chunk-37SDA65J.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +936 -47
  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 +14 -8
  7. package/dist/lib/browser/testing/index.mjs.map +4 -4
  8. package/dist/lib/node/chunk-UYNIAO5N.cjs +577 -0
  9. package/dist/lib/node/chunk-UYNIAO5N.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +936 -54
  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 +20 -13
  14. package/dist/lib/node/testing/index.cjs.map +4 -4
  15. package/dist/lib/node-esm/chunk-AR24K7TY.mjs +567 -0
  16. package/dist/lib/node-esm/chunk-AR24K7TY.mjs.map +7 -0
  17. package/dist/lib/node-esm/index.mjs +936 -47
  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 +14 -8
  21. package/dist/lib/node-esm/testing/index.mjs.map +4 -4
  22. package/dist/types/src/ai-service/client.d.ts +16 -32
  23. package/dist/types/src/ai-service/client.d.ts.map +1 -1
  24. package/dist/types/src/ai-service/defs.d.ts +134 -0
  25. package/dist/types/src/ai-service/defs.d.ts.map +1 -0
  26. package/dist/types/src/ai-service/index.d.ts +3 -1
  27. package/dist/types/src/ai-service/index.d.ts.map +1 -1
  28. package/dist/types/src/ai-service/parser.d.ts +40 -0
  29. package/dist/types/src/ai-service/parser.d.ts.map +1 -0
  30. package/dist/types/src/ai-service/stream.d.ts +35 -0
  31. package/dist/types/src/ai-service/stream.d.ts.map +1 -0
  32. package/dist/types/src/ai-service/stream.test.d.ts +2 -0
  33. package/dist/types/src/ai-service/stream.test.d.ts.map +1 -0
  34. package/dist/types/src/ai-service/util/index.d.ts +2 -0
  35. package/dist/types/src/ai-service/util/index.d.ts.map +1 -0
  36. package/dist/types/src/ai-service/{sse.d.ts → util/sse.d.ts} +5 -0
  37. package/dist/types/src/ai-service/util/sse.d.ts.map +1 -0
  38. package/dist/types/src/conversation/conversation.d.ts +56 -5
  39. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  40. package/dist/types/src/conversation/index.d.ts +0 -1
  41. package/dist/types/src/conversation/index.d.ts.map +1 -1
  42. package/dist/types/src/conversation/types.d.ts +44 -13
  43. package/dist/types/src/conversation/types.d.ts.map +1 -1
  44. package/dist/types/src/cypher/combinators.d.ts.map +1 -1
  45. package/dist/types/src/cypher/parjs.d.ts +1 -1
  46. package/dist/types/src/cypher/parjs.d.ts.map +1 -1
  47. package/dist/types/src/cypher/schema.d.ts.map +1 -1
  48. package/dist/types/src/testing/artifacts.test.d.ts +1 -0
  49. package/dist/types/src/testing/artifacts.test.d.ts.map +1 -0
  50. package/dist/types/src/testing/data.d.ts +2 -0
  51. package/dist/types/src/testing/data.d.ts.map +1 -0
  52. package/dist/types/src/testing/defs.d.ts +5 -0
  53. package/dist/types/src/testing/defs.d.ts.map +1 -0
  54. package/dist/types/src/testing/index.d.ts +1 -0
  55. package/dist/types/src/testing/index.d.ts.map +1 -1
  56. package/dist/types/src/testing/logger.d.ts +1 -1
  57. package/dist/types/src/testing/logger.d.ts.map +1 -1
  58. package/dist/types/src/testing/query-promts.d.ts +1 -1
  59. package/dist/types/src/testing/query-promts.d.ts.map +1 -1
  60. package/dist/types/src/testing/test-data.d.ts +1 -1
  61. package/dist/types/src/testing/test-data.d.ts.map +1 -1
  62. package/dist/types/src/testing/test-schema.d.ts +4 -4
  63. package/package.json +20 -18
  64. package/src/ai-service/client.test.ts +28 -28
  65. package/src/ai-service/client.ts +31 -177
  66. package/src/ai-service/defs.ts +98 -0
  67. package/src/ai-service/index.ts +3 -1
  68. package/src/ai-service/parser.ts +183 -0
  69. package/src/ai-service/stream.test.ts +106 -0
  70. package/src/ai-service/stream.test.txt +33 -0
  71. package/src/ai-service/stream.ts +182 -0
  72. package/src/ai-service/util/index.ts +5 -0
  73. package/src/ai-service/{sse.ts → util/sse.ts} +5 -0
  74. package/src/bin/chat.ts +8 -10
  75. package/src/conversation/conversation.test.ts +13 -17
  76. package/src/conversation/conversation.ts +113 -18
  77. package/src/conversation/index.ts +0 -1
  78. package/src/conversation/types.ts +55 -16
  79. package/src/cypher/combinators.test.ts +4 -4
  80. package/src/cypher/combinators.ts +0 -1
  81. package/src/cypher/execution-plan.test.ts +5 -3
  82. package/src/cypher/parjs-shims.d.ts +4 -0
  83. package/src/cypher/parjs.ts +2 -2
  84. package/src/cypher/query-executor.test.ts +1 -1
  85. package/src/cypher/schema.ts +0 -1
  86. package/src/index.ts +1 -1
  87. package/src/testing/artifacts.test.ts +182 -0
  88. package/src/testing/data.ts +13 -0
  89. package/src/testing/defs.ts +8 -0
  90. package/src/testing/index.ts +1 -0
  91. package/src/testing/logger.ts +3 -2
  92. package/src/testing/query-promts.ts +3 -3
  93. package/src/testing/query.test.ts +11 -10
  94. package/src/testing/test-data.ts +1 -1
  95. package/vendor/parjs-browser.mjs +4 -0
  96. package/vendor/parjs-default.mjs +8 -0
  97. package/dist/lib/browser/chunk-AKP45LQH.mjs +0 -1394
  98. package/dist/lib/browser/chunk-AKP45LQH.mjs.map +0 -7
  99. package/dist/lib/node/chunk-G6CGWEMO.cjs +0 -1418
  100. package/dist/lib/node/chunk-G6CGWEMO.cjs.map +0 -7
  101. package/dist/lib/node-esm/chunk-WUPUPEFB.mjs +0 -1396
  102. package/dist/lib/node-esm/chunk-WUPUPEFB.mjs.map +0 -7
  103. package/dist/types/src/ai-service/schema.d.ts +0 -296
  104. package/dist/types/src/ai-service/schema.d.ts.map +0 -1
  105. package/dist/types/src/ai-service/sse.d.ts.map +0 -1
  106. package/dist/types/src/sanity.test.d.ts +0 -2
  107. package/dist/types/src/sanity.test.d.ts.map +0 -1
  108. package/src/ai-service/schema.ts +0 -260
  109. package/src/sanity.test.ts +0 -9
@@ -1,1394 +0,0 @@
1
- // packages/experimental/assistant/src/ai-service/schema.ts
2
- import { Schema as S } from "@effect/schema";
3
- import { ulid } from "ulidx";
4
- import { JsonSchemaType } from "@dxos/echo-schema";
5
- import { SpaceId } from "@dxos/keys";
6
- var SpaceIdSchema = S.String.pipe(S.filter(SpaceId.isValid));
7
- var ObjectIdBrand = Symbol("@dxos/echo/ObjectId");
8
- var ObjectIdSchema = S.ULID.pipe(S.brand(ObjectIdBrand));
9
- var ObjectId = class extends ObjectIdSchema {
10
- static random() {
11
- return ulid();
12
- }
13
- };
14
- var Space = S.Struct({
15
- id: SpaceIdSchema
16
- });
17
- var Thread = S.Struct({
18
- id: ObjectId,
19
- spaceId: SpaceIdSchema
20
- });
21
- var MessageRole = S.String.pipe(S.filter((role) => role === "user" || role === "assistant"));
22
- var MessageTextContentBlock = S.Struct({
23
- type: S.Literal("text"),
24
- text: S.String
25
- }).pipe(S.mutable);
26
- var ImageSource = S.Struct({
27
- type: S.Literal("base64"),
28
- media_type: S.Literal("image/jpeg", "image/png", "image/gif", "image/webp"),
29
- data: S.String
30
- }).pipe(S.mutable);
31
- var MessageImageContentBlock = S.Struct({
32
- type: S.Literal("image"),
33
- id: S.optional(S.String),
34
- source: S.optional(ImageSource)
35
- }).pipe(S.mutable);
36
- var MessageToolUseContentBlock = S.Struct({
37
- type: S.Literal("tool_use"),
38
- /**
39
- * Opaque service-defined ID of the tool invocation.
40
- * Used to match the tool result block.
41
- */
42
- id: S.String,
43
- /**
44
- * Tool name.
45
- */
46
- name: S.String,
47
- input: S.Unknown,
48
- /**
49
- * Used to accumulate the partial tool input JSON in streaming mode.
50
- */
51
- inputJson: S.optional(S.String)
52
- }).pipe(S.mutable);
53
- var MessageToolResultContentBlock = S.Struct({
54
- type: S.Literal("tool_result"),
55
- toolUseId: S.String,
56
- content: S.String,
57
- isError: S.optional(S.Boolean)
58
- });
59
- var MessageContentBlock = S.Union(MessageTextContentBlock, MessageImageContentBlock, MessageToolUseContentBlock, MessageToolResultContentBlock);
60
- var Message = S.Struct({
61
- id: ObjectId,
62
- threadId: S.optional(ObjectId),
63
- spaceId: S.optional(SpaceIdSchema),
64
- role: MessageRole,
65
- content: S.Array(MessageContentBlock).pipe(S.mutable),
66
- /**
67
- * ID of the message from the foreign provider.
68
- */
69
- // TODO(dmaretskyi): Should be in meta/keys.
70
- foreignId: S.optional(S.String)
71
- });
72
- var MessageFromDb = S.Struct({
73
- ...Message.fields,
74
- content: S.propertySignature(Message.fields.content.pipe((schema) => S.parseJson(schema))).pipe(S.fromKey("contentJson"))
75
- });
76
- var LLMModel = S.Literal("@hf/nousresearch/hermes-2-pro-mistral-7b", "@anthropic/claude-3-5-sonnet-20241022", "@anthropic/claude-3-5-haiku-20241022", "@ollama/llama-3-2-3b", "@ollama/llama-3-1-nemotron-70b-instruct", "@ollama/llama-3-1-nemotron-mini-4b-instruct");
77
- var ToolTypes = Object.freeze({
78
- // TODO(dmaretskyi): Not implemented yet.
79
- // DatabaseQuery: 'database_query',
80
- TextToImage: "text_to_image"
81
- });
82
- var LLMTool = S.Struct({
83
- name: S.String,
84
- /**
85
- * If the tool is implemented by the service a type should be provided.
86
- * For user-implemented tools, this field should be omitted.
87
- * See {@link ToolTypes} for the list of supported types.
88
- */
89
- type: S.optional(S.String),
90
- /**
91
- * Required for user-implemented tools.
92
- */
93
- description: S.optional(S.String),
94
- /**
95
- * Input schema for the tool in the JSON Schema format.
96
- * Required for user-implemented tools.
97
- */
98
- parameters: S.optional(JsonSchemaType),
99
- /**
100
- * Tool-specific options.
101
- */
102
- options: S.optional(S.Any),
103
- /**
104
- * Javascript function to execute the tool.
105
- */
106
- execute: S.optional(S.Any)
107
- });
108
- var GenerateRequest = S.Struct({
109
- model: LLMModel,
110
- spaceId: SpaceIdSchema,
111
- threadId: ObjectId,
112
- /**
113
- * System instructions to the LLM.
114
- */
115
- // TODO(dmaretskyi): Should this be part of the thread?.
116
- systemPrompt: S.optional(S.String),
117
- /**
118
- * Tools available for the LLM.
119
- */
120
- tools: S.Array(LLMTool).pipe(S.mutable)
121
- });
122
-
123
- // packages/experimental/assistant/src/ai-service/client.ts
124
- import { Schema as S2 } from "@effect/schema";
125
- import { Trigger } from "@dxos/async";
126
- import { invariant } from "@dxos/invariant";
127
-
128
- // packages/experimental/assistant/src/ai-service/sse.ts
129
- async function* iterSSEMessages(response, controller) {
130
- if (!response.body) {
131
- controller.abort();
132
- throw new Error("Attempted to iterate over a response with no body");
133
- }
134
- const sseDecoder = new SSEDecoder();
135
- const lineDecoder = new LineDecoder();
136
- const iter = readableStreamAsyncIterable(response.body);
137
- for await (const sseChunk of iterSSEChunks(iter)) {
138
- for (const line of lineDecoder.decode(sseChunk)) {
139
- const sse = sseDecoder.decode(line);
140
- if (sse) {
141
- yield sse;
142
- }
143
- }
144
- }
145
- for (const line of lineDecoder.flush()) {
146
- const sse = sseDecoder.decode(line);
147
- if (sse) {
148
- yield sse;
149
- }
150
- }
151
- }
152
- async function* iterSSEChunks(iterator) {
153
- let data = new Uint8Array();
154
- for await (const chunk of iterator) {
155
- if (chunk == null) {
156
- continue;
157
- }
158
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
159
- const newData = new Uint8Array(data.length + binaryChunk.length);
160
- newData.set(data);
161
- newData.set(binaryChunk, data.length);
162
- data = newData;
163
- let patternIndex;
164
- while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
165
- yield data.slice(0, patternIndex);
166
- data = data.slice(patternIndex);
167
- }
168
- }
169
- if (data.length > 0) {
170
- yield data;
171
- }
172
- }
173
- var findDoubleNewlineIndex = (buffer) => {
174
- const newline = 10;
175
- const carriage = 13;
176
- for (let i = 0; i < buffer.length - 2; i++) {
177
- if (buffer[i] === newline && buffer[i + 1] === newline) {
178
- return i + 2;
179
- }
180
- if (buffer[i] === carriage && buffer[i + 1] === carriage) {
181
- return i + 2;
182
- }
183
- if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) {
184
- return i + 4;
185
- }
186
- }
187
- return -1;
188
- };
189
- var SSEDecoder = class {
190
- constructor() {
191
- this.event = null;
192
- this.data = [];
193
- this.chunks = [];
194
- }
195
- decode(line) {
196
- if (line.endsWith("\r")) {
197
- line = line.substring(0, line.length - 1);
198
- }
199
- if (!line) {
200
- if (!this.event && !this.data.length) {
201
- return null;
202
- }
203
- const sse = {
204
- event: this.event,
205
- data: this.data.join("\n"),
206
- raw: this.chunks
207
- };
208
- this.event = null;
209
- this.data = [];
210
- this.chunks = [];
211
- return sse;
212
- }
213
- this.chunks.push(line);
214
- if (line.startsWith(":")) {
215
- return null;
216
- }
217
- let [fieldname, _, value] = partition(line, ":");
218
- if (value.startsWith(" ")) {
219
- value = value.substring(1);
220
- }
221
- if (fieldname === "event") {
222
- this.event = value;
223
- } else if (fieldname === "data") {
224
- this.data.push(value);
225
- }
226
- return null;
227
- }
228
- };
229
- var partition = (str, delimiter) => {
230
- const index = str.indexOf(delimiter);
231
- if (index !== -1) {
232
- return [
233
- str.substring(0, index),
234
- delimiter,
235
- str.substring(index + delimiter.length)
236
- ];
237
- }
238
- return [
239
- str,
240
- "",
241
- ""
242
- ];
243
- };
244
- function readableStreamAsyncIterable(stream) {
245
- if (stream[Symbol.asyncIterator]) {
246
- return stream;
247
- }
248
- const reader = stream.getReader();
249
- return {
250
- next: async () => {
251
- try {
252
- const result = await reader.read();
253
- if (result?.done) {
254
- reader.releaseLock();
255
- }
256
- return result;
257
- } catch (e) {
258
- reader.releaseLock();
259
- throw e;
260
- }
261
- },
262
- return: async () => {
263
- const cancelPromise = reader.cancel();
264
- reader.releaseLock();
265
- await cancelPromise;
266
- return {
267
- done: true,
268
- value: void 0
269
- };
270
- },
271
- [Symbol.asyncIterator]() {
272
- return this;
273
- }
274
- };
275
- }
276
- var LineDecoder = class _LineDecoder {
277
- static {
278
- // prettier-ignore
279
- this.NEWLINE_CHARS = /* @__PURE__ */ new Set([
280
- "\n",
281
- "\r"
282
- ]);
283
- }
284
- static {
285
- this.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
286
- }
287
- constructor() {
288
- this.buffer = [];
289
- this.trailingCR = false;
290
- }
291
- decode(chunk) {
292
- let text = this.decodeText(chunk);
293
- if (this.trailingCR) {
294
- text = "\r" + text;
295
- this.trailingCR = false;
296
- }
297
- if (text.endsWith("\r")) {
298
- this.trailingCR = true;
299
- text = text.slice(0, -1);
300
- }
301
- if (!text) {
302
- return [];
303
- }
304
- const trailingNewline = _LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || "");
305
- let lines = text.split(_LineDecoder.NEWLINE_REGEXP);
306
- if (trailingNewline) {
307
- lines.pop();
308
- }
309
- if (lines.length === 1 && !trailingNewline) {
310
- this.buffer.push(lines[0]);
311
- return [];
312
- }
313
- if (this.buffer.length > 0) {
314
- lines = [
315
- this.buffer.join("") + lines[0],
316
- ...lines.slice(1)
317
- ];
318
- this.buffer = [];
319
- }
320
- if (!trailingNewline) {
321
- this.buffer = [
322
- lines.pop() || ""
323
- ];
324
- }
325
- return lines;
326
- }
327
- decodeText(bytes) {
328
- if (bytes == null) {
329
- return "";
330
- }
331
- if (typeof bytes === "string") {
332
- return bytes;
333
- }
334
- if (typeof Buffer !== "undefined") {
335
- if (bytes instanceof Buffer) {
336
- return bytes.toString();
337
- }
338
- if (bytes instanceof Uint8Array) {
339
- return Buffer.from(bytes).toString();
340
- }
341
- 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.`);
342
- }
343
- if (typeof TextDecoder !== "undefined") {
344
- if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
345
- this.textDecoder ??= new TextDecoder("utf8");
346
- return this.textDecoder.decode(bytes);
347
- }
348
- throw new Error(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
349
- }
350
- throw new Error("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.");
351
- }
352
- flush() {
353
- if (!this.buffer.length && !this.trailingCR) {
354
- return [];
355
- }
356
- const lines = [
357
- this.buffer.join("")
358
- ];
359
- this.buffer = [];
360
- this.trailingCR = false;
361
- return lines;
362
- }
363
- };
364
-
365
- // packages/experimental/assistant/src/ai-service/client.ts
366
- var __dxlog_file = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/ai-service/client.ts";
367
- var AIServiceClientImpl = class {
368
- constructor({ endpoint }) {
369
- this._endpoint = endpoint;
370
- }
371
- async getSpace(spaceId) {
372
- throw new Error("Not implemented");
373
- }
374
- async getThread(spaceId, threadId) {
375
- throw new Error("Not implemented");
376
- }
377
- async getMessagesInThread(spaceId, threadId) {
378
- const res = await fetch(`${this._endpoint}/space/${spaceId}/thread/${threadId}/message`);
379
- return S2.decodePromise(S2.Array(Message).pipe(S2.mutable))((await res.json()).data.results);
380
- }
381
- async insertMessages(messages) {
382
- const res = await fetch(`${this._endpoint}/message`, {
383
- method: "POST",
384
- headers: {
385
- "Content-Type": "application/json"
386
- },
387
- body: JSON.stringify({
388
- messages: await S2.encodePromise(S2.Array(Message))(messages)
389
- })
390
- });
391
- if (!res.ok) {
392
- throw new Error(await res.text());
393
- }
394
- }
395
- // TODO(dmaretskyi): Accept partial message schema.
396
- async updateMessage(spaceId, threadId, messageId, message) {
397
- throw new Error("Not implemented");
398
- }
399
- async generate(request) {
400
- const response = await fetch(`${this._endpoint}/generate`, {
401
- method: "POST",
402
- headers: {
403
- "Content-Type": "application/json"
404
- },
405
- body: JSON.stringify(request)
406
- });
407
- invariant(response.body instanceof ReadableStream, void 0, {
408
- F: __dxlog_file,
409
- L: 81,
410
- S: this,
411
- A: [
412
- "response.body instanceof ReadableStream",
413
- ""
414
- ]
415
- });
416
- return GenerationStream.fromSSEResponse({
417
- spaceId: request.spaceId,
418
- threadId: request.threadId
419
- }, response);
420
- }
421
- };
422
- var GenerationStream = class _GenerationStream {
423
- static fromSSEResponse(params, response) {
424
- const controller = new AbortController();
425
- const iterator = async function* () {
426
- for await (const sse of iterSSEMessages(response, controller)) {
427
- if (sse.event === "completion") {
428
- try {
429
- yield JSON.parse(sse.data);
430
- } catch (e) {
431
- console.error("Could not parse message into JSON:", sse.data);
432
- console.error("From chunk:", sse.raw);
433
- throw e;
434
- }
435
- }
436
- 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") {
437
- try {
438
- yield JSON.parse(sse.data);
439
- } catch (e) {
440
- console.error("Could not parse message into JSON:", sse.data);
441
- console.error("From chunk:", sse.raw);
442
- throw e;
443
- }
444
- }
445
- if (sse.event === "ping") {
446
- continue;
447
- }
448
- if (sse.event === "error") {
449
- throw new Error(`Message generation error: ${sse.data}`);
450
- }
451
- }
452
- };
453
- return new _GenerationStream(params, iterator);
454
- }
455
- constructor(_params, _getIterator) {
456
- this._params = _params;
457
- this._getIterator = _getIterator;
458
- this._previousMessages = [];
459
- this._accumulatedMessage = void 0;
460
- this._done = new Trigger();
461
- this._iterator = void 0;
462
- }
463
- [Symbol.asyncIterator]() {
464
- return this._createIterator();
465
- }
466
- cancel() {
467
- throw new Error("Not implemented");
468
- }
469
- get accumulatedMessages() {
470
- return [
471
- ...this._previousMessages,
472
- ...this._accumulatedMessage == null ? [] : [
473
- this._accumulatedMessage
474
- ]
475
- ];
476
- }
477
- /**
478
- * Returns the complete message list generated by the AI service.
479
- */
480
- async complete() {
481
- await this._done.wait();
482
- return this.accumulatedMessages;
483
- }
484
- _createIterator() {
485
- const self = this;
486
- return this._iterator ??= async function* () {
487
- for await (const event of self._getIterator()) {
488
- self._processEvent(event);
489
- yield event;
490
- }
491
- }();
492
- }
493
- _processEvent(event) {
494
- switch (event.type) {
495
- case "message_start": {
496
- if (this._accumulatedMessage) {
497
- this._previousMessages.push(this._accumulatedMessage);
498
- this._accumulatedMessage = void 0;
499
- }
500
- this._accumulatedMessage = {
501
- ...event.message,
502
- threadId: this._params.threadId,
503
- spaceId: this._params.spaceId
504
- };
505
- break;
506
- }
507
- case "message_delta": {
508
- if (this._accumulatedMessage === void 0) {
509
- throw new Error("Received message delta without a message start");
510
- }
511
- break;
512
- }
513
- case "message_stop": {
514
- if (this._accumulatedMessage === void 0) {
515
- throw new Error("Received message stop without a message start");
516
- }
517
- break;
518
- }
519
- case "content_block_start": {
520
- invariant(this._accumulatedMessage, void 0, {
521
- F: __dxlog_file,
522
- L: 212,
523
- S: this,
524
- A: [
525
- "this._accumulatedMessage",
526
- ""
527
- ]
528
- });
529
- this._accumulatedMessage.content.push(event.content);
530
- break;
531
- }
532
- case "content_block_delta": {
533
- invariant(this._accumulatedMessage, void 0, {
534
- F: __dxlog_file,
535
- L: 217,
536
- S: this,
537
- A: [
538
- "this._accumulatedMessage",
539
- ""
540
- ]
541
- });
542
- const snapshotContent = this._accumulatedMessage.content.at(event.index);
543
- if (snapshotContent?.type === "text" && event.delta.type === "text_delta") {
544
- snapshotContent.text += event.delta.text;
545
- } else if (snapshotContent?.type === "tool_use" && event.delta.type === "input_json_delta") {
546
- snapshotContent.inputJson ??= "";
547
- snapshotContent.inputJson += event.delta.partial_json;
548
- }
549
- break;
550
- }
551
- case "content_block_stop": {
552
- invariant(this._accumulatedMessage, void 0, {
553
- F: __dxlog_file,
554
- L: 233,
555
- S: this,
556
- A: [
557
- "this._accumulatedMessage",
558
- ""
559
- ]
560
- });
561
- const lastBlock = this._accumulatedMessage.content.at(-1);
562
- if (lastBlock?.type === "tool_use") {
563
- lastBlock.input = JSON.parse(lastBlock.inputJson ?? "");
564
- }
565
- break;
566
- }
567
- }
568
- this._done.wake();
569
- }
570
- };
571
-
572
- // packages/experimental/assistant/src/cypher/parjs.ts
573
- import { parjsCombinators, parjs } from "#parjs";
574
-
575
- // packages/experimental/assistant/src/cypher/combinators.ts
576
- var ws = parjs.whitespace();
577
- var nothing = parjs.string("").pipe(parjsCombinators.map(() => null));
578
- var optional = (parser) => parser.pipe(parjsCombinators.recover(() => ({
579
- kind: "Soft"
580
- })), parjsCombinators.or(nothing));
581
- var keyword = (word) => parjs.string(word).pipe(parjsCombinators.map(() => word));
582
- var identifier = parjs.regexp(/[a-zA-Z_][a-zA-Z0-9_]*/).pipe(parjsCombinators.map((match) => ({
583
- astKind: "Identifier",
584
- name: match[0]
585
- })));
586
- var numberLiteral = parjs.regexp(/-?\d+(\.\d+)?/).pipe(parjsCombinators.map(Number));
587
- var stringLiteral = parjs.regexp(/"([^"]*)"|'([^']*)'/).pipe(parjsCombinators.map((match) => ({
588
- astKind: "StringLiteral",
589
- value: match[1] || match[2]
590
- })));
591
- var variableTag = identifier.pipe(parjsCombinators.map((variable) => variable)).expects("variable tag");
592
- var label = identifier.pipe(parjsCombinators.map((name) => name));
593
- var property = identifier.pipe(parjsCombinators.then(parjs.string(":"), ws, stringLiteral), parjsCombinators.map(([key, , , value]) => ({
594
- key,
595
- value
596
- })));
597
- var properties = property.pipe(parjsCombinators.manySepBy(","), parjsCombinators.between("{", "}"), parjsCombinators.map((properties2) => ({
598
- astKind: "Properties",
599
- properties: properties2
600
- })));
601
- var nodePattern = optional(variableTag).pipe(parjsCombinators.then(":"), parjsCombinators.then(ws, label, ws), parjsCombinators.then(optional(properties)), parjsCombinators.between("(", ")"), parjsCombinators.map(([[[variable], _, label2], properties2]) => ({
602
- astKind: "NodePattern",
603
- variable,
604
- label: label2,
605
- properties: properties2
606
- })));
607
- var relationshipPattern = optional(variableTag).pipe(parjsCombinators.then(":"), parjsCombinators.then(ws, label, ws), parjsCombinators.then(optional(properties)), parjsCombinators.between("[", "]"), parjsCombinators.map(([[[variable], _, label2], properties2]) => ({
608
- astKind: "RelationshipPattern",
609
- variable,
610
- label: label2,
611
- properties: properties2
612
- })));
613
- var graphPatternConnector = parjs.string("->").pipe(parjsCombinators.or("<-", "-"), parjsCombinators.map((x) => ({
614
- astKind: "GraphPatternConnector",
615
- direction: x
616
- })));
617
- var graphPattern = nodePattern.pipe(parjsCombinators.or(relationshipPattern), parjsCombinators.manySepBy(graphPatternConnector), parjsCombinators.map((segments) => ({
618
- astKind: "GraphPattern",
619
- segments
620
- })));
621
- var matchClause = keyword("MATCH").pipe(parjsCombinators.then(ws), parjsCombinators.then(graphPattern), parjsCombinators.map(([, pattern]) => ({
622
- astKind: "MatchClause",
623
- pattern
624
- })));
625
- var memberExpression = identifier.pipe(parjsCombinators.manySepBy("."), parjsCombinators.map((path) => ({
626
- astKind: "MemberExpression",
627
- path
628
- })));
629
- var equalsPredicate = memberExpression.pipe(parjsCombinators.then(ws, parjs.string("="), ws, stringLiteral), parjsCombinators.map(([left, , , , right]) => ({
630
- astKind: "EqualsPredicate",
631
- left,
632
- right
633
- })));
634
- var whereClause = keyword("WHERE").pipe(parjsCombinators.then(ws, equalsPredicate.pipe(parjsCombinators.between(ws, ws), parjsCombinators.manySepBy(parjs.string("AND"))), ws), parjsCombinators.map(([, , predicates]) => ({
635
- astKind: "WhereClause",
636
- predicates
637
- })));
638
- 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]) => ({
639
- astKind: "ReturnClause",
640
- fields: fields.map(([f]) => f)
641
- })));
642
- var cypherQuery = ws.pipe(parjsCombinators.then(matchClause, ws, optional(whereClause), ws, returnClause, ws), parjsCombinators.map(([, matchClause2, , whereClause2, , returnClause2]) => ({
643
- astKind: "CypherQuery",
644
- matchClause: matchClause2,
645
- whereClause: whereClause2,
646
- returnClause: returnClause2
647
- })));
648
-
649
- // packages/experimental/assistant/src/cypher/parser.ts
650
- var parseCypherQuery = (query) => {
651
- const parseResult = cypherQuery.parse(query);
652
- if (parseResult.isOk) {
653
- return {
654
- ast: parseResult.value
655
- };
656
- } else {
657
- throw new Error(`Failed to parse query: ${parseResult}`);
658
- }
659
- };
660
-
661
- // packages/experimental/assistant/src/cypher/query-executor.ts
662
- import { log as log2 } from "@dxos/log";
663
- import { mapValues } from "@dxos/util";
664
-
665
- // packages/experimental/assistant/src/cypher/execution-plan.ts
666
- import { invariant as invariant2 } from "@dxos/invariant";
667
- import { log } from "@dxos/log";
668
- var __dxlog_file2 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/cypher/execution-plan.ts";
669
- var createExecutionPlan = (query) => {
670
- return new ExecutionPlanBuilder().build(query);
671
- };
672
- var ExecutionPlanBuilder = class {
673
- constructor() {
674
- this.counter = 0;
675
- }
676
- newVariable() {
677
- return `anon_${this.counter++}`;
678
- }
679
- build(query) {
680
- log("Creating execution plan for query", {
681
- query
682
- }, {
683
- F: __dxlog_file2,
684
- L: 76,
685
- S: this,
686
- C: (f, a) => f(...a)
687
- });
688
- return {
689
- steps: [
690
- ...this.createStepsForMatchClause(query.ast.matchClause),
691
- ...query.ast.whereClause ? this.createStepsForWhereClause(query.ast.whereClause) : [],
692
- ...this.createStepsForReturnClause(query.ast.returnClause)
693
- ],
694
- output: {
695
- fields: this.getOutputFields(query.ast.returnClause)
696
- }
697
- };
698
- }
699
- createStepsForMatchClause(match) {
700
- invariant2(match.pattern.segments.length > 0, void 0, {
701
- F: __dxlog_file2,
702
- L: 90,
703
- S: this,
704
- A: [
705
- "match.pattern.segments.length > 0",
706
- ""
707
- ]
708
- });
709
- const firstSegment = match.pattern.segments[0];
710
- invariant2(firstSegment.astKind === "NodePattern", void 0, {
711
- F: __dxlog_file2,
712
- L: 92,
713
- S: this,
714
- A: [
715
- "firstSegment.astKind === 'NodePattern'",
716
- ""
717
- ]
718
- });
719
- let lastNodeVariable = firstSegment.variable?.name ?? this.newVariable();
720
- const steps = [];
721
- steps.push({
722
- type: "NodeScan",
723
- label: firstSegment.label.name,
724
- into: lastNodeVariable
725
- });
726
- if (firstSegment.properties) {
727
- for (const property2 of firstSegment.properties.properties) {
728
- steps.push({
729
- type: "FilterByProperty",
730
- variable: lastNodeVariable,
731
- property: property2.key.name,
732
- value: property2.value.value
733
- });
734
- }
735
- }
736
- for (let i = 1; i < match.pattern.segments.length; i++) {
737
- const relationshipSegment = match.pattern.segments[i++];
738
- invariant2(relationshipSegment.astKind === "RelationshipPattern", void 0, {
739
- F: __dxlog_file2,
740
- L: 115,
741
- S: this,
742
- A: [
743
- "relationshipSegment.astKind === 'RelationshipPattern'",
744
- ""
745
- ]
746
- });
747
- const nodeSegment = match.pattern.segments[i];
748
- invariant2(nodeSegment.astKind === "NodePattern", void 0, {
749
- F: __dxlog_file2,
750
- L: 117,
751
- S: this,
752
- A: [
753
- "nodeSegment.astKind === 'NodePattern'",
754
- ""
755
- ]
756
- });
757
- const leftSeparator = match.pattern.segments.separators[i - 2];
758
- const rightSeparator = match.pattern.segments.separators[i - 1];
759
- const direction = getDirection(leftSeparator.direction, rightSeparator.direction);
760
- const relationshipVariable = relationshipSegment.variable?.name ?? this.newVariable();
761
- const nodeVariable = nodeSegment.variable?.name ?? this.newVariable();
762
- steps.push({
763
- type: "RelationshipScan",
764
- label: relationshipSegment.label.name,
765
- direction,
766
- anchor: lastNodeVariable,
767
- relationshipInto: relationshipVariable,
768
- nodeInto: nodeVariable
769
- });
770
- if (relationshipSegment.properties) {
771
- for (const property2 of relationshipSegment.properties.properties) {
772
- steps.push({
773
- type: "FilterByProperty",
774
- variable: relationshipVariable,
775
- property: property2.key.name,
776
- value: property2.value.value
777
- });
778
- }
779
- }
780
- if (nodeSegment.label) {
781
- steps.push({
782
- type: "FilterByLabel",
783
- variable: nodeVariable,
784
- label: nodeSegment.label.name
785
- });
786
- }
787
- if (nodeSegment.properties) {
788
- for (const property2 of nodeSegment.properties.properties) {
789
- steps.push({
790
- type: "FilterByProperty",
791
- variable: nodeVariable,
792
- property: property2.key.name,
793
- value: property2.value.value
794
- });
795
- }
796
- }
797
- lastNodeVariable = nodeVariable;
798
- }
799
- return steps;
800
- }
801
- createStepsForWhereClause(where) {
802
- return [];
803
- }
804
- createStepsForReturnClause(returnClause2) {
805
- return [
806
- {
807
- type: "ProduceResults",
808
- fields: returnClause2.fields.map((field) => ({
809
- name: field.path.map((p) => p.name).join("_"),
810
- variable: field.path[0].name,
811
- path: field.path.length > 1 ? field.path.slice(1).map((p) => p.name).join(".") : "$"
812
- }))
813
- }
814
- ];
815
- }
816
- getOutputFields(returnClause2) {
817
- return returnClause2.fields.map((field) => field.path.map((p) => p.name).join("_"));
818
- }
819
- };
820
- var getDirection = (left, right) => {
821
- if (left === "-" && right === "->") {
822
- return "out";
823
- } else if (left === "<-" && right === "-") {
824
- return "in";
825
- } else if (left === "-" && right === "-") {
826
- return "both";
827
- }
828
- throw new Error(`Invalid direction: ()${left}[]${right}()`);
829
- };
830
-
831
- // packages/experimental/assistant/src/cypher/query-executor.ts
832
- var __dxlog_file3 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/cypher/query-executor.ts";
833
- var executeQueryPlan = async (dataSource, plan) => {
834
- let buffer = [];
835
- const results = [];
836
- for (const step of plan.steps) {
837
- log2("begin step", {
838
- step
839
- }, {
840
- F: __dxlog_file3,
841
- L: 41,
842
- S: void 0,
843
- C: (f, a) => f(...a)
844
- });
845
- switch (step.type) {
846
- case "NodeScan": {
847
- const nodes = await dataSource.getNodes({
848
- label: step.label
849
- });
850
- buffer.push(...nodes.map((node) => ({
851
- [step.into]: node
852
- })));
853
- break;
854
- }
855
- case "FilterByLabel": {
856
- buffer = buffer.filter((item) => {
857
- const node = item[step.variable];
858
- return node && node.kind === "node" && node.label === step.label;
859
- });
860
- break;
861
- }
862
- case "FilterByProperty": {
863
- buffer = buffer.filter((item) => {
864
- const node = item[step.variable];
865
- return node && node.kind === "node" && node.properties[step.property] === step.value;
866
- });
867
- break;
868
- }
869
- case "RelationshipScan": {
870
- const relationships = await dataSource.getRelationships({
871
- label: step.label
872
- });
873
- for (const tuple of [
874
- ...buffer
875
- ]) {
876
- if (tuple[step.anchor].kind !== "node") {
877
- continue;
878
- }
879
- const filteredRelationships = relationships.filter((relationship) => {
880
- switch (step.direction) {
881
- case "in":
882
- return relationship.target.id === tuple[step.anchor].id;
883
- case "out":
884
- return relationship.source.id === tuple[step.anchor].id;
885
- case "both":
886
- return relationship.source.id === tuple[step.anchor].id || relationship.target.id === tuple[step.anchor].id;
887
- default:
888
- throw new Error(`Unknown direction: ${step.direction}`);
889
- }
890
- });
891
- for (let i = 0; i < filteredRelationships.length; i++) {
892
- const relationship = filteredRelationships[i];
893
- const newTuple = i === 0 ? tuple : {
894
- ...tuple
895
- };
896
- if (newTuple !== tuple) {
897
- buffer.push(newTuple);
898
- }
899
- newTuple[step.relationshipInto] = relationship;
900
- switch (step.direction) {
901
- case "in":
902
- newTuple[step.nodeInto] = relationship.source;
903
- break;
904
- case "out":
905
- newTuple[step.nodeInto] = relationship.target;
906
- break;
907
- case "both":
908
- newTuple[step.nodeInto] = relationship.source.id === newTuple[step.anchor].id ? relationship.target : relationship.source;
909
- break;
910
- }
911
- }
912
- }
913
- break;
914
- }
915
- case "ProduceResults": {
916
- for (const tuple of buffer) {
917
- const result = {};
918
- for (const field of step.fields) {
919
- result[field.name] = jsonPathGet(tuple[field.variable].properties, field.path);
920
- }
921
- results.push(result);
922
- }
923
- break;
924
- }
925
- }
926
- log2("finish step", {
927
- buffer: buffer.map((tuple) => mapValues(tuple, (x) => x.id)),
928
- results
929
- }, {
930
- F: __dxlog_file3,
931
- L: 118,
932
- S: void 0,
933
- C: (f, a) => f(...a)
934
- });
935
- }
936
- return results;
937
- };
938
- var executeQuery = (dataSource, query) => {
939
- const plan = createExecutionPlan(parseCypherQuery(query));
940
- return executeQueryPlan(dataSource, plan);
941
- };
942
- var jsonPathGet = (obj, path) => {
943
- if (path === "" || path === "$") {
944
- return obj;
945
- }
946
- const parts = path.split(".");
947
- if (parts[0] === "$") {
948
- parts.shift();
949
- }
950
- let result = obj;
951
- for (const part of parts) {
952
- result = result?.[part];
953
- }
954
- return result;
955
- };
956
-
957
- // packages/experimental/assistant/src/cypher/schema.ts
958
- import { raise } from "@dxos/debug";
959
- import { JSON_SCHEMA_ECHO_REF_ID } from "@dxos/echo-schema";
960
-
961
- // packages/experimental/assistant/src/util/trim.ts
962
- var trim = (strings, ...values) => {
963
- const combined = strings.reduce((acc, str, i) => {
964
- return acc + str + (values[i] || "");
965
- }, "");
966
- return combined.replace("/^\n/", "").replace(/\n$/, "");
967
- };
968
-
969
- // packages/experimental/assistant/src/cypher/schema.ts
970
- var formatJsonSchemaForLLM = (schemaTypes) => {
971
- return schemaTypes.flatMap((schema) => [
972
- formatNodeSchema(schema),
973
- ...formatInferredRelationships(schema, schemaTypes)
974
- ]);
975
- };
976
- var formatNodeSchema = (schema) => {
977
- const label2 = formatNodeLabel(schema.typename ?? raise(new Error("Schema must have $id")));
978
- const properties2 = Object.entries(schema.properties).filter(([key, prop]) => key !== "id" && !isReference(prop));
979
- return trim`
980
- <node>
981
- (:${label2})
982
-
983
- <description>${schema.description}</description>
984
-
985
- <properties>
986
- ${properties2.map(([key, value]) => {
987
- return trim`
988
- <${key}>
989
- <type>${value.type}</type>
990
- <description>${value.description}</description>
991
- </${key}>
992
- `;
993
- })}
994
- </properties>
995
- </node>
996
- `;
997
- };
998
- var formatInferredRelationships = (schema, allSchema) => {
999
- const nodeLabel = formatNodeLabel(schema.typename ?? raise(new Error("Schema must have $id")));
1000
- const relationships = Object.entries(schema.properties).filter(([key, prop]) => isReference(prop));
1001
- return relationships.map(([key, value]) => {
1002
- const relationshipLabel = formatInferredRelationshipLabel(schema.typename ?? raise(new Error("Schema must have $id")), key);
1003
- const targetSchema = allSchema.find((schema2) => `dxn:type/${schema2.typename}` === value.reference?.schema.$ref);
1004
- const targetLabel = targetSchema ? formatNodeLabel(targetSchema?.typename ?? "") : "";
1005
- return trim`
1006
- <relationship>
1007
- (:${nodeLabel})-[:${relationshipLabel}]->(:${targetLabel})
1008
-
1009
- <description>${value.description}</description>
1010
- </relationship>
1011
- `;
1012
- });
1013
- };
1014
- var formatNodeLabel = (typename) => {
1015
- return typename.replace(/^example\.com\/type\//g, "");
1016
- };
1017
- var formatInferredRelationshipLabel = (typename, property2) => {
1018
- const nodeLabel = formatNodeLabel(typename);
1019
- return `${nodeLabel}_${property2}`.toUpperCase();
1020
- };
1021
- var isReference = (schema) => schema.$id === JSON_SCHEMA_ECHO_REF_ID || schema.type === "array" && schema.items?.$id === JSON_SCHEMA_ECHO_REF_ID;
1022
-
1023
- // packages/experimental/assistant/src/cypher/echo-data-source.ts
1024
- import { raise as raise2 } from "@dxos/debug";
1025
- import { Filter } from "@dxos/echo-db";
1026
- import { getSchemaTypename, StoredSchema, toJsonSchema } from "@dxos/echo-schema";
1027
- import { getSchema } from "@dxos/live-object";
1028
- import { log as log3 } from "@dxos/log";
1029
- function _ts_decorate(decorators, target, key, desc) {
1030
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1031
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1032
- 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;
1033
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1034
- }
1035
- var __dxlog_file4 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/cypher/echo-data-source.ts";
1036
- var EchoDataSource = class {
1037
- constructor(_db) {
1038
- this._db = _db;
1039
- }
1040
- async getNodes({ label: label2 }) {
1041
- if (!label2) {
1042
- const { objects: objects2 } = await this._db.query().run();
1043
- return objects2.map(this._objectToNode);
1044
- }
1045
- const schema = (await this._getAllSchema()).find((s) => getSchemaTypename(s)?.endsWith(label2));
1046
- if (!schema) {
1047
- return [];
1048
- }
1049
- const { objects } = await this._db.query(Filter.schema(schema)).run();
1050
- return objects.map(this._objectToNode);
1051
- }
1052
- async getRelationships({ label: label2 }) {
1053
- const syntheticRefRelationships = (await this._getAllSchema()).filter((schema) => getSchemaTypename(schema) !== StoredSchema.typename).flatMap((schema) => {
1054
- const jsonSchema = toJsonSchema(schema);
1055
- const relationships = Object.entries(jsonSchema.properties).filter(([key, prop]) => isReference(prop));
1056
- return relationships.map(([key, value]) => {
1057
- const relationshipLabel = formatInferredRelationshipLabel(jsonSchema.typename ?? raise2(new Error("Schema must have typename")), key);
1058
- return {
1059
- label: relationshipLabel,
1060
- schema,
1061
- property: key
1062
- };
1063
- });
1064
- });
1065
- const relationship = syntheticRefRelationships.find((r) => r.label === label2);
1066
- if (!relationship) {
1067
- return [];
1068
- }
1069
- const { objects } = await this._db.query(Filter.schema(relationship.schema)).run();
1070
- return (await Promise.all(objects.map((object) => this._projectRefRelationship(object, relationship.property)))).flat();
1071
- }
1072
- async _getAllSchema() {
1073
- return [
1074
- ...await this._db.schemaRegistry.query().run(),
1075
- // TODO(dmaretskyi): Remove once we can serialize recursive schema.
1076
- ...this._db.graph.schemaRegistry.schemas.filter((s) => getSchemaTypename(s)?.startsWith("example.org"))
1077
- ].filter((schema) => getSchemaTypename(schema) !== StoredSchema.typename);
1078
- }
1079
- _objectToNode(object) {
1080
- const { id, ...properties2 } = object;
1081
- return {
1082
- id,
1083
- kind: "node",
1084
- label: formatNodeLabel(getSchemaTypename(getSchema(object))),
1085
- properties: properties2
1086
- };
1087
- }
1088
- async _projectRefRelationship(object, prop) {
1089
- if (!object[prop]) {
1090
- return [];
1091
- }
1092
- const value = Array.isArray(object[prop]) ? object[prop] : [
1093
- object[prop]
1094
- ];
1095
- return Promise.all(value.map(async (ref) => {
1096
- const target = await ref.load();
1097
- return {
1098
- id: `${object.id}-${prop}-${target.id}`,
1099
- kind: "relationship",
1100
- label: formatInferredRelationshipLabel(getSchemaTypename(getSchema(object)), prop),
1101
- properties: {},
1102
- source: this._objectToNode(object),
1103
- target: this._objectToNode(target)
1104
- };
1105
- }));
1106
- }
1107
- };
1108
- _ts_decorate([
1109
- log3.method(void 0, void 0, {
1110
- F: __dxlog_file4,
1111
- L: 17,
1112
- S: void 0,
1113
- C: (f, a) => f(...a)
1114
- })
1115
- ], EchoDataSource.prototype, "getNodes", null);
1116
- _ts_decorate([
1117
- log3.method(void 0, void 0, {
1118
- F: __dxlog_file4,
1119
- L: 34,
1120
- S: void 0,
1121
- C: (f, a) => f(...a)
1122
- })
1123
- ], EchoDataSource.prototype, "getRelationships", null);
1124
-
1125
- // packages/experimental/assistant/src/conversation/conversation.ts
1126
- import { invariant as invariant3 } from "@dxos/invariant";
1127
- import { log as log4 } from "@dxos/log";
1128
- var __dxlog_file5 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/conversation/conversation.ts";
1129
- var runLLM = async (params) => {
1130
- let conversationResult = null;
1131
- const generate = async () => {
1132
- log4("llm generate", {
1133
- tools: params.tools
1134
- }, {
1135
- F: __dxlog_file5,
1136
- L: 42,
1137
- S: void 0,
1138
- C: (f, a) => f(...a)
1139
- });
1140
- const beginTs = Date.now();
1141
- const result = await params.client.generate({
1142
- model: params.model,
1143
- spaceId: params.spaceId,
1144
- threadId: params.threadId,
1145
- systemPrompt: params.system,
1146
- tools: params.tools
1147
- });
1148
- for await (const event of result) {
1149
- params.logger?.(event);
1150
- }
1151
- const messages = await result.complete();
1152
- const message = messages.at(-1);
1153
- log4("llm result", {
1154
- time: Date.now() - beginTs,
1155
- message
1156
- }, {
1157
- F: __dxlog_file5,
1158
- L: 58,
1159
- S: void 0,
1160
- C: (f, a) => f(...a)
1161
- });
1162
- invariant3(message, void 0, {
1163
- F: __dxlog_file5,
1164
- L: 59,
1165
- S: void 0,
1166
- A: [
1167
- "message",
1168
- ""
1169
- ]
1170
- });
1171
- params.logger?.({
1172
- type: "message",
1173
- message
1174
- });
1175
- await params.client.insertMessages(messages.map((msg) => ({
1176
- ...msg,
1177
- content: msg.content.filter((c) => c.type !== "image")
1178
- })));
1179
- const isToolUse = message.content.at(-1)?.type === "tool_use";
1180
- if (isToolUse) {
1181
- const toolCalls = message.content.filter((c) => c.type === "tool_use");
1182
- invariant3(toolCalls.length === 1, void 0, {
1183
- F: __dxlog_file5,
1184
- L: 68,
1185
- S: void 0,
1186
- A: [
1187
- "toolCalls.length === 1",
1188
- ""
1189
- ]
1190
- });
1191
- const toolCall = toolCalls[0];
1192
- const tool = params.tools.find((t) => t.name === toolCall.name);
1193
- if (!tool) {
1194
- throw new Error(`Tool not found: ${toolCall.name}`);
1195
- }
1196
- const toolResult = await tool.execute(toolCall.input, {});
1197
- switch (toolResult.kind) {
1198
- case "error": {
1199
- log4("tool error", {
1200
- message: toolResult.message
1201
- }, {
1202
- F: __dxlog_file5,
1203
- L: 78,
1204
- S: void 0,
1205
- C: (f, a) => f(...a)
1206
- });
1207
- const resultMessage = {
1208
- id: ObjectId.random(),
1209
- spaceId: params.spaceId,
1210
- threadId: params.threadId,
1211
- role: "user",
1212
- content: [
1213
- {
1214
- type: "tool_result",
1215
- toolUseId: toolCall.id,
1216
- content: toolResult.message,
1217
- isError: true
1218
- }
1219
- ]
1220
- };
1221
- params.logger?.({
1222
- type: "message",
1223
- message: resultMessage
1224
- });
1225
- await params.client.insertMessages([
1226
- resultMessage
1227
- ]);
1228
- return true;
1229
- }
1230
- case "success": {
1231
- log4("tool success", {
1232
- result: toolResult.result
1233
- }, {
1234
- F: __dxlog_file5,
1235
- L: 99,
1236
- S: void 0,
1237
- C: (f, a) => f(...a)
1238
- });
1239
- const resultMessage = {
1240
- id: ObjectId.random(),
1241
- spaceId: params.spaceId,
1242
- threadId: params.threadId,
1243
- role: "user",
1244
- content: [
1245
- {
1246
- type: "tool_result",
1247
- toolUseId: toolCall.id,
1248
- content: JSON.stringify(toolResult.result)
1249
- }
1250
- ]
1251
- };
1252
- params.logger?.({
1253
- type: "message",
1254
- message: resultMessage
1255
- });
1256
- await params.client.insertMessages([
1257
- resultMessage
1258
- ]);
1259
- return true;
1260
- }
1261
- case "break": {
1262
- log4("tool break", {
1263
- result: toolResult.result
1264
- }, {
1265
- F: __dxlog_file5,
1266
- L: 119,
1267
- S: void 0,
1268
- C: (f, a) => f(...a)
1269
- });
1270
- conversationResult = toolResult.result;
1271
- return false;
1272
- }
1273
- }
1274
- }
1275
- return false;
1276
- };
1277
- while (await generate()) {
1278
- }
1279
- return {
1280
- result: conversationResult
1281
- };
1282
- };
1283
-
1284
- // packages/experimental/assistant/src/conversation/types.ts
1285
- import { Schema as S3 } from "@effect/schema";
1286
- import { toJsonSchema as toJsonSchema2 } from "@dxos/echo-schema";
1287
- import { JsonSchemaType as JsonSchemaType2 } from "@dxos/echo-schema";
1288
- import { log as log5 } from "@dxos/log";
1289
- var __dxlog_file6 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/conversation/types.ts";
1290
- var createUserMessage = (spaceId, threadId, text) => ({
1291
- id: ObjectId.random(),
1292
- spaceId,
1293
- threadId,
1294
- role: "user",
1295
- content: [
1296
- {
1297
- type: "text",
1298
- text
1299
- }
1300
- ]
1301
- });
1302
- var LLMToolDefinition = S3.Struct({
1303
- name: S3.String,
1304
- description: S3.String,
1305
- parameters: JsonSchemaType2,
1306
- execute: S3.Any
1307
- });
1308
- var LLMToolResult = Object.freeze({
1309
- /**
1310
- * The tool execution was successful.
1311
- * Gives the result back to the LLM.
1312
- */
1313
- Success: (result) => ({
1314
- kind: "success",
1315
- result
1316
- }),
1317
- Error: (message) => ({
1318
- kind: "error",
1319
- message
1320
- }),
1321
- /**
1322
- * Stop the conversation and return the result.
1323
- */
1324
- Break: (result) => ({
1325
- kind: "break",
1326
- result
1327
- })
1328
- });
1329
- var defineTool = ({ name, description, schema, execute }) => {
1330
- return {
1331
- name,
1332
- description,
1333
- parameters: toFunctionParameterSchema(schema),
1334
- execute: (params, context) => {
1335
- const sanitized = S3.decodeSync(schema)(params);
1336
- return execute(sanitized, context);
1337
- }
1338
- };
1339
- };
1340
- var toFunctionParameterSchema = (schema) => {
1341
- const jsonSchema = toJsonSchema2(schema);
1342
- log5("tool schema", {
1343
- jsonSchema
1344
- }, {
1345
- F: __dxlog_file6,
1346
- L: 83,
1347
- S: void 0,
1348
- C: (f, a) => f(...a)
1349
- });
1350
- for (const key in jsonSchema.properties) {
1351
- if (typeof jsonSchema.properties[key].description !== "string") {
1352
- throw new Error(`Property missing description: ${key}`);
1353
- }
1354
- }
1355
- return jsonSchema;
1356
- };
1357
-
1358
- export {
1359
- SpaceIdSchema,
1360
- ObjectIdBrand,
1361
- ObjectId,
1362
- Space,
1363
- Thread,
1364
- MessageRole,
1365
- MessageTextContentBlock,
1366
- ImageSource,
1367
- MessageImageContentBlock,
1368
- MessageToolUseContentBlock,
1369
- MessageToolResultContentBlock,
1370
- MessageContentBlock,
1371
- Message,
1372
- MessageFromDb,
1373
- LLMModel,
1374
- ToolTypes,
1375
- LLMTool,
1376
- GenerateRequest,
1377
- AIServiceClientImpl,
1378
- GenerationStream,
1379
- parseCypherQuery,
1380
- executeQueryPlan,
1381
- executeQuery,
1382
- trim,
1383
- formatJsonSchemaForLLM,
1384
- formatNodeLabel,
1385
- formatInferredRelationshipLabel,
1386
- isReference,
1387
- EchoDataSource,
1388
- runLLM,
1389
- createUserMessage,
1390
- LLMToolDefinition,
1391
- LLMToolResult,
1392
- defineTool
1393
- };
1394
- //# sourceMappingURL=chunk-AKP45LQH.mjs.map