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