@dxos/assistant 0.8.4-main.fd6878d → 0.8.4-main.fffef41

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 (122) hide show
  1. package/dist/lib/browser/chunk-J5LGTIGS.mjs +10 -0
  2. package/dist/lib/browser/extraction/index.mjs +121 -165
  3. package/dist/lib/browser/extraction/index.mjs.map +4 -4
  4. package/dist/lib/browser/index.mjs +1097 -161
  5. package/dist/lib/browser/index.mjs.map +4 -4
  6. package/dist/lib/browser/meta.json +1 -1
  7. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  8. package/dist/lib/node-esm/extraction/index.mjs +121 -165
  9. package/dist/lib/node-esm/extraction/index.mjs.map +4 -4
  10. package/dist/lib/node-esm/index.mjs +1097 -161
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/types/src/conversation/context.d.ts +23 -10
  14. package/dist/types/src/conversation/context.d.ts.map +1 -1
  15. package/dist/types/src/conversation/conversation.d.ts +22 -31
  16. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  17. package/dist/types/src/diff.d.ts +15 -0
  18. package/dist/types/src/diff.d.ts.map +1 -0
  19. package/dist/types/src/diff.test.d.ts +2 -0
  20. package/dist/types/src/diff.test.d.ts.map +1 -0
  21. package/dist/types/src/errors.d.ts +45 -13
  22. package/dist/types/src/errors.d.ts.map +1 -1
  23. package/dist/types/src/execution-graph.d.ts +85 -0
  24. package/dist/types/src/execution-graph.d.ts.map +1 -0
  25. package/dist/types/src/execution-graph.test.d.ts +2 -0
  26. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  27. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +1 -1
  28. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  29. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +82 -43
  30. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  31. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  32. package/dist/types/src/extraction/extraction.d.ts +262 -225
  33. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  34. package/dist/types/src/extraction/quotes.d.ts +1 -1
  35. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  36. package/dist/types/src/functions/services.d.ts +18 -5
  37. package/dist/types/src/functions/services.d.ts.map +1 -1
  38. package/dist/types/src/index.d.ts +3 -1
  39. package/dist/types/src/index.d.ts.map +1 -1
  40. package/dist/types/src/session/GenericToolkit.d.ts +84 -0
  41. package/dist/types/src/session/GenericToolkit.d.ts.map +1 -0
  42. package/dist/types/src/session/artifact-diff.d.ts +2 -2
  43. package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
  44. package/dist/types/src/session/error-handling.d.ts +4 -0
  45. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  46. package/dist/types/src/session/format.d.ts +5 -161
  47. package/dist/types/src/session/format.d.ts.map +1 -1
  48. package/dist/types/src/session/index.d.ts +3 -0
  49. package/dist/types/src/session/index.d.ts.map +1 -1
  50. package/dist/types/src/session/observer.d.ts +22 -0
  51. package/dist/types/src/session/observer.d.ts.map +1 -0
  52. package/dist/types/src/session/session.d.ts +22 -138
  53. package/dist/types/src/session/session.d.ts.map +1 -1
  54. package/dist/types/src/session/toolkit.d.ts +15 -0
  55. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  56. package/dist/types/src/session/version-pin.d.ts +3 -3
  57. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  58. package/dist/types/src/templates/system.d.ts +8 -12
  59. package/dist/types/src/templates/system.d.ts.map +1 -1
  60. package/dist/types/src/types/artifact.d.ts +20 -0
  61. package/dist/types/src/types/artifact.d.ts.map +1 -0
  62. package/dist/types/src/types/index.d.ts +2 -0
  63. package/dist/types/src/types/index.d.ts.map +1 -0
  64. package/dist/types/tsconfig.tsbuildinfo +1 -1
  65. package/package.json +29 -31
  66. package/src/conversation/context.ts +75 -22
  67. package/src/conversation/conversation.ts +80 -77
  68. package/src/diff.test.ts +43 -0
  69. package/src/diff.ts +84 -0
  70. package/src/errors.ts +6 -1
  71. package/src/execution-graph.test.ts +740 -0
  72. package/src/execution-graph.ts +509 -0
  73. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +9 -9
  74. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +47 -56
  75. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +16 -16
  76. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +42 -43
  77. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  78. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +2 -0
  79. package/src/extraction/extraction.ts +7 -6
  80. package/src/extraction/quotes.test.ts +2 -2
  81. package/src/extraction/quotes.ts +3 -3
  82. package/src/functions/services.ts +104 -56
  83. package/src/index.ts +3 -1
  84. package/src/session/GenericToolkit.ts +130 -0
  85. package/src/session/artifact-diff.ts +8 -4
  86. package/src/session/error-handling.ts +41 -0
  87. package/src/session/format.test.ts +5 -4
  88. package/src/session/format.ts +27 -22
  89. package/src/session/index.ts +4 -0
  90. package/src/session/observer.ts +59 -0
  91. package/src/session/session.conversations.json +1 -0
  92. package/src/session/session.test.ts +35 -191
  93. package/src/session/session.ts +119 -185
  94. package/src/session/toolkit.ts +48 -0
  95. package/src/session/version-pin.ts +4 -5
  96. package/src/templates/{format.tpl → instructions/format.tpl} +8 -2
  97. package/src/templates/{system.tpl → instructions/system.tpl} +15 -14
  98. package/src/templates/system.ts +25 -16
  99. package/src/{types.ts → types/artifact.ts} +22 -3
  100. package/src/types/index.ts +5 -0
  101. package/dist/lib/browser/chunk-6WRGDEMH.mjs +0 -89
  102. package/dist/lib/browser/chunk-6WRGDEMH.mjs.map +0 -7
  103. package/dist/lib/browser/chunk-NZGGCEF3.mjs +0 -341
  104. package/dist/lib/browser/chunk-NZGGCEF3.mjs.map +0 -7
  105. package/dist/lib/browser/named-entity-recognition-O46UTCLR.mjs +0 -13
  106. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs +0 -91
  107. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs.map +0 -7
  108. package/dist/lib/node-esm/chunk-XOOPGSGW.mjs +0 -343
  109. package/dist/lib/node-esm/chunk-XOOPGSGW.mjs.map +0 -7
  110. package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs +0 -14
  111. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  112. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  113. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  114. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  115. package/dist/types/src/types.d.ts +0 -16
  116. package/dist/types/src/types.d.ts.map +0 -1
  117. package/src/session/__snapshots__/session.test.ts.snap +0 -32
  118. package/src/session/version-pin.test.ts +0 -7
  119. package/src/summarization/summarization.test.ts +0 -197
  120. /package/dist/lib/browser/{named-entity-recognition-O46UTCLR.mjs.map → chunk-J5LGTIGS.mjs.map} +0 -0
  121. /package/dist/lib/node-esm/{named-entity-recognition-W4VMRCH6.mjs.map → chunk-HSLMI22Q.mjs.map} +0 -0
  122. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -1,19 +1,20 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
2
  import {
3
- AiAssistantError,
4
- AiSession,
5
- ArtifactDiffResolver,
6
- GenerationObserver,
7
- VersionPin
8
- } from "./chunk-XOOPGSGW.mjs";
3
+ __export
4
+ } from "./chunk-HSLMI22Q.mjs";
9
5
 
10
6
  // src/conversation/context.ts
11
7
  import { computed } from "@preact/signals-core";
12
- import { Schema } from "effect";
13
- import { Array, pipe } from "effect";
8
+ import * as Array2 from "effect/Array";
9
+ import * as Context from "effect/Context";
10
+ import * as Function from "effect/Function";
11
+ import * as Schema from "effect/Schema";
14
12
  import { Blueprint } from "@dxos/blueprints";
15
- import { Obj, Type } from "@dxos/echo";
13
+ import { Resource } from "@dxos/context";
14
+ import { DXN, Filter, Obj, Query, Type } from "@dxos/echo";
15
+ import { invariant } from "@dxos/invariant";
16
16
  import { ComplexSet } from "@dxos/util";
