@dxos/assistant 0.8.4-main.dedc0f3 → 0.8.4-main.e8ec1fe

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 (114) hide show
  1. package/dist/lib/browser/chunk-J5LGTIGS.mjs +10 -0
  2. package/dist/lib/browser/extraction/index.mjs +119 -162
  3. package/dist/lib/browser/extraction/index.mjs.map +4 -4
  4. package/dist/lib/browser/index.mjs +978 -157
  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 +119 -162
  9. package/dist/lib/node-esm/extraction/index.mjs.map +4 -4
  10. package/dist/lib/node-esm/index.mjs +978 -157
  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 +14 -7
  14. package/dist/types/src/conversation/context.d.ts.map +1 -1
  15. package/dist/types/src/conversation/conversation.d.ts +11 -12
  16. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  17. package/dist/types/src/diff.d.ts.map +1 -1
  18. package/dist/types/src/errors.d.ts +38 -42
  19. package/dist/types/src/errors.d.ts.map +1 -1
  20. package/dist/types/src/execution-graph.d.ts +85 -0
  21. package/dist/types/src/execution-graph.d.ts.map +1 -0
  22. package/dist/types/src/execution-graph.test.d.ts +2 -0
  23. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  24. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  25. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +60 -52
  26. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  27. package/dist/types/src/extraction/extraction.d.ts +24 -13
  28. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  29. package/dist/types/src/extraction/quotes.d.ts +1 -1
  30. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  31. package/dist/types/src/functions/services.d.ts +18 -5
  32. package/dist/types/src/functions/services.d.ts.map +1 -1
  33. package/dist/types/src/index.d.ts +2 -1
  34. package/dist/types/src/index.d.ts.map +1 -1
  35. package/dist/types/src/session/GenericToolkit.d.ts +84 -0
  36. package/dist/types/src/session/GenericToolkit.d.ts.map +1 -0
  37. package/dist/types/src/session/artifact-diff.d.ts +2 -2
  38. package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
  39. package/dist/types/src/session/error-handling.d.ts +2 -2
  40. package/dist/types/src/session/error-handling.d.ts.map +1 -1
  41. package/dist/types/src/session/format.d.ts +4 -174
  42. package/dist/types/src/session/format.d.ts.map +1 -1
  43. package/dist/types/src/session/index.d.ts +1 -0
  44. package/dist/types/src/session/index.d.ts.map +1 -1
  45. package/dist/types/src/session/observer.d.ts +3 -3
  46. package/dist/types/src/session/observer.d.ts.map +1 -1
  47. package/dist/types/src/session/session.d.ts +15 -11
  48. package/dist/types/src/session/session.d.ts.map +1 -1
  49. package/dist/types/src/session/toolkit.d.ts +7 -6
  50. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  51. package/dist/types/src/session/version-pin.d.ts +3 -3
  52. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  53. package/dist/types/src/types/artifact.d.ts +20 -0
  54. package/dist/types/src/types/artifact.d.ts.map +1 -0
  55. package/dist/types/src/types/index.d.ts +2 -0
  56. package/dist/types/src/types/index.d.ts.map +1 -0
  57. package/dist/types/tsconfig.tsbuildinfo +1 -1
  58. package/package.json +28 -31
  59. package/src/conversation/context.ts +49 -17
  60. package/src/conversation/conversation.ts +28 -23
  61. package/src/diff.test.ts +3 -3
  62. package/src/diff.ts +5 -0
  63. package/src/errors.ts +4 -4
  64. package/src/execution-graph.test.ts +740 -0
  65. package/src/execution-graph.ts +509 -0
  66. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +2 -2
  67. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +46 -54
  68. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +10 -9
  69. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +38 -44
  70. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  71. package/src/extraction/extraction.ts +7 -6
  72. package/src/extraction/quotes.test.ts +2 -2
  73. package/src/extraction/quotes.ts +3 -3
  74. package/src/functions/services.ts +93 -50
  75. package/src/index.ts +2 -1
  76. package/src/session/GenericToolkit.ts +130 -0
  77. package/src/session/artifact-diff.ts +2 -2
  78. package/src/session/error-handling.ts +11 -6
  79. package/src/session/format.test.ts +5 -4
  80. package/src/session/format.ts +18 -13
  81. package/src/session/index.ts +2 -0
  82. package/src/session/observer.ts +4 -3
  83. package/src/session/session.conversations.json +1 -0
  84. package/src/session/session.test.ts +51 -210
  85. package/src/session/session.ts +40 -28
  86. package/src/session/toolkit.ts +19 -13
  87. package/src/session/version-pin.ts +4 -5
  88. package/src/templates/{format.tpl → instructions/format.tpl} +1 -0
  89. package/src/templates/{system.tpl → instructions/system.tpl} +10 -12
  90. package/src/templates/system.ts +2 -2
  91. package/src/{types.ts → types/artifact.ts} +22 -3
  92. package/src/types/index.ts +5 -0
  93. package/dist/lib/browser/chunk-5GJYG2ML.mjs +0 -396
  94. package/dist/lib/browser/chunk-5GJYG2ML.mjs.map +0 -7
  95. package/dist/lib/browser/chunk-UB26N5UF.mjs +0 -89
  96. package/dist/lib/browser/chunk-UB26N5UF.mjs.map +0 -7
  97. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs +0 -13
  98. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs +0 -91
  99. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs.map +0 -7
  100. package/dist/lib/node-esm/chunk-FLFCEB4P.mjs +0 -398
  101. package/dist/lib/node-esm/chunk-FLFCEB4P.mjs.map +0 -7
  102. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs +0 -14
  103. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  104. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  105. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  106. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  107. package/dist/types/src/types.d.ts +0 -16
  108. package/dist/types/src/types.d.ts.map +0 -1
  109. package/src/session/__snapshots__/session.test.ts.snap +0 -32
  110. package/src/session/version-pin.test.ts +0 -7
  111. package/src/summarization/summarization.test.ts +0 -197
  112. /package/dist/lib/browser/{named-entity-recognition-QPYHML66.mjs.map → chunk-J5LGTIGS.mjs.map} +0 -0
  113. /package/dist/lib/node-esm/{named-entity-recognition-2HDF46YX.mjs.map → chunk-HSLMI22Q.mjs.map} +0 -0
  114. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -1,34 +1,20 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
