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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/lib/browser/chunk-BDMTBYIM.mjs +2285 -0
  2. package/dist/lib/browser/chunk-BDMTBYIM.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +313 -1631
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing/index.mjs +15 -1
  7. package/dist/lib/browser/testing/index.mjs.map +4 -4
  8. package/dist/lib/node/chunk-A44NGSCM.cjs +2296 -0
  9. package/dist/lib/node/chunk-A44NGSCM.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +321 -1629
  11. package/dist/lib/node/index.cjs.map +4 -4
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/testing/index.cjs +18 -7
  14. package/dist/lib/node/testing/index.cjs.map +4 -4
  15. package/dist/lib/node-esm/chunk-J6DMSFSZ.mjs +2287 -0
  16. package/dist/lib/node-esm/chunk-J6DMSFSZ.mjs.map +7 -0
  17. package/dist/lib/node-esm/index.mjs +313 -1631
  18. package/dist/lib/node-esm/index.mjs.map +4 -4
  19. package/dist/lib/node-esm/meta.json +1 -1
  20. package/dist/lib/node-esm/testing/index.mjs +15 -1
  21. package/dist/lib/node-esm/testing/index.mjs.map +4 -4
  22. package/dist/types/src/ai-service/defs.d.ts +8 -2
  23. package/dist/types/src/ai-service/defs.d.ts.map +1 -1
  24. package/dist/types/src/ai-service/edge-client.d.ts.map +1 -1
  25. package/dist/types/src/ai-service/message-collector.d.ts +16 -16
  26. package/dist/types/src/ai-service/message-collector.d.ts.map +1 -1
  27. package/dist/types/src/ai-service/ollama-client.d.ts +1 -5
  28. package/dist/types/src/ai-service/ollama-client.d.ts.map +1 -1
  29. package/dist/types/src/ai-service/parser.d.ts +8 -8
  30. package/dist/types/src/ai-service/parser.d.ts.map +1 -1
  31. package/dist/types/src/ai-service/types.d.ts +90 -156
  32. package/dist/types/src/ai-service/types.d.ts.map +1 -1
  33. package/dist/types/src/conversation/conversation.d.ts +8 -8
  34. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  35. package/dist/types/src/index.d.ts +1 -0
  36. package/dist/types/src/index.d.ts.map +1 -1
  37. package/dist/types/src/session/index.d.ts +2 -0
  38. package/dist/types/src/session/index.d.ts.map +1 -0
  39. package/dist/types/src/session/session.d.ts +215 -0
  40. package/dist/types/src/session/session.d.ts.map +1 -0
  41. package/dist/types/src/session/session.test.d.ts +2 -0
  42. package/dist/types/src/session/session.test.d.ts.map +1 -0
  43. package/dist/types/src/testing/index.d.ts +1 -0
  44. package/dist/types/src/testing/index.d.ts.map +1 -1
  45. package/dist/types/src/testing/ollama.d.ts +6 -0
  46. package/dist/types/src/testing/ollama.d.ts.map +1 -0
  47. package/package.json +13 -13
  48. package/src/ai-service/client.test.ts +10 -10
  49. package/src/ai-service/defs.ts +18 -3
  50. package/src/ai-service/edge-client.ts +3 -2
  51. package/src/ai-service/ollama-client.ts +49 -23
  52. package/src/ai-service/parser.ts +1 -0
  53. package/src/ai-service/types.ts +2 -2
  54. package/src/bin/chat.ts +2 -2
  55. package/src/conversation/conversation.test.ts +3 -3
  56. package/src/index.ts +1 -0
  57. package/src/session/index.ts +5 -0
  58. package/src/session/session.test.ts +256 -0
  59. package/src/session/session.ts +369 -0
  60. package/src/testing/artifacts.test.ts +2 -2
  61. package/src/testing/index.ts +1 -0
  62. package/src/testing/object-extraction.test.ts +1 -1
  63. package/src/testing/ollama.ts +15 -0
  64. package/src/testing/query.test.ts +3 -3
  65. package/dist/lib/browser/chunk-AXUUNA7O.mjs +0 -565
  66. package/dist/lib/browser/chunk-AXUUNA7O.mjs.map +0 -7
  67. package/dist/lib/node/chunk-QPHGQINW.cjs +0 -577
  68. package/dist/lib/node/chunk-QPHGQINW.cjs.map +0 -7
  69. package/dist/lib/node-esm/chunk-GOVFOBIB.mjs +0 -567
  70. package/dist/lib/node-esm/chunk-GOVFOBIB.mjs.map +0 -7
@@ -1,1685 +1,367 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
2
  import {
3
+ AIServiceEdgeClient,
4
+ DEFAULT_EDGE_MODEL,
5
+ DEFAULT_EDGE_MODELS,
6
+ DEFAULT_OLLAMA_ENDPOINT,
7
+ DEFAULT_OLLAMA_MODEL,
8
+ DEFAULT_OLLAMA_MODELS,
3
9
  EchoDataSource,
10
+ GenerateRequest,
11
+ GenerationStreamImpl,
12
+ LLMModel,
13
+ MessageCollector,
14
+ MixedStreamParser,
15
+ OllamaClient,
16
+ StreamTransform,
17
+ ToolTypes,
18
+ createArtifactElement,
19
+ createGenerationStream,
20
+ emitMessageAsEvents,
4
21
  executeQuery,
5
22
  executeQueryPlan,
6
23
  formatInferredRelationshipLabel,
7
24
  formatJsonSchemaForLLM,
8
25
  formatNodeLabel,
9
26
  isReference,
10
- parseCypherQuery
11
- } from "./chunk-GOVFOBIB.mjs";
12
-
13
- // packages/experimental/assistant/src/ai-service/defs.ts
14
- var DEFAULT_LLM_MODEL = "@anthropic/claude-3-5-sonnet-20241022";
15
- var DEFAULT_LLM_MODELS = [
16
- // AI Gateway.
17
- // https://developers.cloudflare.com/ai-gateway
18
- "@anthropic/claude-3-5-haiku-20241022",
19
- "@anthropic/claude-3-5-sonnet-20241022",
20
- "@anthropic/claude-3-7-sonnet-20250219",
21
- // Workers AI.
22
- // https://developers.cloudflare.com/workers-ai/models
23
- "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b",
24
- "@hf/nousresearch/hermes-2-pro-mistral-7b",
25
- "@ollama/llama-3-1-nemotron-70b-instruct",
26
- "@ollama/llama-3-1-nemotron-mini-4b-instruct",
27
- "@ollama/llama-3-2-3b"
28
- ];
27
+ isToolUse,
28
+ mergeMessageBlock,
29
+ parseCypherQuery,
30
+ runLLM,
31
+ runTools
32
+ } from "./chunk-J6DMSFSZ.mjs";
29
33
 
30
- // packages/experimental/assistant/src/ai-service/edge-client.ts
34
+ // packages/experimental/assistant/src/session/session.ts
31
35
  import { Schema as S } from "effect";
32
- import { Message } from "@dxos/artifact";
36
+ import { defineTool, Message, ToolResult } from "@dxos/artifact";
37
+ import { Event, synchronized } from "@dxos/async";
38
+ import { createStatic } from "@dxos/echo-schema";
33
39
  import { invariant } from "@dxos/invariant";
34
- import { log as log2 } from "@dxos/log";
35
-
36
- // packages/experimental/assistant/src/ai-service/stream.ts
37
- import { Trigger } from "@dxos/async";
38
40
  import { log } from "@dxos/log";
39
-
40
- // packages/experimental/assistant/src/ai-service/util/sse.ts
41
- async function* iterSSEMessages(response, controller) {
42
- if (!response.body) {
43
- controller.abort();
44
- throw new Error("Attempted to iterate over a response with no body");
45
- }
46
- const sseDecoder = new SSEDecoder();
47
- const lineDecoder = new LineDecoder();
48
- const iter = readableStreamAsyncIterable(response.body);
49
- for await (const sseChunk of iterSSEChunks(iter)) {
50
- for (const line of lineDecoder.decode(sseChunk)) {
51
- const sse = sseDecoder.decode(line);
52
- if (sse) {
53
- yield sse;
54
- }
55
- }
56
- }
57
- for (const line of lineDecoder.flush()) {
58
- const sse = sseDecoder.decode(line);
59
- if (sse) {
60
- yield sse;
61
- }
62
- }
63
- }
64
- async function* iterSSEChunks(iterator) {
65
- let data = new Uint8Array();
66
- for await (const chunk of iterator) {
67
- if (chunk == null) {
68
- continue;
69
- }
70
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
71
- const newData = new Uint8Array(data.length + binaryChunk.length);
72
- newData.set(data);
73
- newData.set(binaryChunk, data.length);
74
- data = newData;
75
- let patternIndex;
76
- while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
77
- yield data.slice(0, patternIndex);
78
- data = data.slice(patternIndex);
79
- }
80
- }
81
- if (data.length > 0) {
82
- yield data;
83
- }
41
+ function _ts_decorate(decorators, target, key, desc) {
42
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
43
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
44
+ 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;
45
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
84
46
  }
