@dxos/assistant 0.8.4-main.69d29f4 → 0.8.4-main.6fa680abb7

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 (82) hide show
  1. package/README.md +1 -0
  2. package/dist/lib/neutral/chunk-BE6SRJ4N.mjs +193 -0
  3. package/dist/lib/neutral/chunk-BE6SRJ4N.mjs.map +7 -0
  4. package/dist/lib/{browser → neutral}/extraction/index.mjs +4 -6
  5. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  6. package/dist/lib/{node-esm → neutral}/index.mjs +546 -69
  7. package/dist/lib/neutral/index.mjs.map +7 -0
  8. package/dist/lib/neutral/meta.json +1 -0
  9. package/dist/lib/neutral/testing/index.mjs +38 -0
  10. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  11. package/dist/types/src/conversation/context.d.ts +20 -3
  12. package/dist/types/src/conversation/context.d.ts.map +1 -1
  13. package/dist/types/src/conversation/conversation.d.ts +26 -1
  14. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  15. package/dist/types/src/diff.d.ts +3 -1
  16. package/dist/types/src/diff.d.ts.map +1 -1
  17. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +13 -5
  18. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  19. package/dist/types/src/extraction/extraction.d.ts +16 -12
  20. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  21. package/dist/types/src/functions/services.d.ts +5 -6
  22. package/dist/types/src/functions/services.d.ts.map +1 -1
  23. package/dist/types/src/session/index.d.ts +1 -1
  24. package/dist/types/src/session/index.d.ts.map +1 -1
  25. package/dist/types/src/session/observer.d.ts.map +1 -1
  26. package/dist/types/src/session/session.d.ts +12 -7
  27. package/dist/types/src/session/session.d.ts.map +1 -1
  28. package/dist/types/src/session/toolkit.d.ts +6 -2
  29. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  30. package/dist/types/src/testing/layer.d.ts +6 -5
  31. package/dist/types/src/testing/layer.d.ts.map +1 -1
  32. package/dist/types/src/types/artifact.d.ts +5 -5
  33. package/dist/types/src/types/artifact.d.ts.map +1 -1
  34. package/dist/types/tsconfig.tsbuildinfo +1 -1
  35. package/package.json +32 -33
  36. package/src/conversation/context.test.ts +1 -1
  37. package/src/conversation/context.ts +35 -8
  38. package/src/conversation/conversation.ts +136 -14
  39. package/src/diff.test.ts +35 -4
  40. package/src/diff.ts +13 -4
  41. package/src/execution-graph.test.ts +2 -2
  42. package/src/execution-graph.ts +2 -2
  43. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +1 -1
  44. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +1 -1
  45. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +1 -1
  46. package/src/extraction/extraction.ts +2 -2
  47. package/src/functions/services.ts +59 -30
  48. package/src/functions.conversations.json +1 -1
  49. package/src/functions.test.ts +7 -7
  50. package/src/session/format.test.ts +2 -2
  51. package/src/session/index.ts +1 -2
  52. package/src/session/observer.ts +3 -2
  53. package/src/session/session.conversations.json +1 -1
  54. package/src/session/session.test.ts +52 -4
  55. package/src/session/session.ts +68 -51
  56. package/src/session/toolkit.ts +12 -7
  57. package/src/templates/instructions/format.tpl +0 -4
  58. package/src/testing/layer.ts +24 -17
  59. package/src/types/artifact.ts +17 -10
  60. package/dist/lib/browser/chunk-7CDDG6LL.mjs +0 -578
  61. package/dist/lib/browser/chunk-7CDDG6LL.mjs.map +0 -7
  62. package/dist/lib/browser/chunk-J5LGTIGS.mjs +0 -10
  63. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +0 -7
  64. package/dist/lib/browser/extraction/index.mjs.map +0 -7
  65. package/dist/lib/browser/index.mjs +0 -850
  66. package/dist/lib/browser/index.mjs.map +0 -7
  67. package/dist/lib/browser/meta.json +0 -1
  68. package/dist/lib/browser/testing/index.mjs +0 -32
  69. package/dist/lib/browser/testing/index.mjs.map +0 -7
  70. package/dist/lib/node-esm/chunk-CC7ER6Q3.mjs +0 -579
  71. package/dist/lib/node-esm/chunk-CC7ER6Q3.mjs.map +0 -7
  72. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  73. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  74. package/dist/lib/node-esm/extraction/index.mjs +0 -226
  75. package/dist/lib/node-esm/extraction/index.mjs.map +0 -7
  76. package/dist/lib/node-esm/index.mjs.map +0 -7
  77. package/dist/lib/node-esm/meta.json +0 -1
  78. package/dist/lib/node-esm/testing/index.mjs +0 -33
  79. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  80. package/dist/types/src/session/GenericToolkit.d.ts +0 -85
  81. package/dist/types/src/session/GenericToolkit.d.ts.map +0 -1
  82. package/src/session/GenericToolkit.ts +0 -131
@@ -1,44 +1,37 @@
1
- import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
1
  import {
3
- AiAssistantError,
4
- AiModelError,
5
- AiSession,
6
- ArtifactDiffResolver,
7
2
  ArtifactId,
8
- GenerationObserver,
9
- GenericToolkit_exports,
10
3
  RefFromLLM,
11
- VersionPin,
4
+ ToolExecutionServices,
12
5
  createArtifactElement,
13
- createToolkit,
14
6
  makeToolExecutionServiceFromFunctions,
15
7
  makeToolResolverFromFunctions
16
- } from "./chunk-CC7ER6Q3.mjs";
17
- import "./chunk-HSLMI22Q.mjs";
8
+ } from "./chunk-BE6SRJ4N.mjs";
18
9
 
19
10
  // src/conversation/context.ts
20
11
  import { Atom, Registry } from "@effect-atom/atom-react";
21
12
  import * as EArray from "effect/Array";
22
13
  import * as Context from "effect/Context";
