@dxos/assistant 0.7.4-df37807 → 0.7.5-feature-compute.4d9d99a

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 (96) hide show
  1. package/dist/lib/browser/{chunk-AKP45LQH.mjs → chunk-LVLSJQB3.mjs} +506 -357
  2. package/dist/lib/browser/chunk-LVLSJQB3.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +17 -17
  4. package/dist/lib/browser/meta.json +1 -1
  5. package/dist/lib/browser/testing/index.mjs +10 -3
  6. package/dist/lib/browser/testing/index.mjs.map +4 -4
  7. package/dist/lib/node/{chunk-G6CGWEMO.cjs → chunk-SHOSAIOD.cjs} +507 -362
  8. package/dist/lib/node/chunk-SHOSAIOD.cjs.map +7 -0
  9. package/dist/lib/node/index.cjs +42 -42
  10. package/dist/lib/node/index.cjs.map +1 -1
  11. package/dist/lib/node/meta.json +1 -1
  12. package/dist/lib/node/testing/index.cjs +18 -12
  13. package/dist/lib/node/testing/index.cjs.map +4 -4
  14. package/dist/lib/node-esm/{chunk-WUPUPEFB.mjs → chunk-ZLBTRSUY.mjs} +506 -357
  15. package/dist/lib/node-esm/chunk-ZLBTRSUY.mjs.map +7 -0
  16. package/dist/lib/node-esm/index.mjs +17 -17
  17. package/dist/lib/node-esm/meta.json +1 -1
  18. package/dist/lib/node-esm/testing/index.mjs +10 -3
  19. package/dist/lib/node-esm/testing/index.mjs.map +4 -4
  20. package/dist/types/src/ai-service/client.d.ts +15 -32
  21. package/dist/types/src/ai-service/client.d.ts.map +1 -1
  22. package/dist/types/src/ai-service/index.d.ts +2 -1
  23. package/dist/types/src/ai-service/index.d.ts.map +1 -1
  24. package/dist/types/src/ai-service/stream.d.ts +34 -0
  25. package/dist/types/src/ai-service/stream.d.ts.map +1 -0
  26. package/dist/types/src/ai-service/stream.test.d.ts +2 -0
  27. package/dist/types/src/ai-service/stream.test.d.ts.map +1 -0
  28. package/dist/types/src/ai-service/types/index.d.ts +3 -0
  29. package/dist/types/src/ai-service/types/index.d.ts.map +1 -0
  30. package/dist/types/src/ai-service/types/message.d.ts +191 -0
  31. package/dist/types/src/ai-service/types/message.d.ts.map +1 -0
  32. package/dist/types/src/ai-service/types/schema.d.ts +175 -0
  33. package/dist/types/src/ai-service/types/schema.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 +54 -4
  39. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  40. package/dist/types/src/conversation/types.d.ts +35 -4
  41. package/dist/types/src/conversation/types.d.ts.map +1 -1
  42. package/dist/types/src/cypher/combinators.d.ts.map +1 -1
  43. package/dist/types/src/cypher/parjs.d.ts +1 -1
  44. package/dist/types/src/cypher/parjs.d.ts.map +1 -1
  45. package/dist/types/src/cypher/schema.d.ts.map +1 -1
  46. package/dist/types/src/testing/artifacts.test.d.ts +1 -0
  47. package/dist/types/src/testing/artifacts.test.d.ts.map +1 -0
  48. package/dist/types/src/testing/data.d.ts +2 -0
  49. package/dist/types/src/testing/data.d.ts.map +1 -0
  50. package/dist/types/src/testing/defs.d.ts +5 -0
  51. package/dist/types/src/testing/defs.d.ts.map +1 -0
  52. package/dist/types/src/testing/index.d.ts +1 -0
  53. package/dist/types/src/testing/index.d.ts.map +1 -1
  54. package/dist/types/src/testing/test-data.d.ts +1 -1
  55. package/dist/types/src/testing/test-data.d.ts.map +1 -1
  56. package/package.json +20 -18
  57. package/src/ai-service/client.test.ts +25 -26
  58. package/src/ai-service/client.ts +29 -177
  59. package/src/ai-service/index.ts +2 -1
  60. package/src/ai-service/stream.test.ts +186 -0
  61. package/src/ai-service/stream.ts +181 -0
  62. package/src/ai-service/types/index.ts +6 -0
  63. package/src/ai-service/types/message.ts +147 -0
  64. package/src/ai-service/types/schema.ts +128 -0
  65. package/src/ai-service/util/index.ts +5 -0
  66. package/src/ai-service/{sse.ts → util/sse.ts} +5 -0
  67. package/src/bin/chat.ts +6 -9
  68. package/src/conversation/conversation.test.ts +10 -14
  69. package/src/conversation/conversation.ts +109 -14
  70. package/src/conversation/types.ts +47 -6
  71. package/src/cypher/combinators.test.ts +3 -3
  72. package/src/cypher/combinators.ts +0 -1
  73. package/src/cypher/execution-plan.test.ts +5 -3
  74. package/src/cypher/parjs-shims.d.ts +4 -0
  75. package/src/cypher/parjs.ts +2 -2
  76. package/src/cypher/query-executor.test.ts +1 -1
  77. package/src/cypher/schema.ts +0 -1
  78. package/src/index.ts +1 -1
  79. package/src/testing/artifacts.test.ts +182 -0
  80. package/src/testing/data.ts +13 -0
  81. package/src/testing/defs.ts +8 -0
  82. package/src/testing/index.ts +1 -0
  83. package/src/testing/query.test.ts +9 -9
  84. package/src/testing/test-data.ts +1 -1
  85. package/vendor/parjs-browser.mjs +4 -0
  86. package/vendor/parjs-default.mjs +8 -0
  87. package/dist/lib/browser/chunk-AKP45LQH.mjs.map +0 -7
  88. package/dist/lib/node/chunk-G6CGWEMO.cjs.map +0 -7
  89. package/dist/lib/node-esm/chunk-WUPUPEFB.mjs.map +0 -7
  90. package/dist/types/src/ai-service/schema.d.ts +0 -296
  91. package/dist/types/src/ai-service/schema.d.ts.map +0 -1
  92. package/dist/types/src/ai-service/sse.d.ts.map +0 -1
  93. package/dist/types/src/sanity.test.d.ts +0 -2
  94. package/dist/types/src/sanity.test.d.ts.map +0 -1
  95. package/src/ai-service/schema.ts +0 -260
  96. package/src/sanity.test.ts +0 -9
