@dxos/assistant 0.8.4-main.f9ba587 → 0.8.4-main.fcc0d83b33

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 (197) hide show
  1. package/README.md +1 -0
  2. package/dist/lib/neutral/extraction/index.mjs +202 -0
  3. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  4. package/dist/lib/neutral/index.mjs +1693 -0
  5. package/dist/lib/neutral/index.mjs.map +7 -0
  6. package/dist/lib/neutral/meta.json +1 -0
  7. package/dist/types/src/conversation/context.d.ts +152 -0
  8. package/dist/types/src/conversation/context.d.ts.map +1 -0
  9. package/dist/types/src/conversation/context.test.d.ts +2 -0
  10. package/dist/types/src/conversation/context.test.d.ts.map +1 -0
  11. package/dist/types/src/conversation/index.d.ts +2 -1
  12. package/dist/types/src/conversation/index.d.ts.map +1 -1
  13. package/dist/types/src/conversation/session.d.ts +78 -0
  14. package/dist/types/src/conversation/session.d.ts.map +1 -0
  15. package/dist/types/src/diff.d.ts +17 -0
  16. package/dist/types/src/diff.d.ts.map +1 -0
  17. package/dist/types/src/diff.test.d.ts +2 -0
  18. package/dist/types/src/diff.test.d.ts.map +1 -0
  19. package/dist/types/src/errors.d.ts +67 -0
  20. package/dist/types/src/errors.d.ts.map +1 -0
  21. package/dist/types/src/execution-graph.d.ts +85 -0
  22. package/dist/types/src/execution-graph.d.ts.map +1 -0
  23. package/dist/types/src/execution-graph.test.d.ts +2 -0
  24. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  25. package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
  26. package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
  27. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts +1 -1
  28. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  29. package/dist/types/src/extraction/extraction.d.ts +1066 -215
  30. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  31. package/dist/types/src/extraction/index.d.ts +0 -1
  32. package/dist/types/src/extraction/index.d.ts.map +1 -1
  33. package/dist/types/src/extraction/quotes.d.ts +3 -3
  34. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  35. package/dist/types/src/functions/index.d.ts +2 -0
  36. package/dist/types/src/functions/index.d.ts.map +1 -0
  37. package/dist/types/src/functions/services.d.ts +17 -0
  38. package/dist/types/src/functions/services.d.ts.map +1 -0
  39. package/dist/types/src/index.d.ts +6 -5
  40. package/dist/types/src/index.d.ts.map +1 -1
  41. package/dist/types/src/session/artifact-diff.d.ts +27 -0
  42. package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
  43. package/dist/types/src/session/error-handling.d.ts +4 -0
  44. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  45. package/dist/types/src/session/format.d.ts +16 -0
  46. package/dist/types/src/session/format.d.ts.map +1 -0
  47. package/dist/types/src/session/index.d.ts +5 -1
  48. package/dist/types/src/session/index.d.ts.map +1 -1
  49. package/dist/types/src/session/observer.d.ts +23 -0
  50. package/dist/types/src/session/observer.d.ts.map +1 -0
  51. package/dist/types/src/session/request.d.ts +106 -0
  52. package/dist/types/src/session/request.d.ts.map +1 -0
  53. package/dist/types/src/session/toolkit.d.ts +16 -0
  54. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  55. package/dist/types/src/session/version-pin.d.ts +5 -5
  56. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  57. package/dist/types/src/templates/index.d.ts +2 -0
  58. package/dist/types/src/templates/index.d.ts.map +1 -0
  59. package/dist/types/src/templates/system.d.ts +17 -0
  60. package/dist/types/src/templates/system.d.ts.map +1 -0
  61. package/dist/types/src/tracing.d.ts +223 -0
  62. package/dist/types/src/tracing.d.ts.map +1 -0
  63. package/dist/types/src/types/artifact.d.ts +28 -0
  64. package/dist/types/src/types/artifact.d.ts.map +1 -0
  65. package/dist/types/src/types/index.d.ts +2 -0
  66. package/dist/types/src/types/index.d.ts.map +1 -0
  67. package/dist/types/tsconfig.tsbuildinfo +1 -1
  68. package/package.json +42 -29
  69. package/src/conversation/context.test.ts +52 -0
  70. package/src/conversation/context.ts +403 -0
  71. package/src/conversation/index.ts +2 -1
  72. package/src/conversation/session.ts +300 -0
  73. package/src/diff.test.ts +74 -0
  74. package/src/diff.ts +93 -0
  75. package/src/errors.ts +15 -0
  76. package/src/execution-graph.test.ts +740 -0
  77. package/src/execution-graph.ts +519 -0
  78. package/src/extraction/extraction-ner-function/index.ts +0 -1
  79. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  80. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +3 -1
  81. package/src/extraction/extraction.ts +44 -15
  82. package/src/extraction/index.ts +0 -1
  83. package/src/extraction/quotes.test.ts +3 -3
  84. package/src/extraction/quotes.ts +6 -7
  85. package/src/functions/index.ts +5 -0
  86. package/src/functions/services.ts +214 -0
  87. package/src/functions.conversations.json +1 -0
  88. package/src/index.ts +6 -5
  89. package/src/session/artifact-diff.ts +41 -0
  90. package/src/session/error-handling.ts +41 -0
  91. package/src/session/format.ts +149 -0
  92. package/src/session/index.ts +5 -1
  93. package/src/session/observer.ts +62 -0
  94. package/src/session/request.conversations.json +1 -0
  95. package/src/session/request.ts +344 -0
  96. package/src/session/toolkit.ts +47 -0
  97. package/src/session/version-pin.ts +12 -12
  98. package/src/templates/index.ts +5 -0
  99. package/src/templates/instructions/format.tpl +57 -0
  100. package/src/templates/instructions/system.tpl +85 -0
  101. package/src/templates/system.ts +42 -0
  102. package/src/tracing.ts +43 -0
  103. package/src/types/artifact.ts +89 -0
  104. package/src/types/index.ts +5 -0
  105. package/src/typings.d.ts +5 -0
  106. package/dist/lib/browser/index.mjs +0 -2019
  107. package/dist/lib/browser/index.mjs.map +0 -7
  108. package/dist/lib/browser/meta.json +0 -1
  109. package/dist/lib/node-esm/index.mjs +0 -2021
  110. package/dist/lib/node-esm/index.mjs.map +0 -7
  111. package/dist/lib/node-esm/meta.json +0 -1
  112. package/dist/types/bin/chat.d.ts +0 -2
  113. package/dist/types/bin/chat.d.ts.map +0 -1
  114. package/dist/types/src/blueprint/blueprint.d.ts +0 -41
  115. package/dist/types/src/blueprint/blueprint.d.ts.map +0 -1
  116. package/dist/types/src/blueprint/index.d.ts +0 -3
  117. package/dist/types/src/blueprint/index.d.ts.map +0 -1
  118. package/dist/types/src/blueprint/registry.d.ts +0 -7
  119. package/dist/types/src/blueprint/registry.d.ts.map +0 -1
  120. package/dist/types/src/context/binder.d.ts +0 -34
  121. package/dist/types/src/context/binder.d.ts.map +0 -1
  122. package/dist/types/src/context/binding.d.ts +0 -38
  123. package/dist/types/src/context/binding.d.ts.map +0 -1
  124. package/dist/types/src/context/index.d.ts +0 -3
  125. package/dist/types/src/context/index.d.ts.map +0 -1
  126. package/dist/types/src/conversation/conversation.d.ts +0 -44
  127. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  128. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
  129. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
  130. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
  131. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
  132. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
  133. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
  134. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -208
  135. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
  136. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
  137. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
  138. package/dist/types/src/research/exa.d.ts +0 -7
  139. package/dist/types/src/research/exa.d.ts.map +0 -1
  140. package/dist/types/src/research/graph.d.ts +0 -41
  141. package/dist/types/src/research/graph.d.ts.map +0 -1
  142. package/dist/types/src/research/graph.test.d.ts +0 -2
  143. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  144. package/dist/types/src/research/index.d.ts +0 -4
  145. package/dist/types/src/research/index.d.ts.map +0 -1
  146. package/dist/types/src/research/research.d.ts +0 -10
  147. package/dist/types/src/research/research.d.ts.map +0 -1
  148. package/dist/types/src/research/research.test.d.ts +0 -2
  149. package/dist/types/src/research/research.test.d.ts.map +0 -1
  150. package/dist/types/src/session/session.d.ts +0 -283
  151. package/dist/types/src/session/session.d.ts.map +0 -1
  152. package/dist/types/src/session/session.test.d.ts +0 -2
  153. package/dist/types/src/session/session.test.d.ts.map +0 -1
  154. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  155. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  156. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  157. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  158. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  159. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  160. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  161. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  162. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  163. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  164. package/dist/types/src/testing/index.d.ts +0 -3
  165. package/dist/types/src/testing/index.d.ts.map +0 -1
  166. package/dist/types/src/types.d.ts +0 -3
  167. package/dist/types/src/types.d.ts.map +0 -1
  168. package/src/blueprint/blueprint.ts +0 -75
  169. package/src/blueprint/index.ts +0 -6
  170. package/src/blueprint/registry.ts +0 -15
  171. package/src/context/binder.ts +0 -101
  172. package/src/context/binding.ts +0 -31
  173. package/src/context/index.ts +0 -6
  174. package/src/conversation/conversation.ts +0 -103
  175. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -95
  176. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -66
  177. package/src/extraction/extraction-llm-function/index.ts +0 -5
  178. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -115
  179. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -54
  180. package/src/research/exa.ts +0 -100
  181. package/src/research/graph.test.ts +0 -15
  182. package/src/research/graph.ts +0 -337
  183. package/src/research/index.ts +0 -7
  184. package/src/research/instructions-research.tpl +0 -97
  185. package/src/research/research.test.ts +0 -190
  186. package/src/research/research.ts +0 -90
  187. package/src/session/session.test.ts +0 -275
  188. package/src/session/session.ts +0 -582
  189. package/src/session/version-pin.test.ts +0 -26
  190. package/src/summarization/summarization.test.ts +0 -221
  191. package/src/testing/exa-search-1748337321991.ts +0 -131
  192. package/src/testing/exa-search-1748337331526.ts +0 -144
  193. package/src/testing/exa-search-1748337344119.ts +0 -133
  194. package/src/testing/index.ts +0 -11
  195. package/src/typedefs.d.ts +0 -8
  196. package/src/types.ts +0 -8
  197. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -0,0 +1,1693 @@