85
- var findDoubleNewlineIndex = (buffer) => {
86
- const newline = 10;
87
- const carriage = 13;
88
- for (let i = 0; i < buffer.length - 2; i++) {
89
- if (buffer[i] === newline && buffer[i + 1] === newline) {
90
- return i + 2;
91
- }
92
- if (buffer[i] === carriage && buffer[i + 1] === carriage) {
93
- return i + 2;
94
- }
95
- if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) {
96
- return i + 4;
97
- }
98
- }
99
- return -1;
100
- };
101
- var SSEDecoder = class {
102
- constructor() {
103
- this.event = null;
104
- this.data = [];
105
- this.chunks = [];
106
- }
107
- decode(line) {
108
- if (line.endsWith("\r")) {
109
- line = line.substring(0, line.length - 1);
110
- }
111
- if (!line) {
112
- if (!this.event && !this.data.length) {
113
- return null;
114
- }
115
- const sse = {
116
- event: this.event,
117
- data: this.data.join("\n"),
118
- raw: this.chunks
119
- };
120
- this.event = null;
121
- this.data = [];
122
- this.chunks = [];
123
- return sse;
124
- }
125
- this.chunks.push(line);
126
- if (line.startsWith(":")) {
127
- return null;
128
- }
129
- let [fieldname, _, value] = partition(line, ":");
130
- if (value.startsWith(" ")) {
131
- value = value.substring(1);
132
- }
133
- if (fieldname === "event") {
134
- this.event = value;
135
- } else if (fieldname === "data") {
136
- this.data.push(value);
137
- }
138
- return null;
139
- }
140
- };
141
- var partition = (str, delimiter) => {
142
- const index = str.indexOf(delimiter);
143
- if (index !== -1) {
144
- return [
145
- str.substring(0, index),
146
- delimiter,
147
- str.substring(index + delimiter.length)
148
- ];
149
- }
150
- return [
151
- str,
152
- "",
153
- ""
154
- ];
155
- };
156
- function readableStreamAsyncIterable(stream) {
157
- if (stream[Symbol.asyncIterator]) {
158
- return stream;
159
- }
160
- const reader = stream.getReader();
161
- return {
162
- next: async () => {
163
- try {
164
- const result = await reader.read();
165
- if (result?.done) {
166
- reader.releaseLock();
167
- }
168
- return result;
169
- } catch (e) {
170
- reader.releaseLock();
171
- throw e;
172
- }
173
- },
174
- return: async () => {
175
- const cancelPromise = reader.cancel();
176
- reader.releaseLock();
177
- await cancelPromise;
178
- return {
179
- done: true,
180
- value: void 0
181
- };
182
- },
183
- [Symbol.asyncIterator]() {
184
- return this;
185
- }
186
- };
187
- }
188
- var LineDecoder = class _LineDecoder {
189
- static {
190
- // prettier-ignore
191
- this.NEWLINE_CHARS = /* @__PURE__ */ new Set([
192
- "\n",
193
- "\r"
194
- ]);
195
- }
196
- static {
197
- this.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
198
- }
199
- constructor() {
200
- this.buffer = [];
201
- this.trailingCR = false;
202
- }
203
- decode(chunk) {
204
- let text = this.decodeText(chunk);
205
- if (this.trailingCR) {
206
- text = "\r" + text;
207
- this.trailingCR = false;
208
- }
209
- if (text.endsWith("\r")) {
210
- this.trailingCR = true;
211
- text = text.slice(0, -1);
212
- }
213
- if (!text) {
214
- return [];
215
- }
216
- const trailingNewline = _LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || "");
217
- let lines = text.split(_LineDecoder.NEWLINE_REGEXP);
218
- if (trailingNewline) {
219
- lines.pop();
220
- }
221
- if (lines.length === 1 && !trailingNewline) {
222
- this.buffer.push(lines[0]);
223
- return [];
224
- }
225
- if (this.buffer.length > 0) {
226
- lines = [
227
- this.buffer.join("") + lines[0],
228
- ...lines.slice(1)
229
- ];
230
- this.buffer = [];
231
- }
232
- if (!trailingNewline) {
233
- this.buffer = [
234
- lines.pop() || ""
235
- ];
236
- }
237
- return lines;
238
- }
239
- decodeText(bytes) {
240
- if (bytes == null) {
241
- return "";
242
- }
243
- if (typeof bytes === "string") {
244
- return bytes;
245
- }
246
- if (typeof Buffer !== "undefined") {
247
- if (bytes instanceof Buffer) {
248
- return bytes.toString();
249
- }
250
- if (bytes instanceof Uint8Array) {
251
- return Buffer.from(bytes).toString();
252
- }
253
- 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.`);
254
- }
255
- if (typeof TextDecoder !== "undefined") {
256
- if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
257
- this.textDecoder ??= new TextDecoder("utf8");
258
- return this.textDecoder.decode(bytes);
259
- }
260
- throw new Error(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
261
- }
262
- throw new Error("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.");
263
- }
264
- flush() {
265
- if (!this.buffer.length && !this.trailingCR) {
266
- return [];
267
- }
268
- const lines = [
269
- this.buffer.join("")
270
- ];
271
- this.buffer = [];
272
- this.trailingCR = false;
273
- return lines;
47
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/session/session.ts";
48
+ var AISession = class _AISession {
49
+ constructor(_options) {
50
+ this._options = _options;
51
+ this._parser = new MixedStreamParser();
52
+ this._pending = [];
53
+ this._history = [];
54
+ this.message = this._parser.message;
55
+ this.block = this._parser.block;
56
+ this.update = this._parser.update;
57
+ this.streamEvent = this._parser.streamEvent;
58
+ this.userMessage = new Event();
59
+ this._parser.message.on((message) => {
60
+ this._pending.push(message);
61
+ });
274
62
  }
275
- };
276
-
277
- // packages/experimental/assistant/src/ai-service/stream.ts
278
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/stream.ts";
279
- var createGenerationStream = (response, controller = new AbortController()) => {
280
- const iterator = async function* () {
281
- for await (const sse of iterSSEMessages(response, controller)) {
282
- if (sse.event === "completion") {
283
- try {
284
- yield JSON.parse(sse.data);
285
- } catch (err) {
286
- log.error("could not parse message into JSON:", {
287
- data: sse.data,
288
- raw: sse.raw
289
- }, {
290
- F: __dxlog_file,
291
- L: 22,
292
- S: this,
293
- C: (f, a) => f(...a)
63
+ async run(options) {
64
+ const systemTools = [
65
+ defineTool("system", {
66
+ name: "query_artifacts",
67
+ description: "Query the available artifacts",
68
+ schema: S.Struct({}),
69
+ execute: async () => {
70
+ return ToolResult.Success({
71
+ artifacts: options.artifacts.map((artifact) => ({
72
+ id: artifact.id,
73
+ name: artifact.name,
74
+ description: artifact.description
75
+ }))
294
76
  });
295
- throw err;
296
- }
297
- }
298
- 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") {
299
- try {
300
- yield JSON.parse(sse.data);
301
- } catch (err) {
302
- log.error("could not parse message into JSON:", {
303
- data: sse.data,
304
- raw: sse.raw
305
- }, {
306
- F: __dxlog_file,
307
- L: 38,
308
- S: this,
309
- C: (f, a) => f(...a)
310
- });
311
- throw err;
312
- }
313
- }
314
- if (sse.event === "ping") {
315
- continue;
316
- }
317
- if (sse.event === "error") {
318
- throw new Error(`Message generation error: ${sse.data}`);
319
- }
320
- }
321
- };
322
- return new GenerationStreamImpl(controller, iterator);
323
- };
324
- var GenerationStreamImpl = class {
325
- constructor(_controller, _getIterator) {
326
- this._controller = _controller;
327
- this._getIterator = _getIterator;
328
- this._done = new Trigger();
329
- this._iterator = void 0;
330
- }
331
- /**
332
- * Returns an iterator over the stream.
333
- */
334
- [Symbol.asyncIterator]() {
335
- return this._createIterator();
336
- }
337
- /**
338
- * Aborts the stream.
339
- */
340
- abort() {
341
- this._controller.abort();
342
- }
343
- /**
344
- * Returns the complete message list generated by the AI service.
345
- */
346
- async complete() {
347
- await this._done.wait();
348
- }
349
- /**
350
- * Creates an iterator over the stream.
351
- */
352
- _createIterator() {
353
- const self = this;
354
- return this._iterator ??= (() => {
355
- const generator = async function* () {
356
- try {
357
- for await (const event of self._getIterator()) {
358
- yield event;
359
- }
360
- this._done.wake();
361
- } catch (err) {
362
- this._done.throw(err);
363
- throw err;
364
77
  }
365
- };
366
- return generator.call(this);
367
- })();
368
- }
369
- };
370
-
371
- // packages/experimental/assistant/src/ai-service/edge-client.ts
372
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/edge-client.ts";
373
- var AIServiceEdgeClient = class {
374
- constructor({ endpoint }) {
375
- invariant(endpoint, "endpoint is required", {
376
- F: __dxlog_file2,
377
- L: 23,
378
- S: this,
379
- A: [
380
- "endpoint",
381
- "'endpoint is required'"
382
- ]
383
- });
384
- this._endpoint = endpoint;
385
- }
386
- /**
387
- * @deprecated
388
- */
389
- // TODO(burdon): Remove.
390
- async appendMessages(messages) {
391
- const url = `${this._endpoint}/message`;
392
- const res = await fetch(url, {
393
- method: "POST",
394
- headers: {
395
- "Content-Type": "application/json"
396
- },
397
- body: JSON.stringify({
398
- messages: await S.encodePromise(S.Array(Message))(messages)
399
78
  })
400
- });
401
- if (!res.ok) {
402
- throw new Error(`${await res.text()} [${url}]`);
403
- }
404
- }
405
- /**
406
- * Process request and open message stream.
407
- */
408
- async exec(request) {
409
- log2.info("requesting", {
410
- endpoint: this._endpoint
411
- }, {
412
- F: __dxlog_file2,
413
- L: 50,
414
- S: this,
415
- C: (f, a) => f(...a)
416
- });
417
- const controller = new AbortController();
418
- const response = await fetch(`${this._endpoint}/generate`, {
419
- signal: controller.signal,
420
- method: "POST",
421
- headers: {
422
- "Content-Type": "application/json"
423
- },
424
- body: JSON.stringify({
425
- // TODO(dmaretskyi): Errors if tools are not provided.
426
- tools: request.tools ?? [],
427
- ...request
428
- })
429
- });
430
- invariant(response.body instanceof ReadableStream, void 0, {
431
- F: __dxlog_file2,
432
- L: 63,
433
- S: this,
434
- A: [
435
- "response.body instanceof ReadableStream",
436
- ""
437
- ]
438
- });
439
- return createGenerationStream(response, controller);
440
- }
441
- };
442
-
443
- // packages/experimental/assistant/src/ai-service/message-collector.ts
444
- var MessageCollector = class {
445
- constructor() {
446
- this._messages = [];
447
- this._pendingMessage = void 0;
448
- }
449
- get messages() {
450
- return this._messages;
451
- }
452
- get pendingMessage() {
453
- return this._pendingMessage;
454
- }
455
- push(event) {
456
- switch (event.type) {
457
- case "message_start":
458
- this._pendingMessage = event.message;
459
- break;
460
- case "message_stop":
461
- if (this._pendingMessage) {
462
- this._messages.push(this._pendingMessage);
463
- this._pendingMessage = void 0;
464
- }
465
- break;
466
- case "content_block_start":
467
- if (this._pendingMessage) {
468
- this._pendingMessage.content = this._pendingMessage.content || [];
469
- this._pendingMessage.content[event.index] = event.content;
470
- }
471
- break;
472
- case "content_block_delta":
473
- if (this._pendingMessage && this._pendingMessage.content) {
474
- const block = this._pendingMessage.content[event.index];
475
- if (block && event.delta.type === "text_delta" && block.type === "text") {
476
- block.text = (block.text || "") + event.delta.text;
79
+ ];
80
+ switch (this._options.operationModel) {
81
+ case "planning":
82
+ systemTools.push(defineTool("system", {
83
+ name: "create_plan",
84
+ description: "Create a plan. Make sure that each step is independent and can be executed solely on the data returned by the previous step. The steps only share the data that is specified in the plan.",
85
+ schema: S.Struct({
86
+ goal: S.String.annotations({
87
+ description: "The goal that the plan will achieve."
88
+ }),
89
+ steps: S.Array(S.Struct({
90
+ action: S.String.annotations({
91
+ description: "Complete, detailed action to perform."
92
+ }),
93
+ input: S.String.annotations({
94
+ description: "The required input data for this step. First step must not require any data."
95
+ }),
96
+ output: S.String.annotations({
97
+ description: "The output data from this step. This is passed to the next step as input."
98
+ }),
99
+ requiredArtifactIds: S.Array(S.String).annotations({
100
+ description: "The ids of the artifacts required to perform this step.",
101
+ examples: [
102
+ [
103
+ "artifact:dxos.org/example/Test"
104
+ ]
105
+ ]
106
+ })
107
+ })).annotations({
108
+ description: "Steps"
109
+ })
110
+ }),
111
+ execute: async ({ goal, steps }) => {
112
+ const missingArtifactIds = steps.flatMap((step) => step.requiredArtifactIds).filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
113
+ if (missingArtifactIds.length > 0) {
114
+ return ToolResult.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(", ")}`);
115
+ }
116
+ const stepResults = [];
117
+ for (const step of steps) {
118
+ log.info("executing step", {
119
+ action: step.action
120
+ }, {
121
+ F: __dxlog_file,
122
+ L: 158,
123
+ S: this,
124
+ C: (f, a) => f(...a)
125
+ });
126
+ const session = new _AISession({
127
+ operationModel: "immediate"
128
+ });
129
+ session.message.on((ev) => this.message.emit(ev));
130
+ session.block.on((ev) => this.block.emit(ev));
131
+ session.update.on((ev) => this.update.emit(ev));
132
+ session.streamEvent.on((ev) => this.streamEvent.emit(ev));
133
+ session.userMessage.on((ev) => this.userMessage.emit(ev));
134
+ const messages = await session.run({
135
+ client: options.client,
136
+ artifacts: options.artifacts,
137
+ tools: options.tools,
138
+ history: options.history,
139
+ extensions: options.extensions,
140
+ generationOptions: options.generationOptions,
141
+ requiredArtifactIds: step.requiredArtifactIds.slice(),
142
+ prompt: `
143
+ You are an agent that executes the subtask in a plan.
144
+
145
+ While you know the plan's goal only focus on your subtask
146
+ Use the data from the previous step to complete your task.
147
+ Return all of the data from "output" in your last message.
148
+
149
+ Current step (that you need to complete):
150
+ ${JSON.stringify({
151
+ goal,
152
+ input: step.input,
153
+ output: step.output,
154
+ yourTask: step.action
155
+ }, null, 2)}
156
+
157
+ Previous step results:
158
+ ${JSON.stringify(stepResults.at(-1))}.
159
+ `
160
+ });
161
+ const result = messages.at(-1);
162
+ stepResults.push(result);
163
+ }
164
+ return ToolResult.Success({
165
+ stepResults
166
+ });
477
167
  }
