@dxos/assistant 0.8.4-main.3eb6e50203 → 0.8.4-main.3fbcb4aa9b
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.
- package/README.md +1 -0
- package/dist/lib/neutral/extraction/index.mjs +31 -54
- package/dist/lib/neutral/extraction/index.mjs.map +4 -4
- package/dist/lib/neutral/index.mjs +1003 -198
- package/dist/lib/neutral/index.mjs.map +4 -4
- package/dist/lib/neutral/meta.json +1 -1
- package/dist/types/src/conversation/context.d.ts +41 -23
- package/dist/types/src/conversation/context.d.ts.map +1 -1
- package/dist/types/src/conversation/index.d.ts +1 -1
- package/dist/types/src/conversation/index.d.ts.map +1 -1
- package/dist/types/src/conversation/session.d.ts +73 -0
- package/dist/types/src/conversation/session.d.ts.map +1 -0
- package/dist/types/src/diff.d.ts.map +1 -1
- package/dist/types/src/errors.d.ts +12 -12
- package/dist/types/src/errors.d.ts.map +1 -1
- package/dist/types/src/execution-graph.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
- package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction.d.ts +876 -158
- package/dist/types/src/extraction/extraction.d.ts.map +1 -1
- package/dist/types/src/extraction/index.d.ts +0 -1
- package/dist/types/src/extraction/index.d.ts.map +1 -1
- package/dist/types/src/extraction/quotes.d.ts.map +1 -1
- package/dist/types/src/functions/services.d.ts +14 -16
- package/dist/types/src/functions/services.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +1 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
- package/dist/types/src/session/error-handling.d.ts.map +1 -1
- package/dist/types/src/session/format.d.ts +6 -3
- package/dist/types/src/session/format.d.ts.map +1 -1
- package/dist/types/src/session/index.d.ts +1 -2
- package/dist/types/src/session/index.d.ts.map +1 -1
- package/dist/types/src/session/observer.d.ts.map +1 -1
- package/dist/types/src/session/request.d.ts +104 -0
- package/dist/types/src/session/request.d.ts.map +1 -0
- package/dist/types/src/session/toolkit.d.ts +8 -6
- package/dist/types/src/session/toolkit.d.ts.map +1 -1
- package/dist/types/src/templates/system.d.ts +1 -2
- package/dist/types/src/templates/system.d.ts.map +1 -1
- package/dist/types/src/tracing.d.ts +233 -0
- package/dist/types/src/tracing.d.ts.map +1 -0
- package/dist/types/src/types/artifact.d.ts +5 -5
- package/dist/types/src/types/artifact.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +24 -39
- package/src/conversation/context.test.ts +19 -13
- package/src/conversation/context.ts +133 -60
- package/src/conversation/index.ts +1 -1
- package/src/conversation/session.ts +323 -0
- package/src/diff.test.ts +3 -3
- package/src/execution-graph.test.ts +2 -2
- package/src/execution-graph.ts +18 -8
- package/src/extraction/extraction-ner-function/index.ts +0 -1
- package/src/extraction/extraction.ts +38 -10
- package/src/extraction/index.ts +0 -1
- package/src/functions/services.ts +82 -55
- package/src/index.ts +1 -0
- package/src/session/format.ts +14 -10
- package/src/session/index.ts +1 -3
- package/src/session/observer.ts +3 -2
- package/src/session/request.ts +347 -0
- package/src/session/toolkit.ts +21 -13
- package/src/templates/instructions/system.tpl +50 -2
- package/src/templates/system.ts +7 -6
- package/src/tracing.ts +57 -0
- package/src/types/artifact.ts +5 -5
- package/dist/lib/neutral/chunk-J5LGTIGS.mjs +0 -10
- package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +0 -7
- package/dist/lib/neutral/chunk-QBD6NQJK.mjs +0 -604
- package/dist/lib/neutral/chunk-QBD6NQJK.mjs.map +0 -7
- package/dist/lib/neutral/testing/index.mjs +0 -38
- package/dist/lib/neutral/testing/index.mjs.map +0 -7
- package/dist/types/src/conversation/conversation.d.ts +0 -66
- package/dist/types/src/conversation/conversation.d.ts.map +0 -1
- package/dist/types/src/conversation/conversation.test.d.ts +0 -2
- package/dist/types/src/conversation/conversation.test.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
- package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -347
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
- package/dist/types/src/functions.test.d.ts +0 -2
- package/dist/types/src/functions.test.d.ts.map +0 -1
- package/dist/types/src/session/GenericToolkit.d.ts +0 -107
- package/dist/types/src/session/GenericToolkit.d.ts.map +0 -1
- package/dist/types/src/session/format.test.d.ts +0 -2
- package/dist/types/src/session/format.test.d.ts.map +0 -1
- package/dist/types/src/session/session.d.ts +0 -61
- package/dist/types/src/session/session.d.ts.map +0 -1
- package/dist/types/src/session/session.test.d.ts +0 -2
- package/dist/types/src/session/session.test.d.ts.map +0 -1
- package/dist/types/src/testing/index.d.ts +0 -2
- package/dist/types/src/testing/index.d.ts.map +0 -1
- package/dist/types/src/testing/layer.d.ts +0 -22
- package/dist/types/src/testing/layer.d.ts.map +0 -1
- package/src/conversation/conversation.test.ts +0 -65
- package/src/conversation/conversation.ts +0 -210
- package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -84
- package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -62
- package/src/extraction/extraction-llm-function/index.ts +0 -5
- package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -116
- package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -56
- package/src/functions.conversations.json +0 -1
- package/src/functions.test.ts +0 -74
- package/src/session/GenericToolkit.ts +0 -160
- package/src/session/format.test.ts +0 -124
- package/src/session/session.conversations.json +0 -1
- package/src/session/session.test.ts +0 -163
- package/src/session/session.ts +0 -251
- package/src/testing/index.ts +0 -5
- package/src/testing/layer.ts +0 -84
|
@@ -1,48 +1,29 @@
|
|
|
1
|
-
import {
|
|
2
|
-
AiAssistantError,
|
|
3
|
-
AiModelError,
|
|
4
|
-
AiSession,
|
|
5
|
-
ArtifactDiffResolver,
|
|
6
|
-
ArtifactId,
|
|
7
|
-
GenerationObserver,
|
|
8
|
-
GenericToolkit_exports,
|
|
9
|
-
RefFromLLM,
|
|
10
|
-
ToolExecutionServices,
|
|
11
|
-
VersionPin,
|
|
12
|
-
createArtifactElement,
|
|
13
|
-
createToolkit,
|
|
14
|
-
formatSystemPrompt,
|
|
15
|
-
formatUserPrompt,
|
|
16
|
-
makeToolExecutionServiceFromFunctions,
|
|
17
|
-
makeToolResolverFromFunctions
|
|
18
|
-
} from "./chunk-QBD6NQJK.mjs";
|
|
19
|
-
import "./chunk-J5LGTIGS.mjs";
|
|
20
|
-
|
|
21
1
|
// src/conversation/context.ts
|
|
22
2
|
import { Atom, Registry } from "@effect-atom/atom-react";
|
|
23
3
|
import * as EArray from "effect/Array";
|
|
24
4
|
import * as Context from "effect/Context";
|
|
25
5
|
import * as Effect from "effect/Effect";
|
|
26
6
|
import * as Function from "effect/Function";
|
|
7
|
+
import * as Runtime from "effect/Runtime";
|
|
27
8
|
import * as Schema from "effect/Schema";
|
|
28
|
-
import { Blueprint } from "@dxos/
|
|
9
|
+
import { Blueprint } from "@dxos/compute";
|
|
29
10
|
import { Resource } from "@dxos/context";
|
|
30
|
-
import { DXN, Obj, Query, Type } from "@dxos/echo";
|
|
11
|
+
import { DXN, Feed, Obj, Query, Ref, Type } from "@dxos/echo";
|
|
31
12
|
import { assertArgument } from "@dxos/invariant";
|
|
32
13
|
import { log } from "@dxos/log";
|
|
33
|
-
import { ComplexSet,
|
|
34
|
-
var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/conversation/context.ts";
|
|
14
|
+
import { ComplexSet, isNonNullable } from "@dxos/util";
|
|
15
|
+
var __dxlog_file = "/__w/dxos/dxos/packages/core/compute/assistant/src/conversation/context.ts";
|
|
35
16
|
var ContextBinding = Schema.Struct({
|
|
36
17
|
blueprints: Schema.Struct({
|
|
37
|
-
added: Schema.Array(
|
|
38
|
-
removed: Schema.Array(
|
|
18
|
+
added: Schema.Array(Ref.Ref(Blueprint.Blueprint)),
|
|
19
|
+
removed: Schema.Array(Ref.Ref(Blueprint.Blueprint))
|
|
39
20
|
}),
|
|
40
21
|
objects: Schema.Struct({
|
|
41
|
-
added: Schema.Array(
|
|
42
|
-
removed: Schema.Array(
|
|
22
|
+
added: Schema.Array(Ref.Ref(Obj.Unknown)),
|
|
23
|
+
removed: Schema.Array(Ref.Ref(Obj.Unknown))
|
|
43
24
|
})
|
|
44
25
|
}).pipe(Type.object({
|
|
45
|
-
typename: "dxos.
|
|
26
|
+
typename: "org.dxos.type.contextBinding",
|
|
46
27
|
version: "0.1.0"
|
|
47
28
|
}));
|
|
48
29
|
var Bindings = class {
|
|
@@ -60,11 +41,15 @@ var AiContextBinder = class extends Resource {
|
|
|
60
41
|
_blueprints = Atom.make([]).pipe(Atom.keepAlive);
|
|
61
42
|
_objects = Atom.make([]).pipe(Atom.keepAlive);
|
|
62
43
|
_registry;
|
|
63
|
-
|
|
44
|
+
_feed;
|
|
45
|
+
_runtime;
|
|
46
|
+
#bindingsQuery;
|
|
64
47
|
constructor(options) {
|
|
65
48
|
super();
|
|
66
|
-
assertArgument(options.
|
|
67
|
-
|
|
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;
|
|
68
53
|
this._registry = options.registry ?? Registry.make();
|
|
69
54
|
}
|
|
70
55
|
/**
|
|
@@ -104,33 +89,67 @@ var AiContextBinder = class extends Resource {
|
|
|
104
89
|
return this._registry.subscribe(this._objects, () => cb(this._registry.get(this._objects)));
|
|
105
90
|
}
|
|
106
91
|
async _open() {
|
|
107
|
-
|
|
108
|
-
const initialResults = await
|
|
92
|
+
this.#bindingsQuery = await Runtime.runPromise(this._runtime)(Feed.query(this._feed, Query.type(ContextBinding)));
|
|
93
|
+
const initialResults = await this.#bindingsQuery.run();
|
|
109
94
|
await this._updateBindings(initialResults);
|
|
110
|
-
this._ctx.onDispose(
|
|
111
|
-
await this._updateBindings(
|
|
95
|
+
this._ctx.onDispose(this.#bindingsQuery.subscribe(async () => {
|
|
96
|
+
await this._updateBindings(this.#bindingsQuery.results);
|
|
112
97
|
}));
|
|
113
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
|
+
}
|
|
114
115
|
async _updateBindings(items) {
|
|
115
116
|
if (items.length === 0) {
|
|
116
117
|
return;
|
|
117
118
|
}
|
|
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 });
|
|
119
129
|
const currentBlueprints = this._registry.get(this._blueprints);
|
|
120
130
|
const currentObjects = this._registry.get(this._objects);
|
|
121
|
-
const
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
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);
|
|
125
149
|
log("updated bindings", {
|
|
126
|
-
blueprints:
|
|
127
|
-
objects:
|
|
128
|
-
}, {
|
|
129
|
-
F: __dxlog_file,
|
|
130
|
-
L: 159,
|
|
131
|
-
S: this,
|
|
132
|
-
C: (f, a) => f(...a)
|
|
133
|
-
});
|
|
150
|
+
blueprints: mergedBlueprints.length,
|
|
151
|
+
objects: mergedObjects.length
|
|
152
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 155, S: this });
|
|
134
153
|
}
|
|
135
154
|
async _close() {
|
|
136
155
|
this._registry.set(this._blueprints, []);
|
|
@@ -149,13 +168,8 @@ var AiContextBinder = class extends Resource {
|
|
|
149
168
|
log("bind", {
|
|
150
169
|
blueprints: addedBlueprints.length,
|
|
151
170
|
objects: addedObjects.length
|
|
152
|
-
}, {
|
|
153
|
-
|
|
154
|
-
L: 185,
|
|
155
|
-
S: this,
|
|
156
|
-
C: (f, a) => f(...a)
|
|
157
|
-
});
|
|
158
|
-
await this._queue.append([
|
|
171
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 176, S: this });
|
|
172
|
+
await Runtime.runPromise(this._runtime)(Feed.append(this._feed, [
|
|
159
173
|
Obj.make(ContextBinding, {
|
|
160
174
|
blueprints: {
|
|
161
175
|
added: addedBlueprints,
|
|
@@ -166,22 +180,27 @@ var AiContextBinder = class extends Resource {
|
|
|
166
180
|
removed: []
|
|
167
181
|
}
|
|
168
182
|
})
|
|
169
|
-
]);
|
|
183
|
+
]));
|
|
170
184
|
}
|
|
171
185
|
async unbind({ blueprints, objects }) {
|
|
172
186
|
if (!blueprints?.length && !objects?.length) {
|
|
173
187
|
return;
|
|
174
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
|
+
}
|
|
175
199
|
log("unbind", {
|
|
176
200
|
blueprints: blueprints?.length,
|
|
177
201
|
objects: objects?.length
|
|
178
|
-
}, {
|
|
179
|
-
|
|
180
|
-
L: 205,
|
|
181
|
-
S: this,
|
|
182
|
-
C: (f, a) => f(...a)
|
|
183
|
-
});
|
|
184
|
-
await this._queue.append([
|
|
202
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 208, S: this });
|
|
203
|
+
await Runtime.runPromise(this._runtime)(Feed.append(this._feed, [
|
|
185
204
|
Obj.make(ContextBinding, {
|
|
186
205
|
blueprints: {
|
|
187
206
|
added: [],
|
|
@@ -192,7 +211,7 @@ var AiContextBinder = class extends Resource {
|
|
|
192
211
|
removed: objects ?? []
|
|
193
212
|
}
|
|
194
213
|
})
|
|
195
|
-
]);
|
|
214
|
+
]));
|
|
196
215
|
}
|
|
197
216
|
/**
|
|
198
217
|
* Process bindings to filter duplicates and determine next state.
|
|
@@ -246,6 +265,23 @@ var AiContextBinder = class extends Resource {
|
|
|
246
265
|
}));
|
|
247
266
|
}
|
|
248
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
|
+
/**
|
|
249
285
|
* Resolve references to objects, loading them first if needed and falling back to existing objects.
|
|
250
286
|
*/
|
|
251
287
|
async _resolve(refs, current) {
|
|
@@ -259,7 +295,7 @@ var AiContextBinder = class extends Resource {
|
|
|
259
295
|
target = ref.target;
|
|
260
296
|
}
|
|
261
297
|
return target ?? current.find((obj) => Obj.getDXN(obj).toString() === ref.dxn.toString());
|
|
262
|
-
}).filter(
|
|
298
|
+
}).filter(isNonNullable);
|
|
263
299
|
}
|
|
264
300
|
};
|
|
265
301
|
var AiContextService = class _AiContextService extends Context.Tag("@dxos/assistant/AiContextService")() {
|
|
@@ -276,165 +312,926 @@ var AiContextService = class _AiContextService extends Context.Tag("@dxos/assist
|
|
|
276
312
|
return binder.getObjects().filter(Obj.instanceOf(type));
|
|
277
313
|
});
|
|
278
314
|
};
|
|
279
|
-
/**
|
|
280
|
-
* Glorified type cast until we figure out function service typing.
|
|
281
|
-
* For context, the AiContextService is provided to functions called from tool calls, but it's not implemented in types yet.
|
|
282
|
-
* @deprecated
|
|
283
|
-
*/
|
|
284
|
-
static fixFunctionHandlerType = (eff) => eff;
|
|
285
315
|
};
|
|
286
316
|
|
|
287
|
-
// src/conversation/
|
|
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, Trace as Trace3 } 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";
|
|
288
337
|
import * as Context2 from "effect/Context";
|
|
289
338
|
import * as Effect2 from "effect/Effect";
|
|
290
339
|
import * as Layer from "effect/Layer";
|
|
291
|
-
import
|
|
292
|
-
import
|
|
293
|
-
import
|
|
294
|
-
import
|
|
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";
|
|
295
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/compute/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
|
+
var McpServerError = Trace.EventType("assistant.mcpServerError", {
|
|
598
|
+
schema: Schema4.Struct({
|
|
599
|
+
url: Schema4.String,
|
|
600
|
+
protocol: Schema4.Literal("sse", "http"),
|
|
601
|
+
message: Schema4.String
|
|
602
|
+
}),
|
|
603
|
+
isEphemeral: true
|
|
604
|
+
});
|
|
605
|
+
|
|
606
|
+
// src/session/format.ts
|
|
607
|
+
import * as Effect4 from "effect/Effect";
|
|
608
|
+
import * as Function3 from "effect/Function";
|
|
609
|
+
import * as Option2 from "effect/Option";
|
|
610
|
+
import { Template } from "@dxos/compute";
|
|
611
|
+
import { Obj as Obj4 } from "@dxos/echo";
|
|
612
|
+
import { ObjectVersion } from "@dxos/echo-db";
|
|
296
613
|
import { log as log2 } from "@dxos/log";
|
|
297
614
|
import { Message } from "@dxos/types";
|
|
298
|
-
|
|
299
|
-
|
|
615
|
+
import { trim as trim2 } from "@dxos/util";
|
|
616
|
+
|
|
617
|
+
// src/errors.ts
|
|
618
|
+
import { BaseError } from "@dxos/errors";
|
|
619
|
+
var AiModelError = class extends BaseError.extend("AiModelError", "AI model error") {
|
|
620
|
+
};
|
|
621
|
+
var AiAssistantError = class extends BaseError.extend("AiAssistantError", "AI assistant error") {
|
|
622
|
+
};
|
|
623
|
+
|
|
624
|
+
// src/session/format.ts
|
|
625
|
+
var __dxlog_file3 = "/__w/dxos/dxos/packages/core/compute/assistant/src/session/format.ts";
|
|
626
|
+
var formatSystemPrompt = ({ system, blueprints = [], objects = [] }) => Effect4.gen(function* () {
|
|
627
|
+
const blueprintDefs = yield* Function3.pipe(blueprints, Effect4.forEach((blueprint) => Effect4.succeed(blueprint.instructions)), Effect4.flatMap(Effect4.forEach((template) => Effect4.gen(function* () {
|
|
628
|
+
return trim2`
|
|
629
|
+
<blueprint>
|
|
630
|
+
${yield* Template.processTemplate(template)}
|
|
631
|
+
</blueprint>
|
|
632
|
+
`;
|
|
633
|
+
}))), Effect4.map((blueprints2) => blueprints2.length > 0 ? [
|
|
634
|
+
"## Blueprints Definitions",
|
|
635
|
+
...blueprints2
|
|
636
|
+
].join("\n\n") : void 0));
|
|
637
|
+
const objectDefs = yield* Function3.pipe(objects, Effect4.forEach((object) => Effect4.succeed(trim2`
|
|
638
|
+
<object>
|
|
639
|
+
<dxn>${Obj4.getDXN(object)}</dxn>
|
|
640
|
+
<typename>${Obj4.getTypename(object)}</typename>
|
|
641
|
+
</object>
|
|
642
|
+
`)), Effect4.map((objects2) => objects2.length > 0 ? [
|
|
643
|
+
"## Context Objects",
|
|
644
|
+
...objects2
|
|
645
|
+
].join("\n\n") : void 0));
|
|
646
|
+
return yield* Function3.pipe(Effect4.succeed([
|
|
647
|
+
system,
|
|
648
|
+
blueprintDefs,
|
|
649
|
+
objectDefs
|
|
650
|
+
].filter((def) => def !== void 0)), Effect4.map((parts) => parts.join("\n\n")));
|
|
651
|
+
}).pipe(Effect4.withSpan("formatSystemPrompt"));
|
|
652
|
+
var formatUserPrompt = ({ prompt, history = [] }) => Effect4.gen(function* () {
|
|
653
|
+
const blocks = [];
|
|
654
|
+
const artifactDiffResolver = yield* Effect4.serviceOption(ArtifactDiffResolver);
|
|
655
|
+
if (Option2.isSome(artifactDiffResolver)) {
|
|
656
|
+
const versions = gatherObjectVersions(history);
|
|
657
|
+
const artifactDiff = yield* Effect4.tryPromise({
|
|
658
|
+
try: () => artifactDiffResolver.value.resolve([
|
|
659
|
+
...versions.entries()
|
|
660
|
+
].map(([id, version]) => ({
|
|
661
|
+
id,
|
|
662
|
+
lastVersion: version
|
|
663
|
+
}))),
|
|
664
|
+
catch: AiAssistantError.wrap({
|
|
665
|
+
message: "Artifact diff resolution error"
|
|
666
|
+
})
|
|
667
|
+
});
|
|
668
|
+
log2("version", {
|
|
669
|
+
artifactDiff,
|
|
670
|
+
versions
|
|
671
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 65, S: this });
|
|
672
|
+
for (const [id, { version }] of [
|
|
673
|
+
...artifactDiff.entries()
|
|
674
|
+
]) {
|
|
675
|
+
if (ObjectVersion.equals(version, versions.get(id))) {
|
|
676
|
+
artifactDiff.delete(id);
|
|
677
|
+
continue;
|
|
678
|
+
}
|
|
679
|
+
blocks.push({
|
|
680
|
+
_tag: "anchor",
|
|
681
|
+
objectId: id,
|
|
682
|
+
version
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
if (artifactDiff.size > 0) {
|
|
686
|
+
blocks.push(createArtifactUpdateBlock(artifactDiff));
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
return Obj4.make(Message.Message, {
|
|
690
|
+
created: (/* @__PURE__ */ new Date()).toISOString(),
|
|
691
|
+
sender: {
|
|
692
|
+
role: "user"
|
|
693
|
+
},
|
|
694
|
+
blocks: typeof prompt === "string" ? [
|
|
695
|
+
...blocks,
|
|
696
|
+
{
|
|
697
|
+
_tag: "text",
|
|
698
|
+
text: prompt
|
|
699
|
+
}
|
|
700
|
+
] : [
|
|
701
|
+
...blocks,
|
|
702
|
+
...prompt
|
|
703
|
+
]
|
|
704
|
+
});
|
|
705
|
+
}).pipe(Effect4.withSpan("formatUserPrompt"));
|
|
706
|
+
var gatherObjectVersions = (messages) => {
|
|
707
|
+
const artifactIds = /* @__PURE__ */ new Map();
|
|
708
|
+
for (const message of messages) {
|
|
709
|
+
for (const block of message.blocks) {
|
|
710
|
+
if (block._tag === "anchor") {
|
|
711
|
+
artifactIds.set(block.objectId, block.version);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
return artifactIds;
|
|
716
|
+
};
|
|
717
|
+
var createArtifactUpdateBlock = (artifactDiff) => {
|
|
718
|
+
return {
|
|
719
|
+
_tag: "text",
|
|
720
|
+
// TODO(dmaretskyi): Does this need to be a special content-block?
|
|
721
|
+
disposition: "synthetic",
|
|
722
|
+
text: trim2`
|
|
723
|
+
The following artifacts have been updated since the last message:
|
|
724
|
+
${[
|
|
725
|
+
...artifactDiff.entries()
|
|
726
|
+
].map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `
|
|
727
|
+
${diff}` : ""}</changed-artifact>`).join("\n")}
|
|
728
|
+
`
|
|
729
|
+
};
|
|
730
|
+
};
|
|
731
|
+
|
|
732
|
+
// src/session/request.ts
|
|
733
|
+
var __dxlog_file4 = "/__w/dxos/dxos/packages/core/compute/assistant/src/session/request.ts";
|
|
734
|
+
var AiRequest = class {
|
|
735
|
+
_options;
|
|
736
|
+
/** Prevents concurrent execution of session. */
|
|
737
|
+
_semaphore = Effect5.runSync(Effect5.makeSemaphore(1));
|
|
738
|
+
_observer;
|
|
739
|
+
_onOutput;
|
|
740
|
+
/** Message history from queue. */
|
|
741
|
+
// TODO(burdon): Evolve into supporting a git-like graph of messages.
|
|
742
|
+
_history = [];
|
|
743
|
+
/** Pending messages for this session (incl. the current prompt). */
|
|
744
|
+
_pending = [];
|
|
745
|
+
_started = 0;
|
|
746
|
+
_ended = 0;
|
|
747
|
+
_toolCalls = 0;
|
|
748
|
+
constructor(_options = {}) {
|
|
749
|
+
this._options = _options;
|
|
750
|
+
this._observer = _options.observer ?? GenerationObserver.noop();
|
|
751
|
+
this._onOutput = _options.onOutput ?? (() => Effect5.void);
|
|
752
|
+
}
|
|
753
|
+
get duration() {
|
|
754
|
+
return this._ended - this._started;
|
|
755
|
+
}
|
|
756
|
+
get toolCalls() {
|
|
757
|
+
return this._toolCalls;
|
|
758
|
+
}
|
|
759
|
+
get pending() {
|
|
760
|
+
return this._pending;
|
|
761
|
+
}
|
|
762
|
+
_submitMessage = (message) => Effect5.gen(this, function* () {
|
|
763
|
+
this._pending.push(message);
|
|
764
|
+
yield* this._observer.onMessage(message);
|
|
765
|
+
for (const block of message.blocks) {
|
|
766
|
+
log3("write complete block", {
|
|
767
|
+
messageId: message.id,
|
|
768
|
+
role: message.sender.role,
|
|
769
|
+
block: JSON.stringify(block)
|
|
770
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 57, S: this });
|
|
771
|
+
yield* Trace2.write(CompleteBlock, {
|
|
772
|
+
messageId: message.id,
|
|
773
|
+
role: message.sender.role,
|
|
774
|
+
block
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
yield* this._onOutput(message);
|
|
778
|
+
return message;
|
|
779
|
+
});
|
|
780
|
+
getToolCalls = () => pipe3([
|
|
781
|
+
...this._history,
|
|
782
|
+
...this._pending
|
|
783
|
+
], Array3.reverse, Array3.takeWhile((_) => _.sender.role === "assistant"), Array3.flatMap((_) => _.blocks.filter(ContentBlock2.is("toolCall")).map((block) => ({
|
|
784
|
+
block,
|
|
785
|
+
message: _
|
|
786
|
+
}))), Array3.filter((_) => !_.block.providerExecuted), Array3.reverse);
|
|
300
787
|
/**
|
|
301
|
-
*
|
|
788
|
+
* Initialize a session: set up history, perform summarization if needed, and submit the user prompt.
|
|
789
|
+
* Must be called before `runTurn()`.
|
|
790
|
+
*/
|
|
791
|
+
begin = ({ prompt, system, history = [], blueprints = [], objects = [] }) => Effect5.gen(this, function* () {
|
|
792
|
+
this._started = Date.now();
|
|
793
|
+
this._history = [
|
|
794
|
+
...history
|
|
795
|
+
];
|
|
796
|
+
this._pending = [];
|
|
797
|
+
const systemPrompt = yield* formatSystemPrompt({
|
|
798
|
+
system,
|
|
799
|
+
blueprints,
|
|
800
|
+
objects
|
|
801
|
+
}).pipe(Effect5.orDie);
|
|
802
|
+
if (this._options.summarizationThreshold !== void 0) {
|
|
803
|
+
const tokenCount = yield* AiPreprocessor.estimateTokens(yield* AiPreprocessor.preprocessPrompt([
|
|
804
|
+
...this._history
|
|
805
|
+
], {
|
|
806
|
+
system: systemPrompt
|
|
807
|
+
}));
|
|
808
|
+
if (tokenCount > this._options.summarizationThreshold) {
|
|
809
|
+
const summary = yield* AiSummarizer.summarize([
|
|
810
|
+
...this._history
|
|
811
|
+
]);
|
|
812
|
+
yield* this._submitMessage(summary);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
yield* this._submitMessage(yield* formatUserPrompt({
|
|
816
|
+
prompt,
|
|
817
|
+
history
|
|
818
|
+
}));
|
|
819
|
+
}).pipe(Effect5.withSpan("AiRequest.begin"));
|
|
820
|
+
/**
|
|
821
|
+
* Execute a single turn: one LLM generation followed by tool execution.
|
|
822
|
+
* The toolkit and system prompt can be updated between turns to reflect context changes (e.g. dynamically enabled blueprints).
|
|
823
|
+
*/
|
|
824
|
+
runAgentTurn = ({ system, toolkit: opaqueToolkit }) => Effect5.gen(this, function* () {
|
|
825
|
+
log3.info("request", {
|
|
826
|
+
system: {
|
|
827
|
+
snippet: createSnippet(system),
|
|
828
|
+
length: system.length
|
|
829
|
+
},
|
|
830
|
+
pending: this._pending.length,
|
|
831
|
+
history: this._history.length
|
|
832
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 114, S: this });
|
|
833
|
+
const prompt = yield* AiPreprocessor.preprocessPrompt([
|
|
834
|
+
...this._history,
|
|
835
|
+
...this._pending
|
|
836
|
+
], {
|
|
837
|
+
system,
|
|
838
|
+
cacheControl: "ephemeral"
|
|
839
|
+
});
|
|
840
|
+
const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : void 0;
|
|
841
|
+
const observer = this._observer;
|
|
842
|
+
let currentMessageId = null;
|
|
843
|
+
const messages = yield* LanguageModel.streamText({
|
|
844
|
+
prompt,
|
|
845
|
+
toolkit,
|
|
846
|
+
disableToolCallResolution: true
|
|
847
|
+
}).pipe(withoutToolCallParising, AiParser.parseResponse({
|
|
848
|
+
emitPartial: true,
|
|
849
|
+
onBegin: () => observer.onBegin(),
|
|
850
|
+
onBlock: (block) => observer.onBlock(block),
|
|
851
|
+
onPart: (part) => observer.onPart(part),
|
|
852
|
+
onEnd: (summary) => observer.onEnd(summary)
|
|
853
|
+
}), Stream.mapEffect((block) => Effect5.gen(this, function* () {
|
|
854
|
+
if (block.pending) {
|
|
855
|
+
currentMessageId ??= Obj5.ID.random();
|
|
856
|
+
log3("emit ephemeral message", {
|
|
857
|
+
id: currentMessageId,
|
|
858
|
+
type: block._tag
|
|
859
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 145, S: this });
|
|
860
|
+
yield* Trace2.write(PartialBlock, {
|
|
861
|
+
messageId: currentMessageId,
|
|
862
|
+
role: "assistant",
|
|
863
|
+
block
|
|
864
|
+
});
|
|
865
|
+
return Option3.none();
|
|
866
|
+
} else {
|
|
867
|
+
currentMessageId ??= Obj5.ID.random();
|
|
868
|
+
const id = currentMessageId;
|
|
869
|
+
currentMessageId = null;
|
|
870
|
+
log3("emit complete message", {
|
|
871
|
+
id,
|
|
872
|
+
type: block._tag
|
|
873
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 159, S: this });
|
|
874
|
+
const message = Obj5.make(Message2.Message, {
|
|
875
|
+
id,
|
|
876
|
+
created: (/* @__PURE__ */ new Date()).toISOString(),
|
|
877
|
+
sender: {
|
|
878
|
+
role: "assistant"
|
|
879
|
+
},
|
|
880
|
+
blocks: [
|
|
881
|
+
block
|
|
882
|
+
]
|
|
883
|
+
});
|
|
884
|
+
return Option3.some(yield* this._submitMessage(message));
|
|
885
|
+
}
|
|
886
|
+
}), {
|
|
887
|
+
concurrency: 1,
|
|
888
|
+
unordered: false
|
|
889
|
+
}), Stream.filterMap((_) => _), Stream.runCollect, Effect5.map(Chunk.toArray));
|
|
890
|
+
log3.info("messages", {
|
|
891
|
+
messages
|
|
892
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 179, S: this });
|
|
893
|
+
const toolCalls = this.getToolCalls();
|
|
894
|
+
if (toolCalls.length === 0) {
|
|
895
|
+
this._ended = Date.now();
|
|
896
|
+
return {
|
|
897
|
+
messages,
|
|
898
|
+
done: true
|
|
899
|
+
};
|
|
900
|
+
} else if (!toolkit) {
|
|
901
|
+
throw new Error("No toolkit provided");
|
|
902
|
+
}
|
|
903
|
+
return {
|
|
904
|
+
messages,
|
|
905
|
+
done: false
|
|
906
|
+
};
|
|
907
|
+
}).pipe(Effect5.withSpan("AiRequest.runAgentTurn"));
|
|
908
|
+
runTools = ({ toolkit: opaqueToolkit }) => Effect5.gen(this, function* () {
|
|
909
|
+
const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : void 0;
|
|
910
|
+
const toolCalls = this.getToolCalls();
|
|
911
|
+
const toolResults = yield* Effect5.forEach(toolCalls, ({ block, message }) => {
|
|
912
|
+
if (!toolkit) {
|
|
913
|
+
throw new Error("No toolkit provided");
|
|
914
|
+
}
|
|
915
|
+
return callTool(toolkit, block);
|
|
916
|
+
});
|
|
917
|
+
yield* this._submitMessage(Obj5.make(Message2.Message, {
|
|
918
|
+
created: (/* @__PURE__ */ new Date()).toISOString(),
|
|
919
|
+
sender: {
|
|
920
|
+
role: "tool"
|
|
921
|
+
},
|
|
922
|
+
blocks: toolResults
|
|
923
|
+
}));
|
|
924
|
+
this._toolCalls += toolResults.length;
|
|
925
|
+
}).pipe(Effect5.withSpan("AiRequest.runTools"));
|
|
926
|
+
/**
|
|
927
|
+
* Run a full conversation turn loop. Equivalent to calling `begin()` then `runTurn()` in a loop.
|
|
928
|
+
*/
|
|
929
|
+
run = ({ prompt, system: systemTemplate, history = [], objects = [], blueprints = [], toolkit }) => Effect5.gen(this, function* () {
|
|
930
|
+
yield* this.begin({
|
|
931
|
+
prompt,
|
|
932
|
+
system: systemTemplate,
|
|
933
|
+
history,
|
|
934
|
+
objects,
|
|
935
|
+
blueprints
|
|
936
|
+
});
|
|
937
|
+
const system = yield* formatSystemPrompt({
|
|
938
|
+
system: systemTemplate,
|
|
939
|
+
blueprints,
|
|
940
|
+
objects
|
|
941
|
+
}).pipe(Effect5.orDie);
|
|
942
|
+
do {
|
|
943
|
+
const { done } = yield* this.runAgentTurn({
|
|
944
|
+
system,
|
|
945
|
+
toolkit
|
|
946
|
+
});
|
|
947
|
+
if (done) {
|
|
948
|
+
break;
|
|
949
|
+
}
|
|
950
|
+
yield* this.runTools({
|
|
951
|
+
toolkit
|
|
952
|
+
});
|
|
953
|
+
} while (true);
|
|
954
|
+
log3("done", {
|
|
955
|
+
pending: this._pending.length,
|
|
956
|
+
duration: this.duration,
|
|
957
|
+
tools: this._toolCalls
|
|
958
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 242, S: this });
|
|
959
|
+
return this._pending;
|
|
960
|
+
}).pipe(this._semaphore.withPermits(1), Effect5.withSpan("AiRequest.run"));
|
|
961
|
+
};
|
|
962
|
+
var createSnippet = (text, len = 32) => text.length <= len * 2 ? text : [
|
|
963
|
+
text.slice(0, len),
|
|
964
|
+
"...",
|
|
965
|
+
text.slice(-len)
|
|
966
|
+
].join("");
|
|
967
|
+
|
|
968
|
+
// src/session/toolkit.ts
|
|
969
|
+
import * as Toolkit from "@effect/ai/Toolkit";
|
|
970
|
+
import * as Effect6 from "effect/Effect";
|
|
971
|
+
import * as Layer2 from "effect/Layer";
|
|
972
|
+
import { OpaqueToolkit as OpaqueToolkit2, ToolExecutionService as ToolExecutionService2, ToolResolverService as ToolResolverService2 } from "@dxos/ai";
|
|
973
|
+
import { isTruthy } from "@dxos/util";
|
|
974
|
+
var createToolkit = ({ toolkit: toolkitProp, blueprints = [], opaqueToolkits = [] }) => Effect6.gen(function* () {
|
|
975
|
+
const blueprintToolkit = yield* ToolResolverService2.resolveToolkit(blueprints.flatMap(({ tools }) => tools));
|
|
976
|
+
const blueprintToolHandler = yield* blueprintToolkit.toContext(ToolExecutionService2.handlersFor(blueprintToolkit));
|
|
977
|
+
const opaqueToolkit = OpaqueToolkit2.merge(...opaqueToolkits);
|
|
978
|
+
const toolkitDefs = [
|
|
979
|
+
toolkitProp?.toolkit,
|
|
980
|
+
blueprintToolkit,
|
|
981
|
+
opaqueToolkit.toolkit
|
|
982
|
+
].filter(isTruthy);
|
|
983
|
+
const mergedToolkit = Toolkit.merge(...toolkitDefs);
|
|
984
|
+
const combinedHandlerLayer = Layer2.mergeAll(Layer2.succeedContext(blueprintToolHandler), toolkitProp?.layer ?? OpaqueToolkit2.empty.layer, opaqueToolkit.layer);
|
|
985
|
+
return OpaqueToolkit2.make(mergedToolkit, combinedHandlerLayer);
|
|
986
|
+
});
|
|
987
|
+
|
|
988
|
+
// src/session/version-pin.ts
|
|
989
|
+
import * as Schema5 from "effect/Schema";
|
|
990
|
+
import { getVersion } from "@dxos/echo-db";
|
|
991
|
+
import { ObjectId } from "@dxos/keys";
|
|
992
|
+
var ObjectVersionSchema = Schema5.Unknown;
|
|
993
|
+
var VersionPinSchema = Schema5.Struct({
|
|
994
|
+
// TODO(dmaretskyi): Use Ref when those support encoding.
|
|
995
|
+
objectId: ObjectId,
|
|
996
|
+
// TODO(dmaretskyi): Could be opaque.
|
|
997
|
+
version: ObjectVersionSchema
|
|
998
|
+
});
|
|
999
|
+
var VersionPin = class extends VersionPinSchema {
|
|
1000
|
+
static DISPOSITION = "version-pin";
|
|
1001
|
+
static fromObject(object) {
|
|
1002
|
+
return VersionPin.make({
|
|
1003
|
+
objectId: object.id,
|
|
1004
|
+
version: getVersion(object)
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
static createBlock(pin) {
|
|
1008
|
+
return {
|
|
1009
|
+
_tag: "json",
|
|
1010
|
+
disposition: VersionPin.DISPOSITION,
|
|
1011
|
+
data: JSON.stringify(pin)
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
};
|
|
1015
|
+
|
|
1016
|
+
// src/conversation/session.ts
|
|
1017
|
+
var __dxlog_file5 = "/__w/dxos/dxos/packages/core/compute/assistant/src/conversation/session.ts";
|
|
1018
|
+
var SUMMARY_THRESHOLD = 8e4;
|
|
1019
|
+
var AiSession = class extends Resource2 {
|
|
1020
|
+
/**
|
|
1021
|
+
* Blueprints and objects bound to the session.
|
|
302
1022
|
*/
|
|
303
1023
|
_binder;
|
|
304
|
-
|
|
305
|
-
|
|
1024
|
+
_feed;
|
|
1025
|
+
_runtime;
|
|
306
1026
|
constructor(options) {
|
|
307
1027
|
super();
|
|
308
|
-
this.
|
|
309
|
-
this.
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
L: 60,
|
|
313
|
-
S: this,
|
|
314
|
-
A: [
|
|
315
|
-
"this._queue",
|
|
316
|
-
""
|
|
317
|
-
]
|
|
318
|
-
});
|
|
1028
|
+
this._feed = options.feed;
|
|
1029
|
+
this._runtime = options.runtime;
|
|
1030
|
+
invariant2(this._feed, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 41, S: this, A: ["this._feed", ""] });
|
|
1031
|
+
invariant2(this._runtime, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 42, S: this, A: ["this._runtime", ""] });
|
|
319
1032
|
this._binder = new AiContextBinder({
|
|
320
|
-
|
|
1033
|
+
feed: this._feed,
|
|
1034
|
+
runtime: this._runtime,
|
|
321
1035
|
registry: options.registry
|
|
322
1036
|
});
|
|
323
1037
|
}
|
|
324
1038
|
async _open() {
|
|
325
1039
|
await this._binder.open(this._ctx);
|
|
326
1040
|
}
|
|
327
|
-
get
|
|
328
|
-
return this.
|
|
1041
|
+
get feed() {
|
|
1042
|
+
return this._feed;
|
|
329
1043
|
}
|
|
330
1044
|
get context() {
|
|
331
1045
|
return this._binder;
|
|
332
1046
|
}
|
|
333
|
-
get toolkit() {
|
|
334
|
-
return this._toolkit;
|
|
335
|
-
}
|
|
336
1047
|
async getHistory() {
|
|
337
|
-
const
|
|
338
|
-
|
|
1048
|
+
const queryResult = await Runtime2.runPromise(this._runtime)(Feed2.query(this._feed, Filter.type(Message3.Message)));
|
|
1049
|
+
const items = await queryResult.run();
|
|
1050
|
+
return items.filter(Obj6.instanceOf(Message3.Message));
|
|
339
1051
|
}
|
|
340
1052
|
getTools() {
|
|
341
|
-
return
|
|
342
|
-
const
|
|
343
|
-
|
|
344
|
-
toolkit: this._toolkit,
|
|
345
|
-
blueprints
|
|
1053
|
+
return Effect7.gen(this, function* () {
|
|
1054
|
+
const toolkit = yield* createToolkit({
|
|
1055
|
+
blueprints: this.context.getBlueprints()
|
|
346
1056
|
});
|
|
347
|
-
return
|
|
348
|
-
}).pipe(
|
|
1057
|
+
return toolkit.toolkit.tools;
|
|
1058
|
+
}).pipe(Effect7.orDie);
|
|
1059
|
+
}
|
|
1060
|
+
/**
|
|
1061
|
+
* Not provided by default, since users might want to override them.
|
|
1062
|
+
*/
|
|
1063
|
+
makeToolExecutionServices() {
|
|
1064
|
+
return ToolExecutionServices.pipe(Layer3.provide(Operation2.withInvocationOptions({
|
|
1065
|
+
conversation: Obj6.getDXN(this._feed).toString()
|
|
1066
|
+
})));
|
|
349
1067
|
}
|
|
350
1068
|
/**
|
|
351
1069
|
* Creates a new cancelable request effect.
|
|
352
1070
|
*/
|
|
353
1071
|
createRequest(params) {
|
|
354
|
-
return
|
|
355
|
-
const history = yield*
|
|
1072
|
+
return Effect7.gen(this, function* () {
|
|
1073
|
+
const history = yield* Effect7.promise(() => this.getHistory());
|
|
356
1074
|
const blueprints = this.context.getBlueprints();
|
|
357
|
-
const toolkit = yield* createToolkit({
|
|
358
|
-
toolkit: this._toolkit,
|
|
359
|
-
blueprints
|
|
360
|
-
});
|
|
361
1075
|
const objects = this.context.getObjects();
|
|
362
|
-
|
|
1076
|
+
log4("run", {
|
|
363
1077
|
history: history.length,
|
|
364
1078
|
blueprints: blueprints.length,
|
|
365
|
-
tools: Object.keys(toolkit.tools).length,
|
|
366
1079
|
objects: objects.length
|
|
367
|
-
}, {
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
1080
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 85, S: this });
|
|
1081
|
+
const request = new AiRequest({
|
|
1082
|
+
summarizationThreshold: SUMMARY_THRESHOLD,
|
|
1083
|
+
observer: params.observer,
|
|
1084
|
+
onOutput: (message) => Effect7.promise(() => Runtime2.runPromise(this._runtime)(Feed2.append(this._feed, [
|
|
1085
|
+
message
|
|
1086
|
+
])))
|
|
372
1087
|
});
|
|
373
|
-
|
|
374
|
-
const messages = yield* session.run({
|
|
1088
|
+
yield* request.begin({
|
|
375
1089
|
history,
|
|
376
1090
|
blueprints,
|
|
377
|
-
toolkit,
|
|
378
1091
|
objects,
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
message
|
|
382
|
-
]))
|
|
383
|
-
}).pipe(Effect2.provide(Layer.mergeAll(Layer.succeed(AiContextService, {
|
|
384
|
-
binder: this.context
|
|
385
|
-
}), Layer.succeed(AiConversationService, this))));
|
|
386
|
-
log2("result", {
|
|
387
|
-
messages: messages.length,
|
|
388
|
-
duration: session.duration,
|
|
389
|
-
toolCalls: session.toolCalls
|
|
390
|
-
}, {
|
|
391
|
-
F: __dxlog_file2,
|
|
392
|
-
L: 141,
|
|
393
|
-
S: this,
|
|
394
|
-
C: (f, a) => f(...a)
|
|
1092
|
+
prompt: params.prompt,
|
|
1093
|
+
system: params.system
|
|
395
1094
|
});
|
|
396
|
-
|
|
397
|
-
|
|
1095
|
+
do {
|
|
1096
|
+
yield* Effect7.promise(() => this.context.sync());
|
|
1097
|
+
const currentBlueprints = this.context.getBlueprints();
|
|
1098
|
+
const mcps = yield* connectMcpServers(currentBlueprints, params.mcpServers);
|
|
1099
|
+
const toolkit = yield* createToolkit({
|
|
1100
|
+
toolkit: params.toolkit,
|
|
1101
|
+
blueprints: currentBlueprints,
|
|
1102
|
+
opaqueToolkits: mcps
|
|
1103
|
+
});
|
|
1104
|
+
log4("toolkit", {
|
|
1105
|
+
tools: Record2.keys(toolkit.toolkit.tools)
|
|
1106
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 114, S: this });
|
|
1107
|
+
const system = yield* formatSystemPrompt({
|
|
1108
|
+
system: params.system,
|
|
1109
|
+
blueprints: currentBlueprints,
|
|
1110
|
+
objects: this.context.getObjects()
|
|
1111
|
+
}).pipe(Effect7.orDie);
|
|
1112
|
+
const { done } = yield* request.runAgentTurn({
|
|
1113
|
+
system,
|
|
1114
|
+
toolkit
|
|
1115
|
+
});
|
|
1116
|
+
if (done) {
|
|
1117
|
+
break;
|
|
1118
|
+
}
|
|
1119
|
+
yield* request.runTools({
|
|
1120
|
+
toolkit
|
|
1121
|
+
});
|
|
1122
|
+
} while (true);
|
|
1123
|
+
log4("result", {
|
|
1124
|
+
messages: request.pending.length,
|
|
1125
|
+
duration: request.duration,
|
|
1126
|
+
toolCalls: request.toolCalls
|
|
1127
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 133, S: this });
|
|
1128
|
+
return [
|
|
1129
|
+
...request.pending
|
|
1130
|
+
];
|
|
1131
|
+
}).pipe(Effect7.provide(Layer3.mergeAll(Layer3.succeed(AiContextService, {
|
|
1132
|
+
binder: this.context
|
|
1133
|
+
}), Layer3.succeed(AiSessionService, this), Operation2.withInvocationOptions({
|
|
1134
|
+
conversation: Obj6.getDXN(this._feed).toString()
|
|
1135
|
+
}))), Effect7.withSpan("AiSession.createRequest"));
|
|
398
1136
|
}
|
|
399
1137
|
};
|
|
400
|
-
var
|
|
1138
|
+
var AiSessionService = class _AiSessionService extends Context4.Tag("@dxos/assistant/AiSessionService")() {
|
|
401
1139
|
/**
|
|
402
|
-
* Create a new
|
|
1140
|
+
* Create a new session layer from options.
|
|
403
1141
|
*/
|
|
404
|
-
static layer = (options) =>
|
|
405
|
-
const
|
|
406
|
-
return
|
|
1142
|
+
static layer = (options) => aiContextFromSession.pipe(Layer3.provideMerge(Layer3.scoped(_AiSessionService, Effect7.gen(function* () {
|
|
1143
|
+
const session = yield* acquireReleaseResource(() => new AiSession(options));
|
|
1144
|
+
return session;
|
|
407
1145
|
}))));
|
|
408
1146
|
/**
|
|
409
|
-
* Create a new
|
|
1147
|
+
* Create a new session with a new feed.
|
|
410
1148
|
*/
|
|
411
|
-
static
|
|
412
|
-
|
|
1149
|
+
static layerNewFeed = (options) => Layer3.unwrapScoped(Effect7.gen(function* () {
|
|
1150
|
+
const feed = yield* Database2.add(Feed2.make());
|
|
1151
|
+
const runtime2 = yield* Effect7.runtime();
|
|
1152
|
+
return _AiSessionService.layer({
|
|
413
1153
|
...options,
|
|
414
|
-
|
|
1154
|
+
feed,
|
|
1155
|
+
runtime: runtime2
|
|
415
1156
|
});
|
|
416
1157
|
}));
|
|
417
1158
|
/**
|
|
418
|
-
* Run a prompt in the current
|
|
1159
|
+
* Run a prompt in the current session.
|
|
419
1160
|
*/
|
|
420
|
-
static run = (params) =>
|
|
421
|
-
const
|
|
422
|
-
return yield*
|
|
1161
|
+
static run = (params) => Effect7.gen(function* () {
|
|
1162
|
+
const session = yield* _AiSessionService;
|
|
1163
|
+
return yield* session.createRequest(params);
|
|
423
1164
|
});
|
|
424
1165
|
};
|
|
425
|
-
var
|
|
426
|
-
const
|
|
1166
|
+
var aiContextFromSession = Layer3.effect(AiContextService, Effect7.gen(function* () {
|
|
1167
|
+
const session = yield* AiSessionService;
|
|
427
1168
|
return {
|
|
428
|
-
binder:
|
|
1169
|
+
binder: session.context
|
|
429
1170
|
};
|
|
430
1171
|
}));
|
|
1172
|
+
var connectMcpServers = (blueprints, spaceMcpServers = []) => {
|
|
1173
|
+
const blueprintServers = pipe4(blueprints, Array4.flatMap((_) => _.mcpServers ?? []), Array4.map(({ url, protocol, apiKey }) => ({
|
|
1174
|
+
url,
|
|
1175
|
+
protocol,
|
|
1176
|
+
apiKey
|
|
1177
|
+
})));
|
|
1178
|
+
const spaceServers = spaceMcpServers.map(({ url, protocol, apiKey }) => ({
|
|
1179
|
+
url,
|
|
1180
|
+
protocol,
|
|
1181
|
+
apiKey
|
|
1182
|
+
}));
|
|
1183
|
+
const allServers = [
|
|
1184
|
+
...blueprintServers,
|
|
1185
|
+
...spaceServers
|
|
1186
|
+
];
|
|
1187
|
+
return pipe4(allServers, Effect7.forEach((options) => McpToolkit.make(options).pipe(
|
|
1188
|
+
// NOTE: Type-inference fails here without explicit void return.
|
|
1189
|
+
Effect7.tap((toolkit) => log4.info("Connected to MCP server", {
|
|
1190
|
+
url: options.url,
|
|
1191
|
+
tools: Object.keys(toolkit.toolkit.tools).length
|
|
1192
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 197, S: void 0 })),
|
|
1193
|
+
// Surface typed connection failures via ephemeral trace + warn log, then drop the server.
|
|
1194
|
+
Effect7.tapError((error) => Effect7.gen(function* () {
|
|
1195
|
+
log4.warn("Failed to connect to MCP server", {
|
|
1196
|
+
url: error.url,
|
|
1197
|
+
protocol: error.protocol,
|
|
1198
|
+
message: error.message
|
|
1199
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 202, S: this });
|
|
1200
|
+
yield* Trace3.write(McpServerError, {
|
|
1201
|
+
url: error.url,
|
|
1202
|
+
protocol: error.protocol,
|
|
1203
|
+
message: error.message
|
|
1204
|
+
});
|
|
1205
|
+
})),
|
|
1206
|
+
// Catch unexpected defects too (e.g. malformed tool schemas) so a single broken
|
|
1207
|
+
// server can never abort the whole turn — surface them through the same channel.
|
|
1208
|
+
Effect7.catchAllDefect((defect) => Effect7.gen(function* () {
|
|
1209
|
+
const message = defect instanceof Error ? defect.message : String(defect);
|
|
1210
|
+
log4.warn("Unexpected MCP defect", {
|
|
1211
|
+
url: options.url,
|
|
1212
|
+
message
|
|
1213
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 216, S: this });
|
|
1214
|
+
yield* Trace3.write(McpServerError, {
|
|
1215
|
+
url: options.url,
|
|
1216
|
+
protocol: options.protocol,
|
|
1217
|
+
message: `Unexpected MCP failure: ${message}`
|
|
1218
|
+
});
|
|
1219
|
+
return yield* Effect7.fail(new McpToolkit.McpConnectionError({
|
|
1220
|
+
url: options.url,
|
|
1221
|
+
protocol: options.protocol,
|
|
1222
|
+
message
|
|
1223
|
+
}));
|
|
1224
|
+
})),
|
|
1225
|
+
Effect7.either
|
|
1226
|
+
)), Effect7.map(Array4.filterMap((_) => Either.getRight(_))));
|
|
1227
|
+
};
|
|
431
1228
|
|
|
432
1229
|
// src/diff.ts
|
|
433
1230
|
import { next as A } from "@automerge/automerge";
|
|
434
1231
|
import { DocAccessor, toCursorRange } from "@dxos/echo-db";
|
|
435
|
-
import { log as
|
|
436
|
-
import { isNonNullable } from "@dxos/util";
|
|
437
|
-
var
|
|
1232
|
+
import { log as log5 } from "@dxos/log";
|
|
1233
|
+
import { isNonNullable as isNonNullable2 } from "@dxos/util";
|
|
1234
|
+
var __dxlog_file6 = "/__w/dxos/dxos/packages/core/compute/assistant/src/diff.ts";
|
|
438
1235
|
var reduceDiffs = (diffs) => {
|
|
439
1236
|
return diffs.reduce((acc, diff) => {
|
|
440
1237
|
const current = acc[acc.length - 1];
|
|
@@ -478,7 +1275,7 @@ var computeDiffsWithCursors = (accessor, diffs) => {
|
|
|
478
1275
|
text: diff.replace
|
|
479
1276
|
};
|
|
480
1277
|
}
|
|
481
|
-
}).filter(
|
|
1278
|
+
}).filter(isNonNullable2);
|
|
482
1279
|
};
|
|
483
1280
|
var applyDiffs = (accessor, diffs, { errorOnNotFound = false } = {}) => {
|
|
484
1281
|
for (const diff of reduceDiffs(diffs)) {
|
|
@@ -491,12 +1288,7 @@ var applyDiffs = (accessor, diffs, { errorOnNotFound = false } = {}) => {
|
|
|
491
1288
|
if (errorOnNotFound) {
|
|
492
1289
|
throw new Error(`Diff not found: ${diff.match}`);
|
|
493
1290
|
} else {
|
|
494
|
-
|
|
495
|
-
F: __dxlog_file3,
|
|
496
|
-
L: 86,
|
|
497
|
-
S: void 0,
|
|
498
|
-
C: (f, a) => f(...a)
|
|
499
|
-
});
|
|
1291
|
+
log5.warn("diff not found", diff, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 71, S: void 0 });
|
|
500
1292
|
}
|
|
501
1293
|
}
|
|
502
1294
|
});
|
|
@@ -506,11 +1298,11 @@ var applyDiffs = (accessor, diffs, { errorOnNotFound = false } = {}) => {
|
|
|
506
1298
|
|
|
507
1299
|
// src/execution-graph.ts
|
|
508
1300
|
import { AgentStatus } from "@dxos/ai";
|
|
509
|
-
import { Obj as
|
|
1301
|
+
import { Obj as Obj7 } from "@dxos/echo";
|
|
510
1302
|
import { MESSAGE_PROPERTY_TOOL_CALL_ID } from "@dxos/functions";
|
|
511
1303
|
import { LogLevel } from "@dxos/log";
|
|
512
|
-
import { ContentBlock, Message as
|
|
513
|
-
import { isNonNullable as
|
|
1304
|
+
import { ContentBlock as ContentBlock3, Message as Message4 } from "@dxos/types";
|
|
1305
|
+
import { isNonNullable as isNonNullable3 } from "@dxos/util";
|
|
514
1306
|
var SKIP_BLOCKS = [
|
|
515
1307
|
"text"
|
|
516
1308
|
];
|
|
@@ -533,9 +1325,9 @@ var ExecutionGraph = class {
|
|
|
533
1325
|
addEvents(events) {
|
|
534
1326
|
const sortedEvents = this.sortObjectsByCreated(events);
|
|
535
1327
|
for (const event of sortedEvents) {
|
|
536
|
-
if (
|
|
1328
|
+
if (Obj7.instanceOf(Message4.Message, event)) {
|
|
537
1329
|
this._processMessage(event);
|
|
538
|
-
} else if (
|
|
1330
|
+
} else if (Obj7.instanceOf(AgentStatus, event)) {
|
|
539
1331
|
this._processAgentStatus(event);
|
|
540
1332
|
}
|
|
541
1333
|
}
|
|
@@ -637,11 +1429,17 @@ var ExecutionGraph = class {
|
|
|
637
1429
|
*/
|
|
638
1430
|
_updatePendingToolResults(toolCallId, agentStatusId) {
|
|
639
1431
|
const toolResultId = this._pendingToolResults.get(toolCallId);
|
|
640
|
-
if (!toolResultId)
|
|
1432
|
+
if (!toolResultId) {
|
|
1433
|
+
return;
|
|
1434
|
+
}
|
|
641
1435
|
const toolResultCommit = this._commits.find((c) => c.id === toolResultId);
|
|
642
|
-
if (!toolResultCommit)
|
|
1436
|
+
if (!toolResultCommit) {
|
|
1437
|
+
return;
|
|
1438
|
+
}
|
|
643
1439
|
const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);
|
|
644
|
-
if (!toolCallCommitId)
|
|
1440
|
+
if (!toolCallCommitId) {
|
|
1441
|
+
return;
|
|
1442
|
+
}
|
|
645
1443
|
const toolCallIndex = toolResultCommit.parents.indexOf(toolCallCommitId);
|
|
646
1444
|
if (toolCallIndex !== -1) {
|
|
647
1445
|
toolResultCommit.parents[toolCallIndex] = agentStatusId;
|
|
@@ -653,7 +1451,9 @@ var ExecutionGraph = class {
|
|
|
653
1451
|
*/
|
|
654
1452
|
_handleLateToolResultUpdate(toolCallId, toolResultId) {
|
|
655
1453
|
const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);
|
|
656
|
-
if (!toolCallCommitId)
|
|
1454
|
+
if (!toolCallCommitId) {
|
|
1455
|
+
return;
|
|
1456
|
+
}
|
|
657
1457
|
const messageId = toolCallCommitId.split("_toolCall_")[0];
|
|
658
1458
|
const toolCallBranch = `${messageId}_${toolCallId}`;
|
|
659
1459
|
const agentStatusCommitId = this._lastCommitByBranch.get(toolCallBranch);
|
|
@@ -722,7 +1522,7 @@ var messageToCommits = (message, lastBlockId, toolCallIds, lastCommitByBranch, s
|
|
|
722
1522
|
previousBlockId = commit.id;
|
|
723
1523
|
}
|
|
724
1524
|
return commit;
|
|
725
|
-
}).filter(
|
|
1525
|
+
}).filter(isNonNullable3);
|
|
726
1526
|
};
|
|
727
1527
|
var getBlockParents = (block, previousBlockId, message, toolCallIds, lastCommitByBranch) => {
|
|
728
1528
|
const parents = [];
|
|
@@ -756,7 +1556,9 @@ var createBlockCommit = (block, message, branch, parents, idx) => {
|
|
|
756
1556
|
const timestamp = new Date(message.created);
|
|
757
1557
|
switch (block._tag) {
|
|
758
1558
|
case "text":
|
|
759
|
-
if (!block.text.trim().length)
|
|
1559
|
+
if (!block.text.trim().length) {
|
|
1560
|
+
return null;
|
|
1561
|
+
}
|
|
760
1562
|
return {
|
|
761
1563
|
id: getGenericBlockId(message.id, idx),
|
|
762
1564
|
branch,
|
|
@@ -769,7 +1571,7 @@ var createBlockCommit = (block, message, branch, parents, idx) => {
|
|
|
769
1571
|
],
|
|
770
1572
|
message: "Processing request..."
|
|
771
1573
|
} : {
|
|
772
|
-
icon: "ph--
|
|
1574
|
+
icon: "ph--drone--regular",
|
|
773
1575
|
message: `Response (${block.text.split(" ").length} words)`
|
|
774
1576
|
}
|
|
775
1577
|
};
|
|
@@ -793,7 +1595,7 @@ var createBlockCommit = (block, message, branch, parents, idx) => {
|
|
|
793
1595
|
level: block.error ? LogLevel.ERROR : LogLevel.INFO,
|
|
794
1596
|
message: block.error ? "Tool error: " + block.error : "Tool call succeeded"
|
|
795
1597
|
};
|
|
796
|
-
case "
|
|
1598
|
+
case "stats":
|
|
797
1599
|
return {
|
|
798
1600
|
id: getGenericBlockId(message.id, idx),
|
|
799
1601
|
branch,
|
|
@@ -801,7 +1603,7 @@ var createBlockCommit = (block, message, branch, parents, idx) => {
|
|
|
801
1603
|
timestamp,
|
|
802
1604
|
icon: "ph--rocket--regular",
|
|
803
1605
|
level: LogLevel.INFO,
|
|
804
|
-
message:
|
|
1606
|
+
message: ContentBlock3.createStatsMessage(block)
|
|
805
1607
|
};
|
|
806
1608
|
case "status":
|
|
807
1609
|
return {
|
|
@@ -871,48 +1673,49 @@ var stringifyRef = (ref) => {
|
|
|
871
1673
|
return ref.dxn.asEchoDXN()?.echoId ?? ref.dxn.asQueueDXN()?.objectId ?? "";
|
|
872
1674
|
};
|
|
873
1675
|
var stringifyObject = (obj) => {
|
|
874
|
-
return
|
|
1676
|
+
return Obj7.getLabel(obj) ?? Obj7.getTypename(obj) ?? obj.id;
|
|
875
1677
|
};
|
|
876
1678
|
|
|
877
1679
|
// src/templates/system.ts
|
|
878
1680
|
import defaultsDeep from "lodash.defaultsdeep";
|
|
879
|
-
import { Template } from "@dxos/
|
|
1681
|
+
import { Template as Template2 } from "@dxos/compute";
|
|
880
1682
|
|
|
881
|
-
// raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/instructions/format.tpl?raw
|
|
1683
|
+
// raw-loader:/__w/dxos/dxos/packages/core/compute/assistant/src/templates/instructions/format.tpl?raw
|
|
882
1684
|
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";
|
|
883
1685
|
|
|
884
|
-
// raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/instructions/system.tpl?raw
|
|
885
|
-
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##
|
|
1686
|
+
// raw-loader:/__w/dxos/dxos/packages/core/compute/assistant/src/templates/instructions/system.tpl?raw
|
|
1687
|
+
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- NEVER output narration text outside `<status>` tags or the final user-facing answer. Any progress update, transition sentence, or \"let me\u2026\" lead-in MUST be wrapped in `<status>...</status>`. Violating this is an error.\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- After a `</status>` tag, the next output must be either another `<status>` tag, a tool call, or the final user-facing answer \u2014 never a transition sentence.\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\nDo not do (transition sentence after a status tag, before tool calls):\n\n<incorrect_example>\n<status>Doing X</status>\nLet me start by doing X:\n// tool call\n</incorrect_example>\n\n- NEVER write a lead-in sentence before a tool call. Use a `<status>` tag instead.\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>";
|
|
886
1688
|
|
|
887
1689
|
// src/templates/system.ts
|
|
888
|
-
var createSystemPrompt = (options = {}) =>
|
|
1690
|
+
var createSystemPrompt = (options = {}) => Template2.process(format_default, defaultsDeep(options, {
|
|
889
1691
|
DATETIME: (/* @__PURE__ */ new Date()).toISOString()
|
|
890
1692
|
}));
|
|
1693
|
+
var SYSTEM_ID = "01K2J2FZWH39F55CS7B26GP1Q3";
|
|
891
1694
|
var templates = {
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
/**
|
|
895
|
-
* NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.
|
|
896
|
-
*/
|
|
897
|
-
id: "01K2J2FZWH39F55CS7B26GP1Q3",
|
|
1695
|
+
system: Template2.make({
|
|
1696
|
+
id: SYSTEM_ID,
|
|
898
1697
|
source: system_default
|
|
899
1698
|
})
|
|
900
1699
|
};
|
|
901
1700
|
export {
|
|
1701
|
+
AgentRequestBegin,
|
|
1702
|
+
AgentRequestEnd,
|
|
902
1703
|
AiAssistantError,
|
|
903
1704
|
AiContextBinder,
|
|
904
1705
|
AiContextService,
|
|
905
|
-
AiConversation,
|
|
906
|
-
AiConversationService,
|
|
907
1706
|
AiModelError,
|
|
1707
|
+
AiRequest,
|
|
908
1708
|
AiSession,
|
|
1709
|
+
AiSessionService,
|
|
909
1710
|
ArtifactDiffResolver,
|
|
910
1711
|
ArtifactId,
|
|
911
1712
|
Bindings,
|
|
1713
|
+
CompleteBlock,
|
|
912
1714
|
ContextBinding,
|
|
913
1715
|
ExecutionGraph,
|
|
914
1716
|
GenerationObserver,
|
|
915
|
-
|
|
1717
|
+
McpServerError,
|
|
1718
|
+
PartialBlock,
|
|
916
1719
|
RefFromLLM,
|
|
917
1720
|
ToolExecutionServices,
|
|
918
1721
|
VersionPin,
|
|
@@ -923,8 +1726,10 @@ export {
|
|
|
923
1726
|
createToolkit,
|
|
924
1727
|
formatSystemPrompt,
|
|
925
1728
|
formatUserPrompt,
|
|
926
|
-
|
|
927
|
-
|
|
1729
|
+
getOperationFromTool,
|
|
1730
|
+
makeToolExecutionService,
|
|
1731
|
+
makeToolExecutionServiceFromOperationInvoker,
|
|
1732
|
+
makeToolResolverFromOperations,
|
|
928
1733
|
reduceDiffs,
|
|
929
1734
|
templates
|
|
930
1735
|
};
|