14
+ import * as Effect from "effect/Effect";
23
15
  import * as Function from "effect/Function";
24
16
  import * as Schema from "effect/Schema";
25
17
  import { Blueprint } from "@dxos/blueprints";
26
18
  import { Resource } from "@dxos/context";
27
- import { DXN, Obj, Query, Type } from "@dxos/echo";
19
+ import { DXN, Obj, Query, Ref, Type } from "@dxos/echo";
20
+ import { assertArgument } from "@dxos/invariant";
28
21
  import { log } from "@dxos/log";
29
22
  import { ComplexSet, isTruthy } from "@dxos/util";
30
23
  var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/conversation/context.ts";
31
24
  var ContextBinding = Schema.Struct({
32
25
  blueprints: Schema.Struct({
33
- added: Schema.Array(Type.Ref(Blueprint.Blueprint)),
34
- removed: Schema.Array(Type.Ref(Blueprint.Blueprint))
26
+ added: Schema.Array(Ref.Ref(Blueprint.Blueprint)),
27
+ removed: Schema.Array(Ref.Ref(Blueprint.Blueprint))
35
28
  }),
36
29
  objects: Schema.Struct({
37
- added: Schema.Array(Type.Ref(Type.Obj)),
38
- removed: Schema.Array(Type.Ref(Type.Obj))
30
+ added: Schema.Array(Ref.Ref(Obj.Unknown)),
31
+ removed: Schema.Array(Ref.Ref(Obj.Unknown))
39
32
  })
40
33
  }).pipe(Type.object({
41
- typename: "dxos.org/type/ContextBinding",
34
+ typename: "org.dxos.type.context-binding",
42
35
  version: "0.1.0"
43
36
  }));
44
37
  var Bindings = class {
@@ -59,6 +52,7 @@ var AiContextBinder = class extends Resource {
59
52
  _queue;
60
53
  constructor(options) {
61
54
  super();
55
+ assertArgument(options.queue, "options.queue", "Queue is required");
62
56
  this._queue = options.queue;
63
57
  this._registry = options.registry ?? Registry.make();
64
58
  }
@@ -122,7 +116,7 @@ var AiContextBinder = class extends Resource {
122
116
  objects: newObjects.length
123
117
  }, {
124
118
  F: __dxlog_file,
125
- L: 156,
119
+ L: 159,
126
120
  S: this,
127
121
  C: (f, a) => f(...a)
128
122
  });
@@ -146,7 +140,7 @@ var AiContextBinder = class extends Resource {
146
140
  objects: addedObjects.length
147
141
  }, {
148
142
  F: __dxlog_file,
149
- L: 182,
143
+ L: 185,
150
144
  S: this,
151
145
  C: (f, a) => f(...a)
152
146
  });
@@ -172,7 +166,7 @@ var AiContextBinder = class extends Resource {
172
166
  objects: objects?.length
173
167
  }, {
174
168
  F: __dxlog_file,
175
- L: 202,
169
+ L: 205,
176
170
  S: this,
177
171
  C: (f, a) => f(...a)
178
172
  });