@@ -16,12 +16,13 @@ var __copyProps = (to, from, except, desc) => {
16
16
  return to;
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var chunk_G6CGWEMO_exports = {};
20
- __export(chunk_G6CGWEMO_exports, {
19
+ var chunk_SHOSAIOD_exports = {};
20
+ __export(chunk_SHOSAIOD_exports, {
21
21
  AIServiceClientImpl: () => AIServiceClientImpl,
22
22
  EchoDataSource: () => EchoDataSource,
23
23
  GenerateRequest: () => GenerateRequest,
24
24
  GenerationStream: () => GenerationStream,
25
+ ImageContentBlock: () => ImageContentBlock,
25
26
  ImageSource: () => ImageSource,
26
27
  LLMModel: () => LLMModel,
27
28
  LLMTool: () => LLMTool,
@@ -29,18 +30,15 @@ __export(chunk_G6CGWEMO_exports, {
29
30
  LLMToolResult: () => LLMToolResult,
30
31
  Message: () => Message,
31
32
  MessageContentBlock: () => MessageContentBlock,
32
- MessageFromDb: () => MessageFromDb,
33
- MessageImageContentBlock: () => MessageImageContentBlock,
34
33
  MessageRole: () => MessageRole,
35
- MessageTextContentBlock: () => MessageTextContentBlock,
36
- MessageToolResultContentBlock: () => MessageToolResultContentBlock,
37
- MessageToolUseContentBlock: () => MessageToolUseContentBlock,
38
- ObjectId: () => ObjectId,
39
- ObjectIdBrand: () => ObjectIdBrand,
40
34
  Space: () => Space,
41
35
  SpaceIdSchema: () => SpaceIdSchema,
36
+ TagContentBlock: () => TagContentBlock,
37
+ TextContentBlock: () => TextContentBlock,
42
38
  Thread: () => Thread,
39
+ ToolResultContentBlock: () => ToolResultContentBlock,
43
40
  ToolTypes: () => ToolTypes,
41
+ ToolUseContentBlock: () => ToolUseContentBlock,
44
42
  createUserMessage: () => createUserMessage,
45
43
  defineTool: () => defineTool,
46
44
  executeQuery: () => executeQuery,
@@ -49,152 +47,41 @@ __export(chunk_G6CGWEMO_exports, {
49
47
  formatJsonSchemaForLLM: () => formatJsonSchemaForLLM,
50
48
  formatNodeLabel: () => formatNodeLabel,
51
49
  isReference: () => isReference,
50
+ isToolUse: () => isToolUse,
52
51
  parseCypherQuery: () => parseCypherQuery,
53
52
  runLLM: () => runLLM,
53
+ runTools: () => runTools,
54
54
  trim: () => trim
55
55
  });
56
- module.exports = __toCommonJS(chunk_G6CGWEMO_exports);
56
+ module.exports = __toCommonJS(chunk_SHOSAIOD_exports);
57
+ var import_async = require("@dxos/async");
58
+ var import_invariant = require("@dxos/invariant");
59
+ var import_log = require("@dxos/log");
57
60
  var import_schema = require("@effect/schema");
58
- var import_ulidx = require("ulidx");
59
61
  var import_echo_schema = require("@dxos/echo-schema");
60
62
  var import_keys = require("@dxos/keys");
61
63
  var import_schema2 = require("@effect/schema");
62
- var import_async = require("@dxos/async");
63
- var import_invariant = require("@dxos/invariant");
64
- var import_parjs = require("#parjs");
65
- var import_log = require("@dxos/log");
66
- var import_util = require("@dxos/util");
64
+ var import_echo_schema2 = require("@dxos/echo-schema");
65
+ var import_schema3 = require("@effect/schema");
67
66
  var import_invariant2 = require("@dxos/invariant");
67
+ var import_parjs = require("#parjs");
68
68
  var import_log2 = require("@dxos/log");
69
+ var import_util = require("@dxos/util");
70
+ var import_invariant3 = require("@dxos/invariant");
71
+ var import_log3 = require("@dxos/log");
69
72
  var import_debug = require("@dxos/debug");
70
- var import_echo_schema2 = require("@dxos/echo-schema");
73
+ var import_echo_schema3 = require("@dxos/echo-schema");
71
74
  var import_debug2 = require("@dxos/debug");
72
75
  var import_echo_db = require("@dxos/echo-db");
73
- var import_echo_schema3 = require("@dxos/echo-schema");
76
+ var import_echo_schema4 = require("@dxos/echo-schema");
74
77
  var import_live_object = require("@dxos/live-object");
75
- var import_log3 = require("@dxos/log");
76
- var import_invariant3 = require("@dxos/invariant");
77
78
  var import_log4 = require("@dxos/log");
78
- var import_schema3 = require("@effect/schema");
79
- var import_echo_schema4 = require("@dxos/echo-schema");
79
+ var import_schema4 = require("@effect/schema");
80
80
  var import_echo_schema5 = require("@dxos/echo-schema");
81
81
  var import_log5 = require("@dxos/log");
82
- var SpaceIdSchema = import_schema.Schema.String.pipe(import_schema.Schema.filter(import_keys.SpaceId.isValid));
83
- var ObjectIdBrand = Symbol("@dxos/echo/ObjectId");
84
- var ObjectIdSchema = import_schema.Schema.ULID.pipe(import_schema.Schema.brand(ObjectIdBrand));
85
- var ObjectId = class extends ObjectIdSchema {
86
- static random() {
87
- return (0, import_ulidx.ulid)();
88
- }
89
- };
90
- var Space = import_schema.Schema.Struct({
91
- id: SpaceIdSchema
92
- });
93
- var Thread = import_schema.Schema.Struct({
94
- id: ObjectId,
95
- spaceId: SpaceIdSchema
96
- });
97
- var MessageRole = import_schema.Schema.String.pipe(import_schema.Schema.filter((role) => role === "user" || role === "assistant"));
98
- var MessageTextContentBlock = import_schema.Schema.Struct({
99
- type: import_schema.Schema.Literal("text"),
100
- text: import_schema.Schema.String
101
- }).pipe(import_schema.Schema.mutable);
102
- var ImageSource = import_schema.Schema.Struct({
103
- type: import_schema.Schema.Literal("base64"),
104
- media_type: import_schema.Schema.Literal("image/jpeg", "image/png", "image/gif", "image/webp"),
105
- data: import_schema.Schema.String
106
- }).pipe(import_schema.Schema.mutable);
107
- var MessageImageContentBlock = import_schema.Schema.Struct({
108
- type: import_schema.Schema.Literal("image"),
109
- id: import_schema.Schema.optional(import_schema.Schema.String),
110
- source: import_schema.Schema.optional(ImageSource)
111
- }).pipe(import_schema.Schema.mutable);
112
- var MessageToolUseContentBlock = import_schema.Schema.Struct({
113
- type: import_schema.Schema.Literal("tool_use"),
114
- /**
115
- * Opaque service-defined ID of the tool invocation.
116
- * Used to match the tool result block.
117
- */
118
- id: import_schema.Schema.String,
119
- /**
120
- * Tool name.
121
- */
122
- name: import_schema.Schema.String,
123
- input: import_schema.Schema.Unknown,
124
- /**
125
- * Used to accumulate the partial tool input JSON in streaming mode.
126
- */
127
- inputJson: import_schema.Schema.optional(import_schema.Schema.String)
128
- }).pipe(import_schema.Schema.mutable);
129
- var MessageToolResultContentBlock = import_schema.Schema.Struct({
130
- type: import_schema.Schema.Literal("tool_result"),
131
- toolUseId: import_schema.Schema.String,
132
- content: import_schema.Schema.String,
133
- isError: import_schema.Schema.optional(import_schema.Schema.Boolean)
134
- });
135
- var MessageContentBlock = import_schema.Schema.Union(MessageTextContentBlock, MessageImageContentBlock, MessageToolUseContentBlock, MessageToolResultContentBlock);
136
- var Message = import_schema.Schema.Struct({
137
- id: ObjectId,
138
- threadId: import_schema.Schema.optional(ObjectId),
139
- spaceId: import_schema.Schema.optional(SpaceIdSchema),
140
- role: MessageRole,
141
- content: import_schema.Schema.Array(MessageContentBlock).pipe(import_schema.Schema.mutable),
142
- /**
143
- * ID of the message from the foreign provider.
144
- */
145
- // TODO(dmaretskyi): Should be in meta/keys.
146
- foreignId: import_schema.Schema.optional(import_schema.Schema.String)
147
- });
148
- var MessageFromDb = import_schema.Schema.Struct({
149
- ...Message.fields,
150
- content: import_schema.Schema.propertySignature(Message.fields.content.pipe((schema) => import_schema.Schema.parseJson(schema))).pipe(import_schema.Schema.fromKey("contentJson"))
151
- });
152
- var LLMModel = import_schema.Schema.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");
153
- var ToolTypes = Object.freeze({
154
- // TODO(dmaretskyi): Not implemented yet.
155
- // DatabaseQuery: 'database_query',
156
- TextToImage: "text_to_image"
157
- });
158
- var LLMTool = import_schema.Schema.Struct({
159
- name: import_schema.Schema.String,
160
- /**
161
- * If the tool is implemented by the service a type should be provided.
162
- * For user-implemented tools, this field should be omitted.
163
- * See {@link ToolTypes} for the list of supported types.
164
- */
165
- type: import_schema.Schema.optional(import_schema.Schema.String),
166
- /**
167
- * Required for user-implemented tools.
168
- */
169
- description: import_schema.Schema.optional(import_schema.Schema.String),
170
- /**
171
- * Input schema for the tool in the JSON Schema format.
172
- * Required for user-implemented tools.
173
- */
174
- parameters: import_schema.Schema.optional(import_echo_schema.JsonSchemaType),
175
- /**
176
- * Tool-specific options.
177
- */
178
- options: import_schema.Schema.optional(import_schema.Schema.Any),
179
- /**
180
- * Javascript function to execute the tool.
181
- */
182
- execute: import_schema.Schema.optional(import_schema.Schema.Any)
183
- });
184
- var GenerateRequest = import_schema.Schema.Struct({
185
- model: LLMModel,
186
- spaceId: SpaceIdSchema,
187
- threadId: ObjectId,
188
- /**
189
- * System instructions to the LLM.
190
- */
191
- // TODO(dmaretskyi): Should this be part of the thread?.
192
- systemPrompt: import_schema.Schema.optional(import_schema.Schema.String),
193
- /**
194
- * Tools available for the LLM.
195
- */
196
- tools: import_schema.Schema.Array(LLMTool).pipe(import_schema.Schema.mutable)
197
- });
82
+ var import_echo_schema6 = require("@dxos/echo-schema");
83
+ var import_invariant4 = require("@dxos/invariant");
84
+ var import_log6 = require("@dxos/log");
198
85
  async function* iterSSEMessages(response, controller) {
199
86
  if (!response.body) {
200
87
  controller.abort();
@@ -429,83 +316,44 @@ var LineDecoder = class _LineDecoder {
429
316
  return lines;
430
317
  }
431
318
  };
432
- var __dxlog_file = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/ai-service/client.ts";
433
- var AIServiceClientImpl = class {
434
- constructor({ endpoint }) {
435
- this._endpoint = endpoint;
436
- }
437
- async getSpace(spaceId) {
438
- throw new Error("Not implemented");
439
- }
440
- async getThread(spaceId, threadId) {
441
- throw new Error("Not implemented");
442
- }
443
- async getMessagesInThread(spaceId, threadId) {
444
- const res = await fetch(`${this._endpoint}/space/${spaceId}/thread/${threadId}/message`);
445
- return import_schema2.Schema.decodePromise(import_schema2.Schema.Array(Message).pipe(import_schema2.Schema.mutable))((await res.json()).data.results);
446
- }
447
- async insertMessages(messages) {
448
- const res = await fetch(`${this._endpoint}/message`, {
449
- method: "POST",
450
- headers: {
451
- "Content-Type": "application/json"
452
- },
453
- body: JSON.stringify({
454
- messages: await import_schema2.Schema.encodePromise(import_schema2.Schema.Array(Message))(messages)
455
- })
456
- });
457
- if (!res.ok) {
458
- throw new Error(await res.text());
459
- }
460
- }
461
- // TODO(dmaretskyi): Accept partial message schema.
462
- async updateMessage(spaceId, threadId, messageId, message) {
463
- throw new Error("Not implemented");
464
- }
465
- async generate(request) {
466
- const response = await fetch(`${this._endpoint}/generate`, {
467
- method: "POST",
468
- headers: {
469
- "Content-Type": "application/json"
470
- },
471
- body: JSON.stringify(request)
472
- });
473
- (0, import_invariant.invariant)(response.body instanceof ReadableStream, void 0, {
474
- F: __dxlog_file,
475
- L: 81,
476
- S: this,
477
- A: [
478
- "response.body instanceof ReadableStream",
479
- ""
480
- ]
481
- });
482
- return GenerationStream.fromSSEResponse({
483
- spaceId: request.spaceId,
484
- threadId: request.threadId
485
- }, response);
486
- }
487
- };
319
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/stream.ts";
488
320
  var GenerationStream = class _GenerationStream {
489
- static fromSSEResponse(params, response) {
490
- const controller = new AbortController();
321
+ /**
322
+ * Creates a stream from an SSE response.
323
+ */
324
+ static fromSSEResponse(params, response, controller = new AbortController()) {
491
325
  const iterator = async function* () {
492
326
  for await (const sse of iterSSEMessages(response, controller)) {
493
327
  if (sse.event === "completion") {
494
328
  try {
495
329
  yield JSON.parse(sse.data);
496
- } catch (e) {
497
- console.error("Could not parse message into JSON:", sse.data);
498
- console.error("From chunk:", sse.raw);
499
- throw e;
330
+ } catch (err) {
331
+ import_log.log.error("could not parse message into JSON:", {
332
+ data: sse.data,
333
+ raw: sse.raw
334
+ }, {
335
+ F: __dxlog_file,
336
+ L: 30,
337
+ S: this,
338
+ C: (f, a) => f(...a)
339
+ });
340
+ throw err;
500
341
  }
501
342
  }
502
343
  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") {
503
344
  try {
504
345
  yield JSON.parse(sse.data);
505
- } catch (e) {
506
- console.error("Could not parse message into JSON:", sse.data);
507
- console.error("From chunk:", sse.raw);
508
- throw e;
346
+ } catch (err) {
347
+ import_log.log.error("could not parse message into JSON:", {
348
+ data: sse.data,
349
+ raw: sse.raw
350
+ }, {
351
+ F: __dxlog_file,
352
+ L: 46,
353
+ S: this,
354
+ C: (f, a) => f(...a)
355
+ });
356
+ throw err;
509
357
  }
510
358
  }
511
359
  if (sse.event === "ping") {
@@ -516,22 +364,20 @@ var GenerationStream = class _GenerationStream {
516
364
  }
517
365
  }
518
366
  };
519
- return new _GenerationStream(params, iterator);
367
+ return new _GenerationStream(controller, iterator, params);
520
368
  }
521
- constructor(_params, _getIterator) {
522
- this._params = _params;
369
+ constructor(_controller, _getIterator, _params) {
370
+ this._controller = _controller;
523
371
  this._getIterator = _getIterator;
372
+ this._params = _params;
373
+ this._done = new import_async.Trigger();
524
374
  this._previousMessages = [];
525
375
  this._accumulatedMessage = void 0;
526
- this._done = new import_async.Trigger();
527
376
  this._iterator = void 0;
528
377
  }
529
378
  [Symbol.asyncIterator]() {
530
379
  return this._createIterator();
531
380
  }
532
- cancel() {
533
- throw new Error("Not implemented");
534
- }
535
381
  get accumulatedMessages() {
536
382
  return [
537
383
  ...this._previousMessages,
@@ -541,6 +387,12 @@ var GenerationStream = class _GenerationStream {
541
387
  ];
542
388
  }
543
389
  /**
390
+ * Aborts the stream.
391
+ */
392
+ abort() {
393
+ this._controller.abort();
394
+ }
395
+ /**
544
396
  * Returns the complete message list generated by the AI service.
545
397
  */
546
398
  async complete() {
@@ -549,12 +401,20 @@ var GenerationStream = class _GenerationStream {
549
401
  }
550
402
  _createIterator() {
551
403
  const self = this;
552
- return this._iterator ??= async function* () {
553
- for await (const event of self._getIterator()) {
554
- self._processEvent(event);
555
- yield event;
556
- }
557
- }();
404
+ return this._iterator ??= (() => {
405
+ const generator = async function* () {
406
+ try {
407
+ for await (const event of self._getIterator()) {
408
+ self._processEvent(event);
409
+ yield event;
410
+ }
411
+ this._done.wake();
412
+ } catch (err) {
413
+ this._done.throw(err);
414
+ }
415
+ };
416
+ return generator.call(this);
417
+ })();
558
418
  }
559
419
  _processEvent(event) {
560
420
  switch (event.type) {
@@ -585,7 +445,7 @@ var GenerationStream = class _GenerationStream {
585
445
  case "content_block_start": {
586
446
  (0, import_invariant.invariant)(this._accumulatedMessage, void 0, {
587
447
  F: __dxlog_file,
588
- L: 212,
448
+ L: 148,
589
449
  S: this,
590
450
  A: [
591
451
  "this._accumulatedMessage",
@@ -598,7 +458,7 @@ var GenerationStream = class _GenerationStream {
598
458
  case "content_block_delta": {
599
459
  (0, import_invariant.invariant)(this._accumulatedMessage, void 0, {
600
460
  F: __dxlog_file,
601
- L: 217,
461
+ L: 154,
602
462
  S: this,
603
463
  A: [
604
464
  "this._accumulatedMessage",
@@ -617,7 +477,7 @@ var GenerationStream = class _GenerationStream {
617
477
  case "content_block_stop": {
618
478
  (0, import_invariant.invariant)(this._accumulatedMessage, void 0, {
619
479
  F: __dxlog_file,
620
- L: 233,
480
+ L: 171,
621
481
  S: this,
622
482
  A: [
623
483
  "this._accumulatedMessage",
@@ -626,12 +486,194 @@ var GenerationStream = class _GenerationStream {
626
486
  });
627
487
  const lastBlock = this._accumulatedMessage.content.at(-1);
628
488
  if (lastBlock?.type === "tool_use") {
629
- lastBlock.input = JSON.parse(lastBlock.inputJson ?? "");
489
+ lastBlock.input = lastBlock.inputJson == null || lastBlock.inputJson === "" ? {} : JSON.parse(lastBlock.inputJson ?? "");
630
490
  }
631
491
  break;
632
492
  }
633
493
  }
634
- this._done.wake();
494
+ }
495
+ };
496
+ var SpaceIdSchema = import_schema.Schema.String.pipe(import_schema.Schema.filter(import_keys.SpaceId.isValid));
497
+ var Space = import_schema.Schema.Struct({
498
+ id: SpaceIdSchema
499
+ });
500
+ var Thread = import_schema.Schema.Struct({
501
+ id: import_echo_schema.ObjectId,
502
+ spaceId: SpaceIdSchema
503
+ });
504
+ var MessageRole = import_schema.Schema.String.pipe(import_schema.Schema.filter((role) => role === "user" || role === "assistant"));
505
+ var TagContentBlock = import_schema.Schema.Struct({
506
+ type: import_schema.Schema.Literal("tag"),
507
+ tag: import_schema.Schema.String,
508
+ text: import_schema.Schema.String
509
+ }).pipe(import_schema.Schema.mutable);
510
+ var TextContentBlock = import_schema.Schema.Struct({
511
+ type: import_schema.Schema.Literal("text"),
512
+ text: import_schema.Schema.String
513
+ }).pipe(import_schema.Schema.mutable);
514
+ var ImageSource = import_schema.Schema.Struct({
515
+ type: import_schema.Schema.Literal("base64"),
516
+ media_type: import_schema.Schema.Literal("image/jpeg", "image/png", "image/gif", "image/webp"),
517
+ data: import_schema.Schema.String
518
+ }).pipe(import_schema.Schema.mutable);
519
+ var ImageContentBlock = import_schema.Schema.Struct({
520
+ type: import_schema.Schema.Literal("image"),
521
+ id: import_schema.Schema.optional(import_schema.Schema.String),
522
+ source: import_schema.Schema.optional(ImageSource)
523
+ }).pipe(import_schema.Schema.mutable);
524
+ var ToolUseContentBlock = import_schema.Schema.Struct({
525
+ type: import_schema.Schema.Literal("tool_use"),
526
+ /**
527
+ * Opaque service-defined ID of the tool invocation.
528
+ * Used to match the tool result block.
529
+ */
530
+ id: import_schema.Schema.String,
531
+ /**
532
+ * Tool name.
533
+ */
534
+ name: import_schema.Schema.String,
535
+ input: import_schema.Schema.Unknown,
536
+ /**
537
+ * Used to accumulate the partial tool input JSON in streaming mode.
538
+ */
539
+ // TODO(burdon): Remove?
540
+ inputJson: import_schema.Schema.optional(import_schema.Schema.String)
541
+ }).pipe(import_schema.Schema.mutable);
542
+ var ToolResultContentBlock = import_schema.Schema.Struct({
543
+ type: import_schema.Schema.Literal("tool_result"),
544
+ toolUseId: import_schema.Schema.String,
545
+ content: import_schema.Schema.String,
546
+ isError: import_schema.Schema.optional(import_schema.Schema.Boolean)
547
+ });
548
+ var MessageContentBlock = import_schema.Schema.Union(TagContentBlock, TextContentBlock, ImageContentBlock, ToolUseContentBlock, ToolResultContentBlock);
549
+ var MessageSchema = import_schema.Schema.Struct({
550
+ id: import_echo_schema.ObjectId,
551
+ threadId: import_schema.Schema.optional(import_echo_schema.ObjectId),
552
+ spaceId: import_schema.Schema.optional(SpaceIdSchema),
553
+ /**
554
+ * ID of the message from the foreign provider.
555
+ */
556
+ // TODO(dmaretskyi): Should be in meta/keys.
557
+ foreignId: import_schema.Schema.optional(import_schema.Schema.String),
558
+ // TODO(dmaretskyi): Figure out how to deal with those.
559
+ // created: S.optional(S.DateFromString),
560
+ // updated: S.optional(S.DateFromString),
561
+ role: MessageRole,
562
+ // TODO(burdon): Rename blocks?
563
+ content: import_schema.Schema.Array(MessageContentBlock).pipe(import_schema.Schema.mutable)
564
+ });
565
+ var Message = MessageSchema.pipe((0, import_echo_schema.EchoObject)("dxos.org/type/Message", "0.1.0"));
566
+ var LLMModel = import_schema2.Schema.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", "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b");
567
+ var ToolTypes = Object.freeze({
568
+ // TODO(dmaretskyi): Not implemented yet.
569
+ // DatabaseQuery: 'database_query',
570
+ TextToImage: "text_to_image"
571
+ });
572
+ var LLMTool = import_schema2.Schema.Struct({
573
+ name: import_schema2.Schema.String,
574
+ /**
575
+ * If the tool is implemented by the service a type should be provided.
576
+ * For user-implemented tools, this field should be omitted.
577
+ * See {@link ToolTypes} for the list of supported types.
578
+ */
579
+ type: import_schema2.Schema.optional(import_schema2.Schema.String),
580
+ /**
581
+ * Required for user-implemented tools.
582
+ */
583
+ description: import_schema2.Schema.optional(import_schema2.Schema.String),
584
+ /**
585
+ * Input schema for the tool in the JSON Schema format.
586
+ * Required for user-implemented tools.
587
+ */
588
+ parameters: import_schema2.Schema.optional(import_echo_schema2.JsonSchemaType),
589
+ /**
590
+ * Tool-specific options.
591
+ */
592
+ options: import_schema2.Schema.optional(import_schema2.Schema.Any),
593
+ /**
594
+ * Javascript function to execute the tool.
595
+ */
596
+ execute: import_schema2.Schema.optional(import_schema2.Schema.Any)
597
+ });
598
+ var GenerateRequest = import_schema2.Schema.Struct({
599
+ model: LLMModel,
600
+ spaceId: import_schema2.Schema.optional(SpaceIdSchema),
601
+ threadId: import_schema2.Schema.optional(import_echo_schema2.ObjectId),
602
+ /**
603
+ * History of messages to include in the context window.
604
+ */
605
+ history: import_schema2.Schema.optional(import_schema2.Schema.Array(Message)),
606
+ /**
607
+ * System instructions to the LLM.
608
+ */
609
+ // TODO(dmaretskyi): Should this be part of the thread?.
610
+ systemPrompt: import_schema2.Schema.optional(import_schema2.Schema.String),
611
+ /**
612
+ * Tools available for the LLM.
613
+ */
614
+ tools: import_schema2.Schema.optional(import_schema2.Schema.Array(LLMTool).pipe(import_schema2.Schema.mutable))
615
+ });
616
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/client.ts";
617
+ var AIServiceClientImpl = class {
618
+ constructor({ endpoint }) {
619
+ this._endpoint = endpoint;
620
+ }
621
+ async getSpace(spaceId) {
622
+ throw new Error("Not implemented");
623
+ }
624
+ async getThread(spaceId, threadId) {
625
+ throw new Error("Not implemented");
626
+ }
627
+ async getMessages(spaceId, threadId) {
628
+ const res = await fetch(`${this._endpoint}/space/${spaceId}/thread/${threadId}/message`);
629
+ return import_schema3.Schema.decodePromise(import_schema3.Schema.Array(Message).pipe(import_schema3.Schema.mutable))((await res.json()).data.results);
630
+ }
631
+ async appendMessages(messages) {
632
+ const url = `${this._endpoint}/message`;
633
+ const res = await fetch(url, {
634
+ method: "POST",
635
+ headers: {
636
+ "Content-Type": "application/json"
637
+ },
638
+ body: JSON.stringify({
639
+ messages: await import_schema3.Schema.encodePromise(import_schema3.Schema.Array(Message))(messages)
640
+ })
641
+ });
642
+ if (!res.ok) {
643
+ throw new Error(`${await res.text()} [${url}]`);
644
+ }
645
+ }
646
+ // TODO(dmaretskyi): Accept partial message schema.
647
+ async updateMessage(spaceId, threadId, messageId, message) {
648
+ throw new Error("Not implemented");
649
+ }
650
+ /**
651
+ * Open message stream.
652
+ */
653
+ async generate(request) {
654
+ const controller = new AbortController();
655
+ const signal = controller.signal;
656
+ const response = await fetch(`${this._endpoint}/generate`, {
657
+ method: "POST",
658
+ headers: {
659
+ "Content-Type": "application/json"
660
+ },
661
+ body: JSON.stringify(request),
662
+ signal
663
+ });
664
+ (0, import_invariant2.invariant)(response.body instanceof ReadableStream, void 0, {
665
+ F: __dxlog_file2,
666
+ L: 85,
667
+ S: this,
668
+ A: [
669
+ "response.body instanceof ReadableStream",
670
+ ""
671
+ ]
672
+ });
673
+ return GenerationStream.fromSSEResponse({
674
+ spaceId: request.spaceId,
675
+ threadId: request.threadId
676
+ }, response, controller);
635
677
  }
636
678
  };
637
679
  var ws = import_parjs.parjs.whitespace();
@@ -716,7 +758,7 @@ var parseCypherQuery = (query) => {
716
758
  throw new Error(`Failed to parse query: ${parseResult}`);
717
759
  }
718
760
  };
719
- var __dxlog_file2 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/cypher/execution-plan.ts";
761
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/cypher/execution-plan.ts";
720
762
  var createExecutionPlan = (query) => {
721
763
  return new ExecutionPlanBuilder().build(query);
722
764
  };
@@ -728,10 +770,10 @@ var ExecutionPlanBuilder = class {
728
770
  return `anon_${this.counter++}`;
729
771
  }
730
772
  build(query) {
731
- (0, import_log2.log)("Creating execution plan for query", {
773
+ (0, import_log3.log)("Creating execution plan for query", {
732
774
  query
733
775
  }, {
734
- F: __dxlog_file2,
776
+ F: __dxlog_file3,
735
777
  L: 76,
736
778
  S: this,
737
779
  C: (f, a) => f(...a)
@@ -748,8 +790,8 @@ var ExecutionPlanBuilder = class {
748
790
  };
749
791
  }
750
792
  createStepsForMatchClause(match) {
751
- (0, import_invariant2.invariant)(match.pattern.segments.length > 0, void 0, {
752
- F: __dxlog_file2,
793
+ (0, import_invariant3.invariant)(match.pattern.segments.length > 0, void 0, {
794
+ F: __dxlog_file3,
753
795
  L: 90,
754
796
  S: this,
755
797
  A: [
@@ -758,8 +800,8 @@ var ExecutionPlanBuilder = class {
758
800
  ]
759
801
  });
760
802
  const firstSegment = match.pattern.segments[0];
761
- (0, import_invariant2.invariant)(firstSegment.astKind === "NodePattern", void 0, {
762
- F: __dxlog_file2,
803
+ (0, import_invariant3.invariant)(firstSegment.astKind === "NodePattern", void 0, {
804
+ F: __dxlog_file3,
763
805
  L: 92,
764
806
  S: this,
765
807
  A: [
@@ -786,8 +828,8 @@ var ExecutionPlanBuilder = class {
786
828
  }
787
829
  for (let i = 1; i < match.pattern.segments.length; i++) {
788
830
  const relationshipSegment = match.pattern.segments[i++];
789
- (0, import_invariant2.invariant)(relationshipSegment.astKind === "RelationshipPattern", void 0, {
790
- F: __dxlog_file2,
831
+ (0, import_invariant3.invariant)(relationshipSegment.astKind === "RelationshipPattern", void 0, {
832
+ F: __dxlog_file3,
791
833
  L: 115,
792
834
  S: this,
793
835
  A: [
@@ -796,8 +838,8 @@ var ExecutionPlanBuilder = class {
796
838
  ]
797
839
  });
798
840
  const nodeSegment = match.pattern.segments[i];
799
- (0, import_invariant2.invariant)(nodeSegment.astKind === "NodePattern", void 0, {
800
- F: __dxlog_file2,
841
+ (0, import_invariant3.invariant)(nodeSegment.astKind === "NodePattern", void 0, {
842
+ F: __dxlog_file3,
801
843
  L: 117,
802
844
  S: this,
803
845
  A: [
@@ -878,15 +920,15 @@ var getDirection = (left, right) => {
878
920
  }
879
921
  throw new Error(`Invalid direction: ()${left}[]${right}()`);
880
922
  };
881
- var __dxlog_file3 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/cypher/query-executor.ts";
923
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/cypher/query-executor.ts";
882
924
  var executeQueryPlan = async (dataSource, plan) => {
883
925
  let buffer = [];
884
926
  const results = [];
885
927
  for (const step of plan.steps) {
886
- (0, import_log.log)("begin step", {
928
+ (0, import_log2.log)("begin step", {
887
929
  step
888
930
  }, {
889
- F: __dxlog_file3,
931
+ F: __dxlog_file4,
890
932
  L: 41,
891
933
  S: void 0,
892
934
  C: (f, a) => f(...a)
@@ -972,11 +1014,11 @@ var executeQueryPlan = async (dataSource, plan) => {
972
1014
  break;
973
1015
  }
974
1016
  }
975
- (0, import_log.log)("finish step", {
1017
+ (0, import_log2.log)("finish step", {
976
1018
  buffer: buffer.map((tuple) => (0, import_util.mapValues)(tuple, (x) => x.id)),
977
1019
  results
978
1020
  }, {
979
- F: __dxlog_file3,
1021
+ F: __dxlog_file4,
980
1022
  L: 118,
981
1023
  S: void 0,
982
1024
  C: (f, a) => f(...a)
@@ -1059,14 +1101,14 @@ var formatInferredRelationshipLabel = (typename, property2) => {
1059
1101
  const nodeLabel = formatNodeLabel(typename);
1060
1102
  return `${nodeLabel}_${property2}`.toUpperCase();
1061
1103
  };
1062
- var isReference = (schema) => schema.$id === import_echo_schema2.JSON_SCHEMA_ECHO_REF_ID || schema.type === "array" && schema.items?.$id === import_echo_schema2.JSON_SCHEMA_ECHO_REF_ID;
1104
+ var isReference = (schema) => schema.$id === import_echo_schema3.JSON_SCHEMA_ECHO_REF_ID || schema.type === "array" && schema.items?.$id === import_echo_schema3.JSON_SCHEMA_ECHO_REF_ID;
1063
1105
  function _ts_decorate(decorators, target, key, desc) {
1064
1106
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1065
1107
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1066
1108
  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;
1067
1109
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1068
1110
  }
1069
- var __dxlog_file4 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/cypher/echo-data-source.ts";
1111
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/cypher/echo-data-source.ts";
1070
1112
  var EchoDataSource = class {
1071
1113
  constructor(_db) {
1072
1114
  this._db = _db;
@@ -1076,7 +1118,7 @@ var EchoDataSource = class {
1076
1118
  const { objects: objects2 } = await this._db.query().run();
1077
1119
  return objects2.map(this._objectToNode);
1078
1120
  }
1079
- const schema = (await this._getAllSchema()).find((s) => (0, import_echo_schema3.getSchemaTypename)(s)?.endsWith(label2));
1121
+ const schema = (await this._getAllSchema()).find((s) => (0, import_echo_schema4.getSchemaTypename)(s)?.endsWith(label2));
1080
1122
  if (!schema) {
1081
1123
  return [];
1082
1124
  }
@@ -1084,8 +1126,8 @@ var EchoDataSource = class {
1084
1126
  return objects.map(this._objectToNode);
1085
1127
  }
1086
1128
  async getRelationships({ label: label2 }) {
1087
- const syntheticRefRelationships = (await this._getAllSchema()).filter((schema) => (0, import_echo_schema3.getSchemaTypename)(schema) !== import_echo_schema3.StoredSchema.typename).flatMap((schema) => {
1088
- const jsonSchema = (0, import_echo_schema3.toJsonSchema)(schema);
1129
+ const syntheticRefRelationships = (await this._getAllSchema()).filter((schema) => (0, import_echo_schema4.getSchemaTypename)(schema) !== import_echo_schema4.StoredSchema.typename).flatMap((schema) => {
1130
+ const jsonSchema = (0, import_echo_schema4.toJsonSchema)(schema);
1089
1131
  const relationships = Object.entries(jsonSchema.properties).filter(([key, prop]) => isReference(prop));
1090
1132
  return relationships.map(([key, value]) => {
1091
1133
  const relationshipLabel = formatInferredRelationshipLabel(jsonSchema.typename ?? (0, import_debug2.raise)(new Error("Schema must have typename")), key);
@@ -1107,15 +1149,15 @@ var EchoDataSource = class {
1107
1149
  return [
1108
1150
  ...await this._db.schemaRegistry.query().run(),
1109
1151
  // TODO(dmaretskyi): Remove once we can serialize recursive schema.
1110
- ...this._db.graph.schemaRegistry.schemas.filter((s) => (0, import_echo_schema3.getSchemaTypename)(s)?.startsWith("example.org"))
1111
- ].filter((schema) => (0, import_echo_schema3.getSchemaTypename)(schema) !== import_echo_schema3.StoredSchema.typename);
1152
+ ...this._db.graph.schemaRegistry.schemas.filter((s) => (0, import_echo_schema4.getSchemaTypename)(s)?.startsWith("example.org"))
1153
+ ].filter((schema) => (0, import_echo_schema4.getSchemaTypename)(schema) !== import_echo_schema4.StoredSchema.typename);
1112
1154
  }
1113
1155
  _objectToNode(object) {
1114
1156
  const { id, ...properties2 } = object;
1115
1157
  return {
1116
1158
  id,
1117
1159
  kind: "node",
1118
- label: formatNodeLabel((0, import_echo_schema3.getSchemaTypename)((0, import_live_object.getSchema)(object))),
1160
+ label: formatNodeLabel((0, import_echo_schema4.getSchemaTypename)((0, import_live_object.getSchema)(object))),
1119
1161
  properties: properties2
1120
1162
  };
1121
1163
  }
@@ -1131,7 +1173,7 @@ var EchoDataSource = class {
1131
1173
  return {
1132
1174
  id: `${object.id}-${prop}-${target.id}`,
1133
1175
  kind: "relationship",
1134
- label: formatInferredRelationshipLabel((0, import_echo_schema3.getSchemaTypename)((0, import_live_object.getSchema)(object)), prop),
1176
+ label: formatInferredRelationshipLabel((0, import_echo_schema4.getSchemaTypename)((0, import_live_object.getSchema)(object)), prop),
1135
1177
  properties: {},
1136
1178
  source: this._objectToNode(object),
1137
1179
  target: this._objectToNode(target)
@@ -1140,58 +1182,133 @@ var EchoDataSource = class {
1140
1182
  }
1141
1183
  };
1142
1184
  _ts_decorate([
1143
- import_log3.log.method(void 0, void 0, {
1144
- F: __dxlog_file4,
1185
+ import_log4.log.method(void 0, void 0, {
1186
+ F: __dxlog_file5,
1145
1187
  L: 17,
1146
1188
  S: void 0,
1147
1189
  C: (f, a) => f(...a)
1148
1190
  })
1149
1191
  ], EchoDataSource.prototype, "getNodes", null);
1150
1192
  _ts_decorate([
1151
- import_log3.log.method(void 0, void 0, {
1152
- F: __dxlog_file4,
1193
+ import_log4.log.method(void 0, void 0, {
1194
+ F: __dxlog_file5,
1153
1195
  L: 34,
1154
1196
  S: void 0,
1155
1197
  C: (f, a) => f(...a)
1156
1198
  })
1157
1199
  ], EchoDataSource.prototype, "getRelationships", null);
1158
- var __dxlog_file5 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/conversation/conversation.ts";
1200
+ var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/conversation/types.ts";
1201
+ var createUserMessage = (spaceId, threadId, text) => ({
1202
+ id: import_echo_schema5.ObjectId.random(),
1203
+ spaceId,
1204
+ threadId,
1205
+ role: "user",
1206
+ content: [
1207
+ {
1208
+ type: "text",
1209
+ text
1210
+ }
1211
+ ]
1212
+ });
1213
+ var LLMToolDefinition = import_schema4.Schema.Struct({
1214
+ name: import_schema4.Schema.String,
1215
+ description: import_schema4.Schema.String,
1216
+ parameters: import_echo_schema5.JsonSchemaType,
1217
+ execute: import_schema4.Schema.Any
1218
+ });
1219
+ var LLMToolResult = Object.freeze({
1220
+ /**
1221
+ * The tool execution was successful.
1222
+ * Gives the result back to the LLM.
1223
+ */
1224
+ Success: (result, extractContentBlocks) => ({
1225
+ kind: "success",
1226
+ result,
1227
+ extractContentBlocks
1228
+ }),
1229
+ Error: (message) => ({
1230
+ kind: "error",
1231
+ message
1232
+ }),
1233
+ /**
1234
+ * Stop the conversation and return the result.
1235
+ */
1236
+ Break: (result) => ({
1237
+ kind: "break",
1238
+ result
1239
+ })
1240
+ });
1241
+ var defineTool = ({ name, description, schema, execute }) => {
1242
+ return {
1243
+ name,
1244
+ description,
1245
+ parameters: toFunctionParameterSchema(schema),
1246
+ execute: (params, context) => {
1247
+ const sanitized = import_schema4.Schema.decodeSync(schema)(params);
1248
+ return execute(sanitized, context);
1249
+ }
1250
+ };
1251
+ };
1252
+ var toFunctionParameterSchema = (schema) => {
1253
+ const jsonSchema = (0, import_echo_schema5.toJsonSchema)(schema);
1254
+ (0, import_log5.log)("tool schema", {
1255
+ jsonSchema
1256
+ }, {
1257
+ F: __dxlog_file6,
1258
+ L: 120,
1259
+ S: void 0,
1260
+ C: (f, a) => f(...a)
1261
+ });
1262
+ delete jsonSchema.anyOf;
1263
+ delete jsonSchema.$id;
1264
+ jsonSchema.type = "object";
1265
+ jsonSchema.properties ??= {};
1266
+ for (const key in jsonSchema.properties) {
1267
+ if (typeof jsonSchema.properties[key].description !== "string") {
1268
+ throw new Error(`Property missing description: ${key}`);
1269
+ }
1270
+ }
1271
+ return jsonSchema;
1272
+ };
1273
+ var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/conversation/conversation.ts";
1159
1274
  var runLLM = async (params) => {
1160
1275
  let conversationResult = null;
1276
+ const history = params.history ?? [];
1161
1277
  const generate = async () => {
1162
- (0, import_log4.log)("llm generate", {
1278
+ (0, import_log6.log)("llm generate", {
1163
1279
  tools: params.tools
1164
1280
  }, {
1165
- F: __dxlog_file5,
1166
- L: 42,
1281
+ F: __dxlog_file7,
1282
+ L: 45,
1167
1283
  S: void 0,
1168
1284
  C: (f, a) => f(...a)
1169
1285
  });
1170
1286
  const beginTs = Date.now();
1171
- const result = await params.client.generate({
1287
+ const stream = await params.client.generate({
1172
1288
  model: params.model,
1173
1289
  spaceId: params.spaceId,
1174
1290
  threadId: params.threadId,
1291
+ history,
1175
1292
  systemPrompt: params.system,
1176
1293
  tools: params.tools
1177
1294
  });
1178
- for await (const event of result) {
1295
+ for await (const event of stream) {
1179
1296
  params.logger?.(event);
1180
1297
  }
1181
- const messages = await result.complete();
1298
+ const messages = await stream.complete();
1182
1299
  const message = messages.at(-1);
1183
- (0, import_log4.log)("llm result", {
1300
+ (0, import_log6.log)("llm result", {
1184
1301
  time: Date.now() - beginTs,
1185
1302
  message
1186
1303
  }, {
1187
- F: __dxlog_file5,
1188
- L: 58,
1304
+ F: __dxlog_file7,
1305
+ L: 62,
1189
1306
  S: void 0,
1190
1307
  C: (f, a) => f(...a)
1191
1308
  });
1192
- (0, import_invariant3.invariant)(message, void 0, {
1193
- F: __dxlog_file5,
1194
- L: 59,
1309
+ (0, import_invariant4.invariant)(message, void 0, {
1310
+ F: __dxlog_file7,
1311
+ L: 63,
1195
1312
  S: void 0,
1196
1313
  A: [
1197
1314
  "message",
@@ -1202,16 +1319,16 @@ var runLLM = async (params) => {
1202
1319
  type: "message",
1203
1320
  message
1204
1321
  });
1205
- await params.client.insertMessages(messages.map((msg) => ({
1206
- ...msg,
1207
- content: msg.content.filter((c) => c.type !== "image")
1322
+ history.push(...messages.map((message2) => ({
1323
+ ...message2,
1324
+ content: message2.content.filter((block) => block.type !== "image")
1208
1325
  })));
1209
- const isToolUse = message.content.at(-1)?.type === "tool_use";
1210
- if (isToolUse) {
1326
+ const isToolUse2 = message.content.at(-1)?.type === "tool_use";
1327
+ if (isToolUse2) {
1211
1328
  const toolCalls = message.content.filter((c) => c.type === "tool_use");
1212
- (0, import_invariant3.invariant)(toolCalls.length === 1, void 0, {
1213
- F: __dxlog_file5,
1214
- L: 68,
1329
+ (0, import_invariant4.invariant)(toolCalls.length === 1, void 0, {
1330
+ F: __dxlog_file7,
1331
+ L: 74,
1215
1332
  S: void 0,
1216
1333
  A: [
1217
1334
  "toolCalls.length === 1",
@@ -1219,23 +1336,23 @@ var runLLM = async (params) => {
1219
1336
  ]
1220
1337
  });
1221
1338
  const toolCall = toolCalls[0];
1222
- const tool = params.tools.find((t) => t.name === toolCall.name);
1339
+ const tool = params.tools.find((tool2) => tool2.name === toolCall.name);
1223
1340
  if (!tool) {
1224
1341
  throw new Error(`Tool not found: ${toolCall.name}`);
1225
1342
  }
1226
1343
  const toolResult = await tool.execute(toolCall.input, {});
1227
1344
  switch (toolResult.kind) {
1228
1345
  case "error": {
1229
- (0, import_log4.log)("tool error", {
1346
+ import_log6.log.warn("tool error", {
1230
1347
  message: toolResult.message
1231
1348
  }, {
1232
- F: __dxlog_file5,
1233
- L: 78,
1349
+ F: __dxlog_file7,
1350
+ L: 84,
1234
1351
  S: void 0,
1235
1352
  C: (f, a) => f(...a)
1236
1353
  });
1237
1354
  const resultMessage = {
1238
- id: ObjectId.random(),
1355
+ id: import_echo_schema6.ObjectId.random(),
1239
1356
  spaceId: params.spaceId,
1240
1357
  threadId: params.threadId,
1241
1358
  role: "user",
@@ -1252,22 +1369,20 @@ var runLLM = async (params) => {
1252
1369
  type: "message",
1253
1370
  message: resultMessage
1254
1371
  });
1255
- await params.client.insertMessages([
1256
- resultMessage
1257
- ]);
1372
+ history.push(resultMessage);
1258
1373
  return true;
1259
1374
  }
1260
1375
  case "success": {
1261
- (0, import_log4.log)("tool success", {
1376
+ (0, import_log6.log)("tool success", {
1262
1377
  result: toolResult.result
1263
1378
  }, {
1264
- F: __dxlog_file5,
1265
- L: 99,
1379
+ F: __dxlog_file7,
1380
+ L: 106,
1266
1381
  S: void 0,
1267
1382
  C: (f, a) => f(...a)
1268
1383
  });
1269
1384
  const resultMessage = {
1270
- id: ObjectId.random(),
1385
+ id: import_echo_schema6.ObjectId.random(),
1271
1386
  spaceId: params.spaceId,
1272
1387
  threadId: params.threadId,
1273
1388
  role: "user",
@@ -1283,17 +1398,15 @@ var runLLM = async (params) => {
1283
1398
  type: "message",
1284
1399
  message: resultMessage
1285
1400
  });
1286
- await params.client.insertMessages([
1287
- resultMessage
1288
- ]);
1401
+ history.push(resultMessage);
1289
1402
  return true;
1290
1403
  }
1291
1404
  case "break": {
1292
- (0, import_log4.log)("tool break", {
1405
+ (0, import_log6.log)("tool break", {
1293
1406
  result: toolResult.result
1294
1407
  }, {
1295
- F: __dxlog_file5,
1296
- L: 119,
1408
+ F: __dxlog_file7,
1409
+ L: 127,
1297
1410
  S: void 0,
1298
1411
  C: (f, a) => f(...a)
1299
1412
  });
@@ -1307,76 +1420,108 @@ var runLLM = async (params) => {
1307
1420
  while (await generate()) {
1308
1421
  }
1309
1422
  return {
1310
- result: conversationResult
1423
+ result: conversationResult,
1424
+ history
1311
1425
  };
1312
1426
  };
1313
- var __dxlog_file6 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/conversation/types.ts";
1314
- var createUserMessage = (spaceId, threadId, text) => ({
1315
- id: ObjectId.random(),
1316
- spaceId,
1317
- threadId,
1318
- role: "user",
1319
- content: [
1320
- {
1321
- type: "text",
1322
- text
1323
- }
1324
- ]
1325
- });
1326
- var LLMToolDefinition = import_schema3.Schema.Struct({
1327
- name: import_schema3.Schema.String,
1328
- description: import_schema3.Schema.String,
1329
- parameters: import_echo_schema5.JsonSchemaType,
1330
- execute: import_schema3.Schema.Any
1331
- });
1332
- var LLMToolResult = Object.freeze({
1333
- /**
1334
- * The tool execution was successful.
1335
- * Gives the result back to the LLM.
1336
- */
1337
- Success: (result) => ({
1338
- kind: "success",
1339
- result
1340
- }),
1341
- Error: (message) => ({
1342
- kind: "error",
1343
- message
1344
- }),
1345
- /**
1346
- * Stop the conversation and return the result.
1347
- */
1348
- Break: (result) => ({
1349
- kind: "break",
1350
- result
1351
- })
1352
- });
1353
- var defineTool = ({ name, description, schema, execute }) => {
1354
- return {
1355
- name,
1356
- description,
1357
- parameters: toFunctionParameterSchema(schema),
1358
- execute: (params, context) => {
1359
- const sanitized = import_schema3.Schema.decodeSync(schema)(params);
1360
- return execute(sanitized, context);
1361
- }
1362
- };
1363
- };
1364
- var toFunctionParameterSchema = (schema) => {
1365
- const jsonSchema = (0, import_echo_schema4.toJsonSchema)(schema);
1366
- (0, import_log5.log)("tool schema", {
1367
- jsonSchema
1368
- }, {
1369
- F: __dxlog_file6,
1370
- L: 83,
1427
+ var isToolUse = (message) => message.content.at(-1)?.type === "tool_use";
1428
+ var runTools = async ({ message, tools, extensions }) => {
1429
+ const toolCalls = message.content.filter((block) => block.type === "tool_use");
1430
+ (0, import_invariant4.invariant)(toolCalls.length === 1, void 0, {
1431
+ F: __dxlog_file7,
1432
+ L: 165,
1371
1433
  S: void 0,
1372
- C: (f, a) => f(...a)
1434
+ A: [
1435
+ "toolCalls.length === 1",
1436
+ ""
1437
+ ]
1373
1438
  });
1374
- for (const key in jsonSchema.properties) {
1375
- if (typeof jsonSchema.properties[key].description !== "string") {
1376
- throw new Error(`Property missing description: ${key}`);
1439
+ const toolCall = toolCalls[0];
1440
+ const tool = tools.find((tool2) => tool2.name === toolCall.name);
1441
+ if (!tool) {
1442
+ throw new Error(`Tool not found: ${toolCall.name}`);
1443
+ }
1444
+ let toolResult;
1445
+ try {
1446
+ toolResult = await tool.execute(toolCall.input, {
1447
+ extensions
1448
+ });
1449
+ } catch (error) {
1450
+ (0, import_log6.log)("tool error", {
1451
+ error
1452
+ }, {
1453
+ F: __dxlog_file7,
1454
+ L: 176,
1455
+ S: void 0,
1456
+ C: (f, a) => f(...a)
1457
+ });
1458
+ toolResult = LLMToolResult.Error(error.message);
1459
+ }
1460
+ switch (toolResult.kind) {
1461
+ case "error": {
1462
+ (0, import_log6.log)("tool error", {
1463
+ message: toolResult.message
1464
+ }, {
1465
+ F: __dxlog_file7,
1466
+ L: 182,
1467
+ S: void 0,
1468
+ C: (f, a) => f(...a)
1469
+ });
1470
+ const resultMessage = (0, import_echo_schema6.createStatic)(Message, {
1471
+ role: "user",
1472
+ content: [
1473
+ {
1474
+ type: "tool_result",
1475
+ toolUseId: toolCall.id,
1476
+ content: toolResult.message,
1477
+ isError: true
1478
+ }
1479
+ ]
1480
+ });
1481
+ return {
1482
+ type: "continue",
1483
+ message: resultMessage
1484
+ };
1485
+ }
1486
+ case "success": {
1487
+ (0, import_log6.log)("tool success", {
1488
+ result: toolResult.result
1489
+ }, {
1490
+ F: __dxlog_file7,
1491
+ L: 203,
1492
+ S: void 0,
1493
+ C: (f, a) => f(...a)
1494
+ });
1495
+ const resultMessage = (0, import_echo_schema6.createStatic)(Message, {
1496
+ role: "user",
1497
+ content: [
1498
+ {
1499
+ type: "tool_result",
1500
+ toolUseId: toolCall.id,
1501
+ content: typeof toolResult.result === "string" ? toolResult.result : JSON.stringify(toolResult.result)
1502
+ }
1503
+ ]
1504
+ });
1505
+ return {
1506
+ type: "continue",
1507
+ message: resultMessage
1508
+ };
1509
+ }
1510
+ case "break": {
1511
+ (0, import_log6.log)("tool break", {
1512
+ result: toolResult.result
1513
+ }, {
1514
+ F: __dxlog_file7,
1515
+ L: 222,
1516
+ S: void 0,
1517
+ C: (f, a) => f(...a)
1518
+ });
1519
+ return {
1520
+ type: "break",
1521
+ result: toolResult.result
1522
+ };
1377
1523
  }
1378
1524
  }
1379
- return jsonSchema;
1380
1525
  };
1381
1526
  // Annotate the CommonJS export names for ESM import in node:
1382
1527
  0 && (module.exports = {
@@ -1384,6 +1529,7 @@ var toFunctionParameterSchema = (schema) => {
1384
1529
  EchoDataSource,
1385
1530
  GenerateRequest,
1386
1531
  GenerationStream,
1532
+ ImageContentBlock,
1387
1533
  ImageSource,
1388
1534
  LLMModel,
1389
1535
  LLMTool,
@@ -1391,18 +1537,15 @@ var toFunctionParameterSchema = (schema) => {
1391
1537
  LLMToolResult,
1392
1538
  Message,
1393
1539
  MessageContentBlock,
1394
- MessageFromDb,
1395
- MessageImageContentBlock,
1396
1540
  MessageRole,
1397
- MessageTextContentBlock,
1398
- MessageToolResultContentBlock,
1399
- MessageToolUseContentBlock,
1400
- ObjectId,
1401
- ObjectIdBrand,
1402
1541
  Space,
1403
1542
  SpaceIdSchema,
1543
+ TagContentBlock,
1544
+ TextContentBlock,
1404
1545
  Thread,
1546
+ ToolResultContentBlock,
1405
1547
  ToolTypes,
1548
+ ToolUseContentBlock,
1406
1549
  createUserMessage,
1407
1550
  defineTool,
1408
1551
  executeQuery,
@@ -1411,8 +1554,10 @@ var toFunctionParameterSchema = (schema) => {
1411
1554
  formatJsonSchemaForLLM,
1412
1555
  formatNodeLabel,
1413
1556
  isReference,
1557
+ isToolUse,
1414
1558
  parseCypherQuery,
1415
1559
  runLLM,
1560
+ runTools,
1416
1561
  trim
1417
1562
  });
1418
- //# sourceMappingURL=chunk-G6CGWEMO.cjs.map
1563
+ //# sourceMappingURL=chunk-SHOSAIOD.cjs.map