478
- }
168
+ }));
479
169
  break;
480
- case "content_block_stop":
481
- if (this._pendingMessage && this._pendingMessage.content) {
482
- const block = this._pendingMessage.content[event.index];
483
- if (block) {
484
- block.pending = false;
170
+ case "immediate":
171
+ systemTools.push(defineTool("system", {
172
+ name: "require_artifacts",
173
+ description: "Require the use of specific artifacts. This will allow the model to interact with artifacts and use their tools.",
174
+ schema: S.Struct({
175
+ artifactIds: S.Array(S.String).annotations({
176
+ description: "The ids of the artifacts to require",
177
+ examples: [
178
+ [
179
+ "artifact:dxos.org/example/Test"
180
+ ]
181
+ ]
182
+ })
183
+ }),
184
+ execute: async ({ artifactIds }) => {
185
+ const missingArtifactIds = artifactIds.filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
186
+ if (missingArtifactIds.length > 0) {
187
+ return ToolResult.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(", ")}`);
188
+ }
189
+ for (const artifactId of artifactIds) {
190
+ requiredArtifactIds.add(artifactId);
191
+ }
192
+ return ToolResult.Success({});
485
193
  }
486
- }
487
- break;
488
- case "message_delta":
489
- if (this._pendingMessage && event.delta) {
490
- Object.assign(this._pendingMessage, event.delta);
491
- }
194
+ }));
492
195
  break;
493
196
  }
494
- }
495
- pushMessage(message) {
496
- this._messages.push(message);
497
- }
498
- };
499
- function* emitMessageAsEvents(message) {
500
- yield {
501
- type: "message_start",
502
- message
503
- };
504
- yield {
505
- type: "message_stop"
506
- };
507
- }
508
-
509
- // packages/experimental/assistant/src/ai-service/ollama-client.ts
510
- import { defineTool, ToolResult as ToolResult2 } from "@dxos/artifact";
511
- import { ObjectId as ObjectId3, S as S3 } from "@dxos/echo-schema";
512
- import { invariant as invariant3 } from "@dxos/invariant";
513
- import { log as log4 } from "@dxos/log";
514
-
515
- // packages/experimental/assistant/src/ai-service/types.ts
516
- import { Schema as S2 } from "effect";
517
- import { Tool, Message as Message2, SpaceIdSchema } from "@dxos/artifact";
518
- import { ObjectId } from "@dxos/echo-schema";
519
- var createArtifactElement = (id) => `<artifact id=${id} />`;
520
- var LLMModel = S2.Literal(...DEFAULT_LLM_MODELS);
521
- var ToolTypes = Object.freeze({
522
- // TODO(dmaretskyi): Not implemented yet.
523
- // DatabaseQuery: 'database_query',
524
- TextToImage: "text_to_image"
525
- });
526
- var GenerateRequest = S2.Struct({
527
- spaceId: S2.optional(SpaceIdSchema),
528
- threadId: S2.optional(ObjectId),
529
- /**
530
- * Preferred model or system default.
531
- */
532
- model: S2.optional(LLMModel),
533
- /**
534
- * Tools available for the LLM.
535
- */
536
- tools: S2.optional(S2.Array(Tool).pipe(S2.mutable)),
537
- /**
538
- * System instructions to the LLM.
539
- */
540
- systemPrompt: S2.optional(S2.String),
541
- /**
542
- * History of messages to include in the context window.
543
- */
544
- // TODO(burdon): Rename messages.
545
- history: S2.optional(S2.Array(Message2)),
546
- /**
547
- * Current request.
548
- */
549
- prompt: S2.optional(Message2)
550
- });
551
-
552
- // packages/experimental/assistant/src/conversation/conversation.ts
553
- import { ToolResult, Message as Message3 } from "@dxos/artifact";
554
- import { createStatic, ObjectId as ObjectId2 } from "@dxos/echo-schema";
555
- import { invariant as invariant2 } from "@dxos/invariant";
556
- import { log as log3 } from "@dxos/log";
557
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/conversation/conversation.ts";
558
- var runLLM = async (params) => {
559
- let conversationResult = null;
560
- const history = params.history ?? [];
561
- const generate = async () => {
562
- log3("llm generate", {
563
- tools: params.tools
564
- }, {
565
- F: __dxlog_file3,
566
- L: 44,
567
- S: void 0,
568
- C: (f, a) => f(...a)
569
- });
570
- const beginTs = Date.now();
571
- const stream = await params.client.exec({
572
- model: params.model,
573
- spaceId: params.spaceId,
574
- threadId: params.threadId,
575
- history,
576
- systemPrompt: params.system,
577
- tools: params.tools
578
- });
579
- for await (const event of stream) {
580
- params.logger?.(event);
581
- }
582
- await stream.complete();
583
- const messages = [];
584
- const message = messages.at(-1);
585
- invariant2(message, void 0, {
586
- F: __dxlog_file3,
587
- L: 63,
588
- S: void 0,
589
- A: [
590
- "message",
591
- ""
592
- ]
593
- });
594
- log3("llm result", {
595
- time: Date.now() - beginTs,
596
- message
597
- }, {
598
- F: __dxlog_file3,
599
- L: 65,
600
- S: void 0,
601
- C: (f, a) => f(...a)
602
- });
603
- invariant2(message, void 0, {
604
- F: __dxlog_file3,
605
- L: 66,
606
- S: void 0,
607
- A: [
608
- "message",
609
- ""
610
- ]
611
- });
612
- params.logger?.({
613
- type: "message",
614
- message
615
- });
616
- history.push(...messages.map((message2) => ({
617
- ...message2,
618
- content: message2.content.filter((block) => block.type !== "image")
619
- })));
620
- const isToolUse2 = message.content.at(-1)?.type === "tool_use";
621
- if (isToolUse2) {
622
- const toolCalls = message.content.filter((block) => block.type === "tool_use");
623
- invariant2(toolCalls.length === 1, void 0, {
624
- F: __dxlog_file3,
625
- L: 77,
626
- S: void 0,
627
- A: [
628
- "toolCalls.length === 1",
629
- ""
630
- ]
631
- });
632
- const toolCall = toolCalls[0];
633
- const tool = params.tools.find((tool2) => tool2.name === toolCall.name);
634
- if (!tool) {
635
- throw new Error(`Tool not found: ${toolCall.name}`);
636
- }
637
- invariant2(tool.execute, void 0, {
638
- F: __dxlog_file3,
639
- L: 84,
640
- S: void 0,
641
- A: [
642
- "tool.execute",
643
- ""
644
- ]
645
- });
646
- const toolResult = await tool.execute(toolCall.input);
647
- switch (toolResult.kind) {
648
- case "error": {
649
- log3.warn("tool error", {
650
- message: toolResult.message
651
- }, {
652
- F: __dxlog_file3,
653
- L: 88,
654
- S: void 0,
655
- C: (f, a) => f(...a)
656
- });
657
- const resultMessage = {
658
- id: ObjectId2.random(),
659
- spaceId: params.spaceId,
660
- threadId: params.threadId,
661
- role: "user",
662
- content: [
663
- {
664
- type: "tool_result",
665
- toolUseId: toolCall.id,
666
- content: toolResult.message,
667
- isError: true
668
- }
669
- ]
670
- };
671
- params.logger?.({
672
- type: "message",
673
- message: resultMessage
674
- });
675
- history.push(resultMessage);
676
- return true;
677
- }
678
- case "success": {
679
- log3("tool success", {
680
- result: toolResult.result
681
- }, {
682
- F: __dxlog_file3,
683
- L: 110,
684
- S: void 0,
685
- C: (f, a) => f(...a)
686
- });
687
- const resultMessage = {
688
- id: ObjectId2.random(),
689
- spaceId: params.spaceId,
690
- threadId: params.threadId,
691
- role: "user",
692
- content: [
693
- {
694
- type: "tool_result",
695
- toolUseId: toolCall.id,
696
- content: JSON.stringify(toolResult.result)
697
- }
698
- ]
699
- };
700
- params.logger?.({
701
- type: "message",
702
- message: resultMessage
703
- });
704
- history.push(resultMessage);
705
- return true;
706
- }
707
- case "break": {
708
- log3("tool break", {
709
- result: toolResult.result
710
- }, {
711
- F: __dxlog_file3,
712
- L: 131,
713
- S: void 0,
714
- C: (f, a) => f(...a)
715
- });
716
- conversationResult = toolResult.result;
717
- return false;
718
- }
719
- }
720
- }
721
- return false;
722
- };
723
- while (await generate()) {
724
- }
725
- return {
726
- result: conversationResult,
727
- history
728
- };
729
- };
730
- var isToolUse = (message, { onlyToolNames } = {}) => {
731
- const block = message.content.at(-1);
732
- invariant2(block, void 0, {
733
- F: __dxlog_file3,
734
- L: 152,
735
- S: void 0,
736
- A: [
737
- "block",
738
- ""
739
- ]
740
- });
741
- return block.type === "tool_use" && (!onlyToolNames || onlyToolNames.includes(block.name));
742
- };
743
- var runTools = async ({ message, tools, extensions }) => {
744
- const toolCalls = message.content.filter((block) => block.type === "tool_use");
745
- invariant2(toolCalls.length === 1, void 0, {
746
- F: __dxlog_file3,
747
- L: 174,
748
- S: void 0,
749
- A: [
750
- "toolCalls.length === 1",
751
- ""
752
- ]
753
- });
754
- const toolCall = toolCalls[0];
755
- const tool = tools.find((tool2) => tool2.name === toolCall.name);
756
- if (!tool) {
757
- throw new Error(`Tool not found: ${toolCall.name}`);
758
- }
759
- let toolResult;
760
- try {
761
- invariant2(tool.execute, void 0, {
762
- F: __dxlog_file3,
763
- L: 183,
764
- S: void 0,
765
- A: [
766
- "tool.execute",
767
- ""
768
- ]
769
- });
770
- toolResult = await tool.execute(toolCall.input, {
771
- extensions
772
- });
773
- } catch (error) {
774
- log3("tool error", {
775
- error
776
- }, {
777
- F: __dxlog_file3,
778
- L: 186,
779
- S: void 0,
780
- C: (f, a) => f(...a)
781
- });
782
- toolResult = ToolResult.Error(error.message);
783
- }
784
- switch (toolResult.kind) {
785
- case "error": {
786
- log3("tool error", {
787
- message: toolResult.message
788
- }, {
789
- F: __dxlog_file3,
790
- L: 192,
791
- S: void 0,
792
- C: (f, a) => f(...a)
793
- });
794
- const resultMessage = createStatic(Message3, {
197
+ this._history = [
198
+ ...options.history
199
+ ];
200
+ this._pending = [
201
+ createStatic(Message, {
795
202
  role: "user",
796
203
  content: [
797
204
  {
798
- type: "tool_result",
799
- toolUseId: toolCall.id,
800
- content: toolResult.message,
801
- isError: true
205
+ type: "text",
206
+ text: options.prompt
802
207
  }
803
208
  ]
804
- });
805
- return {
806
- type: "continue",
807
- message: resultMessage
808
- };
809
- }
810
- case "success": {
811
- log3("tool success", {
812
- result: toolResult.result
813
- }, {
814
- F: __dxlog_file3,
815
- L: 213,
816
- S: void 0,
817
- C: (f, a) => f(...a)
818
- });
819
- const resultMessage = createStatic(Message3, {
820
- role: "user",
821
- content: [
822
- {
823
- type: "tool_result",
824
- toolUseId: toolCall.id,
825
- content: typeof toolResult.result === "string" ? toolResult.result : JSON.stringify(toolResult.result) ?? ""
826
- },
827
- ...toolResult.extractContentBlocks ?? []
828
- ]
829
- });
830
- return {
831
- type: "continue",
832
- message: resultMessage
833
- };
834
- }
835
- case "break": {
836
- log3("tool break", {
837
- result: toolResult.result
838
- }, {
839
- F: __dxlog_file3,
840
- L: 234,
841
- S: void 0,
842
- C: (f, a) => f(...a)
843
- });
844
- return {
845
- type: "break",
846
- result: toolResult.result
847
- };
848
- }
849
- }
850
- };
851
-
852
- // packages/experimental/assistant/src/ai-service/ollama-client.ts
853
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/ollama-client.ts";
854
- var DEFAULT_OLLAMA_URL = "http://localhost:11434";
855
- var DEFAULT_OLLAMA_MODEL = "llama3.2:1b";
856
- var OllamaClient = class _OllamaClient {
857
- /**
858
- * Create a test client with small local model and no temperature for predictable results.
859
- */
860
- static createClient(options) {
861
- return new _OllamaClient({
862
- tools: options?.tools,
863
- overrides: {
864
- model: DEFAULT_OLLAMA_MODEL,
865
- temperature: 0
866
- }
867
- });
868
- }
869
- /**
870
- * Check if Ollama server is running and accessible.
871
- * @returns Promise that resolves to true if Ollama is running, false otherwise.
872
- */
873
- static async isRunning() {
874
- try {
875
- const response = await fetch(`${DEFAULT_OLLAMA_URL}/api/version`, {
876
- method: "GET",
877
- headers: {
878
- "Content-Type": "application/json"
879
- },
880
- signal: AbortSignal.timeout(100)
881
- });
882
- return response.ok;
883
- } catch (error) {
884
- return false;
885
- }
886
- }
887
- constructor({ endpoint, tools, overrides, maxToolInvocations }) {
888
- this._endpoint = endpoint ?? DEFAULT_OLLAMA_URL;
889
- this._tools = tools ?? [];
890
- this._modelOverride = overrides?.model;
891
- this._temperatureOverride = overrides?.temperature;
892
- this._maxToolInvocations = maxToolInvocations ?? 3;
893
- }
894
- _getEmbededTools(clientTools) {
895
- return [
896
- ...this._tools,
897
- ...clientTools.filter((tool) => tool.type !== void 0 && WELL_KNOWN_TOOLS[tool.type]).map((tool) => WELL_KNOWN_TOOLS[tool.type])
209
+ })
898
210
  ];
899
- }
900
- async *_generateStream(request, signal) {
901
- invariant3(request.prompt === void 0, "Prompt must be in history", {
902
- F: __dxlog_file4,
903
- L: 99,
904
- S: this,
905
- A: [
906
- "request.prompt === undefined",
907
- "'Prompt must be in history'"
908
- ]
909
- });
910
- const ollamaRequest = {
911
- model: this._modelOverride ?? request.model ?? "llama3",
912
- messages: [],
913
- stream: true,
914
- options: {
915
- temperature: this._temperatureOverride ?? 0.7
916
- }
917
- };
918
- if (request.systemPrompt) {
919
- ollamaRequest.messages.push({
920
- role: "system",
921
- content: request.systemPrompt
922
- });
923
- }
924
- if (request.history?.length) {
925
- for (const message of request.history) {
926
- const role = message.role === "assistant" ? "assistant" : "user";
927
- if (message.content.length === 0) {
928
- continue;
929
- }
930
- for (const content of message.content) {
931
- switch (content.type) {
932
- case "text": {
933
- ollamaRequest.messages.push({
934
- role,
935
- content: content.text
936
- });
937
- break;
938
- }
939
- case "tool_use": {
940
- ollamaRequest.messages.push({
941
- role: "assistant",
942
- content: "",
943
- tool_calls: [
944
- {
945
- function: {
946
- name: content.name,
947
- arguments: content.input
948
- }
949
- }
950
- ]
951
- });
952
- break;
953
- }
954
- case "tool_result": {
955
- ollamaRequest.messages.push({
956
- role: "tool",
957
- content: JSON.stringify({
958
- type: "tool_result",
959
- toolUseId: content.toolUseId,
960
- content: content.content
961
- })
962
- });
963
- break;
964
- }
965
- }
966
- }
967
- }
968
- }
969
- if (request.tools?.length || this._tools.length) {
970
- const allTools = [
971
- ...request.tools ?? [],
972
- ...this._tools
973
- ];
974
- const withWellKnownTools = allTools.map((tool) => tool.type !== void 0 && WELL_KNOWN_TOOLS[tool.type] ? WELL_KNOWN_TOOLS[tool.type] : tool);
975
- if (withWellKnownTools.length > 0) {
976
- ollamaRequest.tools = withWellKnownTools.map((tool) => ({
977
- type: "function",
978
- function: {
979
- name: tool.name,
980
- description: tool.description,
981
- parameters: {
982
- type: "object",
983
- properties: tool.parameters?.properties,
984
- required: tool.parameters?.required
985
- }
986
- }
987
- }));
988
- }
989
- }
990
- log4.info("generate request", {
991
- history: request.history,
992
- prompt: request.prompt,
993
- ollamaRequest
994
- }, {
995
- F: __dxlog_file4,
996
- L: 193,
997
- S: this,
998
- C: (f, a) => f(...a)
999
- });
1000
- const response = await fetch(`${this._endpoint}/api/chat`, {
1001
- method: "POST",
1002
- headers: {
1003
- "Content-Type": "application/json"
1004
- },
1005
- body: JSON.stringify(ollamaRequest),
1006
- signal
1007
- });
1008
- if (!response.ok) {
1009
- throw new Error(`Ollama API error: ${response.status} ${response.statusText}`);
1010
- }
1011
- if (!response.body) {
1012
- throw new Error("Ollama API returned no response body");
1013
- }
1014
- const reader = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new OllamaDecoderStream()).getReader();
211
+ this.userMessage.emit(this._pending.at(-1));
212
+ this._stream = void 0;
213
+ let error;
214
+ const requiredArtifactIds = new Set(options.requiredArtifactIds ?? []);
1015
215
  try {
1016
- const messageId = ObjectId3.random();
1017
- yield {
1018
- type: "message_start",
1019
- message: {
1020
- id: messageId,
1021
- role: "assistant",
1022
- content: []
1023
- }
1024
- };
1025
- const textBlock = {
1026
- type: "text",
1027
- text: ""
1028
- };
1029
- let currentBlockIndex = 0;
1030
- yield {
1031
- type: "content_block_start",
1032
- index: currentBlockIndex,
1033
- content: textBlock
1034
- };
1035
- while (true) {
1036
- const { done, value: data } = await reader.read();
1037
- if (done) {
1038
- break;
1039
- }
1040
- log4.info("ollama data", {
1041
- data
216
+ let more = false;
217
+ do {
218
+ const tools = [
219
+ ...systemTools,
220
+ ...options.tools,
221
+ ...options.artifacts.filter((artifact) => requiredArtifactIds.has(artifact.id)).flatMap((artifact) => artifact.tools)
222
+ ];
223
+ log("request", {
224
+ pending: this._pending.length,
225
+ history: this._history.length,
226
+ tools: tools.map((tool) => tool.name)
1042
227
  }, {
1043
- F: __dxlog_file4,
1044
- L: 256,
228
+ F: __dxlog_file,
229
+ L: 260,
1045
230
  S: this,
1046
231
  C: (f, a) => f(...a)
1047
232
  });
1048
- if (data.message?.content) {
1049
- yield {
1050
- type: "content_block_delta",
1051
- index: 0,
1052
- delta: {
1053
- type: "text_delta",
1054
- text: data.message.content
1055
- }
1056
- };
1057
- }
1058
- if (data.message?.tool_calls && data.message?.tool_calls?.length > 0) {
1059
- if (data.message.tool_calls.length > 1) {
1060
- log4.warn("Ollama returned multiple tool calls. Only the first one will be used.", void 0, {
1061
- F: __dxlog_file4,
1062
- L: 273,
1063
- S: this,
1064
- C: (f, a) => f(...a)
1065
- });
1066
- }
1067
- yield {
1068
- type: "content_block_stop",
1069
- index: currentBlockIndex++
1070
- };
1071
- yield {
1072
- type: "content_block_start",
1073
- index: currentBlockIndex,
1074
- content: {
1075
- type: "tool_use",
1076
- id: ObjectId3.random(),
1077
- name: data.message.tool_calls[0].function.name,
1078
- input: sanitizeToolArguments(data.message.tool_calls[0].function.arguments)
1079
- }
1080
- };
1081
- yield {
1082
- type: "message_delta",
1083
- delta: {
1084
- stopReason: "tool_use"
1085
- }
1086
- };
1087
- }
1088
- }
1089
- yield {
1090
- type: "content_block_stop",
1091
- index: currentBlockIndex
1092
- };
1093
- yield {
1094
- type: "message_stop"
1095
- };
1096
- } finally {
1097
- reader.releaseLock();
1098
- }
1099
- }
1100
- async exec(request) {
1101
- const controller = new AbortController();
1102
- try {
1103
- return new GenerationStreamImpl(controller, async function* () {
1104
- const collector = new MessageCollector();
1105
- let toolInvocations = 0;
1106
- while (true) {
1107
- for await (const event of this._generateStream({
1108
- ...request,
1109
- history: [
1110
- ...request.history ?? [],
1111
- ...request.prompt ? [
1112
- request.prompt
1113
- ] : [],
1114
- ...collector.messages
1115
- ],
1116
- prompt: void 0
1117
- }, controller.signal)) {
1118
- collector.push(event);
1119
- yield event;
1120
- }
1121
- if (collector.messages.length > 0 && !isToolUse(collector.messages.at(-1), {
1122
- onlyToolNames: this._getEmbededTools(request.tools ?? []).map((tool) => tool.name)
1123
- })) {
1124
- break;
1125
- }
1126
- if (++toolInvocations > this._maxToolInvocations) {
1127
- throw new Error("Maximum number of tool invocations reached");
1128
- }
1129
- const result = await runTools({
1130
- message: collector.messages.at(-1),
1131
- tools: this._getEmbededTools(request.tools ?? [])
233
+ this._stream = await options.client.exec({
234
+ ...options.generationOptions ?? {},
235
+ // TODO(burdon): Rename messages or separate history/message.
236
+ history: [
237
+ ...this._history,
238
+ ...this._pending
239
+ ],
240
+ tools,
241
+ systemPrompt: createBaseInstructions({
242
+ availableArtifacts: Array.from(requiredArtifactIds),
243
+ operationModel: this._options.operationModel
244
+ })
245
+ });
246
+ await this._parser.parse(this._stream);
247
+ await this._stream.complete();
248
+ log("response", {
249
+ pending: this._pending
250
+ }, {
251
+ F: __dxlog_file,
252
+ L: 283,
253
+ S: this,
254
+ C: (f, a) => f(...a)
255
+ });
256
+ more = false;
257
+ const message = this._pending.at(-1);
258
+ invariant(message, void 0, {
259
+ F: __dxlog_file,
260
+ L: 288,
261
+ S: this,
262
+ A: [
263
+ "message",
264
+ ""
265
+ ]
266
+ });
267
+ if (isToolUse(message)) {
268
+ log("tool request...", void 0, {
269
+ F: __dxlog_file,
270
+ L: 290,
271
+ S: this,
272
+ C: (f, a) => f(...a)
1132
273
  });
1133
- switch (result.type) {
274
+ const response = await runTools({
275
+ message: this._pending.at(-1),
276
+ tools,
277
+ extensions: options.extensions ?? {}
278
+ });
279
+ log("tool response", {
280
+ response
281
+ }, {
282
+ F: __dxlog_file,
283
+ L: 297,
284
+ S: this,
285
+ C: (f, a) => f(...a)
286
+ });
287
+ switch (response.type) {
1134
288
  case "continue": {
1135
- collector.pushMessage(result.message);
1136
- yield* emitMessageAsEvents(result.message);
289
+ this._pending = [
290
+ ...this._pending,
291
+ response.message
292
+ ];
293
+ this.userMessage.emit(response.message);
294
+ more = true;
1137
295
  break;
1138
296
  }
1139
- case "break": {
1140
- throw new Error("Tool use breaks not allowed");
1141
- }
1142
297
  }
1143
298
  }
1144
- }.bind(this));
1145
- } catch (error) {
1146
- controller.abort();
299
+ } while (more);
300
+ } catch (err) {
301
+ log.catch(err, void 0, {
302
+ F: __dxlog_file,
303
+ L: 309,
304
+ S: this,
305
+ C: (f, a) => f(...a)
306
+ });
307
+ if (err instanceof Error && err.message.includes("Overloaded")) {
308
+ error = new AIServiecOverloadedError("AI service overloaded", {
309
+ cause: err
310
+ });
311
+ } else {
312
+ error = new Error("AI service error", {
313
+ cause: err
314
+ });
315
+ }
316
+ } finally {
317
+ this._stream = void 0;
318
+ }
319
+ if (error) {
1147
320
  throw error;
1148
321
  }
322
+ return this._pending;
1149
323
  }
1150
- };
1151
- var sanitizeToolArguments = (args) => {
1152
- if (args.type === "object" && typeof args.properties === "object" && Array.isArray(args.required)) {
1153
- return args.properties;
1154
- }
1155
- return args;
1156
- };
1157
- var SAMPLE_IMAGE_URL = "https://images.nightcafe.studio/jobs/BNmcRhHCM1JRKoUtqSei/BNmcRhHCM1JRKoUtqSei--1--5b9rv.jpg";
1158
- var WELL_KNOWN_TOOLS = {
1159
- [ToolTypes.TextToImage]: defineTool("system", {
1160
- name: "text-to-image",
1161
- description: "Generate an image from a text prompt",
1162
- schema: S3.Struct({
1163
- prompt: S3.String.annotations({
1164
- description: "The text prompt describing the image to generate"
1165
- })
1166
- }),
1167
- execute: async ({ prompt }) => {
1168
- const image = await fetch(SAMPLE_IMAGE_URL).then(async (res) => Buffer.from(await res.arrayBuffer()));
1169
- const imageBase64 = image.toString("base64");
1170
- const id = ObjectId3.random();
1171
- return ToolResult2.Success(`The generation was successful. Image ID: ${id} Prompt: ${prompt}`, [
1172
- {
1173
- type: "image",
1174
- id,
1175
- source: {
1176
- type: "base64",
1177
- mediaType: "image/jpeg",
1178
- data: imageBase64
1179
- }
1180
- }
1181
- ]);
1182
- }
1183
- })
1184
- };
1185
- var OllamaDecoderStream = class extends TransformStream {
1186
- constructor() {
1187
- super({
1188
- transform: (chunk, controller) => {
1189
- this._buffer += chunk;
1190
- const lines = this._buffer.split("\n");
1191
- this._buffer = lines.pop() || "";
1192
- for (const line of lines) {
1193
- controller.enqueue(JSON.parse(line.trim()));
1194
- }
1195
- },
1196
- flush: (controller) => {
1197
- this._buffer = this._buffer.trim();
1198
- if (this._buffer.length > 0) {
1199
- controller.enqueue(JSON.parse(this._buffer));
1200
- }
1201
- }
1202
- });
1203
- this._buffer = "";
324
+ abort() {
325
+ this._stream?.abort();
1204
326
  }
1205
327
  };
328
+ _ts_decorate([
329
+ synchronized
330
+ ], AISession.prototype, "run", null);
331
+ var createBaseInstructions = ({ availableArtifacts, operationModel }) => `
332
+ You are a friendly, advanced AI assistant capable of creating and managing artifacts from available data and tools.
333
+ Your task is to process user commands and questions and decide how best to respond.
334
+ In some cases, you will need to create or reference data objects called artifacts.
1206
335
 
1207
- // packages/experimental/assistant/src/ai-service/parser.ts
1208
- import { Message as Message4 } from "@dxos/artifact";
1209
- import { Event } from "@dxos/async";
1210
- import { createStatic as createStatic2 } from "@dxos/echo-schema";
1211
- import { invariant as invariant4 } from "@dxos/invariant";
1212
- import { log as log5 } from "@dxos/log";
1213
- import { isNotFalsy, safeParseJson } from "@dxos/util";
336
+ Follow these guidelines carefully:
1214
337
 
1215
- // packages/experimental/assistant/src/ai-service/transform.ts
1216
- import * as P from "parsimmon";
1217
- var textChunk = P.regexp(/[^<]+/).map((content) => ({
1218
- type: "text",
1219
- content
1220
- }));
1221
- 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]) => [
1222
- name,
1223
- value
1224
- ]);
1225
- var tagName = P.regexp(/[a-zA-Z_][a-zA-Z0-9_-]*/);
1226
- var selfClosingTag = P.seqMap(
1227
- //
1228
- P.string("<"),
1229
- tagName,
1230
- P.optWhitespace.then(attribute).many(),
1231
- P.optWhitespace.then(P.string("/>")),
1232
- P.optWhitespace,
1233
- (_, tag, attributes, __) => ({
1234
- type: "tag",
1235
- tag,
1236
- attributes: Object.fromEntries(attributes),
1237
- content: [],
1238
- selfClosing: true
1239
- })
1240
- );
1241
- var openTag = P.seqMap(
1242
- //
1243
- P.string("<"),
1244
- tagName,
1245
- P.optWhitespace.then(attribute).many(),
1246
- P.string(">"),
1247
- P.regexp(/[^<]*/),
1248
- (_, tag, attributes, __, content) => ({
1249
- type: "tag",
1250
- tag,
1251
- attributes: Object.fromEntries(attributes),
1252
- content: content.length ? [
1253
- {
1254
- type: "text",
1255
- content
1256
- }
1257
- ] : []
1258
- })
1259
- );
1260
- var closeTag = P.seqMap(
1261
- //
1262
- P.string("</"),
1263
- tagName,
1264
- P.string(">"),
1265
- P.optWhitespace,
1266
- (_, tag) => ({
1267
- type: "tag",
1268
- tag,
1269
- content: [],
1270
- closing: true
1271
- })
1272
- );
1273
- var mixedChunk = P.alt(selfClosingTag, openTag, closeTag, textChunk);
1274
- var StreamTransform = class {
1275
- constructor() {
1276
- this._buffer = "";
1277
- }
1278
- transform(chunk) {
1279
- this._buffer += chunk;
1280
- const results = [];
1281
- const parser = mixedChunk.many().skip(P.optWhitespace);
1282
- const result = parser.parse(this._buffer);
1283
- if (result.status) {
1284
- for (const chunk2 of result.value) {
1285
- results.push(chunk2);
1286
- }
1287
- this._buffer = "";
1288
- }
1289
- return results;
1290
- }
1291
- // TODO(burdon): Process remaining buffer?
1292
- flush() {
1293
- const remaining = this._buffer;
1294
- this._buffer = "";
1295
- return remaining.length > 0 ? [
1296
- {
1297
- type: "text",
1298
- content: remaining
1299
- }
1300
- ] : [];
1301
- }
1302
- };
338
+ Decision-making:
1303
339
 
1304
- // packages/experimental/assistant/src/ai-service/parser.ts
1305
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/parser.ts";
1306
- var MixedStreamParser = class {
1307
- constructor() {
1308
- /**
1309
- * New message.
1310
- */
1311
- this.message = new Event();
1312
- /**
1313
- * Complete block added to Message.
1314
- */
1315
- this.block = new Event();
1316
- /**
1317
- * Update partial block (while streaming).
1318
- */
1319
- this.update = new Event();
1320
- this.streamEvent = new Event();
1321
- }
1322
- _emitBlock(contentBlock, streamBlock) {
1323
- const messageBlock = streamBlock ? mergeMessageBlock(contentBlock, streamBlock) : contentBlock;
1324
- if (messageBlock) {
1325
- if (messageBlock.type === "text" && messageBlock.text.length === 0) {
1326
- return;
1327
- }
1328
- invariant4(this._message, void 0, {
1329
- F: __dxlog_file5,
1330
- L: 49,
1331
- S: this,
1332
- A: [
1333
- "this._message",
1334
- ""
1335
- ]
1336
- });
1337
- this._message.content.push(messageBlock);
1338
- this.block.emit(messageBlock);
1339
- }
1340
- }
1341
- _emitUpdate(contentBlock, streamBlock) {
1342
- const messageBlock = mergeMessageBlock(contentBlock, streamBlock);
1343
- if (messageBlock) {
1344
- messageBlock.pending = true;
1345
- this.update.emit(messageBlock);
1346
- }
1347
- }
1348
- /**
1349
- * Parse stream until end.
1350
- */
1351
- async parse(stream) {
1352
- const transformer = new StreamTransform();
1353
- let contentBlock;
1354
- let streamBlock;
1355
- const stack = [];
1356
- const messagesCollected = [];
1357
- for await (const event of stream) {
1358
- this.streamEvent.emit(event);
1359
- switch (event.type) {
1360
- //
1361
- // Messages.
1362
- //
1363
- case "message_start": {
1364
- if (this._message) {
1365
- log5.warn("unexpected message_start", void 0, {
1366
- F: __dxlog_file5,
1367
- L: 93,
1368
- S: this,
1369
- C: (f, a) => f(...a)
1370
- });
1371
- }
1372
- this._message = createStatic2(Message4, {
1373
- role: event.message.role,
1374
- content: [
1375
- ...event.message.content
1376
- ]
1377
- });
1378
- this.message.emit(this._message);
1379
- break;
1380
- }
1381
- case "message_delta": {
1382
- if (!this._message) {
1383
- log5.warn("unexpected message_delta", void 0, {
1384
- F: __dxlog_file5,
1385
- L: 103,
1386
- S: this,
1387
- C: (f, a) => f(...a)
1388
- });
1389
- }
1390
- break;
1391
- }
1392
- case "message_stop": {
1393
- if (!this._message) {
1394
- log5.warn("unexpected message_stop", void 0, {
1395
- F: __dxlog_file5,
1396
- L: 111,
1397
- S: this,
1398
- C: (f, a) => f(...a)
1399
- });
1400
- } else {
1401
- messagesCollected.push(this._message);
1402
- this._message = void 0;
1403
- }
1404
- break;
1405
- }
1406
- //
1407
- // Content blocks.
1408
- //
1409
- case "content_block_start": {
1410
- if (contentBlock) {
1411
- log5.warn("unexpected content_block_start", {
1412
- content: contentBlock
1413
- }, {
1414
- F: __dxlog_file5,
1415
- L: 125,
1416
- S: this,
1417
- C: (f, a) => f(...a)
1418
- });
1419
- }
1420
- contentBlock = event.content;
1421
- break;
1422
- }
1423
- case "content_block_delta": {
1424
- if (!contentBlock) {
1425
- log5.warn("unexpected content_block_delta", void 0, {
1426
- F: __dxlog_file5,
1427
- L: 135,
1428
- S: this,
1429
- C: (f, a) => f(...a)
1430
- });
1431
- break;
1432
- }
1433
- switch (event.delta.type) {
1434
- //
1435
- // Text
1436
- //
1437
- case "text_delta": {
1438
- const chunks = transformer.transform(event.delta.text);
1439
- for (const chunk of chunks) {
1440
- switch (streamBlock?.type) {
1441
- //
1442
- // XML Fragment.
1443
- //
1444
- case "tag": {
1445
- if (chunk.type === "tag") {
1446
- if (chunk.selfClosing) {
1447
- streamBlock.content.push(chunk);
1448
- } else if (chunk.closing) {
1449
- if (stack.length > 0) {
1450
- const top = stack.pop();
1451
- invariant4(top && top.type === "tag", void 0, {
1452
- F: __dxlog_file5,
1453
- L: 159,
1454
- S: this,
1455
- A: [
1456
- "top && top.type === 'tag'",
1457
- ""
1458
- ]
1459
- });
1460
- top.content.push(streamBlock);
1461
- streamBlock = top;
1462
- } else {
1463
- this._emitBlock(contentBlock, streamBlock);
1464
- streamBlock = void 0;
1465
- }
1466
- } else {
1467
- stack.push(streamBlock);
1468
- streamBlock = chunk;
1469
- }
1470
- } else {
1471
- if (streamBlock.content.length === 0) {
1472
- streamBlock.content.push(chunk);
1473
- } else {
1474
- const last = streamBlock.content.at(-1);
1475
- invariant4(last, void 0, {
1476
- F: __dxlog_file5,
1477
- L: 176,
1478
- S: this,
1479
- A: [
1480
- "last",
1481
- ""
1482
- ]
1483
- });
1484
- if (last.type === "text") {
1485
- last.content += chunk.content;
1486
- } else {
1487
- streamBlock.content.push(chunk);
1488
- }
1489
- }
1490
- }
1491
- break;
1492
- }
1493
- //
1494
- // Text Fragment.
1495
- //
1496
- case "text": {
1497
- if (chunk.type === "tag") {
1498
- this._emitBlock(contentBlock, streamBlock);
1499
- if (chunk.selfClosing) {
1500
- this._emitBlock(contentBlock, chunk);
1501
- streamBlock = void 0;
1502
- } else {
1503
- streamBlock = chunk;
1504
- }
1505
- } else {
1506
- streamBlock.content += chunk.content;
1507
- }
1508
- break;
1509
- }
1510
- //
1511
- // No current chunk.
1512
- //
1513
- default: {
1514
- if (chunk.type === "tag" && chunk.selfClosing) {
1515
- this._emitBlock(contentBlock, chunk);
1516
- } else {
1517
- streamBlock = chunk;
1518
- }
1519
- }
1520
- }
1521
- }
1522
- break;
1523
- }
1524
- //
1525
- // JSON
1526
- //
1527
- case "input_json_delta": {
1528
- if (!contentBlock) {
1529
- log5.warn("unexpected input_json_delta", {
1530
- contentBlock
1531
- }, {
1532
- F: __dxlog_file5,
1533
- L: 226,
1534
- S: this,
1535
- C: (f, a) => f(...a)
1536
- });
1537
- break;
1538
- }
1539
- if (streamBlock?.type === "json") {
1540
- streamBlock.content += event.delta.partial_json;
1541
- } else {
1542
- streamBlock = {
1543
- type: "json",
1544
- content: event.delta.partial_json
1545
- };
1546
- }
1547
- break;
1548
- }
1549
- }
1550
- break;
1551
- }
1552
- case "content_block_stop": {
1553
- if (!contentBlock) {
1554
- log5.warn("unexpected content_block_stop", void 0, {
1555
- F: __dxlog_file5,
1556
- L: 243,
1557
- S: this,
1558
- C: (f, a) => f(...a)
1559
- });
1560
- break;
1561
- }
1562
- this._emitBlock(contentBlock, streamBlock);
1563
- contentBlock = void 0;
1564
- streamBlock = void 0;
1565
- break;
1566
- }
1567
- }
1568
- if (contentBlock && streamBlock) {
1569
- this._emitUpdate(contentBlock, streamBlock);
1570
- }
1571
- }
1572
- return messagesCollected;
1573
- }
1574
- };
1575
- var mergeMessageBlock = (contentBlock, streamBlock) => {
1576
- log5("mergeMessageBlock", {
1577
- contentBlock,
1578
- streamBlock
1579
- }, {
1580
- F: __dxlog_file5,
1581
- L: 270,
1582
- S: void 0,
1583
- C: (f, a) => f(...a)
1584
- });
1585
- switch (streamBlock.type) {
1586
- //
1587
- // Text
1588
- //
1589
- case "text": {
1590
- return {
1591
- ...contentBlock,
1592
- type: "text",
1593
- text: streamBlock.content
1594
- };
1595
- }
1596
- //
1597
- // XML
1598
- //
1599
- case "tag": {
1600
- switch (streamBlock.tag) {
1601
- case "cot": {
1602
- const content = streamBlock.content.map((block) => {
1603
- switch (block.type) {
1604
- case "text":
1605
- return block.content;
1606
- default:
1607
- return null;
1608
- }
1609
- }).filter(isNotFalsy).join("\n");
1610
- return {
1611
- ...contentBlock,
1612
- type: "text",
1613
- disposition: "cot",
1614
- text: content
1615
- };
1616
- }
1617
- case "artifact": {
1618
- const { attributes } = streamBlock;
1619
- return {
1620
- type: "json",
1621
- disposition: "artifact",
1622
- json: JSON.stringify(attributes)
1623
- };
1624
- }
1625
- case "suggest": {
1626
- if (streamBlock.content.length === 1 && streamBlock.content[0].type === "text") {
1627
- return {
1628
- type: "json",
1629
- disposition: "suggest",
1630
- json: JSON.stringify({
1631
- text: streamBlock.content[0].content
1632
- })
1633
- };
1634
- }
1635
- break;
1636
- }
1637
- case "select": {
1638
- return {
1639
- type: "json",
1640
- disposition: "select",
1641
- json: JSON.stringify({
1642
- options: streamBlock.content.flatMap((content) => content.type === "tag" && content.content.length === 1 && content.content[0].type === "text" ? [
1643
- content.content[0].content
1644
- ] : [])
1645
- })
1646
- };
1647
- }
1648
- case "tool-list": {
1649
- return {
1650
- type: "json",
1651
- disposition: "tool_list",
1652
- json: JSON.stringify({})
1653
- };
1654
- }
1655
- }
1656
- break;
1657
- }
1658
- //
1659
- // JSON
1660
- //
1661
- case "json": {
1662
- switch (contentBlock.type) {
1663
- case "tool_use": {
1664
- return {
1665
- ...contentBlock,
1666
- input: safeParseJson(streamBlock.content) ?? {}
1667
- };
1668
- }
1669
- }
1670
- return {
1671
- ...contentBlock,
1672
- type: "json",
1673
- disposition: "artifact",
1674
- json: streamBlock.content
1675
- };
1676
- }
1677
- }
340
+ - Analyze the structure and type of the content in the user's message.
341
+ - Can you complete the task using the available artifacts?
342
+ - If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
343
+ - Identify which artifacts are relevant to the user's request.
344
+ ${operationModel === "planning" ? `
345
+ - Break down the user's request into a step-by-step plan that you will use to execute the user's request, the plan items should include artifacts which will be used to perform the actions.
346
+ ` : `
347
+ - Are the required artifacts already available?
348
+ - If not, select which artifact(s) will be the most relevant and require them using the require_artifacts tool.
349
+ - The require'd artifact tools will be available for use after require.
350
+ `}
351
+
352
+ Artifacts already required: ${availableArtifacts.join("\n")}
353
+ `;
354
+ var AIServiecOverloadedError = class extends S.TaggedError()("AIServiecOverloadedError", {}) {
1678
355
  };
1679
356
  export {
1680
357
  AIServiceEdgeClient,
1681
- DEFAULT_LLM_MODEL,
1682
- DEFAULT_LLM_MODELS,
358
+ AIServiecOverloadedError,
359
+ AISession,
360
+ DEFAULT_EDGE_MODEL,
361
+ DEFAULT_EDGE_MODELS,
362
+ DEFAULT_OLLAMA_ENDPOINT,
363
+ DEFAULT_OLLAMA_MODEL,
364
+ DEFAULT_OLLAMA_MODELS,
1683
365
  EchoDataSource,
1684
366
  GenerateRequest,
1685
367
  GenerationStreamImpl,