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