@dxos/assistant 0.8.4-main.fffef41 → 0.8.4-staging.60fe92afc8

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 (174) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +2 -1
  3. package/dist/lib/{browser → neutral}/extraction/index.mjs +42 -59
  4. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  5. package/dist/lib/neutral/index.mjs +1886 -0
  6. package/dist/lib/neutral/index.mjs.map +7 -0
  7. package/dist/lib/neutral/meta.json +1 -0
  8. package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
  9. package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
  10. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  11. package/dist/types/src/extraction/extraction.d.ts +1649 -317
  12. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  13. package/dist/types/src/extraction/index.d.ts +0 -1
  14. package/dist/types/src/extraction/index.d.ts.map +1 -1
  15. package/dist/types/src/extraction/quotes.d.ts +2 -2
  16. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  17. package/dist/types/src/functions/services.d.ts +14 -16
  18. package/dist/types/src/functions/services.d.ts.map +1 -1
  19. package/dist/types/src/index.d.ts +2 -5
  20. package/dist/types/src/index.d.ts.map +1 -1
  21. package/dist/types/src/request/AiRequest.d.ts +308 -0
  22. package/dist/types/src/request/AiRequest.d.ts.map +1 -0
  23. package/dist/types/src/{session → request}/artifact-diff.d.ts +4 -4
  24. package/dist/types/src/request/artifact-diff.d.ts.map +1 -0
  25. package/dist/types/src/request/format.d.ts +15 -0
  26. package/dist/types/src/request/format.d.ts.map +1 -0
  27. package/dist/types/src/request/index.d.ts +4 -0
  28. package/dist/types/src/request/index.d.ts.map +1 -0
  29. package/dist/types/src/{session → request}/observer.d.ts +4 -3
  30. package/dist/types/src/request/observer.d.ts.map +1 -0
  31. package/dist/types/src/{session → request}/version-pin.d.ts +4 -4
  32. package/dist/types/src/request/version-pin.d.ts.map +1 -0
  33. package/dist/types/src/session/AiContext.d.ts +178 -0
  34. package/dist/types/src/session/AiContext.d.ts.map +1 -0
  35. package/dist/types/src/session/AiContext.test.d.ts +2 -0
  36. package/dist/types/src/session/AiContext.test.d.ts.map +1 -0
  37. package/dist/types/src/session/AiSession.d.ts +79 -0
  38. package/dist/types/src/session/AiSession.d.ts.map +1 -0
  39. package/dist/types/src/session/AiSession.test.d.ts +2 -0
  40. package/dist/types/src/session/AiSession.test.d.ts.map +1 -0
  41. package/dist/types/src/session/SessionLink.d.ts +17 -0
  42. package/dist/types/src/session/SessionLink.d.ts.map +1 -0
  43. package/dist/types/src/session/SessionLoader.d.ts +15 -0
  44. package/dist/types/src/session/SessionLoader.d.ts.map +1 -0
  45. package/dist/types/src/session/SessionLoader.test.d.ts +2 -0
  46. package/dist/types/src/session/SessionLoader.test.d.ts.map +1 -0
  47. package/dist/types/src/session/index.d.ts +4 -5
  48. package/dist/types/src/session/index.d.ts.map +1 -1
  49. package/dist/types/src/session/toolkit.d.ts +10 -9
  50. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  51. package/dist/types/src/templates/system.d.ts +12 -3
  52. package/dist/types/src/templates/system.d.ts.map +1 -1
  53. package/dist/types/src/util/artifact.d.ts +18 -0
  54. package/dist/types/src/util/artifact.d.ts.map +1 -0
  55. package/dist/types/src/{diff.d.ts → util/diff.d.ts} +4 -2
  56. package/dist/types/src/util/diff.d.ts.map +1 -0
  57. package/dist/types/src/{diff.test.d.ts.map → util/diff.test.d.ts.map} +1 -1
  58. package/dist/types/src/util/error-handling.d.ts.map +1 -0
  59. package/dist/types/src/{errors.d.ts → util/errors.d.ts} +24 -28
  60. package/dist/types/src/util/errors.d.ts.map +1 -0
  61. package/dist/types/src/{execution-graph.d.ts → util/execution-graph.d.ts} +2 -2
  62. package/dist/types/src/util/execution-graph.d.ts.map +1 -0
  63. package/dist/types/src/util/execution-graph.test.d.ts.map +1 -0
  64. package/dist/types/src/util/index.d.ts +7 -0
  65. package/dist/types/src/util/index.d.ts.map +1 -0
  66. package/dist/types/src/util/tracing.d.ts +296 -0
  67. package/dist/types/src/util/tracing.d.ts.map +1 -0
  68. package/dist/types/tsconfig.tsbuildinfo +1 -1
  69. package/package.json +36 -44
  70. package/src/extraction/extraction-ner-function/index.ts +0 -1
  71. package/src/extraction/extraction.ts +47 -18
  72. package/src/extraction/index.ts +0 -1
  73. package/src/extraction/quotes.test.ts +2 -2
  74. package/src/extraction/quotes.ts +6 -8
  75. package/src/functions/services.ts +129 -63
  76. package/src/index.ts +2 -5
  77. package/src/request/AiRequest.ts +387 -0
  78. package/src/{session → request}/artifact-diff.ts +4 -4
  79. package/src/{session → request}/format.ts +28 -25
  80. package/src/request/index.ts +8 -0
  81. package/src/{session → request}/observer.ts +4 -1
  82. package/src/{session → request}/version-pin.ts +6 -5
  83. package/src/session/AiContext.test.ts +49 -0
  84. package/src/session/AiContext.ts +420 -0
  85. package/src/session/AiSession.test.ts +111 -0
  86. package/src/session/AiSession.ts +328 -0
  87. package/src/session/SessionLink.ts +23 -0
  88. package/src/session/SessionLoader.test.ts +115 -0
  89. package/src/session/SessionLoader.ts +55 -0
  90. package/src/session/index.ts +4 -5
  91. package/src/session/toolkit.ts +27 -28
  92. package/src/templates/instructions/format.tpl +0 -4
  93. package/src/templates/instructions/system.tpl +50 -2
  94. package/src/templates/system.ts +7 -6
  95. package/src/util/artifact.ts +96 -0
  96. package/src/util/diff.test.ts +74 -0
  97. package/src/{diff.ts → util/diff.ts} +14 -5
  98. package/src/{session → util}/error-handling.ts +3 -2
  99. package/src/util/errors.ts +15 -0
  100. package/src/{execution-graph.test.ts → util/execution-graph.test.ts} +4 -4
  101. package/src/{execution-graph.ts → util/execution-graph.ts} +30 -19
  102. package/src/util/index.ts +10 -0
  103. package/src/util/tracing.ts +60 -0
  104. package/dist/lib/browser/extraction/index.mjs.map +0 -7
  105. package/dist/lib/browser/index.mjs +0 -1290
  106. package/dist/lib/browser/index.mjs.map +0 -7
  107. package/dist/lib/browser/meta.json +0 -1
  108. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  109. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  110. package/dist/lib/node-esm/extraction/index.mjs +0 -226
  111. package/dist/lib/node-esm/extraction/index.mjs.map +0 -7
  112. package/dist/lib/node-esm/index.mjs +0 -1291
  113. package/dist/lib/node-esm/index.mjs.map +0 -7
  114. package/dist/lib/node-esm/meta.json +0 -1
  115. package/dist/types/src/conversation/context.d.ts +0 -103
  116. package/dist/types/src/conversation/context.d.ts.map +0 -1
  117. package/dist/types/src/conversation/conversation.d.ts +0 -41
  118. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  119. package/dist/types/src/conversation/index.d.ts +0 -3
  120. package/dist/types/src/conversation/index.d.ts.map +0 -1
  121. package/dist/types/src/diff.d.ts.map +0 -1
  122. package/dist/types/src/errors.d.ts.map +0 -1
  123. package/dist/types/src/execution-graph.d.ts.map +0 -1
  124. package/dist/types/src/execution-graph.test.d.ts.map +0 -1
  125. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
  126. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
  127. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
  128. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
  129. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
  130. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
  131. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -345
  132. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
  133. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
  134. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
  135. package/dist/types/src/session/GenericToolkit.d.ts +0 -84
  136. package/dist/types/src/session/GenericToolkit.d.ts.map +0 -1
  137. package/dist/types/src/session/artifact-diff.d.ts.map +0 -1
  138. package/dist/types/src/session/error-handling.d.ts.map +0 -1
  139. package/dist/types/src/session/format.d.ts +0 -12
  140. package/dist/types/src/session/format.d.ts.map +0 -1
  141. package/dist/types/src/session/format.test.d.ts +0 -2
  142. package/dist/types/src/session/format.test.d.ts.map +0 -1
  143. package/dist/types/src/session/observer.d.ts.map +0 -1
  144. package/dist/types/src/session/session.d.ts +0 -51
  145. package/dist/types/src/session/session.d.ts.map +0 -1
  146. package/dist/types/src/session/session.test.d.ts +0 -2
  147. package/dist/types/src/session/session.test.d.ts.map +0 -1
  148. package/dist/types/src/session/version-pin.d.ts.map +0 -1
  149. package/dist/types/src/types/artifact.d.ts +0 -20
  150. package/dist/types/src/types/artifact.d.ts.map +0 -1
  151. package/dist/types/src/types/index.d.ts +0 -2
  152. package/dist/types/src/types/index.d.ts.map +0 -1
  153. package/src/conversation/context.ts +0 -186
  154. package/src/conversation/conversation.ts +0 -128
  155. package/src/conversation/index.ts +0 -6
  156. package/src/diff.test.ts +0 -43
  157. package/src/errors.ts +0 -15
  158. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -84
  159. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -62
  160. package/src/extraction/extraction-llm-function/index.ts +0 -5
  161. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -116
  162. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -56
  163. package/src/session/GenericToolkit.ts +0 -130
  164. package/src/session/format.test.ts +0 -61
  165. package/src/session/session.conversations.json +0 -1
  166. package/src/session/session.test.ts +0 -149
  167. package/src/session/session.ts +0 -213
  168. package/src/types/artifact.ts +0 -71
  169. package/src/types/index.ts +0 -5
  170. /package/dist/lib/{browser → neutral}/chunk-J5LGTIGS.mjs +0 -0
  171. /package/dist/lib/{browser → neutral}/chunk-J5LGTIGS.mjs.map +0 -0
  172. /package/dist/types/src/{diff.test.d.ts → util/diff.test.d.ts} +0 -0
  173. /package/dist/types/src/{session → util}/error-handling.d.ts +0 -0
  174. /package/dist/types/src/{execution-graph.test.d.ts → util/execution-graph.test.d.ts} +0 -0
