@dxos/assistant 0.7.4 → 0.7.5-labs.071a3e2

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 (115) hide show
  1. package/dist/lib/browser/chunk-AXUUNA7O.mjs +565 -0
  2. package/dist/lib/browser/chunk-AXUUNA7O.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +1212 -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 +15 -9
  7. package/dist/lib/browser/testing/index.mjs.map +4 -4
  8. package/dist/lib/node/chunk-QPHGQINW.cjs +577 -0
  9. package/dist/lib/node/chunk-QPHGQINW.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +1212 -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 +21 -14
  14. package/dist/lib/node/testing/index.cjs.map +4 -4
  15. package/dist/lib/node-esm/chunk-GOVFOBIB.mjs +567 -0
  16. package/dist/lib/node-esm/chunk-GOVFOBIB.mjs.map +7 -0
  17. package/dist/lib/node-esm/index.mjs +1212 -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 +15 -9
  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/index.d.ts +4 -1
  25. package/dist/types/src/ai-service/index.d.ts.map +1 -1
  26. package/dist/types/src/ai-service/parser.d.ts +136 -0
  27. package/dist/types/src/ai-service/parser.d.ts.map +1 -0
  28. package/dist/types/src/ai-service/stream.d.ts +39 -0
  29. package/dist/types/src/ai-service/stream.d.ts.map +1 -0
  30. package/dist/types/src/ai-service/stream.test.d.ts +2 -0
  31. package/dist/types/src/ai-service/stream.test.d.ts.map +1 -0
  32. package/dist/types/src/ai-service/testing.d.ts +7 -0
  33. package/dist/types/src/ai-service/testing.d.ts.map +1 -0
  34. package/dist/types/src/ai-service/transform.d.ts +27 -0
  35. package/dist/types/src/ai-service/transform.d.ts.map +1 -0
  36. package/dist/types/src/ai-service/types.d.ts +150 -0
  37. package/dist/types/src/ai-service/types.d.ts.map +1 -0
  38. package/dist/types/src/ai-service/util/index.d.ts +2 -0
  39. package/dist/types/src/ai-service/util/index.d.ts.map +1 -0
  40. package/dist/types/src/ai-service/{sse.d.ts → util/sse.d.ts} +5 -0
  41. package/dist/types/src/ai-service/util/sse.d.ts.map +1 -0
  42. package/dist/types/src/conversation/conversation.d.ts +61 -6
  43. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  44. package/dist/types/src/conversation/index.d.ts +0 -1
  45. package/dist/types/src/conversation/index.d.ts.map +1 -1
  46. package/dist/types/src/conversation/types.d.ts +44 -13
  47. package/dist/types/src/conversation/types.d.ts.map +1 -1
  48. package/dist/types/src/cypher/combinators.d.ts.map +1 -1
  49. package/dist/types/src/cypher/parjs.d.ts +1 -1
  50. package/dist/types/src/cypher/parjs.d.ts.map +1 -1
  51. package/dist/types/src/cypher/schema.d.ts.map +1 -1
  52. package/dist/types/src/testing/artifacts.test.d.ts +1 -0
  53. package/dist/types/src/testing/artifacts.test.d.ts.map +1 -0
  54. package/dist/types/src/testing/data.d.ts +2 -0
  55. package/dist/types/src/testing/data.d.ts.map +1 -0
  56. package/dist/types/src/testing/defs.d.ts +5 -0
  57. package/dist/types/src/testing/defs.d.ts.map +1 -0
  58. package/dist/types/src/testing/index.d.ts +1 -0
  59. package/dist/types/src/testing/index.d.ts.map +1 -1
  60. package/dist/types/src/testing/logger.d.ts +1 -1
  61. package/dist/types/src/testing/logger.d.ts.map +1 -1
  62. package/dist/types/src/testing/query-promts.d.ts +1 -1
  63. package/dist/types/src/testing/query-promts.d.ts.map +1 -1
  64. package/dist/types/src/testing/test-data.d.ts +1 -1
  65. package/dist/types/src/testing/test-data.d.ts.map +1 -1
  66. package/dist/types/src/testing/test-schema.d.ts +4 -4
  67. package/dist/types/tsconfig.tsbuildinfo +1 -1
  68. package/package.json +22 -18
  69. package/src/ai-service/client.test.ts +69 -54
  70. package/src/ai-service/client.ts +29 -184
  71. package/src/ai-service/index.ts +4 -1
  72. package/src/ai-service/parser.ts +338 -0
  73. package/src/ai-service/stream.test.ts +101 -0
  74. package/src/ai-service/stream.ts +116 -0
  75. package/src/ai-service/testing.ts +93 -0
  76. package/src/ai-service/transform.ts +121 -0
  77. package/src/ai-service/types.ts +107 -0
  78. package/src/ai-service/util/index.ts +5 -0
  79. package/src/ai-service/{sse.ts → util/sse.ts} +5 -0
  80. package/src/bin/chat.ts +10 -11
  81. package/src/conversation/conversation.test.ts +16 -17
  82. package/src/conversation/conversation.ts +126 -20
  83. package/src/conversation/index.ts +0 -1
  84. package/src/conversation/types.ts +55 -16
  85. package/src/cypher/combinators.test.ts +4 -4
  86. package/src/cypher/combinators.ts +0 -1
  87. package/src/cypher/execution-plan.test.ts +5 -3
  88. package/src/cypher/parjs-shims.d.ts +4 -0
  89. package/src/cypher/parjs.ts +2 -2
  90. package/src/cypher/query-executor.test.ts +1 -1
  91. package/src/cypher/schema.ts +6 -2
  92. package/src/index.ts +1 -1
  93. package/src/testing/artifacts.test.ts +182 -0
  94. package/src/testing/data.ts +13 -0
  95. package/src/testing/defs.ts +8 -0
  96. package/src/testing/index.ts +1 -0
  97. package/src/testing/logger.ts +3 -2
  98. package/src/testing/query-promts.ts +3 -3
  99. package/src/testing/query.test.ts +11 -10
  100. package/src/testing/test-data.ts +8 -2
  101. package/vendor/parjs-browser.mjs +4 -0
  102. package/vendor/parjs-default.mjs +8 -0
  103. package/dist/lib/browser/chunk-AKP45LQH.mjs +0 -1394
  104. package/dist/lib/browser/chunk-AKP45LQH.mjs.map +0 -7
  105. package/dist/lib/node/chunk-G6CGWEMO.cjs +0 -1418
  106. package/dist/lib/node/chunk-G6CGWEMO.cjs.map +0 -7
  107. package/dist/lib/node-esm/chunk-WUPUPEFB.mjs +0 -1396
  108. package/dist/lib/node-esm/chunk-WUPUPEFB.mjs.map +0 -7
  109. package/dist/types/src/ai-service/schema.d.ts +0 -296
  110. package/dist/types/src/ai-service/schema.d.ts.map +0 -1
  111. package/dist/types/src/ai-service/sse.d.ts.map +0 -1
  112. package/dist/types/src/sanity.test.d.ts +0 -2
  113. package/dist/types/src/sanity.test.d.ts.map +0 -1
  114. package/src/ai-service/schema.ts +0 -260
  115. package/src/sanity.test.ts +0 -9
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,79 +17,1235 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
  var node_exports = {};
