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