1
+ // src/conversation/context.ts
2
+ import { Atom, Registry } from "@effect-atom/atom-react";
3
+ import * as EArray from "effect/Array";
4
+ import * as Context from "effect/Context";
5
+ import * as Effect from "effect/Effect";
6
+ import * as Function from "effect/Function";
7
+ import * as Runtime from "effect/Runtime";
8
+ import * as Schema from "effect/Schema";
9
+ import { Blueprint } from "@dxos/compute";
10
+ import { Resource } from "@dxos/context";
11
+ import { DXN, Feed, Obj, Query, Ref, Type } from "@dxos/echo";
12
+ import { assertArgument } from "@dxos/invariant";
13
+ import { log } from "@dxos/log";
14
+ import { ComplexSet, isNonNullable } from "@dxos/util";
15
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/conversation/context.ts";
16
+ var ContextBinding = Schema.Struct({
17
+ blueprints: Schema.Struct({
18
+ added: Schema.Array(Ref.Ref(Blueprint.Blueprint)),
19
+ removed: Schema.Array(Ref.Ref(Blueprint.Blueprint))
20
+ }),
21
+ objects: Schema.Struct({
22
+ added: Schema.Array(Ref.Ref(Obj.Unknown)),
23
+ removed: Schema.Array(Ref.Ref(Obj.Unknown))
24
+ })
25
+ }).pipe(Type.object({
26
+ typename: "org.dxos.type.contextBinding",
27
+ version: "0.1.0"
28
+ }));
29
+ var Bindings = class {
30
+ blueprints = new ComplexSet((ref) => ref.dxn.toString());
31
+ // TODO(burdon): Some DXNs have the Space prefix so only compare the object ID.
32
+ objects = new ComplexSet((ref) => ref.dxn.asEchoDXN()?.echoId);
33
+ toJSON() {
34
+ return {
35
+ blueprints: EArray.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),
36
+ objects: EArray.fromIterable(this.objects).map((ref) => ref.dxn.toString())
37
+ };
38
+ }
39
+ };
40
+ var AiContextBinder = class extends Resource {
41
+ _blueprints = Atom.make([]).pipe(Atom.keepAlive);
42
+ _objects = Atom.make([]).pipe(Atom.keepAlive);
43
+ _registry;
44
+ _feed;
45
+ _runtime;
46
+ #bindingsQuery;
47
+ constructor(options) {
48
+ super();
49
+ assertArgument(options.feed, "options.feed", "Feed is required");
50
+ assertArgument(options.runtime, "options.runtime", "Feed runtime is required");
51
+ this._feed = options.feed;
52
+ this._runtime = options.runtime;
53
+ this._registry = options.registry ?? Registry.make();
54
+ }
55
+ /**
56
+ * Returns the blueprints atom for subscription.
57
+ */
58
+ get blueprints() {
59
+ return this._blueprints;
60
+ }
61
+ /**
62
+ * Returns the objects atom for subscription.
63
+ */
64
+ get objects() {
65
+ return this._objects;
66
+ }
67
+ /**
68
+ * Gets the current blueprints value.
69
+ */
70
+ getBlueprints() {
71
+ return this._registry.get(this._blueprints);
72
+ }
73
+ /**
74
+ * Gets the current objects value.
75
+ */
76
+ getObjects() {
77
+ return this._registry.get(this._objects);
78
+ }
79
+ /**
80
+ * Subscribe to changes in blueprints.
81
+ */
82
+ subscribeBlueprints(cb) {
83
+ return this._registry.subscribe(this._blueprints, () => cb(this._registry.get(this._blueprints)));
84
+ }
85
+ /**
86
+ * Subscribe to changes in objects.
87
+ */
88
+ subscribeObjects(cb) {
89
+ return this._registry.subscribe(this._objects, () => cb(this._registry.get(this._objects)));
90
+ }
91
+ async _open() {
92
+ this.#bindingsQuery = await Runtime.runPromise(this._runtime)(Feed.query(this._feed, Query.type(ContextBinding)));
93
+ const initialResults = await this.#bindingsQuery.run();
94
+ await this._updateBindings(initialResults);
95
+ this._ctx.onDispose(this.#bindingsQuery.subscribe(async () => {
96
+ await this._updateBindings(this.#bindingsQuery.results);
97
+ }));
98
+ }
99
+ /**
100
+ * Re-reads bindings from the feed to pick up changes made by other processes.
101
+ */
102
+ async sync() {
103
+ if (this.#bindingsQuery) {
104
+ const results = await this.#bindingsQuery.run();
105
+ log("sync", {
106
+ bindingItems: results.length
107
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 107, S: this });
108
+ await this._updateBindings(results);
109
+ log("sync complete", {
110
+ blueprints: this._registry.get(this._blueprints).length,
111
+ blueprintKeys: this._registry.get(this._blueprints).map((bp) => bp.key)
112
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 111, S: this });
113
+ }
114
+ }
115
+ async _updateBindings(items) {
116
+ if (items.length === 0) {
117
+ return;
118
+ }
119
+ const bindings = this._reduce(items);
120
+ log("_updateBindings", {
121
+ items: items.length,
122
+ blueprintRefs: [
123
+ ...bindings.blueprints
124
+ ].map((ref) => ({
125
+ dxn: ref.dxn.toString(),
126
+ available: ref.isAvailable
127
+ }))
128
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 123, S: this });
129
+ const currentBlueprints = this._registry.get(this._blueprints);
130
+ const currentObjects = this._registry.get(this._objects);
131
+ const resolvedBlueprints = await this._resolve(bindings.blueprints, currentBlueprints);
132
+ const resolvedObjects = await this._resolve(bindings.objects, currentObjects);
133
+ log("_updateBindings resolved", {
134
+ resolvedBlueprints: resolvedBlueprints.length,
135
+ resolvedBlueprintKeys: resolvedBlueprints.map((bp) => bp.key)
136
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 137, S: this });
137
+ const reducedBlueprintDxns = new ComplexSet(DXN.hash, [
138
+ ...bindings.blueprints
139
+ ].map((ref) => ref.dxn));
140
+ const reducedObjectDxns = new ComplexSet(DXN.hash, [
141
+ ...bindings.objects
142
+ ].map((ref) => ref.dxn));
143
+ const filteredBlueprints = currentBlueprints.filter((obj) => reducedBlueprintDxns.has(Obj.getDXN(obj)));
144
+ const filteredObjects = currentObjects.filter((obj) => reducedObjectDxns.has(Obj.getDXN(obj)));
145
+ const mergedBlueprints = this._mergeInto(filteredBlueprints, resolvedBlueprints);
146
+ const mergedObjects = this._mergeInto(filteredObjects, resolvedObjects);
147
+ this._registry.set(this._blueprints, mergedBlueprints);
148
+ this._registry.set(this._objects, mergedObjects);
149
+ log("updated bindings", {
150
+ blueprints: mergedBlueprints.length,
151
+ objects: mergedObjects.length
152
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 155, S: this });
153
+ }
154
+ async _close() {
155
+ this._registry.set(this._blueprints, []);
156
+ this._registry.set(this._objects, []);
157
+ }
158
+ async bind({ blueprints, objects }) {
159
+ const currentBlueprints = this._registry.get(this._blueprints);
160
+ const currentObjects = this._registry.get(this._objects);
161
+ const { added: addedBlueprints, next: nextBlueprints } = this._processBindings(blueprints, currentBlueprints);
162
+ const { added: addedObjects, next: nextObjects } = this._processBindings(objects, currentObjects);
163
+ if (!addedBlueprints.length && !addedObjects.length) {
164
+ return;
165
+ }
166
+ this._registry.set(this._blueprints, nextBlueprints);
167
+ this._registry.set(this._objects, nextObjects);
168
+ log("bind", {
169
+ blueprints: addedBlueprints.length,
170
+ objects: addedObjects.length
171
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 176, S: this });
172
+ await Runtime.runPromise(this._runtime)(Feed.append(this._feed, [
173
+ Obj.make(ContextBinding, {
174
+ blueprints: {
175
+ added: addedBlueprints,
176
+ removed: []
177
+ },
178
+ objects: {
179
+ added: addedObjects,
180
+ removed: []
181
+ }
182
+ })
183
+ ]));
184
+ }
185
+ async unbind({ blueprints, objects }) {
186
+ if (!blueprints?.length && !objects?.length) {
187
+ return;
188
+ }
189
+ const removedBlueprintDxns = (blueprints ?? []).map((ref) => ref.dxn);
190
+ const removedObjectDxns = (objects ?? []).map((ref) => ref.dxn);
191
+ if (removedBlueprintDxns.length > 0) {
192
+ const current = this._registry.get(this._blueprints);
193
+ this._registry.set(this._blueprints, current.filter((obj) => !removedBlueprintDxns.some((dxn) => DXN.equalsEchoId(Obj.getDXN(obj), dxn))));
194
+ }
195
+ if (removedObjectDxns.length > 0) {
196
+ const current = this._registry.get(this._objects);
197
+ this._registry.set(this._objects, current.filter((obj) => !removedObjectDxns.some((dxn) => DXN.equalsEchoId(Obj.getDXN(obj), dxn))));
198
+ }
199
+ log("unbind", {
200
+ blueprints: blueprints?.length,
201
+ objects: objects?.length
202
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 208, S: this });
203
+ await Runtime.runPromise(this._runtime)(Feed.append(this._feed, [
204
+ Obj.make(ContextBinding, {
205
+ blueprints: {
206
+ added: [],
207
+ removed: blueprints ?? []
208
+ },
209
+ objects: {
210
+ added: [],
211
+ removed: objects ?? []
212
+ }
213
+ })
214
+ ]));
215
+ }
216
+ /**
217
+ * Process bindings to filter duplicates and determine next state.
218
+ */
219
+ _processBindings(refs, current) {
220
+ const next = [
221
+ ...current
222
+ ];
223
+ const added = [];
224
+ if (!refs?.length) {
225
+ return {
226
+ added,
227
+ next
228
+ };
229
+ }
230
+ const seen = new Set(current.map((obj) => Obj.getDXN(obj).toString()));
231
+ for (const ref of refs) {
232
+ const dxn = ref.dxn.toString();
233
+ if (!seen.has(dxn)) {
234
+ seen.add(dxn);
235
+ added.push(ref);
236
+ if (ref.isAvailable) {
237
+ const target = ref.target;
238
+ if (target) {
239
+ next.push(target);
240
+ }
241
+ }
242
+ }
243
+ }
244
+ return {
245
+ added,
246
+ next
247
+ };
248
+ }
249
+ /**
250
+ * Reduce results into sets of blueprints and objects.
251
+ */
252
+ _reduce(items) {
253
+ return Function.pipe(items, EArray.reduce(new Bindings(), (context, { blueprints, objects }) => {
254
+ blueprints.added.forEach((ref) => context.blueprints.add(ref));
255
+ blueprints.removed.forEach((ref) => context.blueprints.delete(ref));
256
+ objects.added.forEach((ref) => context.objects.add(ref));
257
+ objects.removed.forEach((ref) => {
258
+ for (const obj of context.objects) {
259
+ if (DXN.equalsEchoId(obj.dxn, ref.dxn)) {
260
+ context.objects.delete(obj);
261
+ }
262
+ }
263
+ });
264
+ return context;
265
+ }));
266
+ }
267
+ /**
268
+ * Merge resolved items into the current set, adding only items not already present (by DXN).
269
+ */
270
+ _mergeInto(current, resolved) {
271
+ const seen = new Set(current.map((obj) => Obj.getDXN(obj).toString()));
272
+ const merged = [
273
+ ...current
274
+ ];
275
+ for (const obj of resolved) {
276
+ const dxn = Obj.getDXN(obj).toString();
277
+ if (!seen.has(dxn)) {
278
+ seen.add(dxn);
279
+ merged.push(obj);
280
+ }
281
+ }
282
+ return merged;
283
+ }
284
+ /**
285
+ * Resolve references to objects, loading them first if needed and falling back to existing objects.
286
+ */
287
+ async _resolve(refs, current) {
288
+ const refArray = [
289
+ ...refs
290
+ ];
291
+ await Promise.all(refArray.map((ref) => ref.tryLoad()));
292
+ return refArray.map((ref) => {
293
+ let target;
294
+ if (ref.isAvailable) {
295
+ target = ref.target;
296
+ }
297
+ return target ?? current.find((obj) => Obj.getDXN(obj).toString() === ref.dxn.toString());
298
+ }).filter(isNonNullable);
299
+ }
300
+ };
301
+ var AiContextService = class _AiContextService extends Context.Tag("@dxos/assistant/AiContextService")() {
302
+ static bindContext = ({ blueprints, objects }) => Effect.gen(function* () {
303
+ const { binder } = yield* _AiContextService;
304
+ yield* Effect.promise(() => binder.bind({
305
+ blueprints,
306
+ objects
307
+ }));
308
+ });
309
+ static findObjects = (type) => {
310
+ return Effect.gen(function* () {
311
+ const { binder } = yield* _AiContextService;
312
+ return binder.getObjects().filter(Obj.instanceOf(type));
313
+ });
314
+ };
315
+ };
316
+
317
+ // src/conversation/session.ts
318
+ import * as Array4 from "effect/Array";
319
+ import * as Context4 from "effect/Context";
320
+ import * as Effect7 from "effect/Effect";
321
+ import * as Either from "effect/Either";
322
+ import { pipe as pipe4 } from "effect/Function";
323
+ import * as Layer3 from "effect/Layer";
324
+ import * as Record2 from "effect/Record";
325
+ import * as Runtime2 from "effect/Runtime";
326
+ import { Operation as Operation2 } from "@dxos/compute";
327
+ import { Resource as Resource2 } from "@dxos/context";
328
+ import { Database as Database2, Feed as Feed2, Filter, Obj as Obj6 } from "@dxos/echo";
329
+ import { acquireReleaseResource } from "@dxos/effect";
330
+ import { invariant as invariant2 } from "@dxos/invariant";
331
+ import { log as log4 } from "@dxos/log";
332
+ import { McpToolkit } from "@dxos/mcp-client";
333
+ import { Message as Message3 } from "@dxos/types";
334
+
335
+ // src/functions/services.ts
336
+ import * as Tool from "@effect/ai/Tool";
337
+ import * as Context2 from "effect/Context";
338
+ import * as Effect2 from "effect/Effect";
339
+ import * as Layer from "effect/Layer";
340
+ import * as Option from "effect/Option";
341
+ import * as Record from "effect/Record";
342
+ import * as Schema3 from "effect/Schema";
343
+ import * as SchemaAST from "effect/SchemaAST";
344
+ import { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from "@dxos/ai";
345
+ import { OpaqueToolkit } from "@dxos/ai";
346
+ import { Operation, OperationRegistry } from "@dxos/compute";
347
+ import { todo } from "@dxos/debug";
348
+ import { Ref as Ref3 } from "@dxos/echo";
349
+ import { invariant } from "@dxos/invariant";
350
+
351
+ // src/types/artifact.ts
352
+ import * as Schema2 from "effect/Schema";
353
+ import { Obj as Obj2, Ref as Ref2 } from "@dxos/echo";
354
+ import { Database } from "@dxos/echo";
355
+ import { EncodedReference } from "@dxos/echo-protocol";
356
+ import { DXN as DXN2, LOCAL_SPACE_TAG } from "@dxos/keys";
357
+ import { trim } from "@dxos/util";
358
+ var createArtifactElement = (id) => `<artifact id=${id} />`;
359
+ var ArtifactId = class extends Schema2.String.annotations({
360
+ // TODO(dmaretskyi): This section gets overriden.
361
+ description: trim`
362
+ The ID of the referenced object. Formats accepted:
363
+ - DXN (dxn:echo:@:01KG7R1ZXWFMWQ4DA1Q6TN1DG4). DXNs can be prepended with an @ symbol for compatibility with in-text references.
364
+ - space ID, object ID tuple (spaceID:objectID)
365
+ - Only object ID that is assumed to be in the current space (01KG7R1ZXWFMWQ4DA1Q6TN1DG4)
366
+ `,
367
+ examples: [
368
+ "dxn:echo:@:01KG7R1ZXWFMWQ4DA1Q6TN1DG4",
369
+ "@dxn:echo:@:01KG7R1ZXWFMWQ4DA1Q6TN1DG4",
370
+ "BM3FSHFOMJCHCG5QW7JTVKGYABD2GAA7G:01KG7R1ZXWFMWQ4DA1Q6TN1DG4",
371
+ "01KG7R1ZXWFMWQ4DA1Q6TN1DG4"
372
+ ]
373
+ }) {
374
+ static toDXN(reference, owningSpaceId) {
375
+ if (reference.startsWith("@dxn:")) {
376
+ return DXN2.parse(reference.slice(1));
377
+ } else if (reference.startsWith("dxn:")) {
378
+ return DXN2.parse(reference);
379
+ } else if (/^[A-Z0-9]+:[A-Z0-9]+$/.test(reference)) {
380
+ const [spaceId, objectId] = reference.split(":");
381
+ return new DXN2(DXN2.kind.ECHO, [
382
+ spaceId === owningSpaceId ? LOCAL_SPACE_TAG : spaceId,
383
+ objectId
384
+ ]);
385
+ } else if (/^[A-Z0-9]+$/.test(reference)) {
386
+ return DXN2.fromLocalObjectId(reference);
387
+ } else {
388
+ throw new Error(`Unable to parse object reference: ${reference}`);
389
+ }
390
+ }
391
+ /**
392
+ * Resolves an artifact ID to an object.
393
+ */
394
+ static resolve(schema, ref) {
395
+ const dxn = ArtifactId.toDXN(ref);
396
+ return Database.resolve(dxn, schema);
397
+ }
398
+ };
399
+ var RefFromLLM = Schema2.transform(ArtifactId, Ref2.Ref(Obj2.Unknown), {
400
+ decode: (fromA, fromI) => EncodedReference.fromDXN(ArtifactId.toDXN(fromA)),
401
+ encode: (toI, toA) => EncodedReference.toDXN(toI).toString(),
402
+ strict: false
403
+ }).annotations({
404
+ description: ArtifactId.ast.annotations.description
405
+ });
406
+
407
+ // src/functions/services.ts
408
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/assistant/src/functions/services.ts";
409
+ var makeToolResolverFromOperations = ({ toolkit: extraToolkit = OpaqueToolkit.empty } = {}) => {
410
+ return Layer.effect(ToolResolverService, Effect2.gen(function* () {
411
+ const toolkitProvider = yield* OpaqueToolkit.OpaqueToolkitProvider;
412
+ const operationRegistry = yield* OperationRegistry.Service;
413
+ return {
414
+ resolve: (id) => Effect2.gen(function* () {
415
+ const toolkit = OpaqueToolkit.merge(extraToolkit, toolkitProvider.getToolkit());
416
+ const tool = toolkit.toolkit.tools[id];
417
+ if (tool) {
418
+ return tool;
419
+ }
420
+ return yield* operationRegistry.resolve(id).pipe(Effect2.flatMap(Option.match({
421
+ onSome: (_) => Effect2.succeed(projectFunctionToTool(_)),
422
+ onNone: () => Effect2.fail(new AiToolNotFoundError(id))
423
+ })));
424
+ })
425
+ };
426
+ }));
427
+ };
428
+ var makeToolExecutionService = (opts) => Layer.effect(ToolExecutionService, Effect2.gen(function* () {
429
+ const toolkitProvider = yield* OpaqueToolkit.OpaqueToolkitProvider;
430
+ const toolkit = toolkitProvider.getToolkit();
431
+ const toolkitHandler = yield* toolkit.toolkit.pipe(Effect2.provide(toolkit.layer));
432
+ invariant(isHandlerLike(toolkitHandler), void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 42, S: this, A: ["isHandlerLike(toolkitHandler)", ""] });
433
+ return {
434
+ handlersFor: (toolkit2) => {
435
+ const makeHandler = (tool) => {
436
+ return Effect2.fn(`toolFunctionHandler ${tool.name}`)(function* (input) {
437
+ if (toolkitHandler.tools[tool.name]) {
438
+ if (Tool.isProviderDefined(tool)) {
439
+ throw new Error("Attempted to call a provider-defined tool");
440
+ }
441
+ const { result } = yield* toolkitHandler.handle(tool.name, input);
442
+ return result;
443
+ }
444
+ return yield* opts.invoke(tool, input).pipe(Effect2.catchAllDefect((defect) => Effect2.fail(defect)));
445
+ });
446
+ };
447
+ return toolkit2.of(Record.map(toolkit2.tools, (tool, _name) => Tool.isUserDefined(tool) ? makeHandler(tool) : null));
448
+ }
449
+ };
450
+ }));
451
+ var makeToolExecutionServiceFromOperationInvoker = () => {
452
+ return Layer.unwrapEffect(Effect2.gen(function* () {
453
+ const operationInvoker = yield* Operation.Service;
454
+ return makeToolExecutionService({
455
+ invoke: (tool, input) => Effect2.gen(function* () {
456
+ const operationDef = getOperationFromTool(tool).pipe(Option.getOrThrow);
457
+ return yield* operationInvoker.invoke(operationDef, input).pipe(Effect2.orDie);
458
+ })
459
+ });
460
+ }));
461
+ };
462
+ var ToolExecutionServices = Layer.mergeAll(makeToolResolverFromOperations(), makeToolExecutionServiceFromOperationInvoker());
463
+ var FunctionToolAnnotation = class extends Context2.Tag("@dxos/assistant/FunctionToolAnnotation")() {
464
+ };
465
+ var getOperationFromTool = (tool) => {
466
+ return Context2.getOption(FunctionToolAnnotation)(tool.annotations).pipe(Option.map(({ definition }) => definition));
467
+ };
468
+ var toolCache = /* @__PURE__ */ new WeakMap();
469
+ var projectFunctionToTool = (fn2) => {
470
+ if (toolCache.has(fn2)) {
471
+ return toolCache.get(fn2);
472
+ }
473
+ const tool = Tool.make(makeToolName(fn2.meta.name ?? fn2.meta.key), {
474
+ description: fn2.meta.description,
475
+ parameters: createStructFieldsFromSchema(fn2.input),
476
+ failure: Schema3.Any
477
+ }).annotate(FunctionToolAnnotation, {
478
+ definition: fn2
479
+ });
480
+ toolCache.set(fn2, tool);
481
+ return tool;
482
+ };
483
+ var makeToolName = (name) => {
484
+ const toolName = name.toLowerCase().replace(/[^a-zA-Z0-9]/g, "-");
485
+ invariant(toolName.match(/^[a-z_][a-z0-9-_]*$/), void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 100, S: void 0, A: ["toolName.match(/^[a-z_][a-z0-9-_]*$/)", ""] });
486
+ return toolName;
487
+ };
488
+ var createStructFieldsFromSchema = (schema) => {
489
+ switch (schema.ast._tag) {
490
+ case "TypeLiteral":
491
+ return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [
492
+ prop.name,
493
+ Schema3.make(mapSchemaTypeForLLM(prop.type))
494
+ ]));
495
+ case "VoidKeyword":
496
+ return {};
497
+ default:
498
+ return todo(`Unsupported schema AST: ${schema.ast._tag}`);
499
+ }
500
+ };
501
+ var mapSchemaTypeForLLM = (ast) => {
502
+ if (Ref3.isRefType(ast)) {
503
+ const description = ast.annotations.description ? ast.annotations.description + "\n" + RefFromLLM.ast.annotations.description : RefFromLLM.ast.annotations.description;
504
+ return RefFromLLM.annotations({
505
+ description
506
+ }).ast;
507
+ } else if (SchemaAST.isTupleType(ast)) {
508
+ return new SchemaAST.TupleType(ast.elements.map((t) => new SchemaAST.OptionalType(mapSchemaTypeForLLM(t.type), t.isOptional, t.annotations)), ast.rest.map((t) => new SchemaAST.Type(mapSchemaTypeForLLM(t.type), t.annotations)), ast.isReadonly, ast.annotations);
509
+ } else if (SchemaAST.isTypeLiteral(ast)) {
510
+ return new SchemaAST.TypeLiteral(ast.propertySignatures.map((p) => new SchemaAST.PropertySignature(p.name, mapSchemaTypeForLLM(p.type), p.isOptional, p.isReadonly, p.annotations)), ast.indexSignatures, ast.annotations);
511
+ }
512
+ return ast;
513
+ };
514
+ var isHandlerLike = (value) => {
515
+ return typeof value.tools === "object" && typeof value.handle === "function";
516
+ };
517
+
518
+ // src/session/artifact-diff.ts
519
+ import * as Context3 from "effect/Context";
520
+ var ArtifactDiffResolver = class extends Context3.Tag("@dxos/assistant/ArtifactDiffResolver")() {
521
+ };
522
+
523
+ // src/session/observer.ts
524
+ import * as Effect3 from "effect/Effect";
525
+ import * as Function2 from "effect/Function";
526
+ var GenerationObserver = Object.freeze({
527
+ make: ({ onBegin = Function2.constant(Effect3.void), onPart = Function2.constant(Effect3.void), onBlock = Function2.constant(Effect3.void), onEnd = Function2.constant(Effect3.void), onMessage = Function2.constant(Effect3.void) } = {}) => ({
528
+ onBegin,
529
+ onPart,
530
+ onBlock,
531
+ onEnd,
532
+ onMessage
533
+ }),
534
+ noop: () => GenerationObserver.make(),
535
+ /**
536
+ * Debug printer to be used in unit-tests and browser devtools.
537
+ */
538
+ fromPrinter: (printer) => GenerationObserver.make({
539
+ onBlock: (block) => Effect3.sync(() => {
540
+ if (block.pending) {
541
+ return;
542
+ }
543
+ printer.printContentBlock(block);
544
+ }),
545
+ onMessage: (message) => Effect3.sync(() => {
546
+ if (message.sender.role === "assistant") {
547
+ return;
548
+ }
549
+ printer.printMessage(message);
550
+ })
551
+ })
552
+ });
553
+
554
+ // src/session/request.ts
555
+ import * as LanguageModel from "@effect/ai/LanguageModel";
556
+ import * as Array3 from "effect/Array";
557
+ import * as Chunk from "effect/Chunk";
558
+ import * as Effect5 from "effect/Effect";
559
+ import { pipe as pipe3 } from "effect/Function";
560
+ import * as Option3 from "effect/Option";
561
+ import * as Stream from "effect/Stream";
562
+ import { AiParser, AiPreprocessor, AiSummarizer, callTool, withoutToolCallParising } from "@dxos/ai";
563
+ import { Trace as Trace2 } from "@dxos/compute";
564
+ import { Obj as Obj5 } from "@dxos/echo";
565
+ import { log as log3 } from "@dxos/log";
566
+ import { ContentBlock as ContentBlock2, Message as Message2 } from "@dxos/types";
567
+
568
+ // src/tracing.ts
569
+ import * as Schema4 from "effect/Schema";
570
+ import { Trace } from "@dxos/compute";
571
+ import { Obj as Obj3 } from "@dxos/echo";
572
+ import { ContentBlock, Actor } from "@dxos/types";
573
+ var PartialBlock = Trace.EventType("assistant.partialBlock", {
574
+ schema: Schema4.Struct({
575
+ messageId: Obj3.ID,
576
+ role: Actor.Role,
577
+ block: ContentBlock.Any
578
+ }),
579
+ isEphemeral: true
580
+ });
581
+ var CompleteBlock = Trace.EventType("assistant.completeBlock", {
582
+ schema: Schema4.Struct({
583
+ messageId: Obj3.ID,
584
+ role: Actor.Role,
585
+ block: ContentBlock.Any
586
+ }),
587
+ isEphemeral: false
588
+ });
589
+ var AgentRequestBegin = Trace.EventType("assistant.agentRequestBegin", {
590
+ schema: Schema4.Struct({}),
591
+ isEphemeral: false
592
+ });
593
+ var AgentRequestEnd = Trace.EventType("assistant.agentRequestEnd", {
594
+ schema: Schema4.Struct({}),
595
+ isEphemeral: false
596
+ });
597
+
598
+ // src/session/format.ts
599
+ import * as Effect4 from "effect/Effect";
600
+ import * as Function3 from "effect/Function";
601
+ import * as Option2 from "effect/Option";
602
+ import { Template } from "@dxos/compute";
603
+ import { Obj as Obj4 } from "@dxos/echo";
604
+ import { ObjectVersion } from "@dxos/echo-db";
605
+ import { log as log2 } from "@dxos/log";
606
+ import { Message } from "@dxos/types";
607
+ import { trim as trim2 } from "@dxos/util";
608
+
609
+ // src/errors.ts
610
+ import { BaseError } from "@dxos/errors";
611
+ var AiModelError = class extends BaseError.extend("AiModelError", "AI model error") {
612
+ };
613
+ var AiAssistantError = class extends BaseError.extend("AiAssistantError", "AI assistant error") {
614
+ };
615
+
616
+ // src/session/format.ts
617
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/assistant/src/session/format.ts";
618
+ var formatSystemPrompt = ({ system, blueprints = [], objects = [] }) => Effect4.gen(function* () {
619
+ const blueprintDefs = yield* Function3.pipe(blueprints, Effect4.forEach((blueprint) => Effect4.succeed(blueprint.instructions)), Effect4.flatMap(Effect4.forEach((template) => Effect4.gen(function* () {
620
+ return trim2`
621
+ <blueprint>
622
+ ${yield* Template.processTemplate(template)}
623
+ </blueprint>
624
+ `;
625
+ }))), Effect4.map((blueprints2) => blueprints2.length > 0 ? [
626
+ "## Blueprints Definitions",
627
+ ...blueprints2
628
+ ].join("\n\n") : void 0));
629
+ const objectDefs = yield* Function3.pipe(objects, Effect4.forEach((object) => Effect4.succeed(trim2`
630
+ <object>
631
+ <dxn>${Obj4.getDXN(object)}</dxn>
632
+ <typename>${Obj4.getTypename(object)}</typename>
633
+ </object>
634
+ `)), Effect4.map((objects2) => objects2.length > 0 ? [
635
+ "## Context Objects",
636
+ ...objects2
637
+ ].join("\n\n") : void 0));
638
+ return yield* Function3.pipe(Effect4.succeed([
639
+ system,
640
+ blueprintDefs,
641
+ objectDefs
642
+ ].filter((def) => def !== void 0)), Effect4.map((parts) => parts.join("\n\n")));
643
+ }).pipe(Effect4.withSpan("formatSystemPrompt"));
644
+ var formatUserPrompt = ({ prompt, history = [] }) => Effect4.gen(function* () {
645
+ const blocks = [];
646
+ const artifactDiffResolver = yield* Effect4.serviceOption(ArtifactDiffResolver);
647
+ if (Option2.isSome(artifactDiffResolver)) {
648
+ const versions = gatherObjectVersions(history);
649
+ const artifactDiff = yield* Effect4.tryPromise({
650
+ try: () => artifactDiffResolver.value.resolve([
651
+ ...versions.entries()
652
+ ].map(([id, version]) => ({
653
+ id,
654
+ lastVersion: version
655
+ }))),
656
+ catch: AiAssistantError.wrap({
657
+ message: "Artifact diff resolution error"
658
+ })
659
+ });
660
+ log2("version", {
661
+ artifactDiff,
662
+ versions
663
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 65, S: this });
664
+ for (const [id, { version }] of [
665
+ ...artifactDiff.entries()
666
+ ]) {
667
+ if (ObjectVersion.equals(version, versions.get(id))) {
668
+ artifactDiff.delete(id);
669
+ continue;
670
+ }
671
+ blocks.push({
672
+ _tag: "anchor",
673
+ objectId: id,
674
+ version
675
+ });
676
+ }
677
+ if (artifactDiff.size > 0) {
678
+ blocks.push(createArtifactUpdateBlock(artifactDiff));
679
+ }
680
+ }
681
+ return Obj4.make(Message.Message, {
682
+ created: (/* @__PURE__ */ new Date()).toISOString(),
683
+ sender: {
684
+ role: "user"
685
+ },
686
+ blocks: typeof prompt === "string" ? [
687
+ ...blocks,
688
+ {
689
+ _tag: "text",
690
+ text: prompt
691
+ }
692
+ ] : [
693
+ ...blocks,
694
+ ...prompt
695
+ ]
696
+ });
697
+ }).pipe(Effect4.withSpan("formatUserPrompt"));
698
+ var gatherObjectVersions = (messages) => {
699
+ const artifactIds = /* @__PURE__ */ new Map();
700
+ for (const message of messages) {
701
+ for (const block of message.blocks) {
702
+ if (block._tag === "anchor") {
703
+ artifactIds.set(block.objectId, block.version);
704
+ }
705
+ }
706
+ }
707
+ return artifactIds;
708
+ };
709
+ var createArtifactUpdateBlock = (artifactDiff) => {
710
+ return {
711
+ _tag: "text",
712
+ // TODO(dmaretskyi): Does this need to be a special content-block?
713
+ disposition: "synthetic",
714
+ text: trim2`
715
+ The following artifacts have been updated since the last message:
716
+ ${[
717
+ ...artifactDiff.entries()
718
+ ].map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `
719
+ ${diff}` : ""}</changed-artifact>`).join("\n")}
720
+ `
721
+ };
722
+ };
723
+
724
+ // src/session/request.ts
725
+ var __dxlog_file4 = "/__w/dxos/dxos/packages/core/assistant/src/session/request.ts";
726
+ var AiRequest = class {
727
+ _options;
728
+ /** Prevents concurrent execution of session. */
729
+ _semaphore = Effect5.runSync(Effect5.makeSemaphore(1));
730
+ _observer;
731
+ _onOutput;
732
+ /** Message history from queue. */
733
+ // TODO(burdon): Evolve into supporting a git-like graph of messages.
734
+ _history = [];
735
+ /** Pending messages for this session (incl. the current prompt). */
736
+ _pending = [];
737
+ _started = 0;
738
+ _ended = 0;
739
+ _toolCalls = 0;
740
+ constructor(_options = {}) {
741
+ this._options = _options;
742
+ this._observer = _options.observer ?? GenerationObserver.noop();
743
+ this._onOutput = _options.onOutput ?? (() => Effect5.void);
744
+ }
745
+ get duration() {
746
+ return this._ended - this._started;
747
+ }
748
+ get toolCalls() {
749
+ return this._toolCalls;
750
+ }
751
+ get pending() {
752
+ return this._pending;
753
+ }
754
+ _submitMessage = (message) => Effect5.gen(this, function* () {
755
+ this._pending.push(message);
756
+ yield* this._observer.onMessage(message);
757
+ for (const block of message.blocks) {
758
+ yield* Trace2.write(CompleteBlock, {
759
+ messageId: message.id,
760
+ role: message.sender.role,
761
+ block
762
+ });
763
+ }
764
+ yield* this._onOutput(message);
765
+ return message;
766
+ });
767
+ getToolCalls = () => pipe3([
768
+ ...this._history,
769
+ ...this._pending
770
+ ], Array3.reverse, Array3.takeWhile((_) => _.sender.role === "assistant"), Array3.flatMap((_) => _.blocks.filter(ContentBlock2.is("toolCall")).map((block) => ({
771
+ block,
772
+ message: _
773
+ }))), Array3.filter((_) => !_.block.providerExecuted), Array3.reverse);
774
+ /**
775
+ * Initialize a session: set up history, perform summarization if needed, and submit the user prompt.
776
+ * Must be called before `runTurn()`.
777
+ */
778
+ begin = ({ prompt, system, history = [], blueprints = [], objects = [] }) => Effect5.gen(this, function* () {
779
+ this._started = Date.now();
780
+ this._history = [
781
+ ...history
782
+ ];
783
+ this._pending = [];
784
+ const systemPrompt = yield* formatSystemPrompt({
785
+ system,
786
+ blueprints,
787
+ objects
788
+ }).pipe(Effect5.orDie);
789
+ if (this._options.summarizationThreshold !== void 0) {
790
+ const tokenCount = yield* AiPreprocessor.estimateTokens(yield* AiPreprocessor.preprocessPrompt([
791
+ ...this._history
792
+ ], {
793
+ system: systemPrompt
794
+ }));
795
+ if (tokenCount > this._options.summarizationThreshold) {
796
+ const summary = yield* AiSummarizer.summarize([
797
+ ...this._history
798
+ ]);
799
+ yield* this._submitMessage(summary);
800
+ }
801
+ }
802
+ yield* this._submitMessage(yield* formatUserPrompt({
803
+ prompt,
804
+ history
805
+ }));
806
+ }).pipe(Effect5.withSpan("AiRequest.begin"));
807
+ /**
808
+ * Execute a single turn: one LLM generation followed by tool execution.
809
+ * The toolkit and system prompt can be updated between turns to reflect context changes (e.g. dynamically enabled blueprints).
810
+ */
811
+ runAgentTurn = ({ system, toolkit: opaqueToolkit }) => Effect5.gen(this, function* () {
812
+ log3.info("request", {
813
+ system: {
814
+ snippet: createSnippet(system),
815
+ length: system.length
816
+ },
817
+ pending: this._pending.length,
818
+ history: this._history.length
819
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 109, S: this });
820
+ const prompt = yield* AiPreprocessor.preprocessPrompt([
821
+ ...this._history,
822
+ ...this._pending
823
+ ], {
824
+ system,
825
+ cacheControl: "ephemeral"
826
+ });
827
+ const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : void 0;
828
+ const observer = this._observer;
829
+ let currentMessageId = null;
830
+ const messages = yield* LanguageModel.streamText({
831
+ prompt,
832
+ toolkit,
833
+ disableToolCallResolution: true
834
+ }).pipe(withoutToolCallParising, AiParser.parseResponse({
835
+ emitPartial: true,
836
+ onBegin: () => observer.onBegin(),
837
+ onBlock: (block) => observer.onBlock(block),
838
+ onPart: (part) => observer.onPart(part),
839
+ onEnd: (summary) => observer.onEnd(summary)
840
+ }), Stream.mapEffect((block) => Effect5.gen(this, function* () {
841
+ if (block.pending) {
842
+ currentMessageId ??= Obj5.ID.random();
843
+ log3("emit ephemeral message", {
844
+ id: currentMessageId,
845
+ type: block._tag
846
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 140, S: this });
847
+ yield* Trace2.write(PartialBlock, {
848
+ messageId: currentMessageId,
849
+ role: "assistant",
850
+ block
851
+ });
852
+ return Option3.none();
853
+ } else {
854
+ currentMessageId ??= Obj5.ID.random();
855
+ const id = currentMessageId;
856
+ currentMessageId = null;
857
+ log3("emit complete message", {
858
+ id,
859
+ type: block._tag
860
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 154, S: this });
861
+ const message = Obj5.make(Message2.Message, {
862
+ id,
863
+ created: (/* @__PURE__ */ new Date()).toISOString(),
864
+ sender: {
865
+ role: "assistant"
866
+ },
867
+ blocks: [
868
+ block
869
+ ]
870
+ });
871
+ return Option3.some(yield* this._submitMessage(message));
872
+ }
873
+ }), {
874
+ concurrency: 1,
875
+ unordered: false
876
+ }), Stream.filterMap((_) => _), Stream.runCollect, Effect5.map(Chunk.toArray));
877
+ log3.info("messages", {
878
+ messages
879
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 174, S: this });
880
+ const toolCalls = this.getToolCalls();
881
+ if (toolCalls.length === 0) {
882
+ this._ended = Date.now();
883
+ return {
884
+ messages,
885
+ done: true
886
+ };
887
+ } else if (!toolkit) {
888
+ throw new Error("No toolkit provided");
889
+ }
890
+ return {
891
+ messages,
892
+ done: false
893
+ };
894
+ }).pipe(Effect5.withSpan("AiRequest.runAgentTurn"));
895
+ runTools = ({ toolkit: opaqueToolkit }) => Effect5.gen(this, function* () {
896
+ const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : void 0;
897
+ const toolCalls = this.getToolCalls();
898
+ const toolResults = yield* Effect5.forEach(toolCalls, ({ block, message }) => {
899
+ if (!toolkit) {
900
+ throw new Error("No toolkit provided");
901
+ }
902
+ return callTool(toolkit, block);
903
+ });
904
+ yield* this._submitMessage(Obj5.make(Message2.Message, {
905
+ created: (/* @__PURE__ */ new Date()).toISOString(),
906
+ sender: {
907
+ role: "tool"
908
+ },
909
+ blocks: toolResults
910
+ }));
911
+ this._toolCalls += toolResults.length;
912
+ }).pipe(Effect5.withSpan("AiRequest.runTools"));
913
+ /**
914
+ * Run a full conversation turn loop. Equivalent to calling `begin()` then `runTurn()` in a loop.
915
+ */
916
+ run = ({ prompt, system: systemTemplate, history = [], objects = [], blueprints = [], toolkit }) => Effect5.gen(this, function* () {
917
+ yield* this.begin({
918
+ prompt,
919
+ system: systemTemplate,
920
+ history,
921
+ objects,
922
+ blueprints
923
+ });
924
+ const system = yield* formatSystemPrompt({
925
+ system: systemTemplate,
926
+ blueprints,
927
+ objects
928
+ }).pipe(Effect5.orDie);
929
+ do {
930
+ const { done } = yield* this.runAgentTurn({
931
+ system,
932
+ toolkit
933
+ });
934
+ if (done) {
935
+ break;
936
+ }
937
+ yield* this.runTools({
938
+ toolkit
939
+ });
940
+ } while (true);
941
+ log3("done", {
942
+ pending: this._pending.length,
943
+ duration: this.duration,
944
+ tools: this._toolCalls
945
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 237, S: this });
946
+ return this._pending;
947
+ }).pipe(this._semaphore.withPermits(1), Effect5.withSpan("AiRequest.run"));
948
+ };
949
+ var createSnippet = (text, len = 32) => text.length <= len * 2 ? text : [
950
+ text.slice(0, len),
951
+ "...",
952
+ text.slice(-len)
953
+ ].join("");
954
+
955
+ // src/session/toolkit.ts
956
+ import * as Toolkit from "@effect/ai/Toolkit";
957
+ import * as Effect6 from "effect/Effect";
958
+ import * as Layer2 from "effect/Layer";
959
+ import { OpaqueToolkit as OpaqueToolkit2, ToolExecutionService as ToolExecutionService2, ToolResolverService as ToolResolverService2 } from "@dxos/ai";
960
+ import { isTruthy } from "@dxos/util";
961
+ var createToolkit = ({ toolkit: toolkitProp, blueprints = [], opaqueToolkits = [] }) => Effect6.gen(function* () {
962
+ const blueprintToolkit = yield* ToolResolverService2.resolveToolkit(blueprints.flatMap(({ tools }) => tools));
963
+ const blueprintToolHandler = yield* blueprintToolkit.toContext(ToolExecutionService2.handlersFor(blueprintToolkit));
964
+ const opaqueToolkit = OpaqueToolkit2.merge(...opaqueToolkits);
965
+ const toolkitDefs = [
966
+ toolkitProp?.toolkit,
967
+ blueprintToolkit,
968
+ opaqueToolkit.toolkit
969
+ ].filter(isTruthy);
970
+ const mergedToolkit = Toolkit.merge(...toolkitDefs);
971
+ const combinedHandlerLayer = Layer2.mergeAll(Layer2.succeedContext(blueprintToolHandler), toolkitProp?.layer ?? OpaqueToolkit2.empty.layer, opaqueToolkit.layer);
972
+ return OpaqueToolkit2.make(mergedToolkit, combinedHandlerLayer);
973
+ });
974
+
975
+ // src/session/version-pin.ts
976
+ import * as Schema5 from "effect/Schema";
977
+ import { getVersion } from "@dxos/echo-db";
978
+ import { ObjectId } from "@dxos/keys";
979
+ var ObjectVersionSchema = Schema5.Unknown;
980
+ var VersionPinSchema = Schema5.Struct({
981
+ // TODO(dmaretskyi): Use Ref when those support encoding.
982
+ objectId: ObjectId,
983
+ // TODO(dmaretskyi): Could be opaque.
984
+ version: ObjectVersionSchema
985
+ });
986
+ var VersionPin = class extends VersionPinSchema {
987
+ static DISPOSITION = "version-pin";
988
+ static fromObject(object) {
989
+ return VersionPin.make({
990
+ objectId: object.id,
991
+ version: getVersion(object)
992
+ });
993
+ }
994
+ static createBlock(pin) {
995
+ return {
996
+ _tag: "json",
997
+ disposition: VersionPin.DISPOSITION,
998
+ data: JSON.stringify(pin)
999
+ };
1000
+ }
1001
+ };
1002
+
1003
+ // src/conversation/session.ts
1004
+ var __dxlog_file5 = "/__w/dxos/dxos/packages/core/assistant/src/conversation/session.ts";
1005
+ var SUMMARY_THRESHOLD = 8e4;
1006
+ var AiSession = class extends Resource2 {
1007
+ /**
1008
+ * Blueprints and objects bound to the session.
1009
+ */
1010
+ _binder;
1011
+ _feed;
1012
+ _runtime;
1013
+ constructor(options) {
1014
+ super();
1015
+ this._feed = options.feed;
1016
+ this._runtime = options.runtime;
1017
+ invariant2(this._feed, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 40, S: this, A: ["this._feed", ""] });
1018
+ invariant2(this._runtime, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 41, S: this, A: ["this._runtime", ""] });
1019
+ this._binder = new AiContextBinder({
1020
+ feed: this._feed,
1021
+ runtime: this._runtime,
1022
+ registry: options.registry
1023
+ });
1024
+ }
1025
+ async _open() {
1026
+ await this._binder.open(this._ctx);
1027
+ }
1028
+ get feed() {
1029
+ return this._feed;
1030
+ }
1031
+ get context() {
1032
+ return this._binder;
1033
+ }
1034
+ async getHistory() {
1035
+ const queryResult = await Runtime2.runPromise(this._runtime)(Feed2.query(this._feed, Filter.type(Message3.Message)));
1036
+ const items = await queryResult.run();
1037
+ return items.filter(Obj6.instanceOf(Message3.Message));
1038
+ }
1039
+ getTools() {
1040
+ return Effect7.gen(this, function* () {
1041
+ const toolkit = yield* createToolkit({
1042
+ blueprints: this.context.getBlueprints()
1043
+ });
1044
+ return toolkit.toolkit.tools;
1045
+ }).pipe(Effect7.orDie);
1046
+ }
1047
+ /**
1048
+ * Not provided by default, since users might want to override them.
1049
+ */
1050
+ makeToolExecutionServices() {
1051
+ return ToolExecutionServices.pipe(Layer3.provide(Operation2.withInvocationOptions({
1052
+ conversation: Obj6.getDXN(this._feed).toString()
1053
+ })));
1054
+ }
1055
+ /**
1056
+ * Creates a new cancelable request effect.
1057
+ */
1058
+ createRequest(params) {
1059
+ return Effect7.gen(this, function* () {
1060
+ const history = yield* Effect7.promise(() => this.getHistory());
1061
+ const blueprints = this.context.getBlueprints();
1062
+ const objects = this.context.getObjects();
1063
+ log4("run", {
1064
+ history: history.length,
1065
+ blueprints: blueprints.length,
1066
+ objects: objects.length
1067
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 84, S: this });
1068
+ const request = new AiRequest({
1069
+ summarizationThreshold: SUMMARY_THRESHOLD,
1070
+ observer: params.observer,
1071
+ onOutput: (message) => Effect7.promise(() => Runtime2.runPromise(this._runtime)(Feed2.append(this._feed, [
1072
+ message
1073
+ ])))
1074
+ });
1075
+ yield* request.begin({
1076
+ history,
1077
+ blueprints,
1078
+ objects,
1079
+ prompt: params.prompt,
1080
+ system: params.system
1081
+ });
1082
+ do {
1083
+ yield* Effect7.promise(() => this.context.sync());
1084
+ const currentBlueprints = this.context.getBlueprints();
1085
+ const mcps = yield* connectMcpServers(currentBlueprints, params.mcpServers);
1086
+ const toolkit = yield* createToolkit({
1087
+ toolkit: params.toolkit,
1088
+ blueprints: currentBlueprints,
1089
+ opaqueToolkits: mcps
1090
+ });
1091
+ log4("toolkit", {
1092
+ tools: Record2.keys(toolkit.toolkit.tools)
1093
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 113, S: this });
1094
+ const system = yield* formatSystemPrompt({
1095
+ system: params.system,
1096
+ blueprints: currentBlueprints,
1097
+ objects: this.context.getObjects()
1098
+ }).pipe(Effect7.orDie);
1099
+ const { done } = yield* request.runAgentTurn({
1100
+ system,
1101
+ toolkit
1102
+ });
1103
+ if (done) {
1104
+ break;
1105
+ }
1106
+ yield* request.runTools({
1107
+ toolkit
1108
+ });
1109
+ } while (true);
1110
+ log4("result", {
1111
+ messages: request.pending.length,
1112
+ duration: request.duration,
1113
+ toolCalls: request.toolCalls
1114
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 132, S: this });
1115
+ return [
1116
+ ...request.pending
1117
+ ];
1118
+ }).pipe(Effect7.provide(Layer3.mergeAll(Layer3.succeed(AiContextService, {
1119
+ binder: this.context
1120
+ }), Layer3.succeed(AiSessionService, this), Operation2.withInvocationOptions({
1121
+ conversation: Obj6.getDXN(this._feed).toString()
1122
+ }))), Effect7.withSpan("AiSession.createRequest"));
1123
+ }
1124
+ };
1125
+ var AiSessionService = class _AiSessionService extends Context4.Tag("@dxos/assistant/AiSessionService")() {
1126
+ /**
1127
+ * Create a new session layer from options.
1128
+ */
1129
+ static layer = (options) => aiContextFromSession.pipe(Layer3.provideMerge(Layer3.scoped(_AiSessionService, Effect7.gen(function* () {
1130
+ const session = yield* acquireReleaseResource(() => new AiSession(options));
1131
+ return session;
1132
+ }))));
1133
+ /**
1134
+ * Create a new session with a new feed.
1135
+ */
1136
+ static layerNewFeed = (options) => Layer3.unwrapScoped(Effect7.gen(function* () {
1137
+ const feed = Feed2.make();
1138
+ yield* Database2.add(feed);
1139
+ const runtime2 = yield* Effect7.runtime();
1140
+ return _AiSessionService.layer({
1141
+ ...options,
1142
+ feed,
1143
+ runtime: runtime2
1144
+ });
1145
+ }));
1146
+ /**
1147
+ * Run a prompt in the current session.
1148
+ */
1149
+ static run = (params) => Effect7.gen(function* () {
1150
+ const session = yield* _AiSessionService;
1151
+ return yield* session.createRequest(params);
1152
+ });
1153
+ };
1154
+ var aiContextFromSession = Layer3.effect(AiContextService, Effect7.gen(function* () {
1155
+ const session = yield* AiSessionService;
1156
+ return {
1157
+ binder: session.context
1158
+ };
1159
+ }));
1160
+ var connectMcpServers = (blueprints, spaceMcpServers = []) => {
1161
+ const blueprintServers = pipe4(blueprints, Array4.flatMap((_) => _.mcpServers ?? []), Array4.map(({ url, protocol }) => ({
1162
+ url,
1163
+ kind: protocol
1164
+ })));
1165
+ const spaceServers = spaceMcpServers.map(({ url, protocol, apiKey }) => ({
1166
+ url,
1167
+ kind: protocol,
1168
+ apiKey
1169
+ }));
1170
+ const allServers = [
1171
+ ...blueprintServers,
1172
+ ...spaceServers
1173
+ ];
1174
+ return pipe4(allServers, Effect7.forEach((options) => McpToolkit.make(options).pipe(
1175
+ // NOTE: Type-inference fails here without explicit void return.
1176
+ Effect7.tap((toolkit) => log4.info("Connected to MCP server", {
1177
+ url: options.url,
1178
+ tools: Object.keys(toolkit.toolkit.tools).length
1179
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 196, S: void 0 })),
1180
+ Effect7.tapDefect((error) => Effect7.sync(() => log4.warn("Failed to connect to MCP server", {
1181
+ error
1182
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 199, S: void 0 }))),
1183
+ Effect7.either
1184
+ )), Effect7.map(Array4.filterMap((_) => Either.getRight(_))));
1185
+ };
1186
+
1187
+ // src/diff.ts
1188
+ import { next as A } from "@automerge/automerge";
1189
+ import { DocAccessor, toCursorRange } from "@dxos/echo-db";
1190
+ import { log as log5 } from "@dxos/log";
1191
+ import { isNonNullable as isNonNullable2 } from "@dxos/util";
1192
+ var __dxlog_file6 = "/__w/dxos/dxos/packages/core/assistant/src/diff.ts";
1193
+ var reduceDiffs = (diffs) => {
1194
+ return diffs.reduce((acc, diff) => {
1195
+ const current = acc[acc.length - 1];
1196
+ const [op, ...rest] = diff.split(" ");
1197
+ switch (op) {
1198
+ case "-": {
1199
+ if (current && !current.match) {
1200
+ current.match += rest.join(" ");
1201
+ } else {
1202
+ acc.push({
1203
+ match: rest.join(" "),
1204
+ replace: ""
1205
+ });
1206
+ }
1207
+ return acc;
1208
+ }
1209
+ case "+": {
1210
+ if (current && !current.replace) {
1211
+ current.replace += rest.join(" ");
1212
+ } else {
1213
+ acc.push({
1214
+ match: "",
1215
+ replace: rest.join(" ")
1216
+ });
1217
+ }
1218
+ return acc;
1219
+ }
1220
+ default: {
1221
+ throw new Error(`Invalid diff format: each line must start with "- " or "+ ", got: ${JSON.stringify(diff)}`);
1222
+ }
1223
+ }
1224
+ }, []);
1225
+ };
1226
+ var computeDiffsWithCursors = (accessor, diffs) => {
1227
+ return reduceDiffs(diffs).map((diff) => {
1228
+ const text = DocAccessor.getValue(accessor);
1229
+ const idx = text.indexOf(diff.match);
1230
+ if (idx !== -1) {
1231
+ return {
1232
+ cursor: toCursorRange(accessor, idx, idx + diff.match.length),
1233
+ text: diff.replace
1234
+ };
1235
+ }
1236
+ }).filter(isNonNullable2);
1237
+ };
1238
+ var applyDiffs = (accessor, diffs, { errorOnNotFound = false } = {}) => {
1239
+ for (const diff of reduceDiffs(diffs)) {
1240
+ accessor.handle.change((doc) => {
1241
+ const text = DocAccessor.getValue(accessor);
1242
+ const idx = text.indexOf(diff.match);
1243
+ if (idx !== -1) {
1244
+ A.splice(doc, accessor.path, idx, diff.match.length, diff.replace);
1245
+ } else {
1246
+ if (errorOnNotFound) {
1247
+ throw new Error(`Diff not found: ${diff.match}`);
1248
+ } else {
1249
+ log5.warn("diff not found", diff, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 71, S: void 0 });
1250
+ }
1251
+ }
1252
+ });
1253
+ }
1254
+ return DocAccessor.getValue(accessor);
1255
+ };
1256
+
1257
+ // src/execution-graph.ts
1258
+ import { AgentStatus } from "@dxos/ai";
1259
+ import { MESSAGE_PROPERTY_TOOL_CALL_ID } from "@dxos/compute";
1260
+ import { Obj as Obj7 } from "@dxos/echo";
1261
+ import { LogLevel } from "@dxos/log";
1262
+ import { ContentBlock as ContentBlock3, Message as Message4 } from "@dxos/types";
1263
+ import { isNonNullable as isNonNullable3 } from "@dxos/util";
1264
+ var SKIP_BLOCKS = [
1265
+ "text"
1266
+ ];
1267
+ var ExecutionGraph = class {
1268
+ _skipBlocks;
1269
+ // TODO(dmaretskyi): Evolve the internal state to support chats, functions, circuit workflows, etc.
1270
+ _commits = [];
1271
+ _branchNames = /* @__PURE__ */ new Set();
1272
+ _lastBlockId;
1273
+ // Tool call tracking.
1274
+ _toolCallCommitIds = /* @__PURE__ */ new Map();
1275
+ _lastCommitByBranch = /* @__PURE__ */ new Map();
1276
+ _pendingToolResults = /* @__PURE__ */ new Map();
1277
+ constructor(_skipBlocks = SKIP_BLOCKS) {
1278
+ this._skipBlocks = _skipBlocks;
1279
+ }
1280
+ /**
1281
+ * Adds events to the graph.
1282
+ */
1283
+ addEvents(events) {
1284
+ const sortedEvents = this.sortObjectsByCreated(events);
1285
+ for (const event of sortedEvents) {
1286
+ if (Obj7.instanceOf(Message4.Message, event)) {
1287
+ this._processMessage(event);
1288
+ } else if (Obj7.instanceOf(AgentStatus, event)) {
1289
+ this._processAgentStatus(event);
1290
+ }
1291
+ }
1292
+ }
1293
+ /**
1294
+ * Processes a message event and creates commits for its blocks.
1295
+ */
1296
+ _processMessage(message) {
1297
+ const messageCommits = messageToCommits(message, this._lastBlockId, this._toolCallCommitIds, this._lastCommitByBranch, this._skipBlocks);
1298
+ this._commits.push(...messageCommits);
1299
+ messageCommits.forEach((commit) => this._branchNames.add(commit.branch));
1300
+ this._trackToolCalls(messageCommits);
1301
+ if (messageCommits.length > 0) {
1302
+ this._lastBlockId = messageCommits[messageCommits.length - 1].id;
1303
+ }
1304
+ }
1305
+ /**
1306
+ * Processes an AgentStatus event.
1307
+ */
1308
+ _processAgentStatus(event) {
1309
+ const branch = this._getToolCallBranch(event.parentMessage, event.toolCallId);
1310
+ this._branchNames.add(branch);
1311
+ const agentStatusCommit = {
1312
+ id: event.id,
1313
+ branch,
1314
+ message: event.message,
1315
+ icon: "ph--flag--regular",
1316
+ parents: this._getAgentStatusParents(event),
1317
+ timestamp: new Date(event.created)
1318
+ };
1319
+ this._commits.push(agentStatusCommit);
1320
+ this._lastBlockId = event.id;
1321
+ if (event.toolCallId) {
1322
+ this._lastCommitByBranch.set(branch, event.id);
1323
+ this._updatePendingToolResults(event.toolCallId, event.id);
1324
+ }
1325
+ }
1326
+ /**
1327
+ * Stable sort: objects with 'created' field are sorted by it, others remain in place.
1328
+ */
1329
+ sortObjectsByCreated(objects) {
1330
+ const sortedObjects = objects.slice();
1331
+ const createdObjects = [];
1332
+ sortedObjects.forEach((obj, idx) => {
1333
+ if (obj && typeof obj.created === "string") {
1334
+ createdObjects.push({
1335
+ idx,
1336
+ obj
1337
+ });
1338
+ }
1339
+ });
1340
+ createdObjects.sort((a, b) => {
1341
+ const aDate = new Date(a.obj.created).getTime();
1342
+ const bDate = new Date(b.obj.created).getTime();
1343
+ return aDate - bDate;
1344
+ });
1345
+ let createdIdx = 0;
1346
+ return sortedObjects.map((obj, _idx) => {
1347
+ if (obj && typeof obj.created === "string") {
1348
+ return createdObjects[createdIdx++].obj;
1349
+ }
1350
+ return obj;
1351
+ });
1352
+ }
1353
+ /**
1354
+ * Returns the current state of the graph.
1355
+ */
1356
+ getGraph(lastRequest = false) {
1357
+ const idx = lastRequest ? this._commits.findLastIndex((c) => c.tags?.includes("user")) : -1;
1358
+ const commits = idx === -1 ? this._commits : this._commits.slice(idx);
1359
+ return {
1360
+ branches: Array.from(this._branchNames),
1361
+ commits
1362
+ };
1363
+ }
1364
+ /**
1365
+ * Tracks tool calls and handles pending tool result updates.
1366
+ */
1367
+ _trackToolCalls(commits) {
1368
+ commits.forEach((commit) => {
1369
+ if (this._isToolCallCommit(commit)) {
1370
+ const toolCallId = this._extractToolCallId(commit.id);
1371
+ if (toolCallId) {
1372
+ this._toolCallCommitIds.set(toolCallId, commit.id);
1373
+ }
1374
+ }
1375
+ if (this._isToolResultCommit(commit)) {
1376
+ const toolCallId = this._extractToolCallId(commit.id);
1377
+ if (toolCallId) {
1378
+ this._pendingToolResults.set(toolCallId, commit.id);
1379
+ this._handleLateToolResultUpdate(toolCallId, commit.id);
1380
+ }
1381
+ }
1382
+ this._lastCommitByBranch.set(commit.branch, commit.id);
1383
+ });
1384
+ }
1385
+ /**
1386
+ * Updates pending tool results to point to an AgentStatus event.
1387
+ */
1388
+ _updatePendingToolResults(toolCallId, agentStatusId) {
1389
+ const toolResultId = this._pendingToolResults.get(toolCallId);
1390
+ if (!toolResultId) {
1391
+ return;
1392
+ }
1393
+ const toolResultCommit = this._commits.find((c) => c.id === toolResultId);
1394
+ if (!toolResultCommit) {
1395
+ return;
1396
+ }
1397
+ const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);
1398
+ if (!toolCallCommitId) {
1399
+ return;
1400
+ }
1401
+ const toolCallIndex = toolResultCommit.parents.indexOf(toolCallCommitId);
1402
+ if (toolCallIndex !== -1) {
1403
+ toolResultCommit.parents[toolCallIndex] = agentStatusId;
1404
+ }
1405
+ this._pendingToolResults.delete(toolCallId);
1406
+ }
1407
+ /**
1408
+ * Handles late updates when AgentStatus is processed before tool result.
1409
+ */
1410
+ _handleLateToolResultUpdate(toolCallId, toolResultId) {
1411
+ const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);
1412
+ if (!toolCallCommitId) {
1413
+ return;
1414
+ }
1415
+ const messageId = toolCallCommitId.split("_toolCall_")[0];
1416
+ const toolCallBranch = `${messageId}_${toolCallId}`;
1417
+ const agentStatusCommitId = this._lastCommitByBranch.get(toolCallBranch);
1418
+ if (agentStatusCommitId && agentStatusCommitId !== toolCallCommitId) {
1419
+ const toolResultCommit = this._commits.find((c) => c.id === toolResultId);
1420
+ if (toolResultCommit) {
1421
+ const toolCallIndex = toolResultCommit.parents.indexOf(toolCallCommitId);
1422
+ if (toolCallIndex !== -1) {
1423
+ toolResultCommit.parents[toolCallIndex] = agentStatusCommitId;
1424
+ }
1425
+ }
1426
+ this._pendingToolResults.delete(toolCallId);
1427
+ }
1428
+ }
1429
+ /**
1430
+ * Gets the branch name for a tool call.
1431
+ */
1432
+ _getToolCallBranch(parentMessage, toolCallId) {
1433
+ if (toolCallId) {
1434
+ return toolCallId;
1435
+ }
1436
+ return parentMessage || "main";
1437
+ }
1438
+ /**
1439
+ * Gets the parents for an AgentStatus commit.
1440
+ */
1441
+ _getAgentStatusParents(event) {
1442
+ if (event.parentMessage && event.toolCallId) {
1443
+ return [
1444
+ getToolCallId(event.parentMessage, event.toolCallId)
1445
+ ];
1446
+ }
1447
+ return [];
1448
+ }
1449
+ /**
1450
+ * Checks if a commit is a tool call commit.
1451
+ */
1452
+ _isToolCallCommit(commit) {
1453
+ return commit.message.includes("Calling tool");
1454
+ }
1455
+ /**
1456
+ * Checks if a commit is a tool result commit.
1457
+ */
1458
+ _isToolResultCommit(commit) {
1459
+ return commit.message.includes("Tool call succeeded") || commit.message.includes("Tool error:");
1460
+ }
1461
+ /**
1462
+ * Extracts tool call ID from a commit ID.
1463
+ */
1464
+ _extractToolCallId(commitId) {
1465
+ const toolCallMatch = commitId.match(/_toolCall_(.+)$/);
1466
+ const toolResultMatch = commitId.match(/_toolResult_(.+)$/);
1467
+ return toolCallMatch?.[1] || toolResultMatch?.[1];
1468
+ }
1469
+ };
1470
+ var messageToCommits = (message, lastBlockId, toolCallIds, lastCommitByBranch, skipBlocks) => {
1471
+ let previousBlockId = lastBlockId;
1472
+ return message.blocks.map((block, idx) => {
1473
+ const branch = getMessageBranch(message);
1474
+ const parents = getBlockParents(block, previousBlockId, message, toolCallIds, lastCommitByBranch);
1475
+ if (skipBlocks?.includes(block._tag)) {
1476
+ return null;
1477
+ }
1478
+ const commit = createBlockCommit(block, message, branch, parents, idx);
1479
+ if (commit) {
1480
+ previousBlockId = commit.id;
1481
+ }
1482
+ return commit;
1483
+ }).filter(isNonNullable3);
1484
+ };
1485
+ var getBlockParents = (block, previousBlockId, message, toolCallIds, lastCommitByBranch) => {
1486
+ const parents = [];
1487
+ if (block._tag === "toolResult") {
1488
+ if (previousBlockId) {
1489
+ parents.push(previousBlockId);
1490
+ }
1491
+ const toolCallCommitId = toolCallIds?.get(block.toolCallId);
1492
+ if (toolCallCommitId) {
1493
+ const toolCallBranch = getToolCallBranchFromCommitId(toolCallCommitId, block.toolCallId);
1494
+ const lastBlockFromToolCallBranch = lastCommitByBranch?.get(toolCallBranch);
1495
+ if (lastBlockFromToolCallBranch) {
1496
+ parents.push(lastBlockFromToolCallBranch);
1497
+ } else {
1498
+ parents.push(toolCallCommitId);
1499
+ }
1500
+ }
1501
+ } else {
1502
+ if (previousBlockId) {
1503
+ parents.push(previousBlockId);
1504
+ } else {
1505
+ const toolCallParent = getParentId(message);
1506
+ if (toolCallParent) {
1507
+ parents.push(toolCallParent);
1508
+ }
1509
+ }
1510
+ }
1511
+ return parents;
1512
+ };
1513
+ var createBlockCommit = (block, message, branch, parents, idx) => {
1514
+ const timestamp = new Date(message.created);
1515
+ switch (block._tag) {
1516
+ case "text":
1517
+ if (!block.text.trim().length) {
1518
+ return null;
1519
+ }
1520
+ return {
1521
+ id: getGenericBlockId(message.id, idx),
1522
+ branch,
1523
+ parents,
1524
+ timestamp,
1525
+ ...message.sender.role === "user" ? {
1526
+ icon: "ph--user--regular",
1527
+ tags: [
1528
+ "user"
1529
+ ],
1530
+ message: "Processing request..."
1531
+ } : {
1532
+ icon: "ph--drone--regular",
1533
+ message: `Response (${block.text.split(" ").length} words)`
1534
+ }
1535
+ };
1536
+ case "toolCall":
1537
+ return {
1538
+ id: getToolCallId(message.id, block.toolCallId),
1539
+ branch,
1540
+ parents,
1541
+ timestamp,
1542
+ icon: "ph--wrench--regular",
1543
+ level: LogLevel.INFO,
1544
+ message: `Calling tool (${block.name})`
1545
+ };
1546
+ case "toolResult":
1547
+ return {
1548
+ id: getToolResultId(message.id, block.toolCallId),
1549
+ branch,
1550
+ parents,
1551
+ timestamp,
1552
+ icon: block.error ? "ph--x-circle--regular" : "ph--check-circle--regular",
1553
+ level: block.error ? LogLevel.ERROR : LogLevel.INFO,
1554
+ message: block.error ? "Tool error: " + block.error : "Tool call succeeded"
1555
+ };
1556
+ case "stats":
1557
+ return {
1558
+ id: getGenericBlockId(message.id, idx),
1559
+ branch,
1560
+ parents,
1561
+ timestamp,
1562
+ icon: "ph--rocket--regular",
1563
+ level: LogLevel.INFO,
1564
+ message: ContentBlock3.createStatsMessage(block)
1565
+ };
1566
+ case "status":
1567
+ return {
1568
+ id: getGenericBlockId(message.id, idx),
1569
+ branch,
1570
+ parents,
1571
+ timestamp,
1572
+ message: block.statusText,
1573
+ level: LogLevel.INFO,
1574
+ icon: "ph--flag--regular"
1575
+ };
1576
+ case "reasoning":
1577
+ return {
1578
+ id: getGenericBlockId(message.id, idx),
1579
+ branch,
1580
+ parents,
1581
+ timestamp,
1582
+ message: block.reasoningText ?? "Thinking...",
1583
+ icon: "ph--brain--regular"
1584
+ };
1585
+ case "reference":
1586
+ return {
1587
+ id: getGenericBlockId(message.id, idx),
1588
+ branch,
1589
+ parents,
1590
+ timestamp,
1591
+ icon: "ph--link--regular",
1592
+ message: stringifyRef(block.reference)
1593
+ };
1594
+ default:
1595
+ return null;
1596
+ }
1597
+ };
1598
+ var getToolCallBranchFromCommitId = (toolCallCommitId, toolCallId) => {
1599
+ const messageId = toolCallCommitId.split("_toolCall_")[0];
1600
+ return `${messageId}_${toolCallId}`;
1601
+ };
1602
+ var getToolCallId = (messageId, toolCallId) => `${messageId}_toolCall_${toolCallId}`;
1603
+ var getToolResultId = (messageId, toolCallId) => `${messageId}_toolResult_${toolCallId}`;
1604
+ var getGenericBlockId = (messageId, idx) => `${messageId}_block_${idx}`;
1605
+ var getBranchName = (options) => {
1606
+ if (options.toolCallId) {
1607
+ return options.toolCallId;
1608
+ } else if (options.parentMessage) {
1609
+ return options.parentMessage;
1610
+ } else {
1611
+ return "main";
1612
+ }
1613
+ };
1614
+ var getMessageBranch = (message) => {
1615
+ return getBranchName({
1616
+ parentMessage: message.parentMessage,
1617
+ toolCallId: message.properties?.[MESSAGE_PROPERTY_TOOL_CALL_ID]
1618
+ });
1619
+ };
1620
+ var getParentId = (message) => {
1621
+ if (message.parentMessage && message.properties?.[MESSAGE_PROPERTY_TOOL_CALL_ID]) {
1622
+ return getToolCallId(message.parentMessage, message.properties[MESSAGE_PROPERTY_TOOL_CALL_ID]);
1623
+ } else {
1624
+ return void 0;
1625
+ }
1626
+ };
1627
+ var stringifyRef = (ref) => {
1628
+ if (ref.target) {
1629
+ return stringifyObject(ref.target);
1630
+ }
1631
+ return ref.dxn.asEchoDXN()?.echoId ?? ref.dxn.asQueueDXN()?.objectId ?? "";
1632
+ };
1633
+ var stringifyObject = (obj) => {
1634
+ return Obj7.getLabel(obj) ?? Obj7.getTypename(obj) ?? obj.id;
1635
+ };
1636
+
1637
+ // src/templates/system.ts
1638
+ import defaultsDeep from "lodash.defaultsdeep";
1639
+ import { Template as Template2 } from "@dxos/compute";
1640
+
1641
+ // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/instructions/format.tpl?raw
1642
+ var format_default = "{{! System Core }}\n\n## Input Formats\n\n### Blueprints\n\nYou may be provided with Blueprint definitions that include specific instructions and tools for a given set of tasks.\nBlue print instructions will be enclosed in a <blueprint> tag.\n\n### Context objects\n\nYou may be provided with references to objects that are relevant to the current prompt.\nObjects will be in the form of a <object> tag with a <dxn> element that is the unique key of the object required by many tools.\nThe <typename> element is the type of the object.\n\n<object>\n <dxn>object-id</dxn>\n <typename>example.com/type/TypeName</typename>\n</object>\n\n## Response Formats\n\nIt is very important to respond in the correct format.\nYou response must be valid Markdown.\nIn some cases you should respond with well-formed XML tags along with the content.\nCode snippets should use 2-space indents.\n\n{{#if cot}}\nBefore responding, explain your reasoning and include your detailed chain-of-thought enclosed in a <cot> tag.\nThe <cot> tag should be the first thing in your response.\n{{/if}}\n\n## Block references\n\nYou can reply with a block reference for objects if you have the DXN. For example:\n\n<object>\n <dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n<object>\n <dxn>dxn:echo:@:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n\n### Suggestions\n\nEach suggestion must in the form of a proposed action enclosed in a <suggestion> tag.\nExample: <suggestion>Show on a map</suggestion>\nDo not use bullets when listing suggestions.\n\n### Multiple choice questions\n\nYou may ask multiple choice questions by wrapping consise options inside <option> tags inside a well formed <select> tag.\nExample: <select><option>Yes</option><option>No</option></select>\n\n## Context\n\nThe current date and time is {{DATETIME}}.\n";
1643
+
1644
+ // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/instructions/system.tpl?raw
1645
+ 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## Navigation\n\n- When the user asks to open, go to, navigate to, or show a specific document, page, or object, use the navigation tools instead of loading content inline.\n- First, call the Resolve navigation targets tool to find the navigation path for the requested item.\n - Without arguments, it returns available pages that can be navigated to.\n - With a DXN in the query, it resolves that specific object to a navigation path.\n- If you know the object's DXN (e.g. from a database query or context objects), pass it in the query to get the exact navigation path.\n- Then, call the Open tool with the resolved navigation path(s) in the subject array to navigate the user to that item.\n- Do not respond with the document's content when the user asks to open it \u2014 open it in the main content area instead.\n- If multiple targets match, present the options to the user and let them choose which to open.\n\n## Response format\n\n- When updating the user about the progress of the work you are doing, put the update in a <status> XML tag.\n- Only when you need to show the result to the user or ask a question use a text block without status tags.\n\n<example>\n// reasoning...\n<status>Looking for emails from Depot</status>\n// tool call..\n<status>Found 2 emails from Depot.</status>\n<status>Loading email details</status>\n// tool call\n<status>Located mailbox</status>\nI found **2 emails from Depot**:\n</example>\n\nDo not do (no status tags):\n\n<incorrect_example>\n// reasoning...\n// tool call..\nI found 2 emails from Depot. Let me load their details:\n// tool call\nI found **2 emails from Depot**:\n</incorrect_example>\n\n- Avoid using plain text to tell the user what you are about to do; instead, use status blocks.\n- WRONG: Let me get...\n- CORRECT: <status>Getting...</status>";
1646
+
1647
+ // src/templates/system.ts
1648
+ var createSystemPrompt = (options = {}) => Template2.process(format_default, defaultsDeep(options, {
1649
+ DATETIME: (/* @__PURE__ */ new Date()).toISOString()
1650
+ }));
1651
+ var SYSTEM_ID = "01K2J2FZWH39F55CS7B26GP1Q3";
1652
+ var templates = {
1653
+ system: Template2.make({
1654
+ id: SYSTEM_ID,
1655
+ source: system_default
1656
+ })
1657
+ };
1658
+ export {
1659
+ AgentRequestBegin,
1660
+ AgentRequestEnd,
1661
+ AiAssistantError,
1662
+ AiContextBinder,
1663
+ AiContextService,
1664
+ AiModelError,
1665
+ AiRequest,
1666
+ AiSession,
1667
+ AiSessionService,
1668
+ ArtifactDiffResolver,
1669
+ ArtifactId,
1670
+ Bindings,
1671
+ CompleteBlock,
1672
+ ContextBinding,
1673
+ ExecutionGraph,
1674
+ GenerationObserver,
1675
+ PartialBlock,
1676
+ RefFromLLM,
1677
+ ToolExecutionServices,
1678
+ VersionPin,
1679
+ applyDiffs,
1680
+ computeDiffsWithCursors,
1681
+ createArtifactElement,
1682
+ createSystemPrompt,
1683
+ createToolkit,
1684
+ formatSystemPrompt,
1685
+ formatUserPrompt,
1686
+ getOperationFromTool,
1687
+ makeToolExecutionService,
1688
+ makeToolExecutionServiceFromOperationInvoker,
1689
+ makeToolResolverFromOperations,
1690
+ reduceDiffs,
1691
+ templates
1692
+ };
1693
+ //# sourceMappingURL=index.mjs.map