20
30
  __export(node_exports, {
21
- AIServiceClientImpl: () => import_chunk_G6CGWEMO.AIServiceClientImpl,
22
- EchoDataSource: () => import_chunk_G6CGWEMO.EchoDataSource,
23
- GenerateRequest: () => import_chunk_G6CGWEMO.GenerateRequest,
24
- GenerationStream: () => import_chunk_G6CGWEMO.GenerationStream,
25
- ImageSource: () => import_chunk_G6CGWEMO.ImageSource,
26
- LLMModel: () => import_chunk_G6CGWEMO.LLMModel,
27
- LLMTool: () => import_chunk_G6CGWEMO.LLMTool,
28
- LLMToolDefinition: () => import_chunk_G6CGWEMO.LLMToolDefinition,
29
- LLMToolResult: () => import_chunk_G6CGWEMO.LLMToolResult,
30
- Message: () => import_chunk_G6CGWEMO.Message,
31
- MessageContentBlock: () => import_chunk_G6CGWEMO.MessageContentBlock,
32
- MessageFromDb: () => import_chunk_G6CGWEMO.MessageFromDb,
33
- MessageImageContentBlock: () => import_chunk_G6CGWEMO.MessageImageContentBlock,
34
- MessageRole: () => import_chunk_G6CGWEMO.MessageRole,
35
- MessageTextContentBlock: () => import_chunk_G6CGWEMO.MessageTextContentBlock,
36
- MessageToolResultContentBlock: () => import_chunk_G6CGWEMO.MessageToolResultContentBlock,
37
- MessageToolUseContentBlock: () => import_chunk_G6CGWEMO.MessageToolUseContentBlock,
38
- ObjectId: () => import_chunk_G6CGWEMO.ObjectId,
39
- ObjectIdBrand: () => import_chunk_G6CGWEMO.ObjectIdBrand,
40
- Space: () => import_chunk_G6CGWEMO.Space,
41
- SpaceIdSchema: () => import_chunk_G6CGWEMO.SpaceIdSchema,
42
- Thread: () => import_chunk_G6CGWEMO.Thread,
43
- ToolTypes: () => import_chunk_G6CGWEMO.ToolTypes,
44
- createUserMessage: () => import_chunk_G6CGWEMO.createUserMessage,
45
- defineTool: () => import_chunk_G6CGWEMO.defineTool,
46
- executeQuery: () => import_chunk_G6CGWEMO.executeQuery,
47
- executeQueryPlan: () => import_chunk_G6CGWEMO.executeQueryPlan,
48
- formatInferredRelationshipLabel: () => import_chunk_G6CGWEMO.formatInferredRelationshipLabel,
49
- formatJsonSchemaForLLM: () => import_chunk_G6CGWEMO.formatJsonSchemaForLLM,
50
- formatNodeLabel: () => import_chunk_G6CGWEMO.formatNodeLabel,
51
- isReference: () => import_chunk_G6CGWEMO.isReference,
52
- parseCypherQuery: () => import_chunk_G6CGWEMO.parseCypherQuery,
53
- runLLM: () => import_chunk_G6CGWEMO.runLLM
31
+ AIServiceClientImpl: () => AIServiceClientImpl,
32
+ EchoDataSource: () => import_chunk_QPHGQINW.EchoDataSource,
33
+ GenerateRequest: () => GenerateRequest,
34
+ GenerationStream: () => GenerationStream,
35
+ LLMModel: () => LLMModel,
36
+ MixedStreamParser: () => MixedStreamParser,
37
+ StreamTransform: () => StreamTransform,
38
+ ToolTypes: () => ToolTypes,
39
+ createArtifactElement: () => createArtifactElement,
40
+ createGenerationStream: () => createGenerationStream,
41
+ executeQuery: () => import_chunk_QPHGQINW.executeQuery,
42
+ executeQueryPlan: () => import_chunk_QPHGQINW.executeQueryPlan,
43
+ formatInferredRelationshipLabel: () => import_chunk_QPHGQINW.formatInferredRelationshipLabel,
44
+ formatJsonSchemaForLLM: () => import_chunk_QPHGQINW.formatJsonSchemaForLLM,
45
+ formatNodeLabel: () => import_chunk_QPHGQINW.formatNodeLabel,
46
+ isReference: () => import_chunk_QPHGQINW.isReference,
47
+ isToolUse: () => isToolUse,
48
+ mergeMessageBlock: () => mergeMessageBlock,
49
+ parseCypherQuery: () => import_chunk_QPHGQINW.parseCypherQuery,
50
+ runLLM: () => runLLM,
51
+ runTools: () => runTools
54
52
  });
55
53
  module.exports = __toCommonJS(node_exports);