17
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/conversation/context.ts";
17
18
  var ContextBinding = Schema.Struct({
18
19
  blueprints: Schema.Struct({
19
20
  added: Schema.Array(Type.Ref(Blueprint.Blueprint)),
@@ -30,53 +31,103 @@ var ContextBinding = Schema.Struct({
30
31
  }));
31
32
  var Bindings = class {
32
33
  blueprints = new ComplexSet((ref) => ref.dxn.toString());
33
- objects = new ComplexSet((ref) => ref.dxn.toString());
34
+ // TODO(burdon): Some DXNs have the Space prefix so only compare the object ID.
35
+ objects = new ComplexSet((ref) => ref.dxn.asEchoDXN()?.echoId);
34
36
  toJSON() {
35
37
  return {
36
- blueprints: Array.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),
37
- objects: Array.fromIterable(this.objects).map((ref) => ref.dxn.toString())
38
+ blueprints: Array2.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),
39
+ objects: Array2.fromIterable(this.objects).map((ref) => ref.dxn.toString())
38
40
  };
39
41
  }
40
42
  };
41
- var AiContextBinder = class {
43
+ var AiContextBinder = class extends Resource {
42
44
  _queue;
43
45
  /**
44
46
  * Reactive query of all bindings.
45
47
  */
46
48
  // TODO(burdon): Cache value?
47
- bindings;
48
- blueprints;
49
- objects;
49
+ _bindings;
50
+ _blueprints;
51
+ _objects;
50
52
  constructor(_queue) {
51
- this._queue = _queue;
52
- this.bindings = computed(() => this._reduce(this._queue.objects));
53
- this.blueprints = computed(() => [
53
+ super(), this._queue = _queue;
54
+ }
55
+ get bindings() {
56
+ invariant(this._bindings, "AiContextBinder not open", {
57
+ F: __dxlog_file,
58
+ L: 78,
59
+ S: this,
60
+ A: [
61
+ "this._bindings",
62
+ "'AiContextBinder not open'"
63
+ ]
64
+ });
65
+ return this._bindings;
66
+ }
67
+ get blueprints() {
68
+ invariant(this._blueprints, "AiContextBinder not open", {
69
+ F: __dxlog_file,
70
+ L: 83,
71
+ S: this,
72
+ A: [
73
+ "this._blueprints",
74
+ "'AiContextBinder not open'"
75
+ ]
76
+ });
77
+ return this._blueprints;
78
+ }
79
+ get objects() {
80
+ invariant(this._objects, "AiContextBinder not open", {
81
+ F: __dxlog_file,
82
+ L: 88,
83
+ S: this,
84
+ A: [
85
+ "this._objects",
86
+ "'AiContextBinder not open'"
87
+ ]
88
+ });
89
+ return this._objects;
90
+ }
91
+ // TODO(wittjosiah): Use parent context?
92
+ async _open() {
93
+ const query = this._queue.query(Query.select(Filter.everything()));
94
+ this._ctx.onDispose(query.subscribe(() => {
95
+ }));
96
+ this._bindings = computed(() => this._reduce(query.objects));
97
+ this._blueprints = computed(() => [
54
98
  ...this.bindings.value.blueprints
55
99
  ]);
56
- this.objects = computed(() => [
100
+ this._objects = computed(() => [
57
101
  ...this.bindings.value.objects
58
102
  ]);
59
103
  }
104
+ async _close() {
105
+ this._bindings = void 0;
106
+ this._blueprints = void 0;
107
+ this._objects = void 0;
108
+ }
60
109
  /**
61
110
  * Asynchronous query of all bindings.
62
111
  */
63
112
  async query() {
64
- const queueItems = await this._queue.queryObjects();
65
- return this._reduce(queueItems);
113
+ const { objects } = await this._queue.query(Query.select(Filter.everything())).run();
114
+ return this._reduce(objects);
66
115
  }
67
116
  // TODO(burdon): Pass in Blueprint obj (from registry?) and create reference.
68
117
  async bind(props) {
69
- if (!props.blueprints?.length && !props.objects?.length) {
118
+ const blueprints = props.blueprints?.filter((ref) => !this.blueprints.peek().find((b) => b.dxn.toString() === ref.dxn.toString())) ?? [];
119
+ const objects = props.objects?.filter((ref) => !this.objects.peek().find((o) => o.dxn.toString() === ref.dxn.toString())) ?? [];
120
+ if (!blueprints.length && !objects.length) {
70
121
  return;
71
122
  }
72
123
  await this._queue.append([
73
124
  Obj.make(ContextBinding, {
74
125
  blueprints: {
75
- added: props.blueprints ?? [],
126
+ added: blueprints,
76
127
  removed: []
77
128
  },
78
129
  objects: {
79
- added: props.objects ?? [],
130
+ added: objects,
80
131
  removed: []
81
132
  }
82
133
  })
@@ -100,211 +151,1081 @@ var AiContextBinder = class {
100
151
  ]);
101
152
  }
102
153
  _reduce(items) {
103
- return pipe(items, Array.filter(Obj.instanceOf(ContextBinding)), Array.reduce(new Bindings(), (context, item) => {
104
- item.blueprints.removed.forEach((item2) => context.blueprints.delete(item2));
105
- item.blueprints.added.forEach((item2) => context.blueprints.add(item2));
106
- item.objects.removed.forEach((item2) => context.objects.delete(item2));
107
- item.objects.added.forEach((item2) => context.objects.add(item2));
154
+ return Function.pipe(items, Array2.filter(Obj.instanceOf(ContextBinding)), Array2.reduce(new Bindings(), (context, item) => {
155
+ item.blueprints.removed.forEach((ref) => context.blueprints.delete(ref));
156
+ item.blueprints.added.forEach((ref) => context.blueprints.add(ref));
157
+ item.objects.removed.forEach((ref) => {
158
+ for (const obj of context.objects) {
159
+ if (DXN.equalsEchoId(obj.dxn, ref.dxn)) {
160
+ context.objects.delete(obj);
161
+ }
162
+ }
163
+ });
164
+ item.objects.added.forEach((ref) => context.objects.add(ref));
108
165
  return context;
109
166
  }));
110
167
  }
111
168
  };
169
+ var AiContextService = class extends Context.Tag("@dxos/assistant/AiContextService")() {
170
+ };
112
171
 
113
172
  // src/conversation/conversation.ts
114
- import { Effect } from "effect";
115
- import { Event } from "@dxos/async";
173
+ import * as Array5 from "effect/Array";
174
+ import * as Effect6 from "effect/Effect";
175
+ import * as Option2 from "effect/Option";
176
+ import { Resource as Resource2 } from "@dxos/context";
177
+ import { Obj as Obj4 } from "@dxos/echo";
178
+ import { DatabaseService as DatabaseService2 } from "@dxos/echo-db";
179
+ import { log as log3 } from "@dxos/log";
180
+ import { Message as Message3 } from "@dxos/types";
181
+
182
+ // src/session/artifact-diff.ts
183
+ import * as Context2 from "effect/Context";
184
+ var ArtifactDiffResolver = class extends Context2.Tag("@dxos/assistant/ArtifactDiffResolver")() {
185
+ };
186
+
187
+ // src/session/observer.ts
188
+ import * as Effect from "effect/Effect";
189
+ import * as Function2 from "effect/Function";
190
+ var GenerationObserver = Object.freeze({
191
+ make: ({ onBegin = Function2.constant(Effect.void), onPart = Function2.constant(Effect.void), onBlock = Function2.constant(Effect.void), onEnd = Function2.constant(Effect.void), onMessage = Function2.constant(Effect.void) } = {}) => ({
192
+ onBegin,
193
+ onPart,
194
+ onBlock,
195
+ onEnd,
196
+ onMessage
197
+ }),
198
+ noop: () => GenerationObserver.make(),
199
+ /**
200
+ * Debug printer to be used in unit-tests and browser devtools.
201
+ */
202
+ fromPrinter: (printer) => GenerationObserver.make({
203
+ onBlock: (block) => Effect.sync(() => {
204
+ if (block.pending) {
205
+ return;
206
+ }
207
+ printer.printContentBlock(block);
208
+ }),
209
+ onMessage: (message) => Effect.sync(() => {
210
+ if (message.sender.role === "assistant") {
211
+ return;
212
+ }
213
+ printer.printMessage(message);
214
+ })
215
+ })
216
+ });
217
+
218
+ // src/session/session.ts
219
+ import * as LanguageModel from "@effect/ai/LanguageModel";
220
+ import * as Chunk from "effect/Chunk";
221
+ import * as Effect3 from "effect/Effect";
222
+ import * as Stream from "effect/Stream";
223
+ import { AiParser, AiPreprocessor, callTool, getToolCalls } from "@dxos/ai";
224
+ import { todo } from "@dxos/debug";
225
+ import { Obj as Obj3 } from "@dxos/echo";
226
+ import { TracingService } from "@dxos/functions";
227
+ import { log as log2 } from "@dxos/log";
228
+ import { Message as Message2 } from "@dxos/types";
229
+
230
+ // src/session/format.ts
231
+ import * as Array4 from "effect/Array";
232
+ import * as Effect2 from "effect/Effect";
233
+ import * as Function3 from "effect/Function";
234
+ import * as Option from "effect/Option";
235
+ import { Template } from "@dxos/blueprints";
116
236
  import { Obj as Obj2 } from "@dxos/echo";
117
- import { DatabaseService } from "@dxos/functions";
237
+ import { DatabaseService, ObjectVersion } from "@dxos/echo-db";
118
238
  import { log } from "@dxos/log";
119
- import { DataType } from "@dxos/schema";
120
- var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/conversation/conversation.ts";
121
- var AiConversation = class {
239
+ import { Message } from "@dxos/types";
240
+ import { trim } from "@dxos/util";
241
+
242
+ // src/errors.ts
243
+ import { BaseError } from "@dxos/errors";
244
+ var AiModelError = class extends BaseError.extend("AI_MODEL_ERROR", "AI model error") {
245
+ };
246
+ var AiAssistantError = class extends BaseError.extend("AI_ASSISTANT_ERROR", "AI assistant error") {
247
+ };
248
+
249
+ // src/session/format.ts
250
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/assistant/src/session/format.ts";
251
+ var formatSystemPrompt = ({ system, blueprints = [], objects = [] }) => Effect2.gen(function* () {
252
+ const blueprintDefs = yield* Function3.pipe(blueprints, Effect2.forEach((blueprint) => Effect2.succeed(blueprint.instructions)), Effect2.flatMap(Effect2.forEach((template) => DatabaseService.loadOption(template.source))), Effect2.map(Array4.filter(Option.isSome)), Effect2.map(Array4.map((template) => trim`
253
+ <blueprint>
254
+ ${Template.process(template.value.content)}
255
+ </blueprint>
256
+ `)), Effect2.map((blueprints2) => blueprints2.length > 0 ? [
257
+ "## Blueprints Definitions",
258
+ ...blueprints2
259
+ ].join("\n\n") : void 0));
260
+ const objectDefs = yield* Function3.pipe(objects, Effect2.forEach((object) => Effect2.succeed(trim`
261
+ <object>
262
+ <dxn>${Obj2.getDXN(object)}</dxn>
263
+ <typename>${Obj2.getTypename(object)}</typename>
264
+ </object>
265
+ `)), Effect2.map((objects2) => objects2.length > 0 ? [
266
+ "## Context Objects",
267
+ ...objects2
268
+ ].join("\n\n") : void 0));
269
+ return yield* Function3.pipe(Effect2.succeed([
270
+ system,
271
+ blueprintDefs,
272
+ objectDefs
273
+ ].filter((def) => def !== void 0)), Effect2.map((parts) => parts.join("\n\n")));
274
+ });
275
+ var formatUserPrompt = ({ prompt, history = [] }) => Effect2.gen(function* () {
276
+ const blocks = [];
277
+ const artifactDiffResolver = yield* Effect2.serviceOption(ArtifactDiffResolver);
278
+ if (Option.isSome(artifactDiffResolver)) {
279
+ const versions = gatherObjectVersions(history);
280
+ const artifactDiff = yield* Effect2.tryPromise({
281
+ try: () => artifactDiffResolver.value.resolve([
282
+ ...versions.entries()
283
+ ].map(([id, version]) => ({
284
+ id,
285
+ lastVersion: version
286
+ }))),
287
+ catch: AiAssistantError.wrap({
288
+ message: "Artifact diff resolution error"
289
+ })
290
+ });
291
+ log("version", {
292
+ artifactDiff,
293
+ versions
294
+ }, {
295
+ F: __dxlog_file2,
296
+ L: 95,
297
+ S: this,
298
+ C: (f, a) => f(...a)
299
+ });
300
+ for (const [id, { version }] of [
301
+ ...artifactDiff.entries()
302
+ ]) {
303
+ if (ObjectVersion.equals(version, versions.get(id))) {
304
+ artifactDiff.delete(id);
305
+ continue;
306
+ }
307
+ blocks.push({
308
+ _tag: "anchor",
309
+ objectId: id,
310
+ version
311
+ });
312
+ }
313
+ if (artifactDiff.size > 0) {
314
+ blocks.push(createArtifactUpdateBlock(artifactDiff));
315
+ }
316
+ }
317
+ return Obj2.make(Message.Message, {
318
+ created: (/* @__PURE__ */ new Date()).toISOString(),
319
+ sender: {
320
+ role: "user"
321
+ },
322
+ blocks: [
323
+ ...blocks,
324
+ {
325
+ _tag: "text",
326
+ text: prompt
327
+ }
328
+ ]
329
+ });
330
+ });
331
+ var gatherObjectVersions = (messages) => {
332
+ const artifactIds = /* @__PURE__ */ new Map();
333
+ for (const message of messages) {
334
+ for (const block of message.blocks) {
335
+ if (block._tag === "anchor") {
336
+ artifactIds.set(block.objectId, block.version);
337
+ }
338
+ }
339
+ }
340
+ return artifactIds;
341
+ };
342
+ var createArtifactUpdateBlock = (artifactDiff) => {
343
+ return {
344
+ _tag: "text",
345
+ // TODO(dmaretskyi): Does this need to be a special content-block?
346
+ disposition: "artifact-update",
347
+ text: trim`
348
+ The following artifacts have been updated since the last message:
349
+ ${[
350
+ ...artifactDiff.entries()
351
+ ].map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `
352
+ ${diff}` : ""}</changed-artifact>`).join("\n")}
353
+ `
354
+ };
355
+ };
356
+
357
+ // src/session/session.ts
358
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/assistant/src/session/session.ts";
359
+ var AiSession = class {
360
+ _options;
361
+ /** Prevents concurrent execution of session. */
362
+ _semaphore = Effect3.runSync(Effect3.makeSemaphore(1));
363
+ /** Message history from queue. */
364
+ // TODO(burdon): Evolve into supporting a git-like graph of messages.
365
+ _history = [];
366
+ /** Pending messages for this session (incl. the current prompt). */
367
+ _pending = [];
368
+ constructor(_options = {}) {
369
+ this._options = _options;
370
+ }
371
+ run = ({ prompt, system: systemTemplate, history = [], objects = [], blueprints = [], toolkit, observer = GenerationObserver.noop() }) => Effect3.gen(this, function* () {
372
+ this._history = [
373
+ ...history
374
+ ];
375
+ this._pending = [];
376
+ const pending = this._pending;
377
+ const submitMessage = Effect3.fnUntraced(function* (message) {
378
+ pending.push(message);
379
+ yield* observer.onMessage(message);
380
+ yield* TracingService.emitConverationMessage(message);
381
+ return message;
382
+ });
383
+ const promptMessage = yield* submitMessage(yield* formatUserPrompt({
384
+ prompt,
385
+ history
386
+ }));
387
+ const system = yield* formatSystemPrompt({
388
+ system: systemTemplate,
389
+ blueprints,
390
+ objects
391
+ });
392
+ do {
393
+ log2("request", {
394
+ prompt: promptMessage,
395
+ system: {
396
+ snippet: createSnippet(system),
397
+ length: system.length
398
+ },
399
+ pending: this._pending.length,
400
+ history: this._history.length,
401
+ objects: objects?.length ?? 0
402
+ }, {
403
+ F: __dxlog_file3,
404
+ L: 110,
405
+ S: this,
406
+ C: (f, a) => f(...a)
407
+ });
408
+ const prompt2 = yield* AiPreprocessor.preprocessPrompt([
409
+ ...this._history,
410
+ ...this._pending
411
+ ], {
412
+ system
413
+ });
414
+ const blocks = yield* LanguageModel.streamText({
415
+ prompt: prompt2,
416
+ toolkit,
417
+ disableToolCallResolution: true
418
+ }).pipe(
419
+ // TOOD(dmaretskyi): Error mapping.
420
+ AiParser.parseResponse({
421
+ onBegin: () => observer.onBegin(),
422
+ onBlock: (block) => observer.onBlock(block),
423
+ onPart: (part) => observer.onPart(part),
424
+ onEnd: (summary) => observer.onEnd(summary)
425
+ }),
426
+ Stream.runCollect,
427
+ Effect3.map(Chunk.toArray)
428
+ );
429
+ const response = yield* submitMessage(Obj3.make(Message2.Message, {
430
+ created: (/* @__PURE__ */ new Date()).toISOString(),
431
+ sender: {
432
+ role: "assistant"
433
+ },
434
+ blocks
435
+ }));
436
+ const toolCalls = getToolCalls(response);
437
+ if (toolCalls.length === 0) {
438
+ break;
439
+ } else if (!toolkit) {
440
+ throw new Error("No toolkit provided");
441
+ }
442
+ const toolResults = yield* Effect3.forEach(toolCalls, (toolCall) => {
443
+ return callTool(toolkit, toolCall).pipe(Effect3.provide(TracingService.layerSubframe((context) => ({
444
+ ...context,
445
+ parentMessage: response.id,
446
+ toolCallId: toolCall.toolCallId
447
+ }))));
448
+ });
449
+ yield* submitMessage(Obj3.make(Message2.Message, {
450
+ created: (/* @__PURE__ */ new Date()).toISOString(),
451
+ sender: {
452
+ role: "tool"
453
+ },
454
+ blocks: toolResults
455
+ }));
456
+ } while (true);
457
+ log2("done", {
458
+ pending: this._pending.length
459
+ }, {
460
+ F: __dxlog_file3,
461
+ L: 181,
462
+ S: this,
463
+ C: (f, a) => f(...a)
464
+ });
465
+ return this._pending;
466
+ }).pipe(this._semaphore.withPermits(1), Effect3.withSpan("AiSession.run"));
467
+ /**
468
+ * @deprecated
469
+ */
470
+ // TODO(burdon): Implement or remove.
471
+ async runStructured(_schema, _options) {
472
+ return todo();
473
+ }
474
+ };
475
+ var createSnippet = (text, len = 32) => text.length <= len * 2 ? text : [
476
+ text.slice(0, len),
477
+ "...",
478
+ text.slice(-len)
479
+ ].join("");
480
+
481
+ // src/session/toolkit.ts
482
+ import * as Toolkit from "@effect/ai/Toolkit";
483
+ import * as Effect4 from "effect/Effect";
484
+ import { ToolExecutionService, ToolResolverService } from "@dxos/ai";
485
+ import { isTruthy } from "@dxos/util";
486
+ var createToolkit = ({ toolkit: toolkitParam, toolIds = [], blueprints = [] }) => Effect4.gen(function* () {
487
+ const blueprintToolkit = yield* ToolResolverService.resolveToolkit([
488
+ ...blueprints.flatMap(({ tools }) => tools),
489
+ ...toolIds
490
+ ]);
491
+ const blueprintToolkitHandler = yield* blueprintToolkit.toContext(ToolExecutionService.handlersFor(blueprintToolkit));
492
+ const toolkit = Toolkit.merge(...[
493
+ toolkitParam,
494
+ blueprintToolkit
495
+ ].filter(isTruthy));
496
+ return yield* toolkit.pipe(Effect4.provide(blueprintToolkitHandler));
497
+ });
498
+
499
+ // src/session/version-pin.ts
500
+ import * as Schema2 from "effect/Schema";
501
+ import { ObjectId } from "@dxos/echo/internal";
502
+ import { getVersion } from "@dxos/echo-db";
503
+ var ObjectVersionSchema = Schema2.Unknown;
504
+ var VersionPinSchema = Schema2.Struct({
505
+ // TODO(dmaretskyi): Use Ref when those support encoding.
506
+ objectId: ObjectId,
507
+ // TODO(dmaretskyi): Could be opaque.
508
+ version: ObjectVersionSchema
509
+ });
510
+ var VersionPin = class extends VersionPinSchema {
511
+ static DISPOSITION = "version-pin";
512
+ static fromObject(object) {
513
+ return VersionPin.make({
514
+ objectId: object.id,
515
+ version: getVersion(object)
516
+ });
517
+ }
518
+ static createBlock(pin) {
519
+ return {
520
+ _tag: "json",
521
+ disposition: VersionPin.DISPOSITION,
522
+ data: JSON.stringify(pin)
523
+ };
524
+ }
525
+ };
526
+
527
+ // src/session/GenericToolkit.ts
528
+ var GenericToolkit_exports = {};
529
+ __export(GenericToolkit_exports, {
530
+ TypeId: () => TypeId,
531
+ make: () => make,
532
+ merge: () => merge3
533
+ });
534
+ import * as Toolkit2 from "@effect/ai/Toolkit";
535
+ import * as Effect5 from "effect/Effect";
536
+ import * as Layer from "effect/Layer";
537
+ import * as Pipeable from "effect/Pipeable";
538
+ var TypeId = "~@dxos/assistant/GenericToolkit";
539
+ var make = (toolkit, layer) => {
540
+ return {
541
+ [TypeId]: TypeId,
542
+ toolkit,
543
+ layer,
544
+ handlers: toolkit.pipe(Effect5.provide(layer)),
545
+ pipe() {
546
+ return Pipeable.pipeArguments(this, arguments);
547
+ }
548
+ };
549
+ };
550
+ var merge3 = (...toolkits) => {
551
+ return make(Toolkit2.merge(...toolkits.map((t) => t.toolkit)), Layer.mergeAll(...toolkits.map((t) => t.layer)));
552
+ };
553
+
554
+ // src/conversation/conversation.ts
555
+ var __dxlog_file4 = "/__w/dxos/dxos/packages/core/assistant/src/conversation/conversation.ts";
556
+ var AiConversation = class extends Resource2 {
557
+ /**
558
+ * Message and binding queue.
559
+ */
122
560
  _queue;
123
561
  /**
124
562
  * Blueprints bound to the conversation.
125
563
  */
126
564
  _context;
127
565
  /**
128
- * Fired when the execution loop begins.
129
- * This is called before the first message is sent.
130
- *
131
- * @deprecated Pass in a session instead.
566
+ * Toolkit from the current session request.
132
567
  */
133
- // TODO(burdon): Is this still deprecated?
134
- onBegin = new Event();
135
- constructor(options) {
136
- this._queue = options.queue;
568
+ _toolkit;
569
+ constructor(queue) {
570
+ super();
571
+ this._queue = queue;
137
572
  this._context = new AiContextBinder(this._queue);
138
573
  }
574
+ async _open() {
575
+ await this._context.open();
576
+ }
577
+ async _close() {
578
+ await this._context.close();
579
+ }
139
580
  get context() {
140
581
  return this._context;
141
582
  }
583
+ get toolkit() {
584
+ return this._toolkit;
585
+ }
142
586
  async getHistory() {
143
587
  const queueItems = await this._queue.queryObjects();
144
- return queueItems.filter(Obj2.instanceOf(DataType.Message));
588
+ return queueItems.filter(Obj4.instanceOf(Message3.Message));
145
589
  }
146
590
  /**
147
- * Executes a prompt.
148
- * Each invocation creates a new `AiSession`, which handles potential tool calls.
591
+ * Creates a new cancelable request effect.
149
592
  */
150
- run = ({
151
- // TODO(burdon): Decide whether to pass in or to fully encapsulate.
152
- session = new AiSession(),
153
- ...params
154
- }) => Effect.gen(this, function* () {
155
- const history = yield* Effect.promise(() => this.getHistory());
156
- const context = yield* Effect.promise(() => this.context.query());
157
- const blueprints = yield* Effect.forEach(context.blueprints.values(), DatabaseService.load);
158
- const objects = yield* Effect.forEach(context.objects.values(), DatabaseService.load);
159
- log.info("run", {
160
- prompt: params.prompt,
161
- system: params.system,
162
- history: history.length,
163
- objects: objects.length,
164
- blueprints: blueprints.length,
165
- toolkit: params.toolkit
166
- }, {
167
- F: __dxlog_file,
168
- L: 99,
169
- S: this,
170
- C: (f, a) => f(...a)
593
+ createRequest(params) {
594
+ return Effect6.gen(this, function* () {
595
+ const session = new AiSession();
596
+ const history = yield* Effect6.promise(() => this.getHistory());
597
+ const context = yield* Effect6.promise(() => this.context.query());
598
+ const blueprints = yield* Effect6.forEach(context.blueprints.values(), DatabaseService2.loadOption).pipe(Effect6.map(Array5.filter(Option2.isSome)), Effect6.map(Array5.map((option) => option.value)));
599
+ const objects = yield* Effect6.forEach(context.objects.values(), DatabaseService2.loadOption).pipe(Effect6.map(Array5.filter(Option2.isSome)), Effect6.map(Array5.map((option) => option.value)));
600
+ const toolkit = yield* createToolkit({
601
+ blueprints
602
+ });
603
+ this._toolkit = toolkit;
604
+ const start = Date.now();
605
+ log3("run", {
606
+ history: history.length,
607
+ blueprints: blueprints.length,
608
+ objects: objects.length,
609
+ tools: this._toolkit?.tools.length ?? 0
610
+ }, {
611
+ F: __dxlog_file4,
612
+ L: 107,
613
+ S: this,
614
+ C: (f, a) => f(...a)
615
+ });
616
+ const messages = yield* session.run({
617
+ history,
618
+ blueprints,
619
+ objects,
620
+ toolkit,
621
+ ...params
622
+ }).pipe(Effect6.provideService(AiContextService, {
623
+ binder: this.context
624
+ }));
625
+ log3("result", {
626
+ messages: messages.length,
627
+ duration: Date.now() - start
628
+ }, {
629
+ F: __dxlog_file4,
630
+ L: 121,
631
+ S: this,
632
+ C: (f, a) => f(...a)
633
+ });
634
+ yield* Effect6.promise(() => this._queue.append(messages));
635
+ return messages;
636
+ }).pipe(Effect6.withSpan("AiConversation.request"));
637
+ }
638
+ };
639
+
640
+ // src/diff.ts
641
+ import { next as A } from "@automerge/automerge";
642
+ import { DocAccessor, toCursorRange } from "@dxos/echo-db";
643
+ import { log as log4 } from "@dxos/log";
644
+ import { isNonNullable } from "@dxos/util";
645
+ var __dxlog_file5 = "/__w/dxos/dxos/packages/core/assistant/src/diff.ts";
646
+ var reduceDiffs = (diffs) => {
647
+ return diffs.reduce((acc, diff) => {
648
+ const current = acc[acc.length - 1];
649
+ const [op, ...rest] = diff.split(" ");
650
+ switch (op) {
651
+ case "-": {
652
+ if (current && !current.match) {
653
+ current.match += rest.join(" ");
654
+ } else {
655
+ acc.push({
656
+ match: rest.join(" "),
657
+ replace: ""
658
+ });
659
+ }
660
+ return acc;
661
+ }
662
+ case "+": {
663
+ if (current && !current.replace) {
664
+ current.replace += rest.join(" ");
665
+ } else {
666
+ acc.push({
667
+ match: "",
668
+ replace: rest.join(" ")
669
+ });
670
+ }
671
+ return acc;
672
+ }
673
+ }
674
+ return acc;
675
+ }, []);
676
+ };
677
+ var computeDiffsWithCursors = (accessor, diffs) => {
678
+ return reduceDiffs(diffs).map((diff) => {
679
+ const text = DocAccessor.getValue(accessor);
680
+ const idx = text.indexOf(diff.match);
681
+ if (idx !== -1) {
682
+ return {
683
+ cursor: toCursorRange(accessor, idx, idx + diff.match.length),
684
+ text: diff.replace
685
+ };
686
+ }
687
+ }).filter(isNonNullable);
688
+ };
689
+ var applyDiffs = (accessor, diffs) => {
690
+ for (const diff of reduceDiffs(diffs)) {
691
+ accessor.handle.change((doc) => {
692
+ const text = DocAccessor.getValue(accessor);
693
+ const idx = text.indexOf(diff.match);
694
+ if (idx !== -1) {
695
+ A.splice(doc, accessor.path, idx, diff.match.length, diff.replace);
696
+ } else {
697
+ log4.warn("diff not found", diff, {
698
+ F: __dxlog_file5,
699
+ L: 78,
700
+ S: void 0,
701
+ C: (f, a) => f(...a)
702
+ });
703
+ }
171
704
  });
172
- const start = Date.now();
173
- this.onBegin.emit(session);
174
- const messages = yield* session.run({
175
- prompt: params.prompt,
176
- system: params.system,
177
- history,
178
- objects,
179
- blueprints,
180
- toolkit: params.toolkit,
181
- observer: params.observer
705
+ }
706
+ return DocAccessor.getValue(accessor);
707
+ };
708
+
709
+ // src/execution-graph.ts
710
+ import { AgentStatus } from "@dxos/ai";
711
+ import { Obj as Obj5 } from "@dxos/echo";
712
+ import { MESSAGE_PROPERTY_TOOL_CALL_ID } from "@dxos/functions";
713
+ import { LogLevel } from "@dxos/log";
714
+ import { ContentBlock, Message as Message4 } from "@dxos/types";
715
+ import { isNonNullable as isNonNullable2 } from "@dxos/util";
716
+ var SKIP_BLOCKS = [
717
+ "text"
718
+ ];
719
+ var ExecutionGraph = class {
720
+ _skipBlocks;
721
+ // TODO(dmaretskyi): Evolve the internal state to support chats, functions, circuit workflows, etc.
722
+ _commits = [];
723
+ _branchNames = /* @__PURE__ */ new Set();
724
+ _lastBlockId;
725
+ // Tool call tracking.
726
+ _toolCallCommitIds = /* @__PURE__ */ new Map();
727
+ _lastCommitByBranch = /* @__PURE__ */ new Map();
728
+ _pendingToolResults = /* @__PURE__ */ new Map();
729
+ constructor(_skipBlocks = SKIP_BLOCKS) {
730
+ this._skipBlocks = _skipBlocks;
731
+ }
732
+ /**
733
+ * Adds events to the graph.
734
+ */
735
+ addEvents(events) {
736
+ const sortedEvents = this.sortObjectsByCreated(events);
737
+ for (const event of sortedEvents) {
738
+ if (Obj5.instanceOf(Message4.Message, event)) {
739
+ this._processMessage(event);
740
+ } else if (Obj5.instanceOf(AgentStatus, event)) {
741
+ this._processAgentStatus(event);
742
+ }
743
+ }
744
+ }
745
+ /**
746
+ * Processes a message event and creates commits for its blocks.
747
+ */
748
+ _processMessage(message) {
749
+ const messageCommits = messageToCommits(message, this._lastBlockId, this._toolCallCommitIds, this._lastCommitByBranch, this._skipBlocks);
750
+ this._commits.push(...messageCommits);
751
+ messageCommits.forEach((commit) => this._branchNames.add(commit.branch));
752
+ this._trackToolCalls(messageCommits);
753
+ if (messageCommits.length > 0) {
754
+ this._lastBlockId = messageCommits[messageCommits.length - 1].id;
755
+ }
756
+ }
757
+ /**
758
+ * Processes an AgentStatus event.
759
+ */
760
+ _processAgentStatus(event) {
761
+ const branch = this._getToolCallBranch(event.parentMessage, event.toolCallId);
762
+ this._branchNames.add(branch);
763
+ const agentStatusCommit = {
764
+ id: event.id,
765
+ branch,
766
+ message: event.message,
767
+ icon: "ph--flag--regular",
768
+ parents: this._getAgentStatusParents(event),
769
+ timestamp: new Date(event.created)
770
+ };
771
+ this._commits.push(agentStatusCommit);
772
+ this._lastBlockId = event.id;
773
+ if (event.toolCallId) {
774
+ this._lastCommitByBranch.set(branch, event.id);
775
+ this._updatePendingToolResults(event.toolCallId, event.id);
776
+ }
777
+ }
778
+ /**
779
+ * Stable sort: objects with 'created' field are sorted by it, others remain in place.
780
+ */
781
+ sortObjectsByCreated(objects) {
782
+ const sortedObjects = objects.slice();
783
+ const createdObjects = [];
784
+ sortedObjects.forEach((obj, idx) => {
785
+ if (obj && typeof obj.created === "string") {
786
+ createdObjects.push({
787
+ idx,
788
+ obj
789
+ });
790
+ }
182
791
  });
183
- log.info("result", {
184
- messages,
185
- duration: Date.now() - start
186
- }, {
187
- F: __dxlog_file,
188
- L: 121,
189
- S: this,
190
- C: (f, a) => f(...a)
792
+ createdObjects.sort((a, b) => {
793
+ const aDate = new Date(a.obj.created).getTime();
794
+ const bDate = new Date(b.obj.created).getTime();
795
+ return aDate - bDate;
191
796
  });
192
- yield* Effect.promise(() => this._queue.append(messages));
193
- return messages;
194
- }).pipe(Effect.withSpan("AiConversation.run"));
797
+ let createdIdx = 0;
798
+ return sortedObjects.map((obj, _idx) => {
799
+ if (obj && typeof obj.created === "string") {
800
+ return createdObjects[createdIdx++].obj;
801
+ }
802
+ return obj;
803
+ });
804
+ }
805
+ /**
806
+ * Returns the current state of the graph.
807
+ */
808
+ getGraph(lastRequest = false) {
809
+ const idx = lastRequest ? this._commits.findLastIndex((c) => c.tags?.includes("user")) : -1;
810
+ const commits = idx === -1 ? this._commits : this._commits.slice(idx);
811
+ return {
812
+ branches: Array.from(this._branchNames),
813
+ commits
814
+ };
815
+ }
816
+ /**
817
+ * Tracks tool calls and handles pending tool result updates.
818
+ */
819
+ _trackToolCalls(commits) {
820
+ commits.forEach((commit) => {
821
+ if (this._isToolCallCommit(commit)) {
822
+ const toolCallId = this._extractToolCallId(commit.id);
823
+ if (toolCallId) {
824
+ this._toolCallCommitIds.set(toolCallId, commit.id);
825
+ }
826
+ }
827
+ if (this._isToolResultCommit(commit)) {
828
+ const toolCallId = this._extractToolCallId(commit.id);
829
+ if (toolCallId) {
830
+ this._pendingToolResults.set(toolCallId, commit.id);
831
+ this._handleLateToolResultUpdate(toolCallId, commit.id);
832
+ }
833
+ }
834
+ this._lastCommitByBranch.set(commit.branch, commit.id);
835
+ });
836
+ }
837
+ /**
838
+ * Updates pending tool results to point to an AgentStatus event.
839
+ */
840
+ _updatePendingToolResults(toolCallId, agentStatusId) {
841
+ const toolResultId = this._pendingToolResults.get(toolCallId);
842
+ if (!toolResultId) return;
843
+ const toolResultCommit = this._commits.find((c) => c.id === toolResultId);
844
+ if (!toolResultCommit) return;
845
+ const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);
846
+ if (!toolCallCommitId) return;
847
+ const toolCallIndex = toolResultCommit.parents.indexOf(toolCallCommitId);
848
+ if (toolCallIndex !== -1) {
849
+ toolResultCommit.parents[toolCallIndex] = agentStatusId;
850
+ }
851
+ this._pendingToolResults.delete(toolCallId);
852
+ }
853
+ /**
854
+ * Handles late updates when AgentStatus is processed before tool result.
855
+ */
856
+ _handleLateToolResultUpdate(toolCallId, toolResultId) {
857
+ const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);
858
+ if (!toolCallCommitId) return;
859
+ const messageId = toolCallCommitId.split("_toolCall_")[0];
860
+ const toolCallBranch = `${messageId}_${toolCallId}`;
861
+ const agentStatusCommitId = this._lastCommitByBranch.get(toolCallBranch);
862
+ if (agentStatusCommitId && agentStatusCommitId !== toolCallCommitId) {
863
+ const toolResultCommit = this._commits.find((c) => c.id === toolResultId);
864
+ if (toolResultCommit) {
865
+ const toolCallIndex = toolResultCommit.parents.indexOf(toolCallCommitId);
866
+ if (toolCallIndex !== -1) {
867
+ toolResultCommit.parents[toolCallIndex] = agentStatusCommitId;
868
+ }
869
+ }
870
+ this._pendingToolResults.delete(toolCallId);
871
+ }
872
+ }
873
+ /**
874
+ * Gets the branch name for a tool call.
875
+ */
876
+ _getToolCallBranch(parentMessage, toolCallId) {
877
+ if (toolCallId) {
878
+ return toolCallId;
879
+ }
880
+ return parentMessage || "main";
881
+ }
882
+ /**
883
+ * Gets the parents for an AgentStatus commit.
884
+ */
885
+ _getAgentStatusParents(event) {
886
+ if (event.parentMessage && event.toolCallId) {
887
+ return [
888
+ getToolCallId(event.parentMessage, event.toolCallId)
889
+ ];
890
+ }
891
+ return [];
892
+ }
893
+ /**
894
+ * Checks if a commit is a tool call commit.
895
+ */
896
+ _isToolCallCommit(commit) {
897
+ return commit.message.includes("Calling tool");
898
+ }
899
+ /**
900
+ * Checks if a commit is a tool result commit.
901
+ */
902
+ _isToolResultCommit(commit) {
903
+ return commit.message.includes("Tool call succeeded") || commit.message.includes("Tool error:");
904
+ }
905
+ /**
906
+ * Extracts tool call ID from a commit ID.
907
+ */
908
+ _extractToolCallId(commitId) {
909
+ const toolCallMatch = commitId.match(/_toolCall_(.+)$/);
910
+ const toolResultMatch = commitId.match(/_toolResult_(.+)$/);
911
+ return toolCallMatch?.[1] || toolResultMatch?.[1];
912
+ }
195
913
  };
196
-
197
- // src/functions/services.ts
198
- import { AiTool } from "@effect/ai";
199
- import { Context, Effect as Effect2, Layer, Match, Predicate, Record, Schema as Schema2 } from "effect";
200
- import { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from "@dxos/ai";
201
- import { LocalFunctionExecutionService } from "@dxos/functions";
202
- import { invariant } from "@dxos/invariant";
203
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/assistant/src/functions/services.ts";
204
- var makeToolResolverFromFunctions = (functions, toolkit) => {
205
- return Layer.succeed(ToolResolverService, {
206
- resolve: Effect2.fn("resolveTool")(function* (id) {
207
- const tool = toolkit.tools[id];
208
- if (tool) {
209
- return tool;
914
+ var messageToCommits = (message, lastBlockId, toolCallIds, lastCommitByBranch, skipBlocks) => {
915
+ let previousBlockId = lastBlockId;
916
+ return message.blocks.map((block, idx) => {
917
+ const branch = getMessageBranch(message);
918
+ const parents = getBlockParents(block, previousBlockId, message, toolCallIds, lastCommitByBranch);
919
+ if (skipBlocks?.includes(block._tag)) {
920
+ return null;
921
+ }
922
+ const commit = createBlockCommit(block, message, branch, parents, idx);
923
+ if (commit) {
924
+ previousBlockId = commit.id;
925
+ }
926
+ return commit;
927
+ }).filter(isNonNullable2);
928
+ };
929
+ var getBlockParents = (block, previousBlockId, message, toolCallIds, lastCommitByBranch) => {
930
+ const parents = [];
931
+ if (block._tag === "toolResult") {
932
+ if (previousBlockId) {
933
+ parents.push(previousBlockId);
934
+ }
935
+ const toolCallCommitId = toolCallIds?.get(block.toolCallId);
936
+ if (toolCallCommitId) {
937
+ const toolCallBranch = getToolCallBranchFromCommitId(toolCallCommitId, block.toolCallId);
938
+ const lastBlockFromToolCallBranch = lastCommitByBranch?.get(toolCallBranch);
939
+ if (lastBlockFromToolCallBranch) {
940
+ parents.push(lastBlockFromToolCallBranch);
941
+ } else {
942
+ parents.push(toolCallCommitId);
210
943
  }
211
- const fn = functions.find((f) => f.name === id);
212
- if (!fn) {
213
- return yield* Effect2.fail(new AiToolNotFoundError(id));
944
+ }
945
+ } else {
946
+ if (previousBlockId) {
947
+ parents.push(previousBlockId);
948
+ } else {
949
+ const toolCallParent = getParentId(message);
950
+ if (toolCallParent) {
951
+ parents.push(toolCallParent);
214
952
  }
215
- return projectFunctionToTool(fn);
216
- })
953
+ }
954
+ }
955
+ return parents;
956
+ };
957
+ var createBlockCommit = (block, message, branch, parents, idx) => {
958
+ const timestamp = new Date(message.created);
959
+ switch (block._tag) {
960
+ case "text":
961
+ if (!block.text.trim().length) return null;
962
+ return {
963
+ id: getGenericBlockId(message.id, idx),
964
+ branch,
965
+ parents,
966
+ timestamp,
967
+ ...message.sender.role === "user" ? {
968
+ icon: "ph--user--regular",
969
+ tags: [
970
+ "user"
971
+ ],
972
+ message: "Processing request..."
973
+ } : {
974
+ icon: "ph--robot--regular",
975
+ message: `Response (${block.text.split(" ").length} words)`
976
+ }
977
+ };
978
+ case "toolCall":
979
+ return {
980
+ id: getToolCallId(message.id, block.toolCallId),
981
+ branch,
982
+ parents,
983
+ timestamp,
984
+ icon: "ph--wrench--regular",
985
+ level: LogLevel.INFO,
986
+ message: `Calling tool (${block.name})`
987
+ };
988
+ case "toolResult":
989
+ return {
990
+ id: getToolResultId(message.id, block.toolCallId),
991
+ branch,
992
+ parents,
993
+ timestamp,
994
+ icon: block.error ? "ph--x-circle--regular" : "ph--check-circle--regular",
995
+ level: block.error ? LogLevel.ERROR : LogLevel.INFO,
996
+ message: block.error ? "Tool error: " + block.error : "Tool call succeeded"
997
+ };
998
+ case "summary":
999
+ return {
1000
+ id: getGenericBlockId(message.id, idx),
1001
+ branch,
1002
+ parents,
1003
+ timestamp,
1004
+ icon: "ph--rocket--regular",
1005
+ level: LogLevel.INFO,
1006
+ message: ContentBlock.createSummaryMessage(block)
1007
+ };
1008
+ case "status":
1009
+ return {
1010
+ id: getGenericBlockId(message.id, idx),
1011
+ branch,
1012
+ parents,
1013
+ timestamp,
1014
+ message: block.statusText,
1015
+ level: LogLevel.INFO,
1016
+ icon: "ph--flag--regular"
1017
+ };
1018
+ case "reasoning":
1019
+ return {
1020
+ id: getGenericBlockId(message.id, idx),
1021
+ branch,
1022
+ parents,
1023
+ timestamp,
1024
+ message: block.reasoningText ?? "Thinking...",
1025
+ icon: "ph--brain--regular"
1026
+ };
1027
+ case "reference":
1028
+ return {
1029
+ id: getGenericBlockId(message.id, idx),
1030
+ branch,
1031
+ parents,
1032
+ timestamp,
1033
+ icon: "ph--link--regular",
1034
+ message: stringifyRef(block.reference)
1035
+ };
1036
+ default:
1037
+ return null;
1038
+ }
1039
+ };
1040
+ var getToolCallBranchFromCommitId = (toolCallCommitId, toolCallId) => {
1041
+ const messageId = toolCallCommitId.split("_toolCall_")[0];
1042
+ return `${messageId}_${toolCallId}`;
1043
+ };
1044
+ var getToolCallId = (messageId, toolCallId) => `${messageId}_toolCall_${toolCallId}`;
1045
+ var getToolResultId = (messageId, toolCallId) => `${messageId}_toolResult_${toolCallId}`;
1046
+ var getGenericBlockId = (messageId, idx) => `${messageId}_block_${idx}`;
1047
+ var getBranchName = (options) => {
1048
+ if (options.toolCallId) {
1049
+ return options.toolCallId;
1050
+ } else if (options.parentMessage) {
1051
+ return options.parentMessage;
1052
+ } else {
1053
+ return "main";
1054
+ }
1055
+ };
1056
+ var getMessageBranch = (message) => {
1057
+ return getBranchName({
1058
+ parentMessage: message.parentMessage,
1059
+ toolCallId: message.properties?.[MESSAGE_PROPERTY_TOOL_CALL_ID]
217
1060
  });
218
1061
  };
219
- var makeToolExecutionServiceFromFunctions = (functions, toolkit, handlersLayer) => {
220
- return Layer.effect(ToolExecutionService, Effect2.gen(function* () {
221
- const toolkitHandler = yield* toolkit.pipe(Effect2.provide(handlersLayer));
222
- const localFunctionExecutionService = yield* LocalFunctionExecutionService;
1062
+ var getParentId = (message) => {
1063
+ if (message.parentMessage && message.properties?.[MESSAGE_PROPERTY_TOOL_CALL_ID]) {
1064
+ return getToolCallId(message.parentMessage, message.properties[MESSAGE_PROPERTY_TOOL_CALL_ID]);
1065
+ } else {
1066
+ return void 0;
1067
+ }
1068
+ };
1069
+ var stringifyRef = (ref) => {
1070
+ if (ref.target) {
1071
+ return stringifyObject(ref.target);
1072
+ }
1073
+ return ref.dxn.asEchoDXN()?.echoId ?? ref.dxn.asQueueDXN()?.objectId ?? "";
1074
+ };
1075
+ var stringifyObject = (obj) => {
1076
+ return Obj5.getLabel(obj) ?? Obj5.getTypename(obj) ?? obj.id;
1077
+ };
1078
+
1079
+ // src/functions/services.ts
1080
+ import * as Tool from "@effect/ai/Tool";
1081
+ import * as Context3 from "effect/Context";
1082
+ import * as Effect7 from "effect/Effect";
1083
+ import * as Layer2 from "effect/Layer";
1084
+ import * as Record from "effect/Record";
1085
+ import * as Schema3 from "effect/Schema";
1086
+ import { AiToolNotFoundError, ToolExecutionService as ToolExecutionService2, ToolResolverService as ToolResolverService2 } from "@dxos/ai";
1087
+ import { todo as todo2 } from "@dxos/debug";
1088
+ import { Query as Query2 } from "@dxos/echo";
1089
+ import { DatabaseService as DatabaseService3 } from "@dxos/echo-db";
1090
+ import { Function as Function4, FunctionDefinition, FunctionInvocationService } from "@dxos/functions";
1091
+ import { invariant as invariant2 } from "@dxos/invariant";
1092
+ var __dxlog_file6 = "/__w/dxos/dxos/packages/core/assistant/src/functions/services.ts";
1093
+ var makeToolResolverFromFunctions = (functions, toolkit) => {
1094
+ return Layer2.effect(ToolResolverService2, Effect7.gen(function* () {
1095
+ const dbService = yield* DatabaseService3;
1096
+ return {
1097
+ resolve: (id) => Effect7.gen(function* () {
1098
+ const tool = toolkit.tools[id];
1099
+ if (tool) {
1100
+ return tool;
1101
+ }
1102
+ const { objects: [dbFunction] } = yield* DatabaseService3.runQuery(Query2.type(Function4.Function, {
1103
+ key: id
1104
+ }));
1105
+ const functionDef = dbFunction ? FunctionDefinition.deserialize(dbFunction) : functions.find((fn2) => fn2.key === id);
1106
+ if (!functionDef) {
1107
+ return yield* Effect7.fail(new AiToolNotFoundError(id));
1108
+ }
1109
+ return projectFunctionToTool(functionDef);
1110
+ }).pipe(Effect7.provideService(DatabaseService3, dbService))
1111
+ };
1112
+ }));
1113
+ };
1114
+ var makeToolExecutionServiceFromFunctions = (toolkit, handlersLayer) => {
1115
+ return Layer2.effect(ToolExecutionService2, Effect7.gen(function* () {
1116
+ const toolkitHandler = yield* toolkit.pipe(Effect7.provide(handlersLayer));
1117
+ invariant2(isHandlerLike(toolkitHandler), void 0, {
1118
+ F: __dxlog_file6,
1119
+ L: 74,
1120
+ S: this,
1121
+ A: [
1122
+ "isHandlerLike(toolkitHandler)",
1123
+ ""
1124
+ ]
1125
+ });
1126
+ const functionInvocationService = yield* FunctionInvocationService;
223
1127
  return {
224
1128
  handlersFor: (toolkit2) => {
225
1129
  const makeHandler = (tool) => {
226
- return Effect2.fn("toolFunctionHandler")(function* (input) {
227
- if (toolkitHandler.tools.find((t) => t.name === tool.name)) {
228
- return yield* toolkitHandler.handle(tool.name, input);
229
- }
230
- const { functionName } = Context.get(FunctionToolAnnotation)(tool.annotations);
231
- const fnDef = functions.find((f) => f.name === functionName);
232
- if (!fnDef) {
233
- return yield* Effect2.fail(new AiToolNotFoundError(tool.name));
1130
+ return Effect7.fn(`toolFunctionHandler ${tool.name}`)(function* (input) {
1131
+ if (toolkitHandler.tools[tool.name]) {
1132
+ if (Tool.isProviderDefined(tool)) {
1133
+ throw new Error("Attempted to call a provider-defined tool");
1134
+ }
1135
+ const { result } = yield* toolkitHandler.handle(tool.name, input);
1136
+ return result;
234
1137
  }
235
- return yield* localFunctionExecutionService.invokeFunction(fnDef, input).pipe(Effect2.catchAllDefect((defect) => Effect2.fail(defect)));
1138
+ const { definition: functionDef } = Context3.get(FunctionToolAnnotation)(tool.annotations);
1139
+ return yield* functionInvocationService.invokeFunction(functionDef, input).pipe(Effect7.catchAllDefect((defect) => Effect7.fail(defect)));
236
1140
  });
237
1141
  };
238
- return toolkit2.of(Record.map(toolkit2.tools, (tool, _name) => makeHandler(tool)));
1142
+ return toolkit2.of(Record.map(toolkit2.tools, (tool, _name) => Tool.isUserDefined(tool) ? makeHandler(tool) : null));
239
1143
  }
240
1144
  };
241
1145
  }));
242
1146
  };
243
- var FunctionToolAnnotation = class extends Context.Tag("@dxos/assisatnt/FunctionToolAnnotation")() {
1147
+ var FunctionToolAnnotation = class extends Context3.Tag("@dxos/assistant/FunctionToolAnnotation")() {
244
1148
  };
245
1149
  var toolCache = /* @__PURE__ */ new WeakMap();
246
- var projectFunctionToTool = (fn) => {
247
- if (toolCache.has(fn)) {
248
- return toolCache.get(fn);
1150
+ var projectFunctionToTool = (fn2) => {
1151
+ if (toolCache.has(fn2)) {
1152
+ return toolCache.get(fn2);
249
1153
  }
250
- const tool = AiTool.make(makeToolName(fn.name), {
251
- description: fn.description,
252
- parameters: createStructFieldsFromSchema(fn.inputSchema),
1154
+ const tool = Tool.make(makeToolName(fn2.name), {
1155
+ description: fn2.description,
1156
+ parameters: createStructFieldsFromSchema(fn2.inputSchema),
253
1157
  // TODO(dmaretskyi): Include output schema.
254
- failure: Schema2.Any
1158
+ failure: Schema3.Any
255
1159
  }).annotate(FunctionToolAnnotation, {
256
- functionName: fn.name
1160
+ definition: fn2
257
1161
  });
258
- toolCache.set(fn, tool);
1162
+ toolCache.set(fn2, tool);
259
1163
  return tool;
260
1164
  };
261
1165
  var makeToolName = (name) => {
262
- const toolName = name.replace(/[^a-zA-Z0-9]/g, "_");
263
- invariant(toolName.match(/^[a-zA-Z_][a-zA-Z0-9-_]*$/), void 0, {
264
- F: __dxlog_file2,
265
- L: 102,
1166
+ const toolName = name.toLowerCase().replace(/[^a-zA-Z0-9]/g, "-");
1167
+ invariant2(toolName.match(/^[a-z_][a-z0-9-_]*$/), void 0, {
1168
+ F: __dxlog_file6,
1169
+ L: 144,
266
1170
  S: void 0,
267
1171
  A: [
268
- "toolName.match(/^[a-zA-Z_][a-zA-Z0-9-_]*$/)",
1172
+ "toolName.match(/^[a-z_][a-z0-9-_]*$/)",
269
1173
  ""
270
1174
  ]
271
1175
  });
272
1176
  return toolName;
273
1177
  };
274
1178
  var createStructFieldsFromSchema = (schema) => {
275
- return Match.value(schema.ast).pipe(Match.when(Predicate.isTagged("TypeLiteral"), (ast) => {
276
- return Object.fromEntries(ast.propertySignatures.map((prop) => [
277
- prop.name,
278
- Schema2.make(prop.type)
279
- ]));
280
- }), Match.orElseAbsurd);
1179
+ switch (schema.ast._tag) {
1180
+ case "TypeLiteral":
1181
+ return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [
1182
+ prop.name,
1183
+ Schema3.make(prop.type)
1184
+ ]));
1185
+ case "VoidKeyword":
1186
+ return {};
1187
+ default:
1188
+ return todo2(`Unsupported schema AST: ${schema.ast._tag}`);
1189
+ }
1190
+ };
1191
+ var isHandlerLike = (value) => {
1192
+ return typeof value.tools === "object" && typeof value.handle === "function";
281
1193
  };
282
1194
 
283
1195
  // src/templates/system.ts
284
- import { Template } from "@dxos/blueprints";
1196
+ import defaultsDeep from "lodash.defaultsdeep";
1197
+ import { Template as Template2 } from "@dxos/blueprints";
285
1198
 
286
- // raw-loader:./format.tpl?raw
287
- 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.\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 <suggest> tag.\nExample: <suggest>Show on a map</suggest>\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";
1199
+ // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/instructions/format.tpl?raw
1200
+ 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";
288
1201
 
289
- // raw-loader:./system.tpl?raw
290
- var system_default = "{{! System Prompt }}\n\nYou are a helpful assistant called Kai. \nYour name is Kai and you are powered by different language models.\nYou were created by DXOS and operate in Composer and on the DXOS EDGE network.\nIn your initial greeting state your name and make some suggestions based on the current context objects.\n\nYou are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.\nYour task is to process user commands and questions and decide how best to respond.\nIn general be concise and direct.\n\nFollow these guidelines carefully:\n\nInclude the following steps:\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\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\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\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";
1202
+ // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/instructions/system.tpl?raw
1203
+ 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";
291
1204
 
292
1205
  // src/templates/system.ts
293
- var createSystemPrompt = (options) => Template.process(format_default, options);
1206
+ var createSystemPrompt = (options = {}) => Template2.process(format_default, defaultsDeep(options, {
1207
+ DATETIME: (/* @__PURE__ */ new Date()).toISOString()
1208
+ }));
294
1209
  var templates = {
295
- // Editable system prompt.
296
- system: Template.make({
1210
+ /** Editable system prompt.*/
1211
+ system: Template2.make({
1212
+ /**
1213
+ * NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.
1214
+ */
1215
+ id: "01K2J2FZWH39F55CS7B26GP1Q3",
297
1216
  source: system_default
298
1217
  })
299
1218
  };
300
1219
 
301
- // src/types.ts
302
- import { Schema as Schema3 } from "effect";
303
- import { DXN, LOCAL_SPACE_TAG } from "@dxos/keys";
304
- import { trim } from "@dxos/util";
1220
+ // src/types/artifact.ts
1221
+ import * as Schema4 from "effect/Schema";
1222
+ import { DatabaseService as DatabaseService4 } from "@dxos/echo-db";
1223
+ import { DXN as DXN2, LOCAL_SPACE_TAG } from "@dxos/keys";
1224
+ import { trim as trim2 } from "@dxos/util";
305
1225
  var createArtifactElement = (id) => `<artifact id=${id} />`;
306
- var ArtifactId = class extends Schema3.String.annotations({
307
- description: trim`
1226
+ var ArtifactId = class extends Schema4.String.annotations({
1227
+ // TODO(dmaretskyi): This section gets overriden.
1228
+ description: trim2`
308
1229
  The ID of the referenced object. Formats accepted:
309
1230
  - DXN (dxn:echo:@:XXXXX). DXNs can be prepended with an @ symbol for compatibility with in-text references.
310
1231
  - space ID, object ID tuple (spaceID:objectID)
@@ -319,37 +1240,52 @@ var ArtifactId = class extends Schema3.String.annotations({
319
1240
  }) {
320
1241
  static toDXN(reference, owningSpaceId) {
321
1242
  if (reference.startsWith("@dxn:")) {
322
- return DXN.parse(reference.slice(1));
1243
+ return DXN2.parse(reference.slice(1));
323
1244
  } else if (reference.startsWith("dxn:")) {
324
- return DXN.parse(reference);
1245
+ return DXN2.parse(reference);
325
1246
  } else if (/^[A-Z0-9]+:[A-Z0-9]+$/.test(reference)) {
326
1247
  const [spaceId, objectId] = reference.split(":");
327
- return new DXN(DXN.kind.ECHO, [
1248
+ return new DXN2(DXN2.kind.ECHO, [
328
1249
  spaceId === owningSpaceId ? LOCAL_SPACE_TAG : spaceId,
329
1250
  objectId
330
1251
  ]);
331
1252
  } else if (/^[A-Z0-9]+$/.test(reference)) {
332
- return DXN.fromLocalObjectId(reference);
1253
+ return DXN2.fromLocalObjectId(reference);
333
1254
  } else {
334
1255
  throw new Error(`Unable to parse object reference: ${reference}`);
335
1256
  }
336
1257
  }
1258
+ /**
1259
+ * Resolves an artifact ID to an object.
1260
+ */
1261
+ static resolve(schema, ref) {
1262
+ const dxn = ArtifactId.toDXN(ref);
1263
+ return DatabaseService4.resolve(dxn, schema);
1264
+ }
337
1265
  };
338
1266
  export {
339
1267
  AiAssistantError,
340
1268
  AiContextBinder,
1269
+ AiContextService,
341
1270
  AiConversation,
1271
+ AiModelError,
342
1272
  AiSession,
343
1273
  ArtifactDiffResolver,
344
1274
  ArtifactId,
345
1275
  Bindings,
346
1276
  ContextBinding,
1277
+ ExecutionGraph,
347
1278
  GenerationObserver,
1279
+ GenericToolkit_exports as GenericToolkit,
348
1280
  VersionPin,
1281
+ applyDiffs,
1282
+ computeDiffsWithCursors,
349
1283
  createArtifactElement,
350
1284
  createSystemPrompt,
1285
+ createToolkit,
351
1286
  makeToolExecutionServiceFromFunctions,
352
1287
  makeToolResolverFromFunctions,
1288
+ reduceDiffs,
353
1289
  templates
354
1290
  };
355
1291
  //# sourceMappingURL=index.mjs.map