2
  import {
3
- AiAssistantError,
4
- AiSession,
5
- AnthropicError,
6
- ArtifactDiffResolver,
7
- GenerationObserver,
8
- VersionPin,
9
- createToolkit
10
- } from "./chunk-FLFCEB4P.mjs";
3
+ __export
4
+ } from "./chunk-HSLMI22Q.mjs";
11
5
 
12
6
  // src/conversation/context.ts
13
7
  import { computed } from "@preact/signals-core";
14
- import { Context, Schema } from "effect";
15
- 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";
16
12
  import { Blueprint } from "@dxos/blueprints";
17
- import { DXN, 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";
18
16
  import { ComplexSet } from "@dxos/util";
19
- function _define_property(obj, key, value) {
20
- if (key in obj) {
21
- Object.defineProperty(obj, key, {
22
- value,
23
- enumerable: true,
24
- configurable: true,
25
- writable: true
26
- });
27
- } else {
28
- obj[key] = value;
29
- }
30
- return obj;
31
- }
17
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/conversation/context.ts";
32
18
  var ContextBinding = Schema.Struct({
33
19
  blueprints: Schema.Struct({
34
20
  added: Schema.Array(Type.Ref(Blueprint.Blueprint)),
@@ -44,32 +30,96 @@ var ContextBinding = Schema.Struct({
44
30
  version: "0.1.0"
45
31
  }));
46
32
  var Bindings = class {
33
+ blueprints = 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);
47
36
  toJSON() {
48
37
  return {
49
- blueprints: Array.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),
50
- 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())
51
40
  };
52
41
  }
53
- constructor() {
54
- _define_property(this, "blueprints", new ComplexSet((ref) => ref.dxn.toString()));
55
- _define_property(this, "objects", new ComplexSet((ref) => ref.dxn.asEchoDXN()?.echoId));
56
- }
57
42
  };
58
- var AiContextBinder = class {
43
+ var AiContextBinder = class extends Resource {
44
+ _queue;
45
+ /**
46
+ * Reactive query of all bindings.
47
+ */
48
+ // TODO(burdon): Cache value?
49
+ _bindings;
50
+ _blueprints;
51
+ _objects;
52
+ constructor(_queue) {
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(() => [
98
+ ...this.bindings.value.blueprints
99
+ ]);
100
+ this._objects = computed(() => [
101
+ ...this.bindings.value.objects
102
+ ]);
103
+ }
104
+ async _close() {
105
+ this._bindings = void 0;
106
+ this._blueprints = void 0;
107
+ this._objects = void 0;
108
+ }
59
109
  /**
60
110
  * Asynchronous query of all bindings.
61
111
  */
62
112
  async query() {
63
- const queueItems = await this._queue.queryObjects();
64
- return this._reduce(queueItems);
113
+ const { objects } = await this._queue.query(Query.select(Filter.everything())).run();
114
+ return this._reduce(objects);
65
115
  }
66
116
  // TODO(burdon): Pass in Blueprint obj (from registry?) and create reference.
67
117
  async bind(props) {
68
- if (!props.blueprints?.length && !props.objects?.length) {
69
- return;
70
- }
71
118
  const blueprints = props.blueprints?.filter((ref) => !this.blueprints.peek().find((b) => b.dxn.toString() === ref.dxn.toString())) ?? [];
72
119
  const objects = props.objects?.filter((ref) => !this.objects.peek().find((o) => o.dxn.toString() === ref.dxn.toString())) ?? [];
120
+ if (!blueprints.length && !objects.length) {
121
+ return;
122
+ }
73
123
  await this._queue.append([
74
124
  Obj.make(ContextBinding, {
75
125
  blueprints: {
@@ -101,7 +151,7 @@ var AiContextBinder = class {
101
151
  ]);
102
152
  }
103
153
  _reduce(items) {
104
- return pipe(items, Array.filter(Obj.instanceOf(ContextBinding)), Array.reduce(new Bindings(), (context, item) => {
154
+ return Function.pipe(items, Array2.filter(Obj.instanceOf(ContextBinding)), Array2.reduce(new Bindings(), (context, item) => {
105
155
  item.blueprints.removed.forEach((ref) => context.blueprints.delete(ref));
106
156
  item.blueprints.added.forEach((ref) => context.blueprints.add(ref));
107
157
  item.objects.removed.forEach((ref) => {
@@ -115,45 +165,418 @@ var AiContextBinder = class {
115
165
  return context;
116
166
  }));
117
167
  }
118
- constructor(_queue) {
119
- _define_property(this, "_queue", void 0);
120
- _define_property(this, "bindings", void 0);
121
- _define_property(this, "blueprints", void 0);
122
- _define_property(this, "objects", void 0);
123
- this._queue = _queue;
124
- this.bindings = computed(() => this._reduce(this._queue.objects));
125
- this.blueprints = computed(() => [
126
- ...this.bindings.value.blueprints
127
- ]);
128
- this.objects = computed(() => [
129
- ...this.bindings.value.objects
130
- ]);
131
- }
132
168
  };
133
169
  var AiContextService = class extends Context.Tag("@dxos/assistant/AiContextService")() {
134
170
  };
135
171
 
136
172
  // src/conversation/conversation.ts
137
- import { Array as Array2, Effect, Option } from "effect";
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";
138
236
  import { Obj as Obj2 } from "@dxos/echo";
139
- import { DatabaseService } from "@dxos/functions";
237
+ import { DatabaseService, ObjectVersion } from "@dxos/echo-db";
140
238
  import { log } from "@dxos/log";
141
- import { DataType } from "@dxos/schema";
142
- function _define_property2(obj, key, value) {
143
- if (key in obj) {
144
- Object.defineProperty(obj, key, {
145
- value,
146
- enumerable: true,
147
- configurable: true,
148
- writable: true
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
+ })
149
290
  });
150
- } else {
151
- obj[key] = value;
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
+ */
560
+ _queue;
561
+ /**
562
+ * Blueprints bound to the conversation.
563
+ */
564
+ _context;
565
+ /**
566
+ * Toolkit from the current session request.
567
+ */
568
+ _toolkit;
569
+ constructor(queue) {
570
+ super();
571
+ this._queue = queue;
572
+ this._context = new AiContextBinder(this._queue);
573
+ }
574
+ async _open() {
575
+ await this._context.open();
576
+ }
577
+ async _close() {
578
+ await this._context.close();
152
579
  }
153
- return obj;
154
- }
155
- var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/conversation/conversation.ts";
156
- var AiConversation = class {
157
580
  get context() {
158
581
  return this._context;
159
582
  }
@@ -162,31 +585,31 @@ var AiConversation = class {
162
585
  }
163
586
  async getHistory() {
164
587
  const queueItems = await this._queue.queryObjects();
165
- return queueItems.filter(Obj2.instanceOf(DataType.Message));
588
+ return queueItems.filter(Obj4.instanceOf(Message3.Message));
166
589
  }
167
590
  /**
168
591
  * Creates a new cancelable request effect.
169
592
  */
170
593
  createRequest(params) {
171
- return Effect.gen(this, function* () {
594
+ return Effect6.gen(this, function* () {
172
595
  const session = new AiSession();
173
- const history = yield* Effect.promise(() => this.getHistory());
174
- const context = yield* Effect.promise(() => this.context.query());
175
- const blueprints = yield* Effect.forEach(context.blueprints.values(), DatabaseService.loadOption).pipe(Effect.map(Array2.filter(Option.isSome)), Effect.map(Array2.map((option) => option.value)));
176
- const objects = yield* Effect.forEach(context.objects.values(), DatabaseService.loadOption).pipe(Effect.map(Array2.filter(Option.isSome)), Effect.map(Array2.map((option) => option.value)));
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)));
177
600
  const toolkit = yield* createToolkit({
178
601
  blueprints
179
602
  });
180
603
  this._toolkit = toolkit;
181
604
  const start = Date.now();
182
- log("run", {
605
+ log3("run", {
183
606
  history: history.length,
184
607
  blueprints: blueprints.length,
185
608
  objects: objects.length,
186
609
  tools: this._toolkit?.tools.length ?? 0
187
610
  }, {
188
- F: __dxlog_file,
189
- L: 102,
611
+ F: __dxlog_file4,
612
+ L: 107,
190
613
  S: this,
191
614
  C: (f, a) => f(...a)
192
615
  });
@@ -196,37 +619,30 @@ var AiConversation = class {
196
619
  objects,
197
620
  toolkit,
198
621
  ...params
199
- }).pipe(Effect.provideService(AiContextService, {
622
+ }).pipe(Effect6.provideService(AiContextService, {
200
623
  binder: this.context
201
624
  }));
202
- log("result", {
625
+ log3("result", {
203
626
  messages: messages.length,
204
627
  duration: Date.now() - start
205
628
  }, {
206
- F: __dxlog_file,
207
- L: 116,
629
+ F: __dxlog_file4,
630
+ L: 121,
208
631
  S: this,
209
632
  C: (f, a) => f(...a)
210
633
  });
211
- yield* Effect.promise(() => this._queue.append(messages));
634
+ yield* Effect6.promise(() => this._queue.append(messages));
212
635
  return messages;
213
- }).pipe(Effect.withSpan("AiConversation.request"));
214
- }
215
- constructor(options) {
216
- _define_property2(this, "_queue", void 0);
217
- _define_property2(this, "_context", void 0);
218
- _define_property2(this, "_toolkit", void 0);
219
- this._queue = options.queue;
220
- this._context = new AiContextBinder(this._queue);
636
+ }).pipe(Effect6.withSpan("AiConversation.request"));
221
637
  }
222
638
  };
223
639
 
224
640
  // src/diff.ts
225
641
  import { next as A } from "@automerge/automerge";
226
642
  import { DocAccessor, toCursorRange } from "@dxos/echo-db";
227
- import { log as log2 } from "@dxos/log";
643
+ import { log as log4 } from "@dxos/log";
228
644
  import { isNonNullable } from "@dxos/util";
229
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/assistant/src/diff.ts";
645
+ var __dxlog_file5 = "/__w/dxos/dxos/packages/core/assistant/src/diff.ts";
230
646
  var reduceDiffs = (diffs) => {
231
647
  return diffs.reduce((acc, diff) => {
232
648
  const current = acc[acc.length - 1];
@@ -278,9 +694,9 @@ var applyDiffs = (accessor, diffs) => {
278
694
  if (idx !== -1) {
279
695
  A.splice(doc, accessor.path, idx, diff.match.length, diff.replace);
280
696
  } else {
281
- log2.warn("diff not found", diff, {
282
- F: __dxlog_file2,
283
- L: 73,
697
+ log4.warn("diff not found", diff, {
698
+ F: __dxlog_file5,
699
+ L: 78,
284
700
  S: void 0,
285
701
  C: (f, a) => f(...a)
286
702
  });
@@ -290,79 +706,470 @@ var applyDiffs = (accessor, diffs) => {
290
706
  return DocAccessor.getValue(accessor);
291
707
  };
292
708
 
293
- // src/functions/services.ts
294
- import { AiTool } from "@effect/ai";
295
- import { Context as Context2, Effect as Effect2, Layer, Record, Schema as Schema2 } from "effect";
296
- import { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from "@dxos/ai";
297
- import { todo } from "@dxos/debug";
298
- import { LocalFunctionExecutionService } from "@dxos/functions";
299
- import { invariant } from "@dxos/invariant";
300
- var __dxlog_file3 = "/__w/dxos/dxos/packages/core/assistant/src/functions/services.ts";
301
- var makeToolResolverFromFunctions = (functions, toolkit) => {
302
- return Layer.succeed(ToolResolverService, {
303
- resolve: Effect2.fn("resolveTool")(function* (id) {
304
- const tool = toolkit.tools[id];
305
- if (tool) {
306
- return tool;
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
+ });
307
790
  }
308
- const functionDef = functions.find((fn) => fn.name === id);
309
- if (!functionDef) {
310
- return yield* Effect2.fail(new AiToolNotFoundError(id));
791
+ });
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;
796
+ });
797
+ let createdIdx = 0;
798
+ return sortedObjects.map((obj, _idx) => {
799
+ if (obj && typeof obj.created === "string") {
800
+ return createdObjects[createdIdx++].obj;
311
801
  }
312
- return projectFunctionToTool(functionDef);
313
- })
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
+ }
913
+ };
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);
943
+ }
944
+ }
945
+ } else {
946
+ if (previousBlockId) {
947
+ parents.push(previousBlockId);
948
+ } else {
949
+ const toolCallParent = getParentId(message);
950
+ if (toolCallParent) {
951
+ parents.push(toolCallParent);
952
+ }
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]
314
1060
  });
315
1061
  };
316
- var makeToolExecutionServiceFromFunctions = (functions, toolkit, handlersLayer) => {
317
- return Layer.effect(ToolExecutionService, Effect2.gen(function* () {
318
- const toolkitHandler = yield* toolkit.pipe(Effect2.provide(handlersLayer));
319
- 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;
320
1127
  return {
321
1128
  handlersFor: (toolkit2) => {
322
1129
  const makeHandler = (tool) => {
323
- return Effect2.fn("toolFunctionHandler")(function* (input) {
324
- if (toolkitHandler.tools.find((t) => t.name === tool.name)) {
325
- return yield* toolkitHandler.handle(tool.name, input);
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;
326
1137
  }
327
- const { functionName } = Context2.get(FunctionToolAnnotation)(tool.annotations);
328
- const functionDef = functions.find((fn) => fn.name === functionName);
329
- if (!functionDef) {
330
- return yield* Effect2.fail(new AiToolNotFoundError(tool.name));
331
- }
332
- return yield* localFunctionExecutionService.invokeFunction(functionDef, 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)));
333
1140
  });
334
1141
  };
335
- 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));
336
1143
  }
337
1144
  };
338
1145
  }));
339
1146
  };
340
- var FunctionToolAnnotation = class extends Context2.Tag("@dxos/assisatnt/FunctionToolAnnotation")() {
1147
+ var FunctionToolAnnotation = class extends Context3.Tag("@dxos/assistant/FunctionToolAnnotation")() {
341
1148
  };
342
1149
  var toolCache = /* @__PURE__ */ new WeakMap();
343
- var projectFunctionToTool = (fn) => {
344
- if (toolCache.has(fn)) {
345
- return toolCache.get(fn);
1150
+ var projectFunctionToTool = (fn2) => {
1151
+ if (toolCache.has(fn2)) {
1152
+ return toolCache.get(fn2);
346
1153
  }
347
- const tool = AiTool.make(makeToolName(fn.name), {
348
- description: fn.description,
349
- parameters: createStructFieldsFromSchema(fn.inputSchema),
1154
+ const tool = Tool.make(makeToolName(fn2.name), {
1155
+ description: fn2.description,
1156
+ parameters: createStructFieldsFromSchema(fn2.inputSchema),
350
1157
  // TODO(dmaretskyi): Include output schema.
351
- failure: Schema2.Any
1158
+ failure: Schema3.Any
352
1159
  }).annotate(FunctionToolAnnotation, {
353
- functionName: fn.name
1160
+ definition: fn2
354
1161
  });
355
- toolCache.set(fn, tool);
1162
+ toolCache.set(fn2, tool);
356
1163
  return tool;
357
1164
  };
358
1165
  var makeToolName = (name) => {
359
- const toolName = name.replace(/[^a-zA-Z0-9]/g, "_");
360
- invariant(toolName.match(/^[a-zA-Z_][a-zA-Z0-9-_]*$/), void 0, {
361
- F: __dxlog_file3,
362
- L: 105,
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,
363
1170
  S: void 0,
364
1171
  A: [
365
- "toolName.match(/^[a-zA-Z_][a-zA-Z0-9-_]*$/)",
1172
+ "toolName.match(/^[a-z_][a-z0-9-_]*$/)",
366
1173
  ""
367
1174
  ]
368
1175
  });
@@ -373,32 +1180,35 @@ var createStructFieldsFromSchema = (schema) => {
373
1180
  case "TypeLiteral":
374
1181
  return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [
375
1182
  prop.name,
376
- Schema2.make(prop.type)
1183
+ Schema3.make(prop.type)
377
1184
  ]));
378
1185
  case "VoidKeyword":
379
1186
  return {};
380
1187
  default:
381
- return todo(`Unsupported schema AST: ${schema.ast._tag}`);
1188
+ return todo2(`Unsupported schema AST: ${schema.ast._tag}`);
382
1189
  }
383
1190
  };
1191
+ var isHandlerLike = (value) => {
1192
+ return typeof value.tools === "object" && typeof value.handle === "function";
1193
+ };
384
1194
 
385
1195
  // src/templates/system.ts
386
1196
  import defaultsDeep from "lodash.defaultsdeep";
387
- import { Template } from "@dxos/blueprints";
1197
+ import { Template as Template2 } from "@dxos/blueprints";
388
1198
 
389
- // raw-loader:./format.tpl?raw
390
- 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>\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";
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";
391
1201
 
392
- // raw-loader:./system.tpl?raw
393
- 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 instructions carefully.\n\n## Include 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- 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";
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";
394
1204
 
395
1205
  // src/templates/system.ts
396
- var createSystemPrompt = (options = {}) => Template.process(format_default, defaultsDeep(options, {
1206
+ var createSystemPrompt = (options = {}) => Template2.process(format_default, defaultsDeep(options, {
397
1207
  DATETIME: (/* @__PURE__ */ new Date()).toISOString()
398
1208
  }));
399
1209
  var templates = {
400
1210
  /** Editable system prompt.*/
401
- system: Template.make({
1211
+ system: Template2.make({
402
1212
  /**
403
1213
  * NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.
404
1214
  */
@@ -407,13 +1217,15 @@ var templates = {
407
1217
  })
408
1218
  };
409
1219
 
410
- // src/types.ts
411
- import { Schema as Schema3 } from "effect";
1220
+ // src/types/artifact.ts
1221
+ import * as Schema4 from "effect/Schema";
1222
+ import { DatabaseService as DatabaseService4 } from "@dxos/echo-db";
412
1223
  import { DXN as DXN2, LOCAL_SPACE_TAG } from "@dxos/keys";
413
- import { trim } from "@dxos/util";
1224
+ import { trim as trim2 } from "@dxos/util";
414
1225
  var createArtifactElement = (id) => `<artifact id=${id} />`;
415
- var ArtifactId = class extends Schema3.String.annotations({
416
- description: trim`
1226
+ var ArtifactId = class extends Schema4.String.annotations({
1227
+ // TODO(dmaretskyi): This section gets overriden.
1228
+ description: trim2`
417
1229
  The ID of the referenced object. Formats accepted:
418
1230
  - DXN (dxn:echo:@:XXXXX). DXNs can be prepended with an @ symbol for compatibility with in-text references.
419
1231
  - space ID, object ID tuple (spaceID:objectID)
@@ -443,19 +1255,28 @@ var ArtifactId = class extends Schema3.String.annotations({
443
1255
  throw new Error(`Unable to parse object reference: ${reference}`);
444
1256
  }
445
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
+ }
446
1265
  };
447
1266
  export {
448
1267
  AiAssistantError,
449
1268
  AiContextBinder,
450
1269
  AiContextService,
451
1270
  AiConversation,
1271
+ AiModelError,
452
1272
  AiSession,
453
- AnthropicError,
454
1273
  ArtifactDiffResolver,
455
1274
  ArtifactId,
456
1275
  Bindings,
457
1276
  ContextBinding,
1277
+ ExecutionGraph,
458
1278
  GenerationObserver,
1279
+ GenericToolkit_exports as GenericToolkit,
459
1280
  VersionPin,
460
1281
  applyDiffs,
461
1282
  computeDiffsWithCursors,