56
- var import_chunk_G6CGWEMO = require("./chunk-G6CGWEMO.cjs");
54
+ var import_chunk_QPHGQINW = require("./chunk-QPHGQINW.cjs");
55
+ var import_schema = require("@effect/schema");
56
+ var import_artifact = require("@dxos/artifact");
57
+ var import_invariant = require("@dxos/invariant");
58
+ var import_async = require("@dxos/async");
59
+ var import_log = require("@dxos/log");
60
+ var import_artifact2 = require("@dxos/artifact");
61
+ var import_async2 = require("@dxos/async");
62
+ var import_echo_schema = require("@dxos/echo-schema");
63
+ var import_invariant2 = require("@dxos/invariant");
64
+ var import_log2 = require("@dxos/log");
65
+ var import_util = require("@dxos/util");
66
+ var P = __toESM(require("parsimmon"));
67
+ var import_schema2 = require("@effect/schema");
68
+ var import_artifact3 = require("@dxos/artifact");
69
+ var import_echo_schema2 = require("@dxos/echo-schema");
70
+ var import_artifact4 = require("@dxos/artifact");
71
+ var import_echo_schema3 = require("@dxos/echo-schema");
72
+ var import_invariant3 = require("@dxos/invariant");
73
+ var import_log3 = require("@dxos/log");
74
+ async function* iterSSEMessages(response, controller) {
75
+ if (!response.body) {
76
+ controller.abort();
77
+ throw new Error("Attempted to iterate over a response with no body");
78
+ }
79
+ const sseDecoder = new SSEDecoder();
80
+ const lineDecoder = new LineDecoder();
81
+ const iter = readableStreamAsyncIterable(response.body);
82
+ for await (const sseChunk of iterSSEChunks(iter)) {
83
+ for (const line of lineDecoder.decode(sseChunk)) {
84
+ const sse = sseDecoder.decode(line);
85
+ if (sse) {
86
+ yield sse;
87
+ }
88
+ }
89
+ }
90
+ for (const line of lineDecoder.flush()) {
91
+ const sse = sseDecoder.decode(line);
92
+ if (sse) {
93
+ yield sse;
94
+ }
95
+ }
96
+ }
97
+ async function* iterSSEChunks(iterator) {
98
+ let data = new Uint8Array();
99
+ for await (const chunk of iterator) {
100
+ if (chunk == null) {
101
+ continue;
102
+ }
103
+ const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
104
+ const newData = new Uint8Array(data.length + binaryChunk.length);
105
+ newData.set(data);
106
+ newData.set(binaryChunk, data.length);
107
+ data = newData;
108
+ let patternIndex;
109
+ while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
110
+ yield data.slice(0, patternIndex);
111
+ data = data.slice(patternIndex);
112
+ }
113
+ }
114
+ if (data.length > 0) {
115
+ yield data;
116
+ }
117
+ }
118
+ var findDoubleNewlineIndex = (buffer) => {
119
+ const newline = 10;
120
+ const carriage = 13;
121
+ for (let i = 0; i < buffer.length - 2; i++) {
122
+ if (buffer[i] === newline && buffer[i + 1] === newline) {
123
+ return i + 2;
124
+ }
125
+ if (buffer[i] === carriage && buffer[i + 1] === carriage) {
126
+ return i + 2;
127
+ }
128
+ if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) {
129
+ return i + 4;
130
+ }
131
+ }
132
+ return -1;
133
+ };
134
+ var SSEDecoder = class {
135
+ constructor() {
136
+ this.event = null;
137
+ this.data = [];
138
+ this.chunks = [];
139
+ }
140
+ decode(line) {
141
+ if (line.endsWith("\r")) {
142
+ line = line.substring(0, line.length - 1);
143
+ }
144
+ if (!line) {
145
+ if (!this.event && !this.data.length) {
146
+ return null;
147
+ }
148
+ const sse = {
149
+ event: this.event,
150
+ data: this.data.join("\n"),
151
+ raw: this.chunks
152
+ };
153
+ this.event = null;
154
+ this.data = [];
155
+ this.chunks = [];
156
+ return sse;
157
+ }
158
+ this.chunks.push(line);
159
+ if (line.startsWith(":")) {
160
+ return null;
161
+ }
162
+ let [fieldname, _, value] = partition(line, ":");
163
+ if (value.startsWith(" ")) {
164
+ value = value.substring(1);
165
+ }
166
+ if (fieldname === "event") {
167
+ this.event = value;
168
+ } else if (fieldname === "data") {
169
+ this.data.push(value);
170
+ }
171
+ return null;
172
+ }
173
+ };
174
+ var partition = (str, delimiter) => {
175
+ const index = str.indexOf(delimiter);
176
+ if (index !== -1) {
177
+ return [
178
+ str.substring(0, index),
179
+ delimiter,
180
+ str.substring(index + delimiter.length)
181
+ ];
182
+ }
183
+ return [
184
+ str,
185
+ "",
186
+ ""
187
+ ];
188
+ };
189
+ function readableStreamAsyncIterable(stream) {
190
+ if (stream[Symbol.asyncIterator]) {
191
+ return stream;
192
+ }
193
+ const reader = stream.getReader();
194
+ return {
195
+ next: async () => {
196
+ try {
197
+ const result = await reader.read();
198
+ if (result?.done) {
199
+ reader.releaseLock();
200
+ }
201
+ return result;
202
+ } catch (e) {
203
+ reader.releaseLock();
204
+ throw e;
205
+ }
206
+ },
207
+ return: async () => {
208
+ const cancelPromise = reader.cancel();
209
+ reader.releaseLock();
210
+ await cancelPromise;
211
+ return {
212
+ done: true,
213
+ value: void 0
214
+ };
215
+ },
216
+ [Symbol.asyncIterator]() {
217
+ return this;
218
+ }
219
+ };
220
+ }
221
+ var LineDecoder = class _LineDecoder {
222
+ static {
223
+ this.NEWLINE_CHARS = /* @__PURE__ */ new Set([
224
+ "\n",
225
+ "\r"
226
+ ]);
227
+ }
228
+ static {
229
+ this.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
230
+ }
231
+ constructor() {
232
+ this.buffer = [];
233
+ this.trailingCR = false;
234
+ }
235
+ decode(chunk) {
236
+ let text = this.decodeText(chunk);
237
+ if (this.trailingCR) {
238
+ text = "\r" + text;
239
+ this.trailingCR = false;
240
+ }
241
+ if (text.endsWith("\r")) {
242
+ this.trailingCR = true;
243
+ text = text.slice(0, -1);
244
+ }
245
+ if (!text) {
246
+ return [];
247
+ }
248
+ const trailingNewline = _LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || "");
249
+ let lines = text.split(_LineDecoder.NEWLINE_REGEXP);
250
+ if (trailingNewline) {
251
+ lines.pop();
252
+ }
253
+ if (lines.length === 1 && !trailingNewline) {
254
+ this.buffer.push(lines[0]);
255
+ return [];
256
+ }
257
+ if (this.buffer.length > 0) {
258
+ lines = [
259
+ this.buffer.join("") + lines[0],
260
+ ...lines.slice(1)
261
+ ];
262
+ this.buffer = [];
263
+ }
264
+ if (!trailingNewline) {
265
+ this.buffer = [
266
+ lines.pop() || ""
267
+ ];
268
+ }
269
+ return lines;
270
+ }
271
+ decodeText(bytes) {
272
+ if (bytes == null) {
273
+ return "";
274
+ }
275
+ if (typeof bytes === "string") {
276
+ return bytes;
277
+ }
278
+ if (typeof Buffer !== "undefined") {
279
+ if (bytes instanceof Buffer) {
280
+ return bytes.toString();
281
+ }
282
+ if (bytes instanceof Uint8Array) {
283
+ return Buffer.from(bytes).toString();
284
+ }
285
+ 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.`);
286
+ }
287
+ if (typeof TextDecoder !== "undefined") {
288
+ if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
289
+ this.textDecoder ??= new TextDecoder("utf8");
290
+ return this.textDecoder.decode(bytes);
291
+ }
292
+ throw new Error(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
293
+ }
294
+ throw new Error("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.");
295
+ }
296
+ flush() {
297
+ if (!this.buffer.length && !this.trailingCR) {
298
+ return [];
299
+ }
300
+ const lines = [
301
+ this.buffer.join("")
302
+ ];
303
+ this.buffer = [];
304
+ this.trailingCR = false;
305
+ return lines;
306
+ }
307
+ };
308
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/stream.ts";
309
+ var createGenerationStream = (response, controller = new AbortController()) => {
310
+ const iterator = async function* () {
311
+ for await (const sse of iterSSEMessages(response, controller)) {
312
+ if (sse.event === "completion") {
313
+ try {
314
+ yield JSON.parse(sse.data);
315
+ } catch (err) {
316
+ import_log.log.error("could not parse message into JSON:", {
317
+ data: sse.data,
318
+ raw: sse.raw
319
+ }, {
320
+ F: __dxlog_file,
321
+ L: 21,
322
+ S: this,
323
+ C: (f, a) => f(...a)
324
+ });
325
+ throw err;
326
+ }
327
+ }
328
+ 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") {
329
+ try {
330
+ yield JSON.parse(sse.data);
331
+ } catch (err) {
332
+ import_log.log.error("could not parse message into JSON:", {
333
+ data: sse.data,
334
+ raw: sse.raw
335
+ }, {
336
+ F: __dxlog_file,
337
+ L: 37,
338
+ S: this,
339
+ C: (f, a) => f(...a)
340
+ });
341
+ throw err;
342
+ }
343
+ }
344
+ if (sse.event === "ping") {
345
+ continue;
346
+ }
347
+ if (sse.event === "error") {
348
+ throw new Error(`Message generation error: ${sse.data}`);
349
+ }
350
+ }
351
+ };
352
+ return new GenerationStream(controller, iterator);
353
+ };
354
+ var GenerationStream = class {
355
+ constructor(_controller, _getIterator) {
356
+ this._controller = _controller;
357
+ this._getIterator = _getIterator;
358
+ this._done = new import_async.Trigger();
359
+ this._iterator = void 0;
360
+ }
361
+ /**
362
+ * Returns an iterator over the stream.
363
+ */
364
+ [Symbol.asyncIterator]() {
365
+ return this._createIterator();
366
+ }
367
+ /**
368
+ * Aborts the stream.
369
+ */
370
+ abort() {
371
+ this._controller.abort();
372
+ }
373
+ /**
374
+ * Returns the complete message list generated by the AI service.
375
+ */
376
+ async complete() {
377
+ await this._done.wait();
378
+ }
379
+ /**
380
+ * Creates an iterator over the stream.
381
+ */
382
+ _createIterator() {
383
+ const self = this;
384
+ return this._iterator ??= (() => {
385
+ const generator = async function* () {
386
+ try {
387
+ for await (const event of self._getIterator()) {
388
+ yield event;
389
+ }
390
+ this._done.wake();
391
+ } catch (err) {
392
+ this._done.throw(err);
393
+ }
394
+ };
395
+ return generator.call(this);
396
+ })();
397
+ }
398
+ };
399
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/client.ts";
400
+ var AIServiceClientImpl = class {
401
+ constructor({ endpoint }) {
402
+ (0, import_invariant.invariant)(endpoint, "endpoint is required", {
403
+ F: __dxlog_file2,
404
+ L: 36,
405
+ S: this,
406
+ A: [
407
+ "endpoint",
408
+ "'endpoint is required'"
409
+ ]
410
+ });
411
+ this._endpoint = endpoint;
412
+ }
413
+ async getSpace(spaceId) {
414
+ throw new Error("Not implemented");
415
+ }
416
+ async getThread(spaceId, threadId) {
417
+ throw new Error("Not implemented");
418
+ }
419
+ async getMessages(spaceId, threadId) {
420
+ const res = await fetch(`${this._endpoint}/space/${spaceId}/thread/${threadId}/message`);
421
+ return import_schema.Schema.decodePromise(import_schema.Schema.Array(import_artifact.Message).pipe(import_schema.Schema.mutable))((await res.json()).data.results);
422
+ }
423
+ async appendMessages(messages) {
424
+ const url = `${this._endpoint}/message`;
425
+ const res = await fetch(url, {
426
+ method: "POST",
427
+ headers: {
428
+ "Content-Type": "application/json"
429
+ },
430
+ body: JSON.stringify({
431
+ messages: await import_schema.Schema.encodePromise(import_schema.Schema.Array(import_artifact.Message))(messages)
432
+ })
433
+ });
434
+ if (!res.ok) {
435
+ throw new Error(`${await res.text()} [${url}]`);
436
+ }
437
+ }
438
+ // TODO(dmaretskyi): Accept partial message schema.
439
+ async updateMessage(spaceId, threadId, messageId, message) {
440
+ throw new Error("Not implemented");
441
+ }
442
+ /**
443
+ * Open message stream.
444
+ */
445
+ async generate(request) {
446
+ const controller = new AbortController();
447
+ const response = await fetch(`${this._endpoint}/generate`, {
448
+ signal: controller.signal,
449
+ method: "POST",
450
+ headers: {
451
+ "Content-Type": "application/json"
452
+ },
453
+ body: JSON.stringify(request)
454
+ });
455
+ (0, import_invariant.invariant)(response.body instanceof ReadableStream, void 0, {
456
+ F: __dxlog_file2,
457
+ L: 85,
458
+ S: this,
459
+ A: [
460
+ "response.body instanceof ReadableStream",
461
+ ""
462
+ ]
463
+ });
464
+ return createGenerationStream(response, controller);
465
+ }
466
+ };
467
+ var textChunk = P.regexp(/[^<]+/).map((content) => ({
468
+ type: "text",
469
+ content
470
+ }));
471
+ var attribute = P.seq(P.regexp(/[a-zA-Z_][a-zA-Z0-9_-]*/), P.string("=").trim(P.optWhitespace), P.alt(P.regexp(/"[^"]*"/).map((s) => s.slice(1, -1)), P.regexp(/'[^']*'/).map((s) => s.slice(1, -1)))).map(([name, _, value]) => [
472
+ name,
473
+ value
474
+ ]);
475
+ var tagName = P.regexp(/[a-zA-Z_][a-zA-Z0-9_-]*/);
476
+ var selfClosingTag = P.seqMap(
477
+ //
478
+ P.string("<"),
479
+ tagName,
480
+ P.optWhitespace.then(attribute).many(),
481
+ P.optWhitespace.then(P.string("/>")),
482
+ P.optWhitespace,
483
+ (_, tag, attributes, __) => ({
484
+ type: "tag",
485
+ tag,
486
+ attributes: Object.fromEntries(attributes),
487
+ content: [],
488
+ selfClosing: true
489
+ })
490
+ );
491
+ var openTag = P.seqMap(
492
+ //
493
+ P.string("<"),
494
+ tagName,
495
+ P.optWhitespace.then(attribute).many(),
496
+ P.string(">"),
497
+ P.regexp(/[^<]*/),
498
+ (_, tag, attributes, __, content) => ({
499
+ type: "tag",
500
+ tag,
501
+ attributes: Object.fromEntries(attributes),
502
+ content: content.length ? [
503
+ {
504
+ type: "text",
505
+ content
506
+ }
507
+ ] : []
508
+ })
509
+ );
510
+ var closeTag = P.seqMap(
511
+ //
512
+ P.string("</"),
513
+ tagName,
514
+ P.string(">"),
515
+ P.optWhitespace,
516
+ (_, tag) => ({
517
+ type: "tag",
518
+ tag,
519
+ content: [],
520
+ closing: true
521
+ })
522
+ );
523
+ var mixedChunk = P.alt(selfClosingTag, openTag, closeTag, textChunk);
524
+ var StreamTransform = class {
525
+ constructor() {
526
+ this._buffer = "";
527
+ }
528
+ transform(chunk) {
529
+ this._buffer += chunk;
530
+ const results = [];
531
+ const parser = mixedChunk.many().skip(P.optWhitespace);
532
+ const result = parser.parse(this._buffer);
533
+ if (result.status) {
534
+ for (const chunk2 of result.value) {
535
+ results.push(chunk2);
536
+ }
537
+ this._buffer = "";
538
+ }
539
+ return results;
540
+ }
541
+ // TODO(burdon): Process remaining buffer?
542
+ flush() {
543
+ const remaining = this._buffer;
544
+ this._buffer = "";
545
+ return remaining.length > 0 ? [
546
+ {
547
+ type: "text",
548
+ content: remaining
549
+ }
550
+ ] : [];
551
+ }
552
+ };
553
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/parser.ts";
554
+ var MixedStreamParser = class {
555
+ constructor() {
556
+ this.message = new import_async2.Event();
557
+ this.block = new import_async2.Event();
558
+ this.update = new import_async2.Event();
559
+ }
560
+ _emitBlock(contentBlock, streamBlock) {
561
+ const messageBlock = streamBlock ? mergeMessageBlock(contentBlock, streamBlock) : contentBlock;
562
+ if (messageBlock) {
563
+ if (messageBlock.type === "text" && messageBlock.text.length === 0) {
564
+ return;
565
+ }
566
+ (0, import_invariant2.invariant)(this._message, void 0, {
567
+ F: __dxlog_file3,
568
+ L: 46,
569
+ S: this,
570
+ A: [
571
+ "this._message",
572
+ ""
573
+ ]
574
+ });
575
+ this._message.content.push(messageBlock);
576
+ this.block.emit(messageBlock);
577
+ }
578
+ }
579
+ _emitUpdate(contentBlock, streamBlock) {
580
+ const messageBlock = mergeMessageBlock(contentBlock, streamBlock);
581
+ if (messageBlock) {
582
+ messageBlock.pending = true;
583
+ this.update.emit(messageBlock);
584
+ }
585
+ }
586
+ /**
587
+ * Parse stream until end.
588
+ */
589
+ async parse(stream) {
590
+ const transformer = new StreamTransform();
591
+ let contentBlock;
592
+ let streamBlock;
593
+ const stack = [];
594
+ for await (const event of stream) {
595
+ switch (event.type) {
596
+ //
597
+ // Messages.
598
+ //
599
+ case "message_start": {
600
+ if (this._message) {
601
+ import_log2.log.warn("unexpected message_start", void 0, {
602
+ F: __dxlog_file3,
603
+ L: 86,
604
+ S: this,
605
+ C: (f, a) => f(...a)
606
+ });
607
+ }
608
+ this._message = (0, import_echo_schema.createStatic)(import_artifact2.Message, {
609
+ role: "assistant",
610
+ content: []
611
+ });
612
+ this.message.emit(this._message);
613
+ break;
614
+ }
615
+ case "message_delta": {
616
+ if (!this._message) {
617
+ import_log2.log.warn("unexpected message_delta", void 0, {
618
+ F: __dxlog_file3,
619
+ L: 96,
620
+ S: this,
621
+ C: (f, a) => f(...a)
622
+ });
623
+ }
624
+ break;
625
+ }
626
+ case "message_stop": {
627
+ if (!this._message) {
628
+ import_log2.log.warn("unexpected message_stop", void 0, {
629
+ F: __dxlog_file3,
630
+ L: 104,
631
+ S: this,
632
+ C: (f, a) => f(...a)
633
+ });
634
+ } else {
635
+ this._message = void 0;
636
+ }
637
+ break;
638
+ }
639
+ //
640
+ // Content blocks.
641
+ //
642
+ case "content_block_start": {
643
+ if (contentBlock) {
644
+ import_log2.log.warn("unexpected content_block_start", {
645
+ content: contentBlock
646
+ }, {
647
+ F: __dxlog_file3,
648
+ L: 117,
649
+ S: this,
650
+ C: (f, a) => f(...a)
651
+ });
652
+ }
653
+ contentBlock = event.content;
654
+ break;
655
+ }
656
+ case "content_block_delta": {
657
+ if (!contentBlock) {
658
+ import_log2.log.warn("unexpected content_block_delta", void 0, {
659
+ F: __dxlog_file3,
660
+ L: 127,
661
+ S: this,
662
+ C: (f, a) => f(...a)
663
+ });
664
+ break;
665
+ }
666
+ switch (event.delta.type) {
667
+ //
668
+ // Text
669
+ //
670
+ case "text_delta": {
671
+ const chunks = transformer.transform(event.delta.text);
672
+ for (const chunk of chunks) {
673
+ switch (streamBlock?.type) {
674
+ //
675
+ // XML Fragment.
676
+ //
677
+ case "tag": {
678
+ if (chunk.type === "tag") {
679
+ if (chunk.selfClosing) {
680
+ streamBlock.content.push(chunk);
681
+ } else if (chunk.closing) {
682
+ if (stack.length > 0) {
683
+ const top = stack.pop();
684
+ (0, import_invariant2.invariant)(top && top.type === "tag", void 0, {
685
+ F: __dxlog_file3,
686
+ L: 151,
687
+ S: this,
688
+ A: [
689
+ "top && top.type === 'tag'",
690
+ ""
691
+ ]
692
+ });
693
+ top.content.push(streamBlock);
694
+ streamBlock = top;
695
+ } else {
696
+ this._emitBlock(contentBlock, streamBlock);
697
+ streamBlock = void 0;
698
+ }
699
+ } else {
700
+ stack.push(streamBlock);
701
+ streamBlock = chunk;
702
+ }
703
+ } else {
704
+ if (streamBlock.content.length === 0) {
705
+ streamBlock.content.push(chunk);
706
+ } else {
707
+ const last = streamBlock.content.at(-1);
708
+ (0, import_invariant2.invariant)(last, void 0, {
709
+ F: __dxlog_file3,
710
+ L: 168,
711
+ S: this,
712
+ A: [
713
+ "last",
714
+ ""
715
+ ]
716
+ });
717
+ if (last.type === "text") {
718
+ last.content += chunk.content;
719
+ } else {
720
+ streamBlock.content.push(chunk);
721
+ }
722
+ }
723
+ }
724
+ break;
725
+ }
726
+ //
727
+ // Text Fragment.
728
+ //
729
+ case "text": {
730
+ if (chunk.type === "tag") {
731
+ this._emitBlock(contentBlock, streamBlock);
732
+ if (chunk.selfClosing) {
733
+ this._emitBlock(contentBlock, chunk);
734
+ streamBlock = void 0;
735
+ } else {
736
+ streamBlock = chunk;
737
+ }
738
+ } else {
739
+ streamBlock.content += chunk.content;
740
+ }
741
+ break;
742
+ }
743
+ //
744
+ // No current chunk.
745
+ //
746
+ default: {
747
+ if (chunk.type === "tag" && chunk.selfClosing) {
748
+ this._emitBlock(contentBlock, chunk);
749
+ } else {
750
+ streamBlock = chunk;
751
+ }
752
+ }
753
+ }
754
+ }
755
+ break;
756
+ }
757
+ //
758
+ // JSON
759
+ //
760
+ case "input_json_delta": {
761
+ if (!contentBlock) {
762
+ import_log2.log.warn("unexpected input_json_delta", {
763
+ contentBlock
764
+ }, {
765
+ F: __dxlog_file3,
766
+ L: 218,
767
+ S: this,
768
+ C: (f, a) => f(...a)
769
+ });
770
+ break;
771
+ }
772
+ if (streamBlock?.type === "json") {
773
+ streamBlock.content += event.delta.partial_json;
774
+ } else {
775
+ streamBlock = {
776
+ type: "json",
777
+ content: event.delta.partial_json
778
+ };
779
+ }
780
+ break;
781
+ }
782
+ }
783
+ break;
784
+ }
785
+ case "content_block_stop": {
786
+ if (!contentBlock) {
787
+ import_log2.log.warn("unexpected content_block_stop", void 0, {
788
+ F: __dxlog_file3,
789
+ L: 235,
790
+ S: this,
791
+ C: (f, a) => f(...a)
792
+ });
793
+ break;
794
+ }
795
+ this._emitBlock(contentBlock, streamBlock);
796
+ contentBlock = void 0;
797
+ streamBlock = void 0;
798
+ break;
799
+ }
800
+ }
801
+ if (contentBlock && streamBlock) {
802
+ this._emitUpdate(contentBlock, streamBlock);
803
+ }
804
+ }
805
+ }
806
+ };
807
+ var mergeMessageBlock = (contentBlock, streamBlock) => {
808
+ (0, import_log2.log)("mergeMessageBlock", {
809
+ contentBlock,
810
+ streamBlock
811
+ }, {
812
+ F: __dxlog_file3,
813
+ L: 260,
814
+ S: void 0,
815
+ C: (f, a) => f(...a)
816
+ });
817
+ switch (streamBlock.type) {
818
+ //
819
+ // Text
820
+ //
821
+ case "text": {
822
+ return {
823
+ ...contentBlock,
824
+ type: "text",
825
+ text: streamBlock.content
826
+ };
827
+ }
828
+ //
829
+ // XML
830
+ //
831
+ case "tag": {
832
+ switch (streamBlock.tag) {
833
+ case "cot": {
834
+ const content = streamBlock.content.map((block) => {
835
+ switch (block.type) {
836
+ case "text":
837
+ return block.content;
838
+ default:
839
+ return null;
840
+ }
841
+ }).filter(import_util.isNotFalsy).join("\n");
842
+ return {
843
+ ...contentBlock,
844
+ type: "text",
845
+ disposition: "cot",
846
+ text: content
847
+ };
848
+ }
849
+ case "artifact": {
850
+ const { attributes } = streamBlock;
851
+ return {
852
+ type: "json",
853
+ disposition: "artifact",
854
+ json: JSON.stringify(attributes)
855
+ };
856
+ }
857
+ case "suggest": {
858
+ if (streamBlock.content.length === 1 && streamBlock.content[0].type === "text") {
859
+ return {
860
+ type: "json",
861
+ disposition: "suggest",
862
+ json: JSON.stringify({
863
+ text: streamBlock.content[0].content
864
+ })
865
+ };
866
+ }
867
+ break;
868
+ }
869
+ case "select": {
870
+ return {
871
+ type: "json",
872
+ disposition: "select",
873
+ json: JSON.stringify({
874
+ options: streamBlock.content.flatMap((content) => content.type === "tag" && content.content.length === 1 && content.content[0].type === "text" ? [
875
+ content.content[0].content
876
+ ] : [])
877
+ })
878
+ };
879
+ }
880
+ }
881
+ break;
882
+ }
883
+ //
884
+ // JSON
885
+ //
886
+ case "json": {
887
+ switch (contentBlock.type) {
888
+ case "tool_use": {
889
+ return {
890
+ ...contentBlock,
891
+ input: (0, import_util.safeParseJson)(streamBlock.content) ?? {}
892
+ };
893
+ }
894
+ }
895
+ return {
896
+ ...contentBlock,
897
+ type: "json",
898
+ disposition: "artifact",
899
+ json: streamBlock.content
900
+ };
901
+ }
902
+ }
903
+ };
904
+ var createArtifactElement = (id) => `<artifact id=${id} />`;
905
+ var LLMModel = import_schema2.Schema.Literal("@anthropic/claude-3-5-haiku-20241022", "@anthropic/claude-3-5-sonnet-20241022", "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b", "@hf/nousresearch/hermes-2-pro-mistral-7b", "@ollama/llama-3-2-3b", "@ollama/llama-3-1-nemotron-70b-instruct", "@ollama/llama-3-1-nemotron-mini-4b-instruct");
906
+ var ToolTypes = Object.freeze({
907
+ // TODO(dmaretskyi): Not implemented yet.
908
+ // DatabaseQuery: 'database_query',
909
+ TextToImage: "text_to_image"
910
+ });
911
+ var GenerateRequest = import_schema2.Schema.Struct({
912
+ spaceId: import_schema2.Schema.optional(import_artifact3.SpaceIdSchema),
913
+ threadId: import_schema2.Schema.optional(import_echo_schema2.ObjectId),
914
+ // TODO(burdon): Make optional with default.
915
+ model: LLMModel,
916
+ /**
917
+ * Current request.
918
+ */
919
+ // TODO(burdon): Remove from history.
920
+ // prompt: Message,
921
+ /**
922
+ * System instructions to the LLM.
923
+ */
924
+ systemPrompt: import_schema2.Schema.optional(import_schema2.Schema.String),
925
+ /**
926
+ * History of messages to include in the context window.
927
+ */
928
+ history: import_schema2.Schema.optional(import_schema2.Schema.Array(import_artifact3.Message)),
929
+ /**
930
+ * Tools available for the LLM.
931
+ */
932
+ tools: import_schema2.Schema.optional(import_schema2.Schema.Array(import_artifact3.Tool).pipe(import_schema2.Schema.mutable))
933
+ });
934
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/conversation/conversation.ts";
935
+ var runLLM = async (params) => {
936
+ let conversationResult = null;
937
+ const history = params.history ?? [];
938
+ const generate = async () => {
939
+ (0, import_log3.log)("llm generate", {
940
+ tools: params.tools
941
+ }, {
942
+ F: __dxlog_file4,
943
+ L: 44,
944
+ S: void 0,
945
+ C: (f, a) => f(...a)
946
+ });
947
+ const beginTs = Date.now();
948
+ const stream = await params.client.generate({
949
+ model: params.model,
950
+ spaceId: params.spaceId,
951
+ threadId: params.threadId,
952
+ history,
953
+ systemPrompt: params.system,
954
+ tools: params.tools
955
+ });
956
+ for await (const event of stream) {
957
+ params.logger?.(event);
958
+ }
959
+ await stream.complete();
960
+ const messages = [];
961
+ const message = messages.at(-1);
962
+ (0, import_invariant3.invariant)(message, void 0, {
963
+ F: __dxlog_file4,
964
+ L: 63,
965
+ S: void 0,
966
+ A: [
967
+ "message",
968
+ ""
969
+ ]
970
+ });
971
+ (0, import_log3.log)("llm result", {
972
+ time: Date.now() - beginTs,
973
+ message
974
+ }, {
975
+ F: __dxlog_file4,
976
+ L: 65,
977
+ S: void 0,
978
+ C: (f, a) => f(...a)
979
+ });
980
+ (0, import_invariant3.invariant)(message, void 0, {
981
+ F: __dxlog_file4,
982
+ L: 66,
983
+ S: void 0,
984
+ A: [
985
+ "message",
986
+ ""
987
+ ]
988
+ });
989
+ params.logger?.({
990
+ type: "message",
991
+ message
992
+ });
993
+ history.push(...messages.map((message2) => ({
994
+ ...message2,
995
+ content: message2.content.filter((block) => block.type !== "image")
996
+ })));
997
+ const isToolUse2 = message.content.at(-1)?.type === "tool_use";
998
+ if (isToolUse2) {
999
+ const toolCalls = message.content.filter((block) => block.type === "tool_use");
1000
+ (0, import_invariant3.invariant)(toolCalls.length === 1, void 0, {
1001
+ F: __dxlog_file4,
1002
+ L: 77,
1003
+ S: void 0,
1004
+ A: [
1005
+ "toolCalls.length === 1",
1006
+ ""
1007
+ ]
1008
+ });
1009
+ const toolCall = toolCalls[0];
1010
+ const tool = params.tools.find((tool2) => tool2.name === toolCall.name);
1011
+ if (!tool) {
1012
+ throw new Error(`Tool not found: ${toolCall.name}`);
1013
+ }
1014
+ (0, import_invariant3.invariant)(tool.execute, void 0, {
1015
+ F: __dxlog_file4,
1016
+ L: 84,
1017
+ S: void 0,
1018
+ A: [
1019
+ "tool.execute",
1020
+ ""
1021
+ ]
1022
+ });
1023
+ const toolResult = await tool.execute(toolCall.input);
1024
+ switch (toolResult.kind) {
1025
+ case "error": {
1026
+ import_log3.log.warn("tool error", {
1027
+ message: toolResult.message
1028
+ }, {
1029
+ F: __dxlog_file4,
1030
+ L: 88,
1031
+ S: void 0,
1032
+ C: (f, a) => f(...a)
1033
+ });
1034
+ const resultMessage = {
1035
+ id: import_echo_schema3.ObjectId.random(),
1036
+ spaceId: params.spaceId,
1037
+ threadId: params.threadId,
1038
+ role: "user",
1039
+ content: [
1040
+ {
1041
+ type: "tool_result",
1042
+ toolUseId: toolCall.id,
1043
+ content: toolResult.message,
1044
+ isError: true
1045
+ }
1046
+ ]
1047
+ };
1048
+ params.logger?.({
1049
+ type: "message",
1050
+ message: resultMessage
1051
+ });
1052
+ history.push(resultMessage);
1053
+ return true;
1054
+ }
1055
+ case "success": {
1056
+ (0, import_log3.log)("tool success", {
1057
+ result: toolResult.result
1058
+ }, {
1059
+ F: __dxlog_file4,
1060
+ L: 110,
1061
+ S: void 0,
1062
+ C: (f, a) => f(...a)
1063
+ });
1064
+ const resultMessage = {
1065
+ id: import_echo_schema3.ObjectId.random(),
1066
+ spaceId: params.spaceId,
1067
+ threadId: params.threadId,
1068
+ role: "user",
1069
+ content: [
1070
+ {
1071
+ type: "tool_result",
1072
+ toolUseId: toolCall.id,
1073
+ content: JSON.stringify(toolResult.result)
1074
+ }
1075
+ ]
1076
+ };
1077
+ params.logger?.({
1078
+ type: "message",
1079
+ message: resultMessage
1080
+ });
1081
+ history.push(resultMessage);
1082
+ return true;
1083
+ }
1084
+ case "break": {
1085
+ (0, import_log3.log)("tool break", {
1086
+ result: toolResult.result
1087
+ }, {
1088
+ F: __dxlog_file4,
1089
+ L: 131,
1090
+ S: void 0,
1091
+ C: (f, a) => f(...a)
1092
+ });
1093
+ conversationResult = toolResult.result;
1094
+ return false;
1095
+ }
1096
+ }
1097
+ }
1098
+ return false;
1099
+ };
1100
+ while (await generate()) {
1101
+ }
1102
+ return {
1103
+ result: conversationResult,
1104
+ history
1105
+ };
1106
+ };
1107
+ var isToolUse = (message) => {
1108
+ const block = message.content.at(-1);
1109
+ (0, import_invariant3.invariant)(block, void 0, {
1110
+ F: __dxlog_file4,
1111
+ L: 152,
1112
+ S: void 0,
1113
+ A: [
1114
+ "block",
1115
+ ""
1116
+ ]
1117
+ });
1118
+ return block.type === "tool_use";
1119
+ };
1120
+ var runTools = async ({ message, tools, extensions }) => {
1121
+ const toolCalls = message.content.filter((block) => block.type === "tool_use");
1122
+ (0, import_invariant3.invariant)(toolCalls.length === 1, void 0, {
1123
+ F: __dxlog_file4,
1124
+ L: 174,
1125
+ S: void 0,
1126
+ A: [
1127
+ "toolCalls.length === 1",
1128
+ ""
1129
+ ]
1130
+ });
1131
+ const toolCall = toolCalls[0];
1132
+ const tool = tools.find((tool2) => tool2.name === toolCall.name);
1133
+ if (!tool) {
1134
+ throw new Error(`Tool not found: ${toolCall.name}`);
1135
+ }
1136
+ let toolResult;
1137
+ try {
1138
+ (0, import_invariant3.invariant)(tool.execute, void 0, {
1139
+ F: __dxlog_file4,
1140
+ L: 183,
1141
+ S: void 0,
1142
+ A: [
1143
+ "tool.execute",
1144
+ ""
1145
+ ]
1146
+ });
1147
+ toolResult = await tool.execute(toolCall.input, {
1148
+ extensions
1149
+ });
1150
+ } catch (error) {
1151
+ (0, import_log3.log)("tool error", {
1152
+ error
1153
+ }, {
1154
+ F: __dxlog_file4,
1155
+ L: 186,
1156
+ S: void 0,
1157
+ C: (f, a) => f(...a)
1158
+ });
1159
+ toolResult = import_artifact4.ToolResult.Error(error.message);
1160
+ }
1161
+ switch (toolResult.kind) {
1162
+ case "error": {
1163
+ (0, import_log3.log)("tool error", {
1164
+ message: toolResult.message
1165
+ }, {
1166
+ F: __dxlog_file4,
1167
+ L: 192,
1168
+ S: void 0,
1169
+ C: (f, a) => f(...a)
1170
+ });
1171
+ const resultMessage = (0, import_echo_schema3.createStatic)(import_artifact4.Message, {
1172
+ role: "user",
1173
+ content: [
1174
+ {
1175
+ type: "tool_result",
1176
+ toolUseId: toolCall.id,
1177
+ content: toolResult.message,
1178
+ isError: true
1179
+ }
1180
+ ]
1181
+ });
1182
+ return {
1183
+ type: "continue",
1184
+ message: resultMessage
1185
+ };
1186
+ }
1187
+ case "success": {
1188
+ (0, import_log3.log)("tool success", {
1189
+ result: toolResult.result
1190
+ }, {
1191
+ F: __dxlog_file4,
1192
+ L: 213,
1193
+ S: void 0,
1194
+ C: (f, a) => f(...a)
1195
+ });
1196
+ const resultMessage = (0, import_echo_schema3.createStatic)(import_artifact4.Message, {
1197
+ role: "user",
1198
+ content: [
1199
+ {
1200
+ type: "tool_result",
1201
+ toolUseId: toolCall.id,
1202
+ content: typeof toolResult.result === "string" ? toolResult.result : JSON.stringify(toolResult.result) ?? ""
1203
+ }
1204
+ ]
1205
+ });
1206
+ return {
1207
+ type: "continue",
1208
+ message: resultMessage
1209
+ };
1210
+ }
1211
+ case "break": {
1212
+ (0, import_log3.log)("tool break", {
1213
+ result: toolResult.result
1214
+ }, {
1215
+ F: __dxlog_file4,
1216
+ L: 233,
1217
+ S: void 0,
1218
+ C: (f, a) => f(...a)
1219
+ });
1220
+ return {
1221
+ type: "break",
1222
+ result: toolResult.result
1223
+ };
1224
+ }
1225
+ }
1226
+ };
57
1227
  // Annotate the CommonJS export names for ESM import in node:
58
1228
  0 && (module.exports = {
59
1229
  AIServiceClientImpl,
60
1230
  EchoDataSource,
61
1231
  GenerateRequest,
62
1232
  GenerationStream,
63
- ImageSource,
64
1233
  LLMModel,
65
- LLMTool,
66
- LLMToolDefinition,
67
- LLMToolResult,
68
- Message,
69
- MessageContentBlock,
70
- MessageFromDb,
71
- MessageImageContentBlock,
72
- MessageRole,
73
- MessageTextContentBlock,
74
- MessageToolResultContentBlock,
75
- MessageToolUseContentBlock,
76
- ObjectId,
77
- ObjectIdBrand,
78
- Space,
79
- SpaceIdSchema,
80
- Thread,
1234
+ MixedStreamParser,
1235
+ StreamTransform,
81
1236
  ToolTypes,
82
- createUserMessage,
83
- defineTool,
1237
+ createArtifactElement,
1238
+ createGenerationStream,
84
1239
  executeQuery,
85
1240
  executeQueryPlan,
86
1241
  formatInferredRelationshipLabel,
87
1242
  formatJsonSchemaForLLM,
88
1243
  formatNodeLabel,
89
1244
  isReference,
1245
+ isToolUse,
1246
+ mergeMessageBlock,
90
1247
  parseCypherQuery,
91
- runLLM
1248
+ runLLM,
1249
+ runTools
92
1250
  });
93
1251
  //# sourceMappingURL=index.cjs.map