@dxos/assistant 0.8.4-main.406dc2a → 0.8.4-main.548089c
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 +114 -161
- package/dist/lib/browser/extraction/index.mjs.map +4 -4
- package/dist/lib/browser/index.mjs +508 -151
- 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 +114 -161
- package/dist/lib/node-esm/extraction/index.mjs.map +4 -4
- package/dist/lib/node-esm/index.mjs +508 -151
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/types/src/conversation/conversation.d.ts +4 -7
- 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 +8 -16
- package/dist/types/src/errors.d.ts.map +1 -1
- package/dist/types/src/execution-graph.d.ts +3 -0
- package/dist/types/src/execution-graph.d.ts.map +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 +28 -24
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction.d.ts +14 -7
- package/dist/types/src/extraction/extraction.d.ts.map +1 -1
- package/dist/types/src/functions/services.d.ts +2 -1
- package/dist/types/src/functions/services.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/format.d.ts +16 -16
- 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 +2 -2
- package/dist/types/src/session/observer.d.ts.map +1 -1
- package/dist/types/src/session/session.d.ts +3 -3
- package/dist/types/src/session/session.d.ts.map +1 -1
- package/dist/types/src/session/version-pin.d.ts +1 -1
- package/dist/types/src/session/version-pin.d.ts.map +1 -1
- package/dist/types/src/types/artifact.d.ts +4 -0
- package/dist/types/src/types/artifact.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +22 -20
- package/src/conversation/conversation.ts +8 -12
- package/src/diff.test.ts +3 -3
- package/src/diff.ts +5 -0
- package/src/execution-graph.test.ts +44 -42
- package/src/execution-graph.ts +19 -10
- package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +2 -2
- package/src/extraction/extraction-llm-function/extraction-llm-function.ts +44 -54
- package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +10 -9
- package/src/extraction/extraction-ner-function/extraction-ner-function.ts +36 -44
- package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +10 -5
- package/src/extraction/extraction.ts +5 -4
- package/src/functions/services.ts +11 -7
- package/src/session/GenericToolkit.ts +130 -0
- package/src/session/format.test.ts +4 -3
- package/src/session/format.ts +4 -5
- package/src/session/index.ts +2 -0
- package/src/session/observer.ts +2 -2
- package/src/session/session.test.ts +2 -2
- package/src/session/session.ts +9 -8
- package/src/session/version-pin.ts +2 -3
- package/src/templates/{format.tpl → instructions/format.tpl} +1 -0
- package/src/templates/system.ts +2 -2
- package/src/types/artifact.ts +20 -1
- package/dist/lib/browser/chunk-CWGVG235.mjs +0 -380
- package/dist/lib/browser/chunk-CWGVG235.mjs.map +0 -7
- package/dist/lib/browser/chunk-UB26N5UF.mjs +0 -89
- package/dist/lib/browser/chunk-UB26N5UF.mjs.map +0 -7
- package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs +0 -13
- package/dist/lib/node-esm/chunk-BCFXTNSK.mjs +0 -91
- package/dist/lib/node-esm/chunk-BCFXTNSK.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-OV5PMQPB.mjs +0 -382
- package/dist/lib/node-esm/chunk-OV5PMQPB.mjs.map +0 -7
- package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs +0 -14
- package/dist/types/src/summarization/summarization.test.d.ts +0 -2
- package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
- package/src/summarization/summarization.test.ts +0 -202
- /package/dist/lib/browser/{named-entity-recognition-QPYHML66.mjs.map → chunk-J5LGTIGS.mjs.map} +0 -0
- /package/dist/lib/node-esm/{named-entity-recognition-2HDF46YX.mjs.map → chunk-HSLMI22Q.mjs.map} +0 -0
- /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
- /package/src/templates/{system.tpl → instructions/system.tpl} +0 -0
|
@@ -1,13 +1,7 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
AiSession,
|
|
6
|
-
ArtifactDiffResolver,
|
|
7
|
-
GenerationObserver,
|
|
8
|
-
VersionPin,
|
|
9
|
-
createToolkit
|
|
10
|
-
} from "./chunk-OV5PMQPB.mjs";
|
|
3
|
+
__export
|
|
4
|
+
} from "./chunk-HSLMI22Q.mjs";
|
|
11
5
|
|
|
12
6
|
// src/conversation/context.ts
|
|
13
7
|
import { computed } from "@preact/signals-core";
|
|
@@ -20,19 +14,6 @@ import { Resource } from "@dxos/context";
|
|
|
20
14
|
import { DXN, Filter, Obj, Query, Type } from "@dxos/echo";
|
|
21
15
|
import { invariant } from "@dxos/invariant";
|
|
22
16
|
import { ComplexSet } from "@dxos/util";
|
|
23
|
-
function _define_property(obj, key, value) {
|
|
24
|
-
if (key in obj) {
|
|
25
|
-
Object.defineProperty(obj, key, {
|
|
26
|
-
value,
|
|
27
|
-
enumerable: true,
|
|
28
|
-
configurable: true,
|
|
29
|
-
writable: true
|
|
30
|
-
});
|
|
31
|
-
} else {
|
|
32
|
-
obj[key] = value;
|
|
33
|
-
}
|
|
34
|
-
return obj;
|
|
35
|
-
}
|
|
36
17
|
var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/conversation/context.ts";
|
|
37
18
|
var ContextBinding = Schema.Struct({
|
|
38
19
|
blueprints: Schema.Struct({
|
|
@@ -49,18 +30,28 @@ var ContextBinding = Schema.Struct({
|
|
|
49
30
|
version: "0.1.0"
|
|
50
31
|
}));
|
|
51
32
|
var Bindings = class {
|
|
33
|
+
blueprints = new ComplexSet((ref) => ref.dxn.toString());
|
|
34
|
+
// TODO(burdon): Some DXNs have the Space prefix so only compare the object ID.
|
|
35
|
+
objects = new ComplexSet((ref) => ref.dxn.asEchoDXN()?.echoId);
|
|
52
36
|
toJSON() {
|
|
53
37
|
return {
|
|
54
38
|
blueprints: Array2.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),
|
|
55
39
|
objects: Array2.fromIterable(this.objects).map((ref) => ref.dxn.toString())
|
|
56
40
|
};
|
|
57
41
|
}
|
|
58
|
-
constructor() {
|
|
59
|
-
_define_property(this, "blueprints", new ComplexSet((ref) => ref.dxn.toString()));
|
|
60
|
-
_define_property(this, "objects", new ComplexSet((ref) => ref.dxn.asEchoDXN()?.echoId));
|
|
61
|
-
}
|
|
62
42
|
};
|
|
63
43
|
var AiContextBinder = class extends Resource {
|
|
44
|
+
_queue;
|
|
45
|
+
/**
|
|
46
|
+
* Reactive query of all bindings.
|
|
47
|
+
*/
|
|
48
|
+
// TODO(burdon): Cache value?
|
|
49
|
+
_bindings;
|
|
50
|
+
_blueprints;
|
|
51
|
+
_objects;
|
|
52
|
+
constructor(_queue) {
|
|
53
|
+
super(), this._queue = _queue;
|
|
54
|
+
}
|
|
64
55
|
get bindings() {
|
|
65
56
|
invariant(this._bindings, "AiContextBinder not open", {
|
|
66
57
|
F: __dxlog_file,
|
|
@@ -174,41 +165,412 @@ var AiContextBinder = class extends Resource {
|
|
|
174
165
|
return context;
|
|
175
166
|
}));
|
|
176
167
|
}
|
|
177
|
-
constructor(_queue) {
|
|
178
|
-
super(), _define_property(this, "_queue", void 0), /**
|
|
179
|
-
* Reactive query of all bindings.
|
|
180
|
-
*/
|
|
181
|
-
// TODO(burdon): Cache value?
|
|
182
|
-
_define_property(this, "_bindings", void 0), _define_property(this, "_blueprints", void 0), _define_property(this, "_objects", void 0), this._queue = _queue;
|
|
183
|
-
}
|
|
184
168
|
};
|
|
185
169
|
var AiContextService = class extends Context.Tag("@dxos/assistant/AiContextService")() {
|
|
186
170
|
};
|
|
187
171
|
|
|
188
172
|
// src/conversation/conversation.ts
|
|
189
|
-
import * as
|
|
173
|
+
import * as Array5 from "effect/Array";
|
|
174
|
+
import * as Effect6 from "effect/Effect";
|
|
175
|
+
import * as Option2 from "effect/Option";
|
|
176
|
+
import { Resource as Resource2 } from "@dxos/context";
|
|
177
|
+
import { Obj as Obj4 } from "@dxos/echo";
|
|
178
|
+
import { DatabaseService as DatabaseService2 } from "@dxos/echo-db";
|
|
179
|
+
import { log as log3 } from "@dxos/log";
|
|
180
|
+
import { Message as Message3 } from "@dxos/types";
|
|
181
|
+
|
|
182
|
+
// src/session/artifact-diff.ts
|
|
183
|
+
import * as Context2 from "effect/Context";
|
|
184
|
+
var ArtifactDiffResolver = class extends Context2.Tag("@dxos/assistant/ArtifactDiffResolver")() {
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
// src/session/observer.ts
|
|
190
188
|
import * as Effect from "effect/Effect";
|
|
189
|
+
import * as Function2 from "effect/Function";
|
|
190
|
+
var GenerationObserver = Object.freeze({
|
|
191
|
+
make: ({ onBegin = Function2.constant(Effect.void), onPart = Function2.constant(Effect.void), onBlock = Function2.constant(Effect.void), onEnd = Function2.constant(Effect.void), onMessage = Function2.constant(Effect.void) } = {}) => ({
|
|
192
|
+
onBegin,
|
|
193
|
+
onPart,
|
|
194
|
+
onBlock,
|
|
195
|
+
onEnd,
|
|
196
|
+
onMessage
|
|
197
|
+
}),
|
|
198
|
+
noop: () => GenerationObserver.make(),
|
|
199
|
+
/**
|
|
200
|
+
* Debug printer to be used in unit-tests and browser devtools.
|
|
201
|
+
*/
|
|
202
|
+
fromPrinter: (printer) => GenerationObserver.make({
|
|
203
|
+
onBlock: (block) => Effect.sync(() => {
|
|
204
|
+
if (block.pending) {
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
printer.printContentBlock(block);
|
|
208
|
+
}),
|
|
209
|
+
onMessage: (message) => Effect.sync(() => {
|
|
210
|
+
if (message.sender.role === "assistant") {
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
printer.printMessage(message);
|
|
214
|
+
})
|
|
215
|
+
})
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
// src/session/session.ts
|
|
219
|
+
import * as LanguageModel from "@effect/ai/LanguageModel";
|
|
220
|
+
import * as Chunk from "effect/Chunk";
|
|
221
|
+
import * as Effect3 from "effect/Effect";
|
|
222
|
+
import * as Stream from "effect/Stream";
|
|
223
|
+
import { AiParser, AiPreprocessor, callTool, getToolCalls } from "@dxos/ai";
|
|
224
|
+
import { todo } from "@dxos/debug";
|
|
225
|
+
import { Obj as Obj3 } from "@dxos/echo";
|
|
226
|
+
import { TracingService } from "@dxos/functions";
|
|
227
|
+
import { log as log2 } from "@dxos/log";
|
|
228
|
+
import { Message as Message2 } from "@dxos/types";
|
|
229
|
+
|
|
230
|
+
// src/session/format.ts
|
|
231
|
+
import * as Array4 from "effect/Array";
|
|
232
|
+
import * as Effect2 from "effect/Effect";
|
|
233
|
+
import * as Function3 from "effect/Function";
|
|
191
234
|
import * as Option from "effect/Option";
|
|
192
|
-
import {
|
|
235
|
+
import { Template } from "@dxos/blueprints";
|
|
193
236
|
import { Obj as Obj2 } from "@dxos/echo";
|
|
194
|
-
import { DatabaseService } from "@dxos/
|
|
237
|
+
import { DatabaseService, ObjectVersion } from "@dxos/echo-db";
|
|
195
238
|
import { log } from "@dxos/log";
|
|
196
|
-
import {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
239
|
+
import { Message } from "@dxos/types";
|
|
240
|
+
import { trim } from "@dxos/util";
|
|
241
|
+
|
|
242
|
+
// src/errors.ts
|
|
243
|
+
import { BaseError } from "@dxos/errors";
|
|
244
|
+
var AiModelError = class extends BaseError.extend("AI_MODEL_ERROR", "AI model error") {
|
|
245
|
+
};
|
|
246
|
+
var AiAssistantError = class extends BaseError.extend("AI_ASSISTANT_ERROR", "AI assistant error") {
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
// src/session/format.ts
|
|
250
|
+
var __dxlog_file2 = "/__w/dxos/dxos/packages/core/assistant/src/session/format.ts";
|
|
251
|
+
var formatSystemPrompt = ({ system, blueprints = [], objects = [] }) => Effect2.gen(function* () {
|
|
252
|
+
const blueprintDefs = yield* Function3.pipe(blueprints, Effect2.forEach((blueprint) => Effect2.succeed(blueprint.instructions)), Effect2.flatMap(Effect2.forEach((template) => DatabaseService.loadOption(template.source))), Effect2.map(Array4.filter(Option.isSome)), Effect2.map(Array4.map((template) => trim`
|
|
253
|
+
<blueprint>
|
|
254
|
+
${Template.process(template.value.content)}
|
|
255
|
+
</blueprint>
|
|
256
|
+
`)), Effect2.map((blueprints2) => blueprints2.length > 0 ? [
|
|
257
|
+
"## Blueprints Definitions",
|
|
258
|
+
...blueprints2
|
|
259
|
+
].join("\n\n") : void 0));
|
|
260
|
+
const objectDefs = yield* Function3.pipe(objects, Effect2.forEach((object) => Effect2.succeed(trim`
|
|
261
|
+
<object>
|
|
262
|
+
<dxn>${Obj2.getDXN(object)}</dxn>
|
|
263
|
+
<typename>${Obj2.getTypename(object)}</typename>
|
|
264
|
+
</object>
|
|
265
|
+
`)), Effect2.map((objects2) => objects2.length > 0 ? [
|
|
266
|
+
"## Context Objects",
|
|
267
|
+
...objects2
|
|
268
|
+
].join("\n\n") : void 0));
|
|
269
|
+
return yield* Function3.pipe(Effect2.succeed([
|
|
270
|
+
system,
|
|
271
|
+
blueprintDefs,
|
|
272
|
+
objectDefs
|
|
273
|
+
].filter((def) => def !== void 0)), Effect2.map((parts) => parts.join("\n\n")));
|
|
274
|
+
});
|
|
275
|
+
var formatUserPrompt = ({ prompt, history = [] }) => Effect2.gen(function* () {
|
|
276
|
+
const blocks = [];
|
|
277
|
+
const artifactDiffResolver = yield* Effect2.serviceOption(ArtifactDiffResolver);
|
|
278
|
+
if (Option.isSome(artifactDiffResolver)) {
|
|
279
|
+
const versions = gatherObjectVersions(history);
|
|
280
|
+
const artifactDiff = yield* Effect2.tryPromise({
|
|
281
|
+
try: () => artifactDiffResolver.value.resolve([
|
|
282
|
+
...versions.entries()
|
|
283
|
+
].map(([id, version]) => ({
|
|
284
|
+
id,
|
|
285
|
+
lastVersion: version
|
|
286
|
+
}))),
|
|
287
|
+
catch: AiAssistantError.wrap({
|
|
288
|
+
message: "Artifact diff resolution error"
|
|
289
|
+
})
|
|
204
290
|
});
|
|
205
|
-
|
|
206
|
-
|
|
291
|
+
log("version", {
|
|
292
|
+
artifactDiff,
|
|
293
|
+
versions
|
|
294
|
+
}, {
|
|
295
|
+
F: __dxlog_file2,
|
|
296
|
+
L: 92,
|
|
297
|
+
S: this,
|
|
298
|
+
C: (f, a) => f(...a)
|
|
299
|
+
});
|
|
300
|
+
for (const [id, { version }] of [
|
|
301
|
+
...artifactDiff.entries()
|
|
302
|
+
]) {
|
|
303
|
+
if (ObjectVersion.equals(version, versions.get(id))) {
|
|
304
|
+
artifactDiff.delete(id);
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
blocks.push({
|
|
308
|
+
_tag: "anchor",
|
|
309
|
+
objectId: id,
|
|
310
|
+
version
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
if (artifactDiff.size > 0) {
|
|
314
|
+
blocks.push(createArtifactUpdateBlock(artifactDiff));
|
|
315
|
+
}
|
|
207
316
|
}
|
|
208
|
-
return
|
|
209
|
-
|
|
210
|
-
|
|
317
|
+
return Obj2.make(Message.Message, {
|
|
318
|
+
created: (/* @__PURE__ */ new Date()).toISOString(),
|
|
319
|
+
sender: {
|
|
320
|
+
role: "user"
|
|
321
|
+
},
|
|
322
|
+
blocks: [
|
|
323
|
+
...blocks,
|
|
324
|
+
{
|
|
325
|
+
_tag: "text",
|
|
326
|
+
text: prompt
|
|
327
|
+
}
|
|
328
|
+
]
|
|
329
|
+
});
|
|
330
|
+
});
|
|
331
|
+
var gatherObjectVersions = (messages) => {
|
|
332
|
+
const artifactIds = /* @__PURE__ */ new Map();
|
|
333
|
+
for (const message of messages) {
|
|
334
|
+
for (const block of message.blocks) {
|
|
335
|
+
if (block._tag === "anchor") {
|
|
336
|
+
artifactIds.set(block.objectId, block.version);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return artifactIds;
|
|
341
|
+
};
|
|
342
|
+
var createArtifactUpdateBlock = (artifactDiff) => {
|
|
343
|
+
return {
|
|
344
|
+
_tag: "text",
|
|
345
|
+
// TODO(dmaretskyi): Does this need to be a special content-block?
|
|
346
|
+
disposition: "artifact-update",
|
|
347
|
+
text: trim`
|
|
348
|
+
The following artifacts have been updated since the last message:
|
|
349
|
+
${[
|
|
350
|
+
...artifactDiff.entries()
|
|
351
|
+
].map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `
|
|
352
|
+
${diff}` : ""}</changed-artifact>`).join("\n")}
|
|
353
|
+
`
|
|
354
|
+
};
|
|
355
|
+
};
|
|
356
|
+
|
|
357
|
+
// src/session/session.ts
|
|
358
|
+
var __dxlog_file3 = "/__w/dxos/dxos/packages/core/assistant/src/session/session.ts";
|
|
359
|
+
var AiSession = class {
|
|
360
|
+
_options;
|
|
361
|
+
/** Prevents concurrent execution of session. */
|
|
362
|
+
_semaphore = Effect3.runSync(Effect3.makeSemaphore(1));
|
|
363
|
+
/** Message history from queue. */
|
|
364
|
+
// TODO(burdon): Evolve into supporting a git-like graph of messages.
|
|
365
|
+
_history = [];
|
|
366
|
+
/** Pending messages for this session (incl. the current prompt). */
|
|
367
|
+
_pending = [];
|
|
368
|
+
constructor(_options = {}) {
|
|
369
|
+
this._options = _options;
|
|
370
|
+
}
|
|
371
|
+
run = ({ prompt, system: systemTemplate, history = [], objects = [], blueprints = [], toolkit, observer = GenerationObserver.noop() }) => Effect3.gen(this, function* () {
|
|
372
|
+
this._history = [
|
|
373
|
+
...history
|
|
374
|
+
];
|
|
375
|
+
this._pending = [];
|
|
376
|
+
const pending = this._pending;
|
|
377
|
+
const submitMessage = Effect3.fnUntraced(function* (message) {
|
|
378
|
+
pending.push(message);
|
|
379
|
+
yield* observer.onMessage(message);
|
|
380
|
+
yield* TracingService.emitConverationMessage(message);
|
|
381
|
+
return message;
|
|
382
|
+
});
|
|
383
|
+
const promptMessage = yield* submitMessage(yield* formatUserPrompt({
|
|
384
|
+
prompt,
|
|
385
|
+
history
|
|
386
|
+
}));
|
|
387
|
+
const system = yield* formatSystemPrompt({
|
|
388
|
+
system: systemTemplate,
|
|
389
|
+
blueprints,
|
|
390
|
+
objects
|
|
391
|
+
});
|
|
392
|
+
do {
|
|
393
|
+
log2("request", {
|
|
394
|
+
prompt: promptMessage,
|
|
395
|
+
system: {
|
|
396
|
+
snippet: createSnippet(system),
|
|
397
|
+
length: system.length
|
|
398
|
+
},
|
|
399
|
+
pending: this._pending.length,
|
|
400
|
+
history: this._history.length,
|
|
401
|
+
objects: objects?.length ?? 0
|
|
402
|
+
}, {
|
|
403
|
+
F: __dxlog_file3,
|
|
404
|
+
L: 110,
|
|
405
|
+
S: this,
|
|
406
|
+
C: (f, a) => f(...a)
|
|
407
|
+
});
|
|
408
|
+
const prompt2 = yield* AiPreprocessor.preprocessPrompt([
|
|
409
|
+
...this._history,
|
|
410
|
+
...this._pending
|
|
411
|
+
], {
|
|
412
|
+
system
|
|
413
|
+
});
|
|
414
|
+
const blocks = yield* LanguageModel.streamText({
|
|
415
|
+
prompt: prompt2,
|
|
416
|
+
toolkit,
|
|
417
|
+
disableToolCallResolution: true
|
|
418
|
+
}).pipe(
|
|
419
|
+
// TOOD(dmaretskyi): Error mapping.
|
|
420
|
+
AiParser.parseResponse({
|
|
421
|
+
onBegin: () => observer.onBegin(),
|
|
422
|
+
onBlock: (block) => observer.onBlock(block),
|
|
423
|
+
onPart: (part) => observer.onPart(part),
|
|
424
|
+
onEnd: (summary) => observer.onEnd(summary)
|
|
425
|
+
}),
|
|
426
|
+
Stream.runCollect,
|
|
427
|
+
Effect3.map(Chunk.toArray)
|
|
428
|
+
);
|
|
429
|
+
const response = yield* submitMessage(Obj3.make(Message2.Message, {
|
|
430
|
+
created: (/* @__PURE__ */ new Date()).toISOString(),
|
|
431
|
+
sender: {
|
|
432
|
+
role: "assistant"
|
|
433
|
+
},
|
|
434
|
+
blocks
|
|
435
|
+
}));
|
|
436
|
+
const toolCalls = getToolCalls(response);
|
|
437
|
+
if (toolCalls.length === 0) {
|
|
438
|
+
break;
|
|
439
|
+
} else if (!toolkit) {
|
|
440
|
+
throw new Error("No toolkit provided");
|
|
441
|
+
}
|
|
442
|
+
const toolResults = yield* Effect3.forEach(toolCalls, (toolCall) => {
|
|
443
|
+
return callTool(toolkit, toolCall).pipe(Effect3.provide(TracingService.layerSubframe((context) => ({
|
|
444
|
+
...context,
|
|
445
|
+
parentMessage: response.id,
|
|
446
|
+
toolCallId: toolCall.toolCallId
|
|
447
|
+
}))));
|
|
448
|
+
});
|
|
449
|
+
yield* submitMessage(Obj3.make(Message2.Message, {
|
|
450
|
+
created: (/* @__PURE__ */ new Date()).toISOString(),
|
|
451
|
+
sender: {
|
|
452
|
+
role: "tool"
|
|
453
|
+
},
|
|
454
|
+
blocks: toolResults
|
|
455
|
+
}));
|
|
456
|
+
} while (true);
|
|
457
|
+
log2("done", {
|
|
458
|
+
pending: this._pending.length
|
|
459
|
+
}, {
|
|
460
|
+
F: __dxlog_file3,
|
|
461
|
+
L: 181,
|
|
462
|
+
S: this,
|
|
463
|
+
C: (f, a) => f(...a)
|
|
464
|
+
});
|
|
465
|
+
return this._pending;
|
|
466
|
+
}).pipe(this._semaphore.withPermits(1), Effect3.withSpan("AiSession.run"));
|
|
467
|
+
/**
|
|
468
|
+
* @deprecated
|
|
469
|
+
*/
|
|
470
|
+
// TODO(burdon): Implement or remove.
|
|
471
|
+
async runStructured(_schema, _options) {
|
|
472
|
+
return todo();
|
|
473
|
+
}
|
|
474
|
+
};
|
|
475
|
+
var createSnippet = (text, len = 32) => text.length <= len * 2 ? text : [
|
|
476
|
+
text.slice(0, len),
|
|
477
|
+
"...",
|
|
478
|
+
text.slice(-len)
|
|
479
|
+
].join("");
|
|
480
|
+
|
|
481
|
+
// src/session/toolkit.ts
|
|
482
|
+
import * as Toolkit from "@effect/ai/Toolkit";
|
|
483
|
+
import * as Effect4 from "effect/Effect";
|
|
484
|
+
import { ToolExecutionService, ToolResolverService } from "@dxos/ai";
|
|
485
|
+
import { isTruthy } from "@dxos/util";
|
|
486
|
+
var createToolkit = ({ toolkit: toolkitParam, toolIds = [], blueprints = [] }) => Effect4.gen(function* () {
|
|
487
|
+
const blueprintToolkit = yield* ToolResolverService.resolveToolkit([
|
|
488
|
+
...blueprints.flatMap(({ tools }) => tools),
|
|
489
|
+
...toolIds
|
|
490
|
+
]);
|
|
491
|
+
const blueprintToolkitHandler = yield* blueprintToolkit.toContext(ToolExecutionService.handlersFor(blueprintToolkit));
|
|
492
|
+
const toolkit = Toolkit.merge(...[
|
|
493
|
+
toolkitParam,
|
|
494
|
+
blueprintToolkit
|
|
495
|
+
].filter(isTruthy));
|
|
496
|
+
return yield* toolkit.pipe(Effect4.provide(blueprintToolkitHandler));
|
|
497
|
+
});
|
|
498
|
+
|
|
499
|
+
// src/session/version-pin.ts
|
|
500
|
+
import * as Schema2 from "effect/Schema";
|
|
501
|
+
import { ObjectId } from "@dxos/echo/internal";
|
|
502
|
+
import { getVersion } from "@dxos/echo-db";
|
|
503
|
+
var ObjectVersionSchema = Schema2.Unknown;
|
|
504
|
+
var VersionPinSchema = Schema2.Struct({
|
|
505
|
+
// TODO(dmaretskyi): Use Ref when those support encoding.
|
|
506
|
+
objectId: ObjectId,
|
|
507
|
+
// TODO(dmaretskyi): Could be opaque.
|
|
508
|
+
version: ObjectVersionSchema
|
|
509
|
+
});
|
|
510
|
+
var VersionPin = class extends VersionPinSchema {
|
|
511
|
+
static DISPOSITION = "version-pin";
|
|
512
|
+
static fromObject(object) {
|
|
513
|
+
return VersionPin.make({
|
|
514
|
+
objectId: object.id,
|
|
515
|
+
version: getVersion(object)
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
static createBlock(pin) {
|
|
519
|
+
return {
|
|
520
|
+
_tag: "json",
|
|
521
|
+
disposition: VersionPin.DISPOSITION,
|
|
522
|
+
data: JSON.stringify(pin)
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
};
|
|
526
|
+
|
|
527
|
+
// src/session/GenericToolkit.ts
|
|
528
|
+
var GenericToolkit_exports = {};
|
|
529
|
+
__export(GenericToolkit_exports, {
|
|
530
|
+
TypeId: () => TypeId,
|
|
531
|
+
make: () => make,
|
|
532
|
+
merge: () => merge3
|
|
533
|
+
});
|
|
534
|
+
import * as Toolkit2 from "@effect/ai/Toolkit";
|
|
535
|
+
import * as Effect5 from "effect/Effect";
|
|
536
|
+
import * as Layer from "effect/Layer";
|
|
537
|
+
import * as Pipeable from "effect/Pipeable";
|
|
538
|
+
var TypeId = "~@dxos/assistant/GenericToolkit";
|
|
539
|
+
var make = (toolkit, layer) => {
|
|
540
|
+
return {
|
|
541
|
+
[TypeId]: TypeId,
|
|
542
|
+
toolkit,
|
|
543
|
+
layer,
|
|
544
|
+
handlers: toolkit.pipe(Effect5.provide(layer)),
|
|
545
|
+
pipe() {
|
|
546
|
+
return Pipeable.pipeArguments(this, arguments);
|
|
547
|
+
}
|
|
548
|
+
};
|
|
549
|
+
};
|
|
550
|
+
var merge3 = (...toolkits) => {
|
|
551
|
+
return make(Toolkit2.merge(...toolkits.map((t) => t.toolkit)), Layer.mergeAll(...toolkits.map((t) => t.layer)));
|
|
552
|
+
};
|
|
553
|
+
|
|
554
|
+
// src/conversation/conversation.ts
|
|
555
|
+
var __dxlog_file4 = "/__w/dxos/dxos/packages/core/assistant/src/conversation/conversation.ts";
|
|
211
556
|
var AiConversation = class extends Resource2 {
|
|
557
|
+
/**
|
|
558
|
+
* Message and binding queue.
|
|
559
|
+
*/
|
|
560
|
+
_queue;
|
|
561
|
+
/**
|
|
562
|
+
* Blueprints bound to the conversation.
|
|
563
|
+
*/
|
|
564
|
+
_context;
|
|
565
|
+
/**
|
|
566
|
+
* Toolkit from the current session request.
|
|
567
|
+
*/
|
|
568
|
+
_toolkit;
|
|
569
|
+
constructor(queue) {
|
|
570
|
+
super();
|
|
571
|
+
this._queue = queue;
|
|
572
|
+
this._context = new AiContextBinder(this._queue);
|
|
573
|
+
}
|
|
212
574
|
async _open() {
|
|
213
575
|
await this._context.open();
|
|
214
576
|
}
|
|
@@ -223,31 +585,31 @@ var AiConversation = class extends Resource2 {
|
|
|
223
585
|
}
|
|
224
586
|
async getHistory() {
|
|
225
587
|
const queueItems = await this._queue.queryObjects();
|
|
226
|
-
return queueItems.filter(
|
|
588
|
+
return queueItems.filter(Obj4.instanceOf(Message3.Message));
|
|
227
589
|
}
|
|
228
590
|
/**
|
|
229
591
|
* Creates a new cancelable request effect.
|
|
230
592
|
*/
|
|
231
593
|
createRequest(params) {
|
|
232
|
-
return
|
|
594
|
+
return Effect6.gen(this, function* () {
|
|
233
595
|
const session = new AiSession();
|
|
234
|
-
const history = yield*
|
|
235
|
-
const context = yield*
|
|
236
|
-
const blueprints = yield*
|
|
237
|
-
const objects = yield*
|
|
596
|
+
const history = yield* Effect6.promise(() => this.getHistory());
|
|
597
|
+
const context = yield* Effect6.promise(() => this.context.query());
|
|
598
|
+
const blueprints = yield* Effect6.forEach(context.blueprints.values(), DatabaseService2.loadOption).pipe(Effect6.map(Array5.filter(Option2.isSome)), Effect6.map(Array5.map((option) => option.value)));
|
|
599
|
+
const objects = yield* Effect6.forEach(context.objects.values(), DatabaseService2.loadOption).pipe(Effect6.map(Array5.filter(Option2.isSome)), Effect6.map(Array5.map((option) => option.value)));
|
|
238
600
|
const toolkit = yield* createToolkit({
|
|
239
601
|
blueprints
|
|
240
602
|
});
|
|
241
603
|
this._toolkit = toolkit;
|
|
242
604
|
const start = Date.now();
|
|
243
|
-
|
|
605
|
+
log3("run", {
|
|
244
606
|
history: history.length,
|
|
245
607
|
blueprints: blueprints.length,
|
|
246
608
|
objects: objects.length,
|
|
247
609
|
tools: this._toolkit?.tools.length ?? 0
|
|
248
610
|
}, {
|
|
249
|
-
F:
|
|
250
|
-
L:
|
|
611
|
+
F: __dxlog_file4,
|
|
612
|
+
L: 107,
|
|
251
613
|
S: this,
|
|
252
614
|
C: (f, a) => f(...a)
|
|
253
615
|
});
|
|
@@ -257,44 +619,30 @@ var AiConversation = class extends Resource2 {
|
|
|
257
619
|
objects,
|
|
258
620
|
toolkit,
|
|
259
621
|
...params
|
|
260
|
-
}).pipe(
|
|
622
|
+
}).pipe(Effect6.provideService(AiContextService, {
|
|
261
623
|
binder: this.context
|
|
262
624
|
}));
|
|
263
|
-
|
|
625
|
+
log3("result", {
|
|
264
626
|
messages: messages.length,
|
|
265
627
|
duration: Date.now() - start
|
|
266
628
|
}, {
|
|
267
|
-
F:
|
|
268
|
-
L:
|
|
629
|
+
F: __dxlog_file4,
|
|
630
|
+
L: 121,
|
|
269
631
|
S: this,
|
|
270
632
|
C: (f, a) => f(...a)
|
|
271
633
|
});
|
|
272
|
-
yield*
|
|
634
|
+
yield* Effect6.promise(() => this._queue.append(messages));
|
|
273
635
|
return messages;
|
|
274
|
-
}).pipe(
|
|
275
|
-
}
|
|
276
|
-
constructor(options) {
|
|
277
|
-
super(), /**
|
|
278
|
-
* Message and binding queue.
|
|
279
|
-
*/
|
|
280
|
-
_define_property2(this, "_queue", void 0), /**
|
|
281
|
-
* Blueprints bound to the conversation.
|
|
282
|
-
*/
|
|
283
|
-
_define_property2(this, "_context", void 0), /**
|
|
284
|
-
* Toolkit from the current session request.
|
|
285
|
-
*/
|
|
286
|
-
_define_property2(this, "_toolkit", void 0);
|
|
287
|
-
this._queue = options.queue;
|
|
288
|
-
this._context = new AiContextBinder(this._queue);
|
|
636
|
+
}).pipe(Effect6.withSpan("AiConversation.request"));
|
|
289
637
|
}
|
|
290
638
|
};
|
|
291
639
|
|
|
292
640
|
// src/diff.ts
|
|
293
641
|
import { next as A } from "@automerge/automerge";
|
|
294
642
|
import { DocAccessor, toCursorRange } from "@dxos/echo-db";
|
|
295
|
-
import { log as
|
|
643
|
+
import { log as log4 } from "@dxos/log";
|
|
296
644
|
import { isNonNullable } from "@dxos/util";
|
|
297
|
-
var
|
|
645
|
+
var __dxlog_file5 = "/__w/dxos/dxos/packages/core/assistant/src/diff.ts";
|
|
298
646
|
var reduceDiffs = (diffs) => {
|
|
299
647
|
return diffs.reduce((acc, diff) => {
|
|
300
648
|
const current = acc[acc.length - 1];
|
|
@@ -346,9 +694,9 @@ var applyDiffs = (accessor, diffs) => {
|
|
|
346
694
|
if (idx !== -1) {
|
|
347
695
|
A.splice(doc, accessor.path, idx, diff.match.length, diff.replace);
|
|
348
696
|
} else {
|
|
349
|
-
|
|
350
|
-
F:
|
|
351
|
-
L:
|
|
697
|
+
log4.warn("diff not found", diff, {
|
|
698
|
+
F: __dxlog_file5,
|
|
699
|
+
L: 78,
|
|
352
700
|
S: void 0,
|
|
353
701
|
C: (f, a) => f(...a)
|
|
354
702
|
});
|
|
@@ -360,34 +708,36 @@ var applyDiffs = (accessor, diffs) => {
|
|
|
360
708
|
|
|
361
709
|
// src/execution-graph.ts
|
|
362
710
|
import { AgentStatus } from "@dxos/ai";
|
|
363
|
-
import { Obj as
|
|
711
|
+
import { Obj as Obj5 } from "@dxos/echo";
|
|
364
712
|
import { MESSAGE_PROPERTY_TOOL_CALL_ID } from "@dxos/functions";
|
|
365
713
|
import { LogLevel } from "@dxos/log";
|
|
366
|
-
import { ContentBlock,
|
|
714
|
+
import { ContentBlock, Message as Message4 } from "@dxos/types";
|
|
367
715
|
import { isNonNullable as isNonNullable2 } from "@dxos/util";
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
value,
|
|
372
|
-
enumerable: true,
|
|
373
|
-
configurable: true,
|
|
374
|
-
writable: true
|
|
375
|
-
});
|
|
376
|
-
} else {
|
|
377
|
-
obj[key] = value;
|
|
378
|
-
}
|
|
379
|
-
return obj;
|
|
380
|
-
}
|
|
716
|
+
var SKIP_BLOCKS = [
|
|
717
|
+
"text"
|
|
718
|
+
];
|
|
381
719
|
var ExecutionGraph = class {
|
|
720
|
+
_skipBlocks;
|
|
721
|
+
// TODO(dmaretskyi): Evolve the internal state to support chats, functions, circuit workflows, etc.
|
|
722
|
+
_commits = [];
|
|
723
|
+
_branchNames = /* @__PURE__ */ new Set();
|
|
724
|
+
_lastBlockId;
|
|
725
|
+
// Tool call tracking.
|
|
726
|
+
_toolCallCommitIds = /* @__PURE__ */ new Map();
|
|
727
|
+
_lastCommitByBranch = /* @__PURE__ */ new Map();
|
|
728
|
+
_pendingToolResults = /* @__PURE__ */ new Map();
|
|
729
|
+
constructor(_skipBlocks = SKIP_BLOCKS) {
|
|
730
|
+
this._skipBlocks = _skipBlocks;
|
|
731
|
+
}
|
|
382
732
|
/**
|
|
383
733
|
* Adds events to the graph.
|
|
384
734
|
*/
|
|
385
735
|
addEvents(events) {
|
|
386
736
|
const sortedEvents = this.sortObjectsByCreated(events);
|
|
387
737
|
for (const event of sortedEvents) {
|
|
388
|
-
if (
|
|
738
|
+
if (Obj5.instanceOf(Message4.Message, event)) {
|
|
389
739
|
this._processMessage(event);
|
|
390
|
-
} else if (
|
|
740
|
+
} else if (Obj5.instanceOf(AgentStatus, event)) {
|
|
391
741
|
this._processAgentStatus(event);
|
|
392
742
|
}
|
|
393
743
|
}
|
|
@@ -396,7 +746,7 @@ var ExecutionGraph = class {
|
|
|
396
746
|
* Processes a message event and creates commits for its blocks.
|
|
397
747
|
*/
|
|
398
748
|
_processMessage(message) {
|
|
399
|
-
const messageCommits = messageToCommits(message, this._lastBlockId, this._toolCallCommitIds, this._lastCommitByBranch);
|
|
749
|
+
const messageCommits = messageToCommits(message, this._lastBlockId, this._toolCallCommitIds, this._lastCommitByBranch, this._skipBlocks);
|
|
400
750
|
this._commits.push(...messageCommits);
|
|
401
751
|
messageCommits.forEach((commit) => this._branchNames.add(commit.branch));
|
|
402
752
|
this._trackToolCalls(messageCommits);
|
|
@@ -560,20 +910,15 @@ var ExecutionGraph = class {
|
|
|
560
910
|
const toolResultMatch = commitId.match(/_toolResult_(.+)$/);
|
|
561
911
|
return toolCallMatch?.[1] || toolResultMatch?.[1];
|
|
562
912
|
}
|
|
563
|
-
constructor() {
|
|
564
|
-
_define_property3(this, "_commits", []);
|
|
565
|
-
_define_property3(this, "_branchNames", /* @__PURE__ */ new Set());
|
|
566
|
-
_define_property3(this, "_lastBlockId", void 0);
|
|
567
|
-
_define_property3(this, "_toolCallCommitIds", /* @__PURE__ */ new Map());
|
|
568
|
-
_define_property3(this, "_lastCommitByBranch", /* @__PURE__ */ new Map());
|
|
569
|
-
_define_property3(this, "_pendingToolResults", /* @__PURE__ */ new Map());
|
|
570
|
-
}
|
|
571
913
|
};
|
|
572
|
-
var messageToCommits = (message, lastBlockId, toolCallIds, lastCommitByBranch) => {
|
|
914
|
+
var messageToCommits = (message, lastBlockId, toolCallIds, lastCommitByBranch, skipBlocks) => {
|
|
573
915
|
let previousBlockId = lastBlockId;
|
|
574
916
|
return message.blocks.map((block, idx) => {
|
|
575
917
|
const branch = getMessageBranch(message);
|
|
576
918
|
const parents = getBlockParents(block, previousBlockId, message, toolCallIds, lastCommitByBranch);
|
|
919
|
+
if (skipBlocks?.includes(block._tag)) {
|
|
920
|
+
return null;
|
|
921
|
+
}
|
|
577
922
|
const commit = createBlockCommit(block, message, branch, parents, idx);
|
|
578
923
|
if (commit) {
|
|
579
924
|
previousBlockId = commit.id;
|
|
@@ -728,49 +1073,50 @@ var stringifyRef = (ref) => {
|
|
|
728
1073
|
return ref.dxn.asEchoDXN()?.echoId ?? ref.dxn.asQueueDXN()?.objectId ?? "";
|
|
729
1074
|
};
|
|
730
1075
|
var stringifyObject = (obj) => {
|
|
731
|
-
return
|
|
1076
|
+
return Obj5.getLabel(obj) ?? Obj5.getTypename(obj) ?? obj.id;
|
|
732
1077
|
};
|
|
733
1078
|
|
|
734
1079
|
// src/functions/services.ts
|
|
735
1080
|
import * as Tool from "@effect/ai/Tool";
|
|
736
|
-
import * as
|
|
737
|
-
import * as
|
|
738
|
-
import * as
|
|
1081
|
+
import * as Context3 from "effect/Context";
|
|
1082
|
+
import * as Effect7 from "effect/Effect";
|
|
1083
|
+
import * as Layer2 from "effect/Layer";
|
|
739
1084
|
import * as Record from "effect/Record";
|
|
740
|
-
import * as
|
|
741
|
-
import { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from "@dxos/ai";
|
|
742
|
-
import { todo } from "@dxos/debug";
|
|
1085
|
+
import * as Schema3 from "effect/Schema";
|
|
1086
|
+
import { AiToolNotFoundError, ToolExecutionService as ToolExecutionService2, ToolResolverService as ToolResolverService2 } from "@dxos/ai";
|
|
1087
|
+
import { todo as todo2 } from "@dxos/debug";
|
|
743
1088
|
import { Query as Query2 } from "@dxos/echo";
|
|
744
|
-
import { DatabaseService as
|
|
1089
|
+
import { DatabaseService as DatabaseService3 } from "@dxos/echo-db";
|
|
1090
|
+
import { Function as Function4, FunctionDefinition, FunctionInvocationService } from "@dxos/functions";
|
|
745
1091
|
import { invariant as invariant2 } from "@dxos/invariant";
|
|
746
|
-
var
|
|
1092
|
+
var __dxlog_file6 = "/__w/dxos/dxos/packages/core/assistant/src/functions/services.ts";
|
|
747
1093
|
var makeToolResolverFromFunctions = (functions, toolkit) => {
|
|
748
|
-
return
|
|
749
|
-
const dbService = yield*
|
|
1094
|
+
return Layer2.effect(ToolResolverService2, Effect7.gen(function* () {
|
|
1095
|
+
const dbService = yield* DatabaseService3;
|
|
750
1096
|
return {
|
|
751
|
-
resolve: (id) =>
|
|
1097
|
+
resolve: (id) => Effect7.gen(function* () {
|
|
752
1098
|
const tool = toolkit.tools[id];
|
|
753
1099
|
if (tool) {
|
|
754
1100
|
return tool;
|
|
755
1101
|
}
|
|
756
|
-
const { objects: [dbFunction] } = yield*
|
|
1102
|
+
const { objects: [dbFunction] } = yield* DatabaseService3.runQuery(Query2.type(Function4.Function, {
|
|
757
1103
|
key: id
|
|
758
1104
|
}));
|
|
759
1105
|
const functionDef = dbFunction ? FunctionDefinition.deserialize(dbFunction) : functions.find((fn2) => fn2.key === id);
|
|
760
1106
|
if (!functionDef) {
|
|
761
|
-
return yield*
|
|
1107
|
+
return yield* Effect7.fail(new AiToolNotFoundError(id));
|
|
762
1108
|
}
|
|
763
1109
|
return projectFunctionToTool(functionDef);
|
|
764
|
-
}).pipe(
|
|
1110
|
+
}).pipe(Effect7.provideService(DatabaseService3, dbService))
|
|
765
1111
|
};
|
|
766
1112
|
}));
|
|
767
1113
|
};
|
|
768
1114
|
var makeToolExecutionServiceFromFunctions = (toolkit, handlersLayer) => {
|
|
769
|
-
return
|
|
770
|
-
const toolkitHandler = yield* toolkit.pipe(
|
|
1115
|
+
return Layer2.effect(ToolExecutionService2, Effect7.gen(function* () {
|
|
1116
|
+
const toolkitHandler = yield* toolkit.pipe(Effect7.provide(handlersLayer));
|
|
771
1117
|
invariant2(isHandlerLike(toolkitHandler), void 0, {
|
|
772
|
-
F:
|
|
773
|
-
L:
|
|
1118
|
+
F: __dxlog_file6,
|
|
1119
|
+
L: 74,
|
|
774
1120
|
S: this,
|
|
775
1121
|
A: [
|
|
776
1122
|
"isHandlerLike(toolkitHandler)",
|
|
@@ -781,15 +1127,16 @@ var makeToolExecutionServiceFromFunctions = (toolkit, handlersLayer) => {
|
|
|
781
1127
|
return {
|
|
782
1128
|
handlersFor: (toolkit2) => {
|
|
783
1129
|
const makeHandler = (tool) => {
|
|
784
|
-
return
|
|
1130
|
+
return Effect7.fn(`toolFunctionHandler ${tool.name}`)(function* (input) {
|
|
785
1131
|
if (toolkitHandler.tools[tool.name]) {
|
|
786
1132
|
if (Tool.isProviderDefined(tool)) {
|
|
787
1133
|
throw new Error("Attempted to call a provider-defined tool");
|
|
788
1134
|
}
|
|
789
|
-
|
|
1135
|
+
const { result } = yield* toolkitHandler.handle(tool.name, input);
|
|
1136
|
+
return result;
|
|
790
1137
|
}
|
|
791
|
-
const { definition: functionDef } =
|
|
792
|
-
return yield* functionInvocationService.invokeFunction(functionDef, input).pipe(
|
|
1138
|
+
const { definition: functionDef } = Context3.get(FunctionToolAnnotation)(tool.annotations);
|
|
1139
|
+
return yield* functionInvocationService.invokeFunction(functionDef, input).pipe(Effect7.catchAllDefect((defect) => Effect7.fail(defect)));
|
|
793
1140
|
});
|
|
794
1141
|
};
|
|
795
1142
|
return toolkit2.of(Record.map(toolkit2.tools, (tool, _name) => Tool.isUserDefined(tool) ? makeHandler(tool) : null));
|
|
@@ -797,7 +1144,7 @@ var makeToolExecutionServiceFromFunctions = (toolkit, handlersLayer) => {
|
|
|
797
1144
|
};
|
|
798
1145
|
}));
|
|
799
1146
|
};
|
|
800
|
-
var FunctionToolAnnotation = class extends
|
|
1147
|
+
var FunctionToolAnnotation = class extends Context3.Tag("@dxos/assistant/FunctionToolAnnotation")() {
|
|
801
1148
|
};
|
|
802
1149
|
var toolCache = /* @__PURE__ */ new WeakMap();
|
|
803
1150
|
var projectFunctionToTool = (fn2) => {
|
|
@@ -808,7 +1155,7 @@ var projectFunctionToTool = (fn2) => {
|
|
|
808
1155
|
description: fn2.description,
|
|
809
1156
|
parameters: createStructFieldsFromSchema(fn2.inputSchema),
|
|
810
1157
|
// TODO(dmaretskyi): Include output schema.
|
|
811
|
-
failure:
|
|
1158
|
+
failure: Schema3.Any
|
|
812
1159
|
}).annotate(FunctionToolAnnotation, {
|
|
813
1160
|
definition: fn2
|
|
814
1161
|
});
|
|
@@ -816,13 +1163,13 @@ var projectFunctionToTool = (fn2) => {
|
|
|
816
1163
|
return tool;
|
|
817
1164
|
};
|
|
818
1165
|
var makeToolName = (name) => {
|
|
819
|
-
const toolName = name.replace(/[^a-zA-Z0-9]/g, "
|
|
820
|
-
invariant2(toolName.match(/^[a-
|
|
821
|
-
F:
|
|
822
|
-
L:
|
|
1166
|
+
const toolName = name.toLowerCase().replace(/[^a-zA-Z0-9]/g, "-");
|
|
1167
|
+
invariant2(toolName.match(/^[a-z_][a-z0-9-_]*$/), void 0, {
|
|
1168
|
+
F: __dxlog_file6,
|
|
1169
|
+
L: 144,
|
|
823
1170
|
S: void 0,
|
|
824
1171
|
A: [
|
|
825
|
-
"toolName.match(/^[a-
|
|
1172
|
+
"toolName.match(/^[a-z_][a-z0-9-_]*$/)",
|
|
826
1173
|
""
|
|
827
1174
|
]
|
|
828
1175
|
});
|
|
@@ -833,12 +1180,12 @@ var createStructFieldsFromSchema = (schema) => {
|
|
|
833
1180
|
case "TypeLiteral":
|
|
834
1181
|
return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [
|
|
835
1182
|
prop.name,
|
|
836
|
-
|
|
1183
|
+
Schema3.make(prop.type)
|
|
837
1184
|
]));
|
|
838
1185
|
case "VoidKeyword":
|
|
839
1186
|
return {};
|
|
840
1187
|
default:
|
|
841
|
-
return
|
|
1188
|
+
return todo2(`Unsupported schema AST: ${schema.ast._tag}`);
|
|
842
1189
|
}
|
|
843
1190
|
};
|
|
844
1191
|
var isHandlerLike = (value) => {
|
|
@@ -847,21 +1194,21 @@ var isHandlerLike = (value) => {
|
|
|
847
1194
|
|
|
848
1195
|
// src/templates/system.ts
|
|
849
1196
|
import defaultsDeep from "lodash.defaultsdeep";
|
|
850
|
-
import { Template } from "@dxos/blueprints";
|
|
1197
|
+
import { Template as Template2 } from "@dxos/blueprints";
|
|
851
1198
|
|
|
852
|
-
// raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/format.tpl?raw
|
|
853
|
-
var format_default = "{{! System Core }}\n\n## Input Formats\n\n### Blueprints\n\nYou may be provided with Blueprint definitions that include specific instructions and tools for a given set of tasks.\nBlue print instructions will be enclosed in a <blueprint> tag.\n\n### Context objects\n\nYou may be provided with references to objects that are relevant to the current prompt.\nObjects will be in the form of a <object> tag with a <dxn> element that is the unique key of the object required by many tools.\nThe <typename> element is the type of the object.\n\n<object>\n <dxn>object-id</dxn>\n <typename>example.com/type/TypeName</typename>\n</object>\n\n## Response Formats\n\nIt is very important to respond in the correct format.\nYou response must be valid Markdown.\nIn some cases you should respond with well-formed XML tags along with the content.\nCode snippets should use 2-space indents.\n\n{{#if cot}}\nBefore responding, explain your reasoning and include your detailed chain-of-thought enclosed in a <cot> tag.\nThe <cot> tag should be the first thing in your response.\n{{/if}}\n\n## Block references\n\nYou can reply with a block reference for objects if you have the DXN. For example:\n\n<object>\n <dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n<object>\n <dxn>dxn:echo:@:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n\n### Suggestions\n\nEach suggestion must in the form of a proposed action enclosed in a <suggestion> tag.\nExample: <suggestion>Show on a map</suggestion>\n\n### Multiple choice questions\n\nYou may ask multiple choice questions by wrapping consise options inside <option> tags inside a well formed <select> tag.\nExample: <select><option>Yes</option><option>No</option></select>\n\n## Toolkit\n\nIf the user asks for a list of tools, then just emit a single self-closing <toolkit/> tag instead of listing the tools.\n\n## Context\n\nThe current date and time is {{DATETIME}}.\n";
|
|
1199
|
+
// raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/instructions/format.tpl?raw
|
|
1200
|
+
var format_default = "{{! System Core }}\n\n## Input Formats\n\n### Blueprints\n\nYou may be provided with Blueprint definitions that include specific instructions and tools for a given set of tasks.\nBlue print instructions will be enclosed in a <blueprint> tag.\n\n### Context objects\n\nYou may be provided with references to objects that are relevant to the current prompt.\nObjects will be in the form of a <object> tag with a <dxn> element that is the unique key of the object required by many tools.\nThe <typename> element is the type of the object.\n\n<object>\n <dxn>object-id</dxn>\n <typename>example.com/type/TypeName</typename>\n</object>\n\n## Response Formats\n\nIt is very important to respond in the correct format.\nYou response must be valid Markdown.\nIn some cases you should respond with well-formed XML tags along with the content.\nCode snippets should use 2-space indents.\n\n{{#if cot}}\nBefore responding, explain your reasoning and include your detailed chain-of-thought enclosed in a <cot> tag.\nThe <cot> tag should be the first thing in your response.\n{{/if}}\n\n## Block references\n\nYou can reply with a block reference for objects if you have the DXN. For example:\n\n<object>\n <dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n<object>\n <dxn>dxn:echo:@:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n\n### Suggestions\n\nEach suggestion must in the form of a proposed action enclosed in a <suggestion> tag.\nExample: <suggestion>Show on a map</suggestion>\nDo not use bullets when listing suggestions.\n\n### Multiple choice questions\n\nYou may ask multiple choice questions by wrapping consise options inside <option> tags inside a well formed <select> tag.\nExample: <select><option>Yes</option><option>No</option></select>\n\n## Toolkit\n\nIf the user asks for a list of tools, then just emit a single self-closing <toolkit/> tag instead of listing the tools.\n\n## Context\n\nThe current date and time is {{DATETIME}}.\n";
|
|
854
1201
|
|
|
855
|
-
// raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/system.tpl?raw
|
|
1202
|
+
// raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/instructions/system.tpl?raw
|
|
856
1203
|
var system_default = "{{! System Prompt }}\n\n- You are a helpful assistant called Kai. \n- Your name is Kai and you are powered by different language models.\n- You were created by DXOS and operate inside of Composer and on the DXOS EDGE network.\n- In your initial greeting state your name and make some suggestions based on the current context objects.\n- You are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.\n- Your task is to process user commands and questions and decide how best to respond.\n- In general be concise and direct.\n- Follow all instructions carefully.\n\n## Planning\n\n- Analyze the structure and type of the content in the user's message.\n- Determine if you complete the task using the available blueprint definitions?\n- If you can't complete the task using the available blueprint definitions, query the list of available blueprint definitions using the appropriate tool.\n- Identify which blueprint definitions are relevant to the user's request.\n- Evaluate the potential benefits of creating an artifact vs. normal processing for each identified element.\n- Make a final decision on whether to create an artifact and explain your reasoning.\n- Are the required blueprint definitions already available?\n- If not, select which blueprint definition(s) will be the most relevant and require them using the require_artifact_definitions tool.\n- The require'd artifact tools will be available for use after require.\n- If creating an artifact, outline how you will structure it within the response.\n- Decide if the artifact needs to be shown to the user.\n- Call the show tool to show the artifact to the user.\n- Your reasoning must include: whether to use artifacts or not, to create one or query, whether to show the artifact to the user, and how to structure the response.\n\n## Blueprints and Artifacts\n\n- Determine if the interaction involves an artifact. Prefer artifacts for tables, lists, spreadsheets, kanbans, games, images, and other structured data.\n- Determine if the user is explicitly talking about creating a new artifact, or wants to use an existing artifact.\n- If it is ambiguous, query for existing artifacts first and then decide.\n- If you decide to create an artifact, call the associated tool to create the artifact.\n- Artifacts are stored in the database. Tools are used to create and query artifacts.\n- If you are unsure about creating an artifact ask the user for clarification.\n- Artifacts are mutable objects that can change over the course of the conversation.\n- Always re-query the artifact using the tool (like query or inspect) to get the latest state of the artifact before answering the user.\n- You must never generate the id of the artifact; only recall the ids that are already in the history.\n- Artifacts are created by requiring the specific artifact using the require_artifact tool and creating it by calling the associated tool.\n- You can add suggested actions at the end of your response.\n- Suggested actions should be very concise and start with a verb and be phrased as a command to an agent -- not a question to the user.\n- Suggested actions must be in the form of a user instruction that you can follow.\n- Suggested actions could include actions that create artifacts.\n- After creating an artifact use a tool to add it to the chat context.\n\n## Context\n\nToday is {{DATETIME}}.\n";
|
|
857
1204
|
|
|
858
1205
|
// src/templates/system.ts
|
|
859
|
-
var createSystemPrompt = (options = {}) =>
|
|
1206
|
+
var createSystemPrompt = (options = {}) => Template2.process(format_default, defaultsDeep(options, {
|
|
860
1207
|
DATETIME: (/* @__PURE__ */ new Date()).toISOString()
|
|
861
1208
|
}));
|
|
862
1209
|
var templates = {
|
|
863
1210
|
/** Editable system prompt.*/
|
|
864
|
-
system:
|
|
1211
|
+
system: Template2.make({
|
|
865
1212
|
/**
|
|
866
1213
|
* NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.
|
|
867
1214
|
*/
|
|
@@ -871,12 +1218,14 @@ var templates = {
|
|
|
871
1218
|
};
|
|
872
1219
|
|
|
873
1220
|
// src/types/artifact.ts
|
|
874
|
-
import * as
|
|
1221
|
+
import * as Schema4 from "effect/Schema";
|
|
1222
|
+
import { DatabaseService as DatabaseService4 } from "@dxos/echo-db";
|
|
875
1223
|
import { DXN as DXN2, LOCAL_SPACE_TAG } from "@dxos/keys";
|
|
876
|
-
import { trim } from "@dxos/util";
|
|
1224
|
+
import { trim as trim2 } from "@dxos/util";
|
|
877
1225
|
var createArtifactElement = (id) => `<artifact id=${id} />`;
|
|
878
|
-
var ArtifactId = class extends
|
|
879
|
-
|
|
1226
|
+
var ArtifactId = class extends Schema4.String.annotations({
|
|
1227
|
+
// TODO(dmaretskyi): This section gets overriden.
|
|
1228
|
+
description: trim2`
|
|
880
1229
|
The ID of the referenced object. Formats accepted:
|
|
881
1230
|
- DXN (dxn:echo:@:XXXXX). DXNs can be prepended with an @ symbol for compatibility with in-text references.
|
|
882
1231
|
- space ID, object ID tuple (spaceID:objectID)
|
|
@@ -906,6 +1255,13 @@ var ArtifactId = class extends Schema3.String.annotations({
|
|
|
906
1255
|
throw new Error(`Unable to parse object reference: ${reference}`);
|
|
907
1256
|
}
|
|
908
1257
|
}
|
|
1258
|
+
/**
|
|
1259
|
+
* Resolves an artifact ID to an object.
|
|
1260
|
+
*/
|
|
1261
|
+
static resolve(schema, ref) {
|
|
1262
|
+
const dxn = ArtifactId.toDXN(ref);
|
|
1263
|
+
return DatabaseService4.resolve(dxn, schema);
|
|
1264
|
+
}
|
|
909
1265
|
};
|
|
910
1266
|
export {
|
|
911
1267
|
AiAssistantError,
|
|
@@ -920,6 +1276,7 @@ export {
|
|
|
920
1276
|
ContextBinding,
|
|
921
1277
|
ExecutionGraph,
|
|
922
1278
|
GenerationObserver,
|
|
1279
|
+
GenericToolkit_exports as GenericToolkit,
|
|
923
1280
|
VersionPin,
|
|
924
1281
|
applyDiffs,
|
|
925
1282
|
computeDiffsWithCursors,
|