@@ -1,1291 +0,0 @@
1
- import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import {
3
- __export
4
- } from "./chunk-HSLMI22Q.mjs";
5
-
6
- // src/conversation/context.ts
7
- import { computed } from "@preact/signals-core";
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";
12
- import { Blueprint } from "@dxos/blueprints";
13
- import { Resource } from "@dxos/context";
14
- import { DXN, Filter, Obj, Query, Type } from "@dxos/echo";
15
- import { invariant } from "@dxos/invariant";
16
- import { ComplexSet } from "@dxos/util";
17
- var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/conversation/context.ts";
18
- var ContextBinding = Schema.Struct({
19
- blueprints: Schema.Struct({
20
- added: Schema.Array(Type.Ref(Blueprint.Blueprint)),
21
- removed: Schema.Array(Type.Ref(Blueprint.Blueprint))
22
- }),
23
- // TODO(burdon): Type.Expando => Type.Obj (or Obj.Any?)
24
- objects: Schema.Struct({
25
- added: Schema.Array(Type.Ref(Type.Expando)),
26
- removed: Schema.Array(Type.Ref(Type.Expando))
27
- })
28
- }).pipe(Type.Obj({
29
- typename: "dxos.org/type/ContextBinding",
30
- version: "0.1.0"
31
- }));
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);
36
- toJSON() {
37
- return {
38
- blueprints: Array2.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),
39
- objects: Array2.fromIterable(this.objects).map((ref) => ref.dxn.toString())
40
- };
41
- }
42
- };
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
- }
109
- /**
110
- * Asynchronous query of all bindings.
111
- */
112
- async query() {
113
- const { objects } = await this._queue.query(Query.select(Filter.everything())).run();
114
- return this._reduce(objects);
115
- }
116
- // TODO(burdon): Pass in Blueprint obj (from registry?) and create reference.
117
- async bind(props) {
118
- const blueprints = props.blueprints?.filter((ref) => !this.blueprints.peek().find((b) => b.dxn.toString() === ref.dxn.toString())) ?? [];
119
- const objects = props.objects?.filter((ref) => !this.objects.peek().find((o) => o.dxn.toString() === ref.dxn.toString())) ?? [];
120
- if (!blueprints.length && !objects.length) {
121
- return;
122
- }
123
- await this._queue.append([
124
- Obj.make(ContextBinding, {
125
- blueprints: {
126
- added: blueprints,
127
- removed: []
128
- },
129
- objects: {
130
- added: objects,
131
- removed: []
132
- }
133
- })
134
- ]);
135
- }
136
- async unbind(props) {
137
- if (!props.blueprints?.length && !props.objects?.length) {
138
- return;
139
- }
140
- await this._queue.append([
141
- Obj.make(ContextBinding, {
142
- blueprints: {
143
- added: [],
144
- removed: props.blueprints ?? []
145
- },
146
- objects: {
147
- added: [],
148
- removed: props.objects ?? []
149
- }
150
- })
151
- ]);
152
- }
153
- _reduce(items) {
154
- return Function.pipe(items, Array2.filter(Obj.instanceOf(ContextBinding)), Array2.reduce(new Bindings(), (context, item) => {
155
- item.blueprints.removed.forEach((ref) => context.blueprints.delete(ref));
156
- item.blueprints.added.forEach((ref) => context.blueprints.add(ref));
157
- item.objects.removed.forEach((ref) => {
158
- for (const obj of context.objects) {
159
- if (DXN.equalsEchoId(obj.dxn, ref.dxn)) {
160
- context.objects.delete(obj);
161
- }
162
- }
163
- });
164
- item.objects.added.forEach((ref) => context.objects.add(ref));
165
- return context;
166
- }));
167
- }
168
- };
169
- var AiContextService = class extends Context.Tag("@dxos/assistant/AiContextService")() {
170
- };
171
-
172
- // src/conversation/conversation.ts
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";
236
- import { Obj as Obj2 } from "@dxos/echo";
237
- import { DatabaseService, ObjectVersion } from "@dxos/echo-db";
238
- import { log } from "@dxos/log";
239
- import { Message } from "@dxos/types";
240
- import { trim } from "@dxos/util";
241
-
242
- // src/errors.ts
243
- import { BaseError } from "@dxos/errors";
244
- var AiModelError = class extends BaseError.extend("AI_MODEL_ERROR", "AI model error") {
245
- };
246
- var AiAssistantError = class extends BaseError.extend("AI_ASSISTANT_ERROR", "AI assistant error") {
247
- };
248
-
249
- // src/session/format.ts
250
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/assistant/src/session/format.ts";
251
- var formatSystemPrompt = ({ system, blueprints = [], objects = [] }) => Effect2.gen(function* () {
252
- const blueprintDefs = yield* Function3.pipe(blueprints, Effect2.forEach((blueprint) => Effect2.succeed(blueprint.instructions)), Effect2.flatMap(Effect2.forEach((template) => DatabaseService.loadOption(template.source))), Effect2.map(Array4.filter(Option.isSome)), Effect2.map(Array4.map((template) => trim`
253
- <blueprint>
254
- ${Template.process(template.value.content)}
255
- </blueprint>
256
- `)), Effect2.map((blueprints2) => blueprints2.length > 0 ? [
257
- "## Blueprints Definitions",
258
- ...blueprints2
259
- ].join("\n\n") : void 0));
260
- const objectDefs = yield* Function3.pipe(objects, Effect2.forEach((object) => Effect2.succeed(trim`
261
- <object>
262
- <dxn>${Obj2.getDXN(object)}</dxn>
263
- <typename>${Obj2.getTypename(object)}</typename>
264
- </object>
265
- `)), Effect2.map((objects2) => objects2.length > 0 ? [
266
- "## Context Objects",
267
- ...objects2
268
- ].join("\n\n") : void 0));
269
- return yield* Function3.pipe(Effect2.succeed([
270
- system,
271
- blueprintDefs,
272
- objectDefs
273
- ].filter((def) => def !== void 0)), Effect2.map((parts) => parts.join("\n\n")));
274
- });
275
- var formatUserPrompt = ({ prompt, history = [] }) => Effect2.gen(function* () {
276
- const blocks = [];
277
- const artifactDiffResolver = yield* Effect2.serviceOption(ArtifactDiffResolver);
278
- if (Option.isSome(artifactDiffResolver)) {
279
- const versions = gatherObjectVersions(history);
280
- const artifactDiff = yield* Effect2.tryPromise({
281
- try: () => artifactDiffResolver.value.resolve([
282
- ...versions.entries()
283
- ].map(([id, version]) => ({
284
- id,
285
- lastVersion: version
286
- }))),
287
- catch: AiAssistantError.wrap({
288
- message: "Artifact diff resolution error"
289
- })
290
- });
291
- log("version", {
292
- artifactDiff,
293
- versions
294
- }, {
295
- F: __dxlog_file2,
296
- L: 95,
297
- S: this,
298
- C: (f, a) => f(...a)
299
- });
300
- for (const [id, { version }] of [
301
- ...artifactDiff.entries()
302
- ]) {
303
- if (ObjectVersion.equals(version, versions.get(id))) {
304
- artifactDiff.delete(id);
305
- continue;
306
- }
307
- blocks.push({
308
- _tag: "anchor",
309
- objectId: id,
310
- version
311
- });
312
- }
313
- if (artifactDiff.size > 0) {
314
- blocks.push(createArtifactUpdateBlock(artifactDiff));
315
- }
316
- }
317
- return Obj2.make(Message.Message, {
318
- created: (/* @__PURE__ */ new Date()).toISOString(),
319
- sender: {
320
- role: "user"
321
- },
322
- blocks: [
323
- ...blocks,
324
- {
325
- _tag: "text",
326
- text: prompt
327
- }
328
- ]
329
- });
330
- });
331
- var gatherObjectVersions = (messages) => {
332
- const artifactIds = /* @__PURE__ */ new Map();
333
- for (const message of messages) {
334
- for (const block of message.blocks) {
335
- if (block._tag === "anchor") {
336
- artifactIds.set(block.objectId, block.version);
337
- }
338
- }
339
- }
340
- return artifactIds;
341
- };
342
- var createArtifactUpdateBlock = (artifactDiff) => {
343
- return {
344
- _tag: "text",
345
- // TODO(dmaretskyi): Does this need to be a special content-block?
346
- disposition: "artifact-update",
347
- text: trim`
348
- The following artifacts have been updated since the last message:
349
- ${[
350
- ...artifactDiff.entries()
351
- ].map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `
352
- ${diff}` : ""}</changed-artifact>`).join("\n")}
353
- `
354
- };
355
- };
356
-
357
- // src/session/session.ts
358
- var __dxlog_file3 = "/__w/dxos/dxos/packages/core/assistant/src/session/session.ts";
359
- var AiSession = class {
360
- _options;
361
- /** Prevents concurrent execution of session. */
362
- _semaphore = Effect3.runSync(Effect3.makeSemaphore(1));
363
- /** Message history from queue. */
364
- // TODO(burdon): Evolve into supporting a git-like graph of messages.
365
- _history = [];
366
- /** Pending messages for this session (incl. the current prompt). */
367
- _pending = [];
368
- constructor(_options = {}) {
369
- this._options = _options;
370
- }
371
- run = ({ prompt, system: systemTemplate, history = [], objects = [], blueprints = [], toolkit, observer = GenerationObserver.noop() }) => Effect3.gen(this, function* () {
372
- this._history = [
373
- ...history
374
- ];
375
- this._pending = [];
376
- const pending = this._pending;
377
- const submitMessage = Effect3.fnUntraced(function* (message) {
378
- pending.push(message);
379
- yield* observer.onMessage(message);
380
- yield* TracingService.emitConverationMessage(message);
381
- return message;
382
- });
383
- const promptMessage = yield* submitMessage(yield* formatUserPrompt({
384
- prompt,
385
- history
386
- }));
387
- const system = yield* formatSystemPrompt({
388
- system: systemTemplate,
389
- blueprints,
390
- objects
391
- });
392
- do {
393
- log2("request", {
394
- prompt: promptMessage,
395
- system: {
396
- snippet: createSnippet(system),
397
- length: system.length
398
- },
399
- pending: this._pending.length,
400
- history: this._history.length,
401
- objects: objects?.length ?? 0
402
- }, {
403
- F: __dxlog_file3,
404
- L: 110,
405
- S: this,
406
- C: (f, a) => f(...a)
407
- });
408
- const prompt2 = yield* AiPreprocessor.preprocessPrompt([
409
- ...this._history,
410
- ...this._pending
411
- ], {
412
- system
413
- });
414
- const blocks = yield* LanguageModel.streamText({
415
- prompt: prompt2,
416
- toolkit,
417
- disableToolCallResolution: true
418
- }).pipe(
419
- // TOOD(dmaretskyi): Error mapping.
420
- AiParser.parseResponse({
421
- onBegin: () => observer.onBegin(),
422
- onBlock: (block) => observer.onBlock(block),
423
- onPart: (part) => observer.onPart(part),
424
- onEnd: (summary) => observer.onEnd(summary)
425
- }),
426
- Stream.runCollect,
427
- Effect3.map(Chunk.toArray)
428
- );
429
- const response = yield* submitMessage(Obj3.make(Message2.Message, {
430
- created: (/* @__PURE__ */ new Date()).toISOString(),
431
- sender: {
432
- role: "assistant"
433
- },
434
- blocks
435
- }));
436
- const toolCalls = getToolCalls(response);
437
- if (toolCalls.length === 0) {
438
- break;
439
- } else if (!toolkit) {
440
- throw new Error("No toolkit provided");
441
- }
442
- const toolResults = yield* Effect3.forEach(toolCalls, (toolCall) => {
443
- return callTool(toolkit, toolCall).pipe(Effect3.provide(TracingService.layerSubframe((context) => ({
444
- ...context,
445
- parentMessage: response.id,
446
- toolCallId: toolCall.toolCallId
447
- }))));
448
- });
449
- yield* submitMessage(Obj3.make(Message2.Message, {
450
- created: (/* @__PURE__ */ new Date()).toISOString(),
451
- sender: {
452
- role: "tool"
453
- },
454
- blocks: toolResults
455
- }));
456
- } while (true);
457
- log2("done", {
458
- pending: this._pending.length
459
- }, {
460
- F: __dxlog_file3,
461
- L: 181,
462
- S: this,
463
- C: (f, a) => f(...a)
464
- });
465
- return this._pending;
466
- }).pipe(this._semaphore.withPermits(1), Effect3.withSpan("AiSession.run"));
467
- /**
468
- * @deprecated
469
- */
470
- // TODO(burdon): Implement or remove.
471
- async runStructured(_schema, _options) {
472
- return todo();
473
- }
474
- };
475
- var createSnippet = (text, len = 32) => text.length <= len * 2 ? text : [
476
- text.slice(0, len),
477
- "...",
478
- text.slice(-len)
479
- ].join("");
480
-
481
- // src/session/toolkit.ts
482
- import * as Toolkit from "@effect/ai/Toolkit";
483
- import * as Effect4 from "effect/Effect";
484
- import { ToolExecutionService, ToolResolverService } from "@dxos/ai";
485
- import { isTruthy } from "@dxos/util";
486
- var createToolkit = ({ toolkit: toolkitParam, toolIds = [], blueprints = [] }) => Effect4.gen(function* () {
487
- const blueprintToolkit = yield* ToolResolverService.resolveToolkit([
488
- ...blueprints.flatMap(({ tools }) => tools),
489
- ...toolIds
490
- ]);
491
- const blueprintToolkitHandler = yield* blueprintToolkit.toContext(ToolExecutionService.handlersFor(blueprintToolkit));
492
- const toolkit = Toolkit.merge(...[
493
- toolkitParam,
494
- blueprintToolkit
495
- ].filter(isTruthy));
496
- return yield* toolkit.pipe(Effect4.provide(blueprintToolkitHandler));
497
- });
498
-
499
- // src/session/version-pin.ts
500
- import * as Schema2 from "effect/Schema";
501
- import { ObjectId } from "@dxos/echo/internal";
502
- import { getVersion } from "@dxos/echo-db";
503
- var ObjectVersionSchema = Schema2.Unknown;
504
- var VersionPinSchema = Schema2.Struct({
505
- // TODO(dmaretskyi): Use Ref when those support encoding.
506
- objectId: ObjectId,
507
- // TODO(dmaretskyi): Could be opaque.
508
- version: ObjectVersionSchema
509
- });
510
- var VersionPin = class extends VersionPinSchema {
511
- static DISPOSITION = "version-pin";
512
- static fromObject(object) {
513
- return VersionPin.make({
514
- objectId: object.id,
515
- version: getVersion(object)
516
- });
517
- }
518
- static createBlock(pin) {
519
- return {
520
- _tag: "json",
521
- disposition: VersionPin.DISPOSITION,
522
- data: JSON.stringify(pin)
523
- };
524
- }
525
- };
526
-
527
- // src/session/GenericToolkit.ts
528
- var GenericToolkit_exports = {};
529
- __export(GenericToolkit_exports, {
530
- TypeId: () => TypeId,
531
- make: () => make,
532
- merge: () => merge3
533
- });
534
- import * as Toolkit2 from "@effect/ai/Toolkit";
535
- import * as Effect5 from "effect/Effect";
536
- import * as Layer from "effect/Layer";
537
- import * as Pipeable from "effect/Pipeable";
538
- var TypeId = "~@dxos/assistant/GenericToolkit";
539
- var make = (toolkit, layer) => {
540
- return {
541
- [TypeId]: TypeId,
542
- toolkit,
543
- layer,
544
- handlers: toolkit.pipe(Effect5.provide(layer)),
545
- pipe() {
546
- return Pipeable.pipeArguments(this, arguments);
547
- }
548
- };
549
- };
550
- var merge3 = (...toolkits) => {
551
- return make(Toolkit2.merge(...toolkits.map((t) => t.toolkit)), Layer.mergeAll(...toolkits.map((t) => t.layer)));
552
- };
553
-
554
- // src/conversation/conversation.ts
555
- var __dxlog_file4 = "/__w/dxos/dxos/packages/core/assistant/src/conversation/conversation.ts";
556
- var AiConversation = class extends Resource2 {
557
- /**
558
- * Message and binding queue.
559
- */
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();
579
- }
580
- get context() {
581
- return this._context;
582
- }
583
- get toolkit() {
584
- return this._toolkit;
585
- }
586
- async getHistory() {
587
- const queueItems = await this._queue.queryObjects();
588
- return queueItems.filter(Obj4.instanceOf(Message3.Message));
589
- }
590
- /**
591
- * Creates a new cancelable request effect.
592
- */
593
- createRequest(params) {
594
- return Effect6.gen(this, function* () {
595
- const session = new AiSession();
596
- const history = yield* Effect6.promise(() => this.getHistory());
597
- const context = yield* Effect6.promise(() => this.context.query());
598
- const blueprints = yield* Effect6.forEach(context.blueprints.values(), DatabaseService2.loadOption).pipe(Effect6.map(Array5.filter(Option2.isSome)), Effect6.map(Array5.map((option) => option.value)));
599
- const objects = yield* Effect6.forEach(context.objects.values(), DatabaseService2.loadOption).pipe(Effect6.map(Array5.filter(Option2.isSome)), Effect6.map(Array5.map((option) => option.value)));
600
- const toolkit = yield* createToolkit({
601
- blueprints
602
- });
603
- this._toolkit = toolkit;
604
- const start = Date.now();
605
- log3("run", {
606
- history: history.length,
607
- blueprints: blueprints.length,
608
- objects: objects.length,
609
- tools: this._toolkit?.tools.length ?? 0
610
- }, {
611
- F: __dxlog_file4,
612
- L: 107,
613
- S: this,
614
- C: (f, a) => f(...a)
615
- });
616
- const messages = yield* session.run({
617
- history,
618
- blueprints,
619
- objects,
620
- toolkit,
621
- ...params
622
- }).pipe(Effect6.provideService(AiContextService, {
623
- binder: this.context
624
- }));
625
- log3("result", {
626
- messages: messages.length,
627
- duration: Date.now() - start
628
- }, {
629
- F: __dxlog_file4,
630
- L: 121,
631
- S: this,
632
- C: (f, a) => f(...a)
633
- });
634
- yield* Effect6.promise(() => this._queue.append(messages));
635
- return messages;
636
- }).pipe(Effect6.withSpan("AiConversation.request"));
637
- }
638
- };
639
-
640
- // src/diff.ts
641
- import { next as A } from "@automerge/automerge";
642
- import { DocAccessor, toCursorRange } from "@dxos/echo-db";
643
- import { log as log4 } from "@dxos/log";
644
- import { isNonNullable } from "@dxos/util";
645
- var __dxlog_file5 = "/__w/dxos/dxos/packages/core/assistant/src/diff.ts";
646
- var reduceDiffs = (diffs) => {
647
- return diffs.reduce((acc, diff) => {
648
- const current = acc[acc.length - 1];
649
- const [op, ...rest] = diff.split(" ");
650
- switch (op) {
651
- case "-": {
652
- if (current && !current.match) {
653
- current.match += rest.join(" ");
654
- } else {
655
- acc.push({
656
- match: rest.join(" "),
657
- replace: ""
658
- });
659
- }
660
- return acc;
661
- }
662
- case "+": {
663
- if (current && !current.replace) {
664
- current.replace += rest.join(" ");
665
- } else {
666
- acc.push({
667
- match: "",
668
- replace: rest.join(" ")
669
- });
670
- }
671
- return acc;
672
- }
673
- }
674
- return acc;
675
- }, []);
676
- };
677
- var computeDiffsWithCursors = (accessor, diffs) => {
678
- return reduceDiffs(diffs).map((diff) => {
679
- const text = DocAccessor.getValue(accessor);
680
- const idx = text.indexOf(diff.match);
681
- if (idx !== -1) {
682
- return {
683
- cursor: toCursorRange(accessor, idx, idx + diff.match.length),
684
- text: diff.replace
685
- };
686
- }
687
- }).filter(isNonNullable);
688
- };
689
- var applyDiffs = (accessor, diffs) => {
690
- for (const diff of reduceDiffs(diffs)) {
691
- accessor.handle.change((doc) => {
692
- const text = DocAccessor.getValue(accessor);
693
- const idx = text.indexOf(diff.match);
694
- if (idx !== -1) {
695
- A.splice(doc, accessor.path, idx, diff.match.length, diff.replace);
696
- } else {
697
- log4.warn("diff not found", diff, {
698
- F: __dxlog_file5,
699
- L: 78,
700
- S: void 0,
701
- C: (f, a) => f(...a)
702
- });
703
- }
704
- });
705
- }
706
- return DocAccessor.getValue(accessor);
707
- };
708
-
709
- // src/execution-graph.ts
710
- import { AgentStatus } from "@dxos/ai";
711
- import { Obj as Obj5 } from "@dxos/echo";
712
- import { MESSAGE_PROPERTY_TOOL_CALL_ID } from "@dxos/functions";
713
- import { LogLevel } from "@dxos/log";
714
- import { ContentBlock, Message as Message4 } from "@dxos/types";
715
- import { isNonNullable as isNonNullable2 } from "@dxos/util";
716
- var SKIP_BLOCKS = [
717
- "text"
718
- ];
719
- var ExecutionGraph = class {
720
- _skipBlocks;
721
- // TODO(dmaretskyi): Evolve the internal state to support chats, functions, circuit workflows, etc.
722
- _commits = [];
723
- _branchNames = /* @__PURE__ */ new Set();
724
- _lastBlockId;
725
- // Tool call tracking.
726
- _toolCallCommitIds = /* @__PURE__ */ new Map();
727
- _lastCommitByBranch = /* @__PURE__ */ new Map();
728
- _pendingToolResults = /* @__PURE__ */ new Map();
729
- constructor(_skipBlocks = SKIP_BLOCKS) {
730
- this._skipBlocks = _skipBlocks;
731
- }
732
- /**
733
- * Adds events to the graph.
734
- */
735
- addEvents(events) {
736
- const sortedEvents = this.sortObjectsByCreated(events);
737
- for (const event of sortedEvents) {
738
- if (Obj5.instanceOf(Message4.Message, event)) {
739
- this._processMessage(event);
740
- } else if (Obj5.instanceOf(AgentStatus, event)) {
741
- this._processAgentStatus(event);
742
- }
743
- }
744
- }
745
- /**
746
- * Processes a message event and creates commits for its blocks.
747
- */
748
- _processMessage(message) {
749
- const messageCommits = messageToCommits(message, this._lastBlockId, this._toolCallCommitIds, this._lastCommitByBranch, this._skipBlocks);
750
- this._commits.push(...messageCommits);
751
- messageCommits.forEach((commit) => this._branchNames.add(commit.branch));
752
- this._trackToolCalls(messageCommits);
753
- if (messageCommits.length > 0) {
754
- this._lastBlockId = messageCommits[messageCommits.length - 1].id;
755
- }
756
- }
757
- /**
758
- * Processes an AgentStatus event.
759
- */
760
- _processAgentStatus(event) {
761
- const branch = this._getToolCallBranch(event.parentMessage, event.toolCallId);
762
- this._branchNames.add(branch);
763
- const agentStatusCommit = {
764
- id: event.id,
765
- branch,
766
- message: event.message,
767
- icon: "ph--flag--regular",
768
- parents: this._getAgentStatusParents(event),
769
- timestamp: new Date(event.created)
770
- };
771
- this._commits.push(agentStatusCommit);
772
- this._lastBlockId = event.id;
773
- if (event.toolCallId) {
774
- this._lastCommitByBranch.set(branch, event.id);
775
- this._updatePendingToolResults(event.toolCallId, event.id);
776
- }
777
- }
778
- /**
779
- * Stable sort: objects with 'created' field are sorted by it, others remain in place.
780
- */
781
- sortObjectsByCreated(objects) {
782
- const sortedObjects = objects.slice();
783
- const createdObjects = [];
784
- sortedObjects.forEach((obj, idx) => {
785
- if (obj && typeof obj.created === "string") {
786
- createdObjects.push({
787
- idx,
788
- obj
789
- });
790
- }
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;
801
- }
802
- return obj;
803
- });
804
- }
805
- /**
806
- * Returns the current state of the graph.
807
- */
808
- getGraph(lastRequest = false) {
809
- const idx = lastRequest ? this._commits.findLastIndex((c) => c.tags?.includes("user")) : -1;
810
- const commits = idx === -1 ? this._commits : this._commits.slice(idx);
811
- return {
812
- branches: Array.from(this._branchNames),
813
- commits
814
- };
815
- }
816
- /**
817
- * Tracks tool calls and handles pending tool result updates.
818
- */
819
- _trackToolCalls(commits) {
820
- commits.forEach((commit) => {
821
- if (this._isToolCallCommit(commit)) {
822
- const toolCallId = this._extractToolCallId(commit.id);
823
- if (toolCallId) {
824
- this._toolCallCommitIds.set(toolCallId, commit.id);
825
- }
826
- }
827
- if (this._isToolResultCommit(commit)) {
828
- const toolCallId = this._extractToolCallId(commit.id);
829
- if (toolCallId) {
830
- this._pendingToolResults.set(toolCallId, commit.id);
831
- this._handleLateToolResultUpdate(toolCallId, commit.id);
832
- }
833
- }
834
- this._lastCommitByBranch.set(commit.branch, commit.id);
835
- });
836
- }
837
- /**
838
- * Updates pending tool results to point to an AgentStatus event.
839
- */
840
- _updatePendingToolResults(toolCallId, agentStatusId) {
841
- const toolResultId = this._pendingToolResults.get(toolCallId);
842
- if (!toolResultId) return;
843
- const toolResultCommit = this._commits.find((c) => c.id === toolResultId);
844
- if (!toolResultCommit) return;
845
- const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);
846
- if (!toolCallCommitId) return;
847
- const toolCallIndex = toolResultCommit.parents.indexOf(toolCallCommitId);
848
- if (toolCallIndex !== -1) {
849
- toolResultCommit.parents[toolCallIndex] = agentStatusId;
850
- }
851
- this._pendingToolResults.delete(toolCallId);
852
- }
853
- /**
854
- * Handles late updates when AgentStatus is processed before tool result.
855
- */
856
- _handleLateToolResultUpdate(toolCallId, toolResultId) {
857
- const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);
858
- if (!toolCallCommitId) return;
859
- const messageId = toolCallCommitId.split("_toolCall_")[0];
860
- const toolCallBranch = `${messageId}_${toolCallId}`;
861
- const agentStatusCommitId = this._lastCommitByBranch.get(toolCallBranch);
862
- if (agentStatusCommitId && agentStatusCommitId !== toolCallCommitId) {
863
- const toolResultCommit = this._commits.find((c) => c.id === toolResultId);
864
- if (toolResultCommit) {
865
- const toolCallIndex = toolResultCommit.parents.indexOf(toolCallCommitId);
866
- if (toolCallIndex !== -1) {
867
- toolResultCommit.parents[toolCallIndex] = agentStatusCommitId;
868
- }
869
- }
870
- this._pendingToolResults.delete(toolCallId);
871
- }
872
- }
873
- /**
874
- * Gets the branch name for a tool call.
875
- */
876
- _getToolCallBranch(parentMessage, toolCallId) {
877
- if (toolCallId) {
878
- return toolCallId;
879
- }
880
- return parentMessage || "main";
881
- }
882
- /**
883
- * Gets the parents for an AgentStatus commit.
884
- */
885
- _getAgentStatusParents(event) {
886
- if (event.parentMessage && event.toolCallId) {
887
- return [
888
- getToolCallId(event.parentMessage, event.toolCallId)
889
- ];
890
- }
891
- return [];
892
- }
893
- /**
894
- * Checks if a commit is a tool call commit.
895
- */
896
- _isToolCallCommit(commit) {
897
- return commit.message.includes("Calling tool");
898
- }
899
- /**
900
- * Checks if a commit is a tool result commit.
901
- */
902
- _isToolResultCommit(commit) {
903
- return commit.message.includes("Tool call succeeded") || commit.message.includes("Tool error:");
904
- }
905
- /**
906
- * Extracts tool call ID from a commit ID.
907
- */
908
- _extractToolCallId(commitId) {
909
- const toolCallMatch = commitId.match(/_toolCall_(.+)$/);
910
- const toolResultMatch = commitId.match(/_toolResult_(.+)$/);
911
- return toolCallMatch?.[1] || toolResultMatch?.[1];
912
- }
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]
1060
- });
1061
- };
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;
1127
- return {
1128
- handlersFor: (toolkit2) => {
1129
- const makeHandler = (tool) => {
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;
1137
- }
1138
- const { definition: functionDef } = Context3.get(FunctionToolAnnotation)(tool.annotations);
1139
- return yield* functionInvocationService.invokeFunction(functionDef, input).pipe(Effect7.catchAllDefect((defect) => Effect7.fail(defect)));
1140
- });
1141
- };
1142
- return toolkit2.of(Record.map(toolkit2.tools, (tool, _name) => Tool.isUserDefined(tool) ? makeHandler(tool) : null));
1143
- }
1144
- };
1145
- }));
1146
- };
1147
- var FunctionToolAnnotation = class extends Context3.Tag("@dxos/assistant/FunctionToolAnnotation")() {
1148
- };
1149
- var toolCache = /* @__PURE__ */ new WeakMap();
1150
- var projectFunctionToTool = (fn2) => {
1151
- if (toolCache.has(fn2)) {
1152
- return toolCache.get(fn2);
1153
- }
1154
- const tool = Tool.make(makeToolName(fn2.name), {
1155
- description: fn2.description,
1156
- parameters: createStructFieldsFromSchema(fn2.inputSchema),
1157
- // TODO(dmaretskyi): Include output schema.
1158
- failure: Schema3.Any
1159
- }).annotate(FunctionToolAnnotation, {
1160
- definition: fn2
1161
- });
1162
- toolCache.set(fn2, tool);
1163
- return tool;
1164
- };
1165
- var makeToolName = (name) => {
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,
1170
- S: void 0,
1171
- A: [
1172
- "toolName.match(/^[a-z_][a-z0-9-_]*$/)",
1173
- ""
1174
- ]
1175
- });
1176
- return toolName;
1177
- };
1178
- var createStructFieldsFromSchema = (schema) => {
1179
- switch (schema.ast._tag) {
1180
- case "TypeLiteral":
1181
- return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [
1182
- prop.name,
1183
- Schema3.make(prop.type)
1184
- ]));
1185
- case "VoidKeyword":
1186
- return {};
1187
- default:
1188
- return todo2(`Unsupported schema AST: ${schema.ast._tag}`);
1189
- }
1190
- };
1191
- var isHandlerLike = (value) => {
1192
- return typeof value.tools === "object" && typeof value.handle === "function";
1193
- };
1194
-
1195
- // src/templates/system.ts
1196
- import defaultsDeep from "lodash.defaultsdeep";
1197
- import { Template as Template2 } from "@dxos/blueprints";
1198
-
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";
1201
-
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";
1204
-
1205
- // src/templates/system.ts
1206
- var createSystemPrompt = (options = {}) => Template2.process(format_default, defaultsDeep(options, {
1207
- DATETIME: (/* @__PURE__ */ new Date()).toISOString()
1208
- }));
1209
- var templates = {
1210
- /** Editable system prompt.*/
1211
- system: Template2.make({
1212
- /**
1213
- * NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.
1214
- */
1215
- id: "01K2J2FZWH39F55CS7B26GP1Q3",
1216
- source: system_default
1217
- })
1218
- };
1219
-
1220
- // src/types/artifact.ts
1221
- import * as Schema4 from "effect/Schema";
1222
- import { DatabaseService as DatabaseService4 } from "@dxos/echo-db";
1223
- import { DXN as DXN2, LOCAL_SPACE_TAG } from "@dxos/keys";
1224
- import { trim as trim2 } from "@dxos/util";
1225
- var createArtifactElement = (id) => `<artifact id=${id} />`;
1226
- var ArtifactId = class extends Schema4.String.annotations({
1227
- // TODO(dmaretskyi): This section gets overriden.
1228
- description: trim2`
1229
- The ID of the referenced object. Formats accepted:
1230
- - DXN (dxn:echo:@:XXXXX). DXNs can be prepended with an @ symbol for compatibility with in-text references.
1231
- - space ID, object ID tuple (spaceID:objectID)
1232
- - Only object ID that is assumed to be in the current space (XXXXX)
1233
- `,
1234
- examples: [
1235
- "dxn:echo:@:XXXXX",
1236
- "@dxn:echo:@:XXXXX",
1237
- "spaceID:objectID",
1238
- "XXXXX"
1239
- ]
1240
- }) {
1241
- static toDXN(reference, owningSpaceId) {
1242
- if (reference.startsWith("@dxn:")) {
1243
- return DXN2.parse(reference.slice(1));
1244
- } else if (reference.startsWith("dxn:")) {
1245
- return DXN2.parse(reference);
1246
- } else if (/^[A-Z0-9]+:[A-Z0-9]+$/.test(reference)) {
1247
- const [spaceId, objectId] = reference.split(":");
1248
- return new DXN2(DXN2.kind.ECHO, [
1249
- spaceId === owningSpaceId ? LOCAL_SPACE_TAG : spaceId,
1250
- objectId
1251
- ]);
1252
- } else if (/^[A-Z0-9]+$/.test(reference)) {
1253
- return DXN2.fromLocalObjectId(reference);
1254
- } else {
1255
- throw new Error(`Unable to parse object reference: ${reference}`);
1256
- }
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
- }
1265
- };
1266
- export {
1267
- AiAssistantError,
1268
- AiContextBinder,
1269
- AiContextService,
1270
- AiConversation,
1271
- AiModelError,
1272
- AiSession,
1273
- ArtifactDiffResolver,
1274
- ArtifactId,
1275
- Bindings,
1276
- ContextBinding,
1277
- ExecutionGraph,
1278
- GenerationObserver,
1279
- GenericToolkit_exports as GenericToolkit,
1280
- VersionPin,
1281
- applyDiffs,
1282
- computeDiffsWithCursors,
1283
- createArtifactElement,
1284
- createSystemPrompt,
1285
- createToolkit,
1286
- makeToolExecutionServiceFromFunctions,
1287
- makeToolResolverFromFunctions,
1288
- reduceDiffs,
1289
- templates
1290
- };
1291
- //# sourceMappingURL=index.mjs.map