@@ -247,7 +241,7 @@ var AiContextBinder = class extends Resource {
247
241
  const refArray = [
248
242
  ...refs
249
243
  ];
250
- await Promise.all(refArray.map((ref) => ref.load()));
244
+ await Promise.all(refArray.map((ref) => ref.tryLoad()));
251
245
  return refArray.map((ref) => {
252
246
  let target;
253
247
  if (ref.isAvailable) {
@@ -257,17 +251,421 @@ var AiContextBinder = class extends Resource {
257
251
  }).filter(isTruthy);
258
252
  }
259
253
  };
260
- var AiContextService = class extends Context.Tag("@dxos/assistant/AiContextService")() {
254
+ var AiContextService = class _AiContextService extends Context.Tag("@dxos/assistant/AiContextService")() {
255
+ static bindContext = ({ blueprints, objects }) => Effect.gen(function* () {
256
+ const { binder } = yield* _AiContextService;
257
+ yield* Effect.promise(() => binder.bind({
258
+ blueprints,
259
+ objects
260
+ }));
261
+ });
262
+ static findObjects = (type) => {
263
+ return Effect.gen(function* () {
264
+ const { binder } = yield* _AiContextService;
265
+ return binder.getObjects().filter(Obj.instanceOf(type));
266
+ });
267
+ };
268
+ /**
269
+ * Glorified type cast until we figure out function service typing.
270
+ * For context, the AiContextService is provided to functions called from tool calls, but it's not implemented in types yet.
271
+ * @deprecated
272
+ */
273
+ static fixFunctionHandlerType = (eff) => eff;
261
274
  };
262
275
 
263
276
  // src/conversation/conversation.ts
264
- import * as Effect from "effect/Effect";
277
+ import * as Array3 from "effect/Array";
278
+ import * as Context3 from "effect/Context";
279
+ import * as Effect6 from "effect/Effect";
280
+ import * as Either from "effect/Either";
281
+ import { pipe as pipe3 } from "effect/Function";
282
+ import * as Layer from "effect/Layer";
265
283
  import { Resource as Resource2 } from "@dxos/context";
266
- import { Obj as Obj2 } from "@dxos/echo";
284
+ import { Obj as Obj4 } from "@dxos/echo";
285
+ import { acquireReleaseResource } from "@dxos/effect";
286
+ import { QueueService } from "@dxos/functions";
267
287
  import { invariant } from "@dxos/invariant";
288
+ import { log as log4 } from "@dxos/log";
289
+ import { McpToolkit } from "@dxos/mcp-client";
290
+ import { Message as Message3 } from "@dxos/types";
291
+
292
+ // src/session/artifact-diff.ts
293
+ import * as Context2 from "effect/Context";
294
+ var ArtifactDiffResolver = class extends Context2.Tag("@dxos/assistant/ArtifactDiffResolver")() {
295
+ };
296
+
297
+ // src/session/observer.ts
298
+ import * as Effect2 from "effect/Effect";
299
+ import * as Function2 from "effect/Function";
300
+ var GenerationObserver = Object.freeze({
301
+ make: ({ onBegin = Function2.constant(Effect2.void), onPart = Function2.constant(Effect2.void), onBlock = Function2.constant(Effect2.void), onEnd = Function2.constant(Effect2.void), onMessage = Function2.constant(Effect2.void) } = {}) => ({
302
+ onBegin,
303
+ onPart,
304
+ onBlock,
305
+ onEnd,
306
+ onMessage
307
+ }),
308
+ noop: () => GenerationObserver.make(),
309
+ /**
310
+ * Debug printer to be used in unit-tests and browser devtools.
311
+ */
312
+ fromPrinter: (printer) => GenerationObserver.make({
313
+ onBlock: (block) => Effect2.sync(() => {
314
+ if (block.pending) {
315
+ return;
316
+ }
317
+ printer.printContentBlock(block);
318
+ }),
319
+ onMessage: (message) => Effect2.sync(() => {
320
+ if (message.sender.role === "assistant") {
321
+ return;
322
+ }
323
+ printer.printMessage(message);
324
+ })
325
+ })
326
+ });
327
+
328
+ // src/session/session.ts
329
+ import * as LanguageModel from "@effect/ai/LanguageModel";
330
+ import * as Chunk from "effect/Chunk";
331
+ import * as Effect4 from "effect/Effect";
332
+ import * as Stream from "effect/Stream";
333
+ import { AiParser, AiPreprocessor, AiSummarizer, callTool, withoutToolCallParising } from "@dxos/ai";
334
+ import { Obj as Obj3 } from "@dxos/echo";
335
+ import { TracingService } from "@dxos/functions";
336
+ import { log as log3 } from "@dxos/log";
337
+ import { Message as Message2 } from "@dxos/types";
338
+
339
+ // src/session/format.ts
340
+ import * as Effect3 from "effect/Effect";
341
+ import * as Function3 from "effect/Function";
342
+ import * as Option from "effect/Option";
343
+ import { Template } from "@dxos/blueprints";
344
+ import { Obj as Obj2 } from "@dxos/echo";
345
+ import { ObjectVersion } from "@dxos/echo-db";
268
346
  import { log as log2 } from "@dxos/log";
269
347
  import { Message } from "@dxos/types";
270
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/assistant/src/conversation/conversation.ts";
348
+ import { trim } from "@dxos/util";
349
+
350
+ // src/errors.ts
351
+ import { BaseError } from "@dxos/errors";
352
+ var AiModelError = class extends BaseError.extend("AiModelError", "AI model error") {
353
+ };
354
+ var AiAssistantError = class extends BaseError.extend("AiAssistantError", "AI assistant error") {
355
+ };
356
+
357
+ // src/session/format.ts
358
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/assistant/src/session/format.ts";
359
+ var formatSystemPrompt = ({ system, blueprints = [], objects = [] }) => Effect3.gen(function* () {
360
+ const blueprintDefs = yield* Function3.pipe(blueprints, Effect3.forEach((blueprint) => Effect3.succeed(blueprint.instructions)), Effect3.flatMap(Effect3.forEach((template) => Effect3.gen(function* () {
361
+ return trim`
362
+ <blueprint>
363
+ ${yield* Template.processTemplate(template)}
364
+ </blueprint>
365
+ `;
366
+ }))), Effect3.map((blueprints2) => blueprints2.length > 0 ? [
367
+ "## Blueprints Definitions",
368
+ ...blueprints2
369
+ ].join("\n\n") : void 0));
370
+ const objectDefs = yield* Function3.pipe(objects, Effect3.forEach((object) => Effect3.succeed(trim`
371
+ <object>
372
+ <dxn>${Obj2.getDXN(object)}</dxn>
373
+ <typename>${Obj2.getTypename(object)}</typename>
374
+ </object>
375
+ `)), Effect3.map((objects2) => objects2.length > 0 ? [
376
+ "## Context Objects",
377
+ ...objects2
378
+ ].join("\n\n") : void 0));
379
+ return yield* Function3.pipe(Effect3.succeed([
380
+ system,
381
+ blueprintDefs,
382
+ objectDefs
383
+ ].filter((def) => def !== void 0)), Effect3.map((parts) => parts.join("\n\n")));
384
+ });
385
+ var formatUserPrompt = ({ prompt, history = [] }) => Effect3.gen(function* () {
386
+ const blocks = [];
387
+ const artifactDiffResolver = yield* Effect3.serviceOption(ArtifactDiffResolver);
388
+ if (Option.isSome(artifactDiffResolver)) {
389
+ const versions = gatherObjectVersions(history);
390
+ const artifactDiff = yield* Effect3.tryPromise({
391
+ try: () => artifactDiffResolver.value.resolve([
392
+ ...versions.entries()
393
+ ].map(([id, version]) => ({
394
+ id,
395
+ lastVersion: version
396
+ }))),
397
+ catch: AiAssistantError.wrap({
398
+ message: "Artifact diff resolution error"
399
+ })
400
+ });
401
+ log2("version", {
402
+ artifactDiff,
403
+ versions
404
+ }, {
405
+ F: __dxlog_file2,
406
+ L: 94,
407
+ S: this,
408
+ C: (f, a) => f(...a)
409
+ });
410
+ for (const [id, { version }] of [
411
+ ...artifactDiff.entries()
412
+ ]) {
413
+ if (ObjectVersion.equals(version, versions.get(id))) {
414
+ artifactDiff.delete(id);
415
+ continue;
416
+ }
417
+ blocks.push({
418
+ _tag: "anchor",
419
+ objectId: id,
420
+ version
421
+ });
422
+ }
423
+ if (artifactDiff.size > 0) {
424
+ blocks.push(createArtifactUpdateBlock(artifactDiff));
425
+ }
426
+ }
427
+ return Obj2.make(Message.Message, {
428
+ created: (/* @__PURE__ */ new Date()).toISOString(),
429
+ sender: {
430
+ role: "user"
431
+ },
432
+ blocks: [
433
+ ...blocks,
434
+ {
435
+ _tag: "text",
436
+ text: prompt
437
+ }
438
+ ]
439
+ });
440
+ });
441
+ var gatherObjectVersions = (messages) => {
442
+ const artifactIds = /* @__PURE__ */ new Map();
443
+ for (const message of messages) {
444
+ for (const block of message.blocks) {
445
+ if (block._tag === "anchor") {
446
+ artifactIds.set(block.objectId, block.version);
447
+ }
448
+ }
449
+ }
450
+ return artifactIds;
451
+ };
452
+ var createArtifactUpdateBlock = (artifactDiff) => {
453
+ return {
454
+ _tag: "text",
455
+ // TODO(dmaretskyi): Does this need to be a special content-block?
456
+ disposition: "artifact-update",
457
+ text: trim`
458
+ The following artifacts have been updated since the last message:
459
+ ${[
460
+ ...artifactDiff.entries()
461
+ ].map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `
462
+ ${diff}` : ""}</changed-artifact>`).join("\n")}
463
+ `
464
+ };
465
+ };
466
+
467
+ // src/session/session.ts
468
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/assistant/src/session/session.ts";
469
+ var AiSession = class {
470
+ _options;
471
+ /** Prevents concurrent execution of session. */
472
+ _semaphore = Effect4.runSync(Effect4.makeSemaphore(1));
473
+ /** Message history from queue. */
474
+ // TODO(burdon): Evolve into supporting a git-like graph of messages.
475
+ _history = [];
476
+ /** Pending messages for this session (incl. the current prompt). */
477
+ _pending = [];
478
+ _started = 0;
479
+ _ended = 0;
480
+ _toolCalls = 0;
481
+ constructor(_options = {}) {
482
+ this._options = _options;
483
+ }
484
+ get duration() {
485
+ return this._ended - this._started;
486
+ }
487
+ get toolCalls() {
488
+ return this._toolCalls;
489
+ }
490
+ run = ({ prompt, system: systemTemplate, history = [], objects = [], blueprints = [], toolkit, observer = GenerationObserver.noop(), onOutput = () => Effect4.void }) => Effect4.gen(this, function* () {
491
+ this._started = Date.now();
492
+ this._history = [
493
+ ...history
494
+ ];
495
+ this._pending = [];
496
+ const submitMessage = (message) => Effect4.gen(this, function* () {
497
+ this._pending.push(message);
498
+ yield* observer.onMessage(message);
499
+ yield* TracingService.emitConverationMessage(message);
500
+ yield* onOutput(message);
501
+ return message;
502
+ });
503
+ const system = yield* formatSystemPrompt({
504
+ system: systemTemplate,
505
+ blueprints,
506
+ objects
507
+ }).pipe(Effect4.orDie);
508
+ if (this._options.summarizationThreshold !== void 0) {
509
+ const tokenCount = yield* AiPreprocessor.estimateTokens(yield* AiPreprocessor.preprocessPrompt([
510
+ ...this._history
511
+ ], {
512
+ system
513
+ }));
514
+ if (tokenCount > this._options.summarizationThreshold) {
515
+ const summary = yield* AiSummarizer.summarize([
516
+ ...this._history
517
+ ]);
518
+ yield* submitMessage(summary);
519
+ }
520
+ }
521
+ const promptMessage = yield* submitMessage(yield* formatUserPrompt({
522
+ prompt,
523
+ history
524
+ }));
525
+ do {
526
+ log3("request", {
527
+ prompt: promptMessage,
528
+ system: {
529
+ snippet: createSnippet(system),
530
+ length: system.length
531
+ },
532
+ pending: this._pending.length,
533
+ history: this._history.length,
534
+ objects: objects?.length ?? 0
535
+ }, {
536
+ F: __dxlog_file3,
537
+ L: 149,
538
+ S: this,
539
+ C: (f, a) => f(...a)
540
+ });
541
+ const prompt2 = yield* AiPreprocessor.preprocessPrompt([
542
+ ...this._history,
543
+ ...this._pending
544
+ ], {
545
+ system,
546
+ cacheControl: "ephemeral"
547
+ });
548
+ const messages = yield* LanguageModel.streamText({
549
+ prompt: prompt2,
550
+ toolkit,
551
+ disableToolCallResolution: true
552
+ }).pipe(
553
+ // Disable tool call parsing so that we can handle parameter schema errors on a per-tool call basis.
554
+ withoutToolCallParising,
555
+ // TOOD(dmaretskyi): Error mapping.
556
+ AiParser.parseResponse({
557
+ onBegin: () => observer.onBegin(),
558
+ onBlock: (block) => observer.onBlock(block),
559
+ onPart: (part) => observer.onPart(part),
560
+ onEnd: (summary) => observer.onEnd(summary)
561
+ }),
562
+ Stream.mapEffect((block) => Effect4.gen(function* () {
563
+ return yield* submitMessage(Obj3.make(Message2.Message, {
564
+ created: (/* @__PURE__ */ new Date()).toISOString(),
565
+ sender: {
566
+ role: "assistant"
567
+ },
568
+ blocks: [
569
+ block
570
+ ]
571
+ }));
572
+ })),
573
+ Stream.runCollect,
574
+ Effect4.map(Chunk.toArray)
575
+ );
576
+ const toolCalls = messages.flatMap((message) => message.blocks.filter((block) => block._tag === "toolCall" && block.providerExecuted === false).map((block) => ({
577
+ block,
578
+ message
579
+ })));
580
+ if (toolCalls.length === 0) {
581
+ break;
582
+ } else if (!toolkit) {
583
+ throw new Error("No toolkit provided");
584
+ }
585
+ const toolResults = yield* Effect4.forEach(toolCalls, ({ block, message }) => {
586
+ return callTool(toolkit, block).pipe(Effect4.provide(TracingService.layerSubframe((context) => ({
587
+ ...context,
588
+ parentMessage: message.id,
589
+ toolCallId: block.toolCallId
590
+ }))));
591
+ });
592
+ yield* submitMessage(Obj3.make(Message2.Message, {
593
+ created: (/* @__PURE__ */ new Date()).toISOString(),
594
+ sender: {
595
+ role: "tool"
596
+ },
597
+ blocks: toolResults
598
+ }));
599
+ this._toolCalls++;
600
+ } while (true);
601
+ this._ended = Date.now();
602
+ log3("done", {
603
+ pending: this._pending.length,
604
+ duration: this.duration,
605
+ tools: this._toolCalls
606
+ }, {
607
+ F: __dxlog_file3,
608
+ L: 236,
609
+ S: this,
610
+ C: (f, a) => f(...a)
611
+ });
612
+ return this._pending;
613
+ }).pipe(this._semaphore.withPermits(1), Effect4.withSpan("AiSession.run"));
614
+ };
615
+ var createSnippet = (text, len = 32) => text.length <= len * 2 ? text : [
616
+ text.slice(0, len),
617
+ "...",
618
+ text.slice(-len)
619
+ ].join("");
620
+
621
+ // src/session/toolkit.ts
622
+ import * as Toolkit from "@effect/ai/Toolkit";
623
+ import * as Effect5 from "effect/Effect";
624
+ import { GenericToolkit, ToolExecutionService, ToolResolverService } from "@dxos/ai";
625
+ import { isTruthy as isTruthy2 } from "@dxos/util";
626
+ var createToolkit = ({ toolkit: toolkitProp, blueprints = [], genericToolkits = [] }) => Effect5.gen(function* () {
627
+ const blueprintToolkit = yield* ToolResolverService.resolveToolkit(blueprints.flatMap(({ tools }) => tools));
628
+ const blueprintToolHandler = yield* blueprintToolkit.toContext(ToolExecutionService.handlersFor(blueprintToolkit));
629
+ const genericToolkit = GenericToolkit.merge(...genericToolkits);
630
+ const toolkit = Toolkit.merge(...[
631
+ toolkitProp,
632
+ blueprintToolkit,
633
+ genericToolkit.toolkit
634
+ ].filter(isTruthy2));
635
+ return yield* toolkit.pipe(Effect5.provide(blueprintToolHandler), Effect5.provide(genericToolkit.layer));
636
+ });
637
+
638
+ // src/session/version-pin.ts
639
+ import * as Schema2 from "effect/Schema";
640
+ import { getVersion } from "@dxos/echo-db";
641
+ import { ObjectId } from "@dxos/keys";
642
+ var ObjectVersionSchema = Schema2.Unknown;
643
+ var VersionPinSchema = Schema2.Struct({
644
+ // TODO(dmaretskyi): Use Ref when those support encoding.
645
+ objectId: ObjectId,
646
+ // TODO(dmaretskyi): Could be opaque.
647
+ version: ObjectVersionSchema
648
+ });
649
+ var VersionPin = class extends VersionPinSchema {
650
+ static DISPOSITION = "version-pin";
651
+ static fromObject(object) {
652
+ return VersionPin.make({
653
+ objectId: object.id,
654
+ version: getVersion(object)
655
+ });
656
+ }
657
+ static createBlock(pin) {
658
+ return {
659
+ _tag: "json",
660
+ disposition: VersionPin.DISPOSITION,
661
+ data: JSON.stringify(pin)
662
+ };
663
+ }
664
+ };
665
+
666
+ // src/conversation/conversation.ts
667
+ var __dxlog_file4 = "/__w/dxos/dxos/packages/core/assistant/src/conversation/conversation.ts";
668
+ var SUMMARY_THRESHOLD = 8e4;
271
669
  var AiConversation = class extends Resource2 {
272
670
  /**
273
671
  * Blueprints and objects bound to the conversation.
@@ -280,8 +678,8 @@ var AiConversation = class extends Resource2 {
280
678
  this._queue = options.queue;
281
679
  this._toolkit = options.toolkit;
282
680
  invariant(this._queue, void 0, {
283
- F: __dxlog_file2,
284
- L: 54,
681
+ F: __dxlog_file4,
682
+ L: 72,
285
683
  S: this,
286
684
  A: [
287
685
  "this._queue",
@@ -307,64 +705,134 @@ var AiConversation = class extends Resource2 {
307
705
  }
308
706
  async getHistory() {
309
707
  const queueItems = await this._queue.queryObjects();
310
- return queueItems.filter(Obj2.instanceOf(Message.Message));
708
+ return queueItems.filter(Obj4.instanceOf(Message3.Message));
709
+ }
710
+ getTools() {
711
+ return Effect6.gen(this, function* () {
712
+ const blueprints = this.context.getBlueprints();
713
+ const tookit = yield* createToolkit({
714
+ toolkit: this._toolkit,
715
+ blueprints
716
+ });
717
+ return tookit.tools;
718
+ }).pipe(Effect6.orDie);
311
719
  }
312
720
  /**
313
721
  * Creates a new cancelable request effect.
314
722
  */
315
723
  createRequest(params) {
316
- const self = this;
317
- return Effect.gen(function* () {
318
- const history = yield* Effect.promise(() => self.getHistory());
319
- const blueprints = self.context.getBlueprints();
724
+ return Effect6.gen(this, function* () {
725
+ const history = yield* Effect6.promise(() => this.getHistory());
726
+ const blueprints = this.context.getBlueprints();
727
+ const mcps = yield* connectMcpServers(blueprints);
320
728
  const toolkit = yield* createToolkit({
321
- toolkit: self._toolkit,
322
- blueprints
729
+ toolkit: this._toolkit,
730
+ blueprints,
731
+ genericToolkits: mcps
323
732
  });
324
- const objects = self.context.getObjects();
325
- log2("run", {
733
+ const objects = this.context.getObjects();
734
+ log4("run", {
326
735
  history: history.length,
327
736
  blueprints: blueprints.length,
328
737
  tools: Object.keys(toolkit.tools).length,
329
738
  objects: objects.length
330
739
  }, {
331
- F: __dxlog_file2,
332
- L: 99,
740
+ F: __dxlog_file4,
741
+ L: 128,
333
742
  S: this,
334
743
  C: (f, a) => f(...a)
335
744
  });
336
- const session = new AiSession();
745
+ const session = new AiSession({
746
+ summarizationThreshold: SUMMARY_THRESHOLD
747
+ });
337
748
  const messages = yield* session.run({
338
749
  history,
339
750
  blueprints,
340
751
  toolkit,
341
752
  objects,
342
- ...params
343
- }).pipe(Effect.provideService(AiContextService, {
344
- binder: self.context
345
- }));
346
- log2("result", {
753
+ ...params,
754
+ onOutput: (message) => Effect6.promise(() => this._queue.append([
755
+ message
756
+ ]))
757
+ }).pipe(Effect6.provide(Layer.mergeAll(Layer.succeed(AiContextService, {
758
+ binder: this.context
759
+ }), Layer.succeed(AiConversationService, this))));
760
+ log4("result", {
347
761
  messages: messages.length,
348
762
  duration: session.duration,
349
763
  toolCalls: session.toolCalls
350
764
  }, {
351
- F: __dxlog_file2,
352
- L: 114,
765
+ F: __dxlog_file4,
766
+ L: 159,
353
767
  S: this,
354
768
  C: (f, a) => f(...a)
355
769
  });
356
- yield* Effect.promise(() => self._queue.append(messages));
357
770
  return messages;
358
771
  });
359
772
  }
360
773
  };
774
+ var AiConversationService = class _AiConversationService extends Context3.Tag("@dxos/assistant/AiConversationService")() {
775
+ /**
776
+ * Create a new conversation layer from options.
777
+ */
778
+ static layer = (options) => aiContextFromConversation.pipe(Layer.provideMerge(Layer.scoped(_AiConversationService, Effect6.gen(function* () {
779
+ const conversation = yield* acquireReleaseResource(() => new AiConversation(options));
780
+ return conversation;
781
+ }))));
782
+ /**
783
+ * Create a new conversation with a new queue.
784
+ */
785
+ static layerNewQueue = (options) => Layer.unwrapScoped(Effect6.gen(function* () {
786
+ return _AiConversationService.layer({
787
+ ...options,
788
+ queue: yield* QueueService.createQueue()
789
+ });
790
+ }));
791
+ /**
792
+ * Run a prompt in the current conversation.
793
+ */
794
+ static run = (params) => Effect6.gen(function* () {
795
+ const conversation = yield* _AiConversationService;
796
+ return yield* conversation.createRequest(params);
797
+ });
798
+ };
799
+ var aiContextFromConversation = Layer.effect(AiContextService, Effect6.gen(function* () {
800
+ const conversation = yield* AiConversationService;
801
+ return {
802
+ binder: conversation.context
803
+ };
804
+ }));
805
+ var connectMcpServers = (blueprints) => pipe3(blueprints, Array3.flatMap((_) => _.mcpServers ?? []), Effect6.forEach(({ url, protocol }) => McpToolkit.make({
806
+ url,
807
+ kind: protocol
808
+ }).pipe(
809
+ // NOTE: Type-inference fails here without explicit void return.
810
+ Effect6.tap((toolkit) => log4.info("Connected to MCP server", {
811
+ url,
812
+ tools: Object.keys(toolkit.toolkit.tools).length
813
+ }, {
814
+ F: __dxlog_file4,
815
+ L: 240,
816
+ S: void 0,
817
+ C: (f, a) => f(...a)
818
+ })),
819
+ Effect6.tapDefect((error) => Effect6.sync(() => log4.warn("Failed to connect to MCP server", {
820
+ error
821
+ }, {
822
+ F: __dxlog_file4,
823
+ L: 242,
824
+ S: void 0,
825
+ C: (f, a) => f(...a)
826
+ }))),
827
+ Effect6.either
828
+ )), Effect6.map(Array3.filterMap((_) => Either.getRight(_))));
361
829
 
362
830
  // src/diff.ts
363
831
  import { next as A } from "@automerge/automerge";
364
832
  import { DocAccessor, toCursorRange } from "@dxos/echo-db";
365
- import { log as log3 } from "@dxos/log";
833
+ import { log as log5 } from "@dxos/log";
366
834
  import { isNonNullable } from "@dxos/util";
367
- var __dxlog_file3 = "/__w/dxos/dxos/packages/core/assistant/src/diff.ts";
835
+ var __dxlog_file5 = "/__w/dxos/dxos/packages/core/assistant/src/diff.ts";
368
836
  var reduceDiffs = (diffs) => {
369
837
  return diffs.reduce((acc, diff) => {
370
838
  const current = acc[acc.length - 1];
@@ -392,8 +860,10 @@ var reduceDiffs = (diffs) => {
392
860
  }
393
861
  return acc;
394
862
  }
863
+ default: {
864
+ throw new Error(`Invalid diff format: each line must start with "- " or "+ ", got: ${JSON.stringify(diff)}`);
865
+ }
395
866
  }
396
- return acc;
397
867
  }, []);
398
868
  };
399
869
  var computeDiffsWithCursors = (accessor, diffs) => {
@@ -408,7 +878,7 @@ var computeDiffsWithCursors = (accessor, diffs) => {
408
878
  }
409
879
  }).filter(isNonNullable);
410
880
  };
411
- var applyDiffs = (accessor, diffs) => {
881
+ var applyDiffs = (accessor, diffs, { errorOnNotFound = false } = {}) => {
412
882
  for (const diff of reduceDiffs(diffs)) {
413
883
  accessor.handle.change((doc) => {
414
884
  const text = DocAccessor.getValue(accessor);
@@ -416,12 +886,16 @@ var applyDiffs = (accessor, diffs) => {
416
886
  if (idx !== -1) {
417
887
  A.splice(doc, accessor.path, idx, diff.match.length, diff.replace);
418
888
  } else {
419
- log3.warn("diff not found", diff, {
420
- F: __dxlog_file3,
421
- L: 78,
422
- S: void 0,
423
- C: (f, a) => f(...a)
424
- });
889
+ if (errorOnNotFound) {
890
+ throw new Error(`Diff not found: ${diff.match}`);
891
+ } else {
892
+ log5.warn("diff not found", diff, {
893
+ F: __dxlog_file5,
894
+ L: 86,
895
+ S: void 0,
896
+ C: (f, a) => f(...a)
897
+ });
898
+ }
425
899
  }
426
900
  });
427
901
  }
@@ -430,10 +904,10 @@ var applyDiffs = (accessor, diffs) => {
430
904
 
431
905
  // src/execution-graph.ts
432
906
  import { AgentStatus } from "@dxos/ai";
433
- import { Obj as Obj3 } from "@dxos/echo";
907
+ import { Obj as Obj5 } from "@dxos/echo";
434
908
  import { MESSAGE_PROPERTY_TOOL_CALL_ID } from "@dxos/functions";
435
909
  import { LogLevel } from "@dxos/log";
436
- import { ContentBlock, Message as Message2 } from "@dxos/types";
910
+ import { ContentBlock, Message as Message4 } from "@dxos/types";
437
911
  import { isNonNullable as isNonNullable2 } from "@dxos/util";
438
912
  var SKIP_BLOCKS = [
439
913
  "text"
@@ -457,9 +931,9 @@ var ExecutionGraph = class {
457
931
  addEvents(events) {
458
932
  const sortedEvents = this.sortObjectsByCreated(events);
459
933
  for (const event of sortedEvents) {
460
- if (Obj3.instanceOf(Message2.Message, event)) {
934
+ if (Obj5.instanceOf(Message4.Message, event)) {
461
935
  this._processMessage(event);
462
- } else if (Obj3.instanceOf(AgentStatus, event)) {
936
+ } else if (Obj5.instanceOf(AgentStatus, event)) {
463
937
  this._processAgentStatus(event);
464
938
  }
465
939
  }
@@ -717,7 +1191,7 @@ var createBlockCommit = (block, message, branch, parents, idx) => {
717
1191
  level: block.error ? LogLevel.ERROR : LogLevel.INFO,
718
1192
  message: block.error ? "Tool error: " + block.error : "Tool call succeeded"
719
1193
  };
720
- case "summary":
1194
+ case "stats":
721
1195
  return {
722
1196
  id: getGenericBlockId(message.id, idx),
723
1197
  branch,
@@ -725,7 +1199,7 @@ var createBlockCommit = (block, message, branch, parents, idx) => {
725
1199
  timestamp,
726
1200
  icon: "ph--rocket--regular",
727
1201
  level: LogLevel.INFO,
728
- message: ContentBlock.createSummaryMessage(block)
1202
+ message: ContentBlock.createStatsMessage(block)
729
1203
  };
730
1204
  case "status":
731
1205
  return {
@@ -795,26 +1269,26 @@ var stringifyRef = (ref) => {
795
1269
  return ref.dxn.asEchoDXN()?.echoId ?? ref.dxn.asQueueDXN()?.objectId ?? "";
796
1270
  };
797
1271
  var stringifyObject = (obj) => {
798
- return Obj3.getLabel(obj) ?? Obj3.getTypename(obj) ?? obj.id;
1272
+ return Obj5.getLabel(obj) ?? Obj5.getTypename(obj) ?? obj.id;
799
1273
  };
800
1274
 
801
1275
  // src/templates/system.ts
802
1276
  import defaultsDeep from "lodash.defaultsdeep";
803
- import { Template } from "@dxos/blueprints";
1277
+ import { Template as Template2 } from "@dxos/blueprints";
804
1278
 
805
1279
  // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/instructions/format.tpl?raw
806
- var format_default = "{{! System Core }}\n\n## Input Formats\n\n### Blueprints\n\nYou may be provided with Blueprint definitions that include specific instructions and tools for a given set of tasks.\nBlue print instructions will be enclosed in a <blueprint> tag.\n\n### Context objects\n\nYou may be provided with references to objects that are relevant to the current prompt.\nObjects will be in the form of a <object> tag with a <dxn> element that is the unique key of the object required by many tools.\nThe <typename> element is the type of the object.\n\n<object>\n <dxn>object-id</dxn>\n <typename>example.com/type/TypeName</typename>\n</object>\n\n## Response Formats\n\nIt is very important to respond in the correct format.\nYou response must be valid Markdown.\nIn some cases you should respond with well-formed XML tags along with the content.\nCode snippets should use 2-space indents.\n\n{{#if cot}}\nBefore responding, explain your reasoning and include your detailed chain-of-thought enclosed in a <cot> tag.\nThe <cot> tag should be the first thing in your response.\n{{/if}}\n\n## Block references\n\nYou can reply with a block reference for objects if you have the DXN. For example:\n\n<object>\n <dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n<object>\n <dxn>dxn:echo:@:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n\n### Suggestions\n\nEach suggestion must in the form of a proposed action enclosed in a <suggestion> tag.\nExample: <suggestion>Show on a map</suggestion>\nDo not use bullets when listing suggestions.\n\n### Multiple choice questions\n\nYou may ask multiple choice questions by wrapping consise options inside <option> tags inside a well formed <select> tag.\nExample: <select><option>Yes</option><option>No</option></select>\n\n## Toolkit\n\nIf the user asks for a list of tools, then just emit a single self-closing <toolkit/> tag instead of listing the tools.\n\n## Context\n\nThe current date and time is {{DATETIME}}.\n";
1280
+ var format_default = "{{! System Core }}\n\n## Input Formats\n\n### Blueprints\n\nYou may be provided with Blueprint definitions that include specific instructions and tools for a given set of tasks.\nBlue print instructions will be enclosed in a <blueprint> tag.\n\n### Context objects\n\nYou may be provided with references to objects that are relevant to the current prompt.\nObjects will be in the form of a <object> tag with a <dxn> element that is the unique key of the object required by many tools.\nThe <typename> element is the type of the object.\n\n<object>\n <dxn>object-id</dxn>\n <typename>example.com/type/TypeName</typename>\n</object>\n\n## Response Formats\n\nIt is very important to respond in the correct format.\nYou response must be valid Markdown.\nIn some cases you should respond with well-formed XML tags along with the content.\nCode snippets should use 2-space indents.\n\n{{#if cot}}\nBefore responding, explain your reasoning and include your detailed chain-of-thought enclosed in a <cot> tag.\nThe <cot> tag should be the first thing in your response.\n{{/if}}\n\n## Block references\n\nYou can reply with a block reference for objects if you have the DXN. For example:\n\n<object>\n <dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n<object>\n <dxn>dxn:echo:@:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n\n### Suggestions\n\nEach suggestion must in the form of a proposed action enclosed in a <suggestion> tag.\nExample: <suggestion>Show on a map</suggestion>\nDo not use bullets when listing suggestions.\n\n### Multiple choice questions\n\nYou may ask multiple choice questions by wrapping consise options inside <option> tags inside a well formed <select> tag.\nExample: <select><option>Yes</option><option>No</option></select>\n\n## Context\n\nThe current date and time is {{DATETIME}}.\n";
807
1281
 
808
1282
  // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/instructions/system.tpl?raw
809
1283
  var system_default = "{{! System Prompt }}\n\n- You are a helpful assistant called Kai. \n- Your name is Kai and you are powered by different language models.\n- You were created by DXOS and operate inside of Composer and on the DXOS EDGE network.\n- In your initial greeting state your name and make some suggestions based on the current context objects.\n- You are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.\n- Your task is to process user commands and questions and decide how best to respond.\n- In general be concise and direct.\n- Follow all instructions carefully.\n\n## Planning\n\n- Analyze the structure and type of the content in the user's message.\n- Determine if you complete the task using the available blueprint definitions?\n- If you can't complete the task using the available blueprint definitions, query the list of available blueprint definitions using the appropriate tool.\n- Identify which blueprint definitions are relevant to the user's request.\n- Evaluate the potential benefits of creating an artifact vs. normal processing for each identified element.\n- Make a final decision on whether to create an artifact and explain your reasoning.\n- Are the required blueprint definitions already available?\n- If not, select which blueprint definition(s) will be the most relevant and require them using the require_artifact_definitions tool.\n- The require'd artifact tools will be available for use after require.\n- If creating an artifact, outline how you will structure it within the response.\n- Decide if the artifact needs to be shown to the user.\n- Call the show tool to show the artifact to the user.\n- Your reasoning must include: whether to use artifacts or not, to create one or query, whether to show the artifact to the user, and how to structure the response.\n\n## Blueprints and Artifacts\n\n- Determine if the interaction involves an artifact. Prefer artifacts for tables, lists, spreadsheets, kanbans, games, images, and other structured data.\n- Determine if the user is explicitly talking about creating a new artifact, or wants to use an existing artifact.\n- If it is ambiguous, query for existing artifacts first and then decide.\n- If you decide to create an artifact, call the associated tool to create the artifact.\n- Artifacts are stored in the database. Tools are used to create and query artifacts.\n- If you are unsure about creating an artifact ask the user for clarification.\n- Artifacts are mutable objects that can change over the course of the conversation.\n- Always re-query the artifact using the tool (like query or inspect) to get the latest state of the artifact before answering the user.\n- You must never generate the id of the artifact; only recall the ids that are already in the history.\n- Artifacts are created by requiring the specific artifact using the require_artifact tool and creating it by calling the associated tool.\n- You can add suggested actions at the end of your response.\n- Suggested actions should be very concise and start with a verb and be phrased as a command to an agent -- not a question to the user.\n- Suggested actions must be in the form of a user instruction that you can follow.\n- Suggested actions could include actions that create artifacts.\n- After creating an artifact use a tool to add it to the chat context.\n\n## Context\n\nToday is {{DATETIME}}.\n";
810
1284
 
811
1285
  // src/templates/system.ts
812
- var createSystemPrompt = (options = {}) => Template.process(format_default, defaultsDeep(options, {
1286
+ var createSystemPrompt = (options = {}) => Template2.process(format_default, defaultsDeep(options, {
813
1287
  DATETIME: (/* @__PURE__ */ new Date()).toISOString()
814
1288
  }));
815
1289
  var templates = {
816
1290
  /** Editable system prompt.*/
817
- system: Template.make({
1291
+ system: Template2.make({
818
1292
  /**
819
1293
  * NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.
820
1294
  */
@@ -827,6 +1301,7 @@ export {
827
1301
  AiContextBinder,
828
1302
  AiContextService,
829
1303
  AiConversation,
1304
+ AiConversationService,
830
1305
  AiModelError,
831
1306
  AiSession,
832
1307
  ArtifactDiffResolver,
@@ -835,14 +1310,16 @@ export {
835
1310
  ContextBinding,
836
1311
  ExecutionGraph,
837
1312
  GenerationObserver,
838
- GenericToolkit_exports as GenericToolkit,
839
1313
  RefFromLLM,
1314
+ ToolExecutionServices,
840
1315
  VersionPin,
841
1316
  applyDiffs,
842
1317
  computeDiffsWithCursors,
843
1318
  createArtifactElement,
844
1319
  createSystemPrompt,
845
1320
  createToolkit,
1321
+ formatSystemPrompt,
1322
+ formatUserPrompt,
846
1323
  makeToolExecutionServiceFromFunctions,
847
1324
  makeToolResolverFromFunctions,
848
1325
  reduceDiffs,