@dxos/assistant 0.8.2-main.2f9c567 → 0.8.2-main.30e4dbb
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/browser/{chunk-OLO6SVOL.mjs → chunk-YSYP7S4W.mjs} +693 -229
- package/dist/lib/browser/chunk-YSYP7S4W.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +4 -443
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +42 -1
- package/dist/lib/browser/testing/index.mjs.map +4 -4
- package/dist/lib/node/{chunk-CI5Q7FBG.cjs → chunk-FTIDW4BA.cjs} +714 -257
- package/dist/lib/node/chunk-FTIDW4BA.cjs.map +7 -0
- package/dist/lib/node/index.cjs +34 -470
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node/testing/index.cjs +49 -9
- package/dist/lib/node/testing/index.cjs.map +4 -4
- package/dist/lib/node-esm/{chunk-Y3SYOFFJ.mjs → chunk-GCJNPQDJ.mjs} +693 -229
- package/dist/lib/node-esm/chunk-GCJNPQDJ.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +4 -443
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/testing/index.mjs +42 -1
- package/dist/lib/node-esm/testing/index.mjs.map +4 -4
- package/dist/types/src/ai-service/parser.d.ts.map +1 -1
- package/dist/types/src/ai-service/stream.d.ts.map +1 -1
- package/dist/types/src/ai-service/testing/test-stream.d.ts.map +1 -1
- package/dist/types/src/ai-service/types.d.ts.map +1 -1
- package/dist/types/src/ai-service/util/sse.d.ts.map +1 -1
- package/dist/types/src/{conversation → experimental/conversation}/conversation.d.ts +2 -18
- package/dist/types/src/experimental/conversation/conversation.d.ts.map +1 -0
- package/dist/types/src/experimental/conversation/conversation.test.d.ts.map +1 -0
- package/dist/types/src/experimental/conversation/index.d.ts.map +1 -0
- package/dist/types/src/experimental/conversation/types.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/ast.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/combinators.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/combinators.test.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/echo-data-source.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/execution-plan.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/execution-plan.test.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/index.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/parjs.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/parser.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/query-executor.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/query-executor.test.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/schema.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/schema.test.d.ts.map +1 -0
- package/dist/types/src/experimental/index.d.ts +3 -0
- package/dist/types/src/experimental/index.d.ts.map +1 -0
- package/dist/types/src/experimental/ner/ner.test.d.ts +2 -0
- package/dist/types/src/experimental/ner/ner.test.d.ts.map +1 -0
- package/dist/types/src/experimental/research/exa.d.ts +6 -0
- package/dist/types/src/experimental/research/exa.d.ts.map +1 -0
- package/dist/types/src/experimental/research/research.test.d.ts +2 -0
- package/dist/types/src/experimental/research/research.test.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +1 -2
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/session/index.d.ts +1 -0
- package/dist/types/src/session/index.d.ts.map +1 -1
- package/dist/types/src/session/session.d.ts +1 -0
- package/dist/types/src/session/session.d.ts.map +1 -1
- package/dist/types/src/session/tools.d.ts +18 -0
- package/dist/types/src/session/tools.d.ts.map +1 -0
- package/dist/types/src/session/version-pin.d.ts +5 -0
- package/dist/types/src/session/version-pin.d.ts.map +1 -1
- package/dist/types/src/testing/index.d.ts +1 -0
- package/dist/types/src/testing/index.d.ts.map +1 -1
- package/dist/types/src/testing/logger.d.ts +1 -1
- package/dist/types/src/testing/logger.d.ts.map +1 -1
- package/dist/types/src/testing/ollama.d.ts.map +1 -1
- package/dist/types/src/testing/printer.d.ts +6 -0
- package/dist/types/src/testing/printer.d.ts.map +1 -0
- package/dist/types/src/testing/query-promts.d.ts +1 -1
- package/dist/types/src/testing/query-promts.d.ts.map +1 -1
- package/dist/types/src/testing/test-data.d.ts +1 -1
- package/dist/types/src/testing/test-data.d.ts.map +1 -1
- package/dist/types/src/util/trim.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +19 -14
- package/src/ai-service/ollama-client.ts +1 -1
- package/src/bin/chat.ts +1 -1
- package/src/{conversation → experimental/conversation}/conversation.test.ts +2 -2
- package/src/{conversation → experimental/conversation}/conversation.ts +3 -112
- package/src/{cypher → experimental/cypher}/query-executor.test.ts +1 -1
- package/src/{cypher → experimental/cypher}/schema.test.ts +1 -1
- package/src/{cypher → experimental/cypher}/schema.ts +1 -1
- package/src/experimental/index.ts +6 -0
- package/src/experimental/ner/ner.test.ts +163 -0
- package/src/experimental/research/exa.ts +38 -0
- package/src/experimental/research/instructions.tpl +64 -0
- package/src/experimental/research/research.test.ts +263 -0
- package/src/index.ts +3 -2
- package/src/session/index.ts +1 -0
- package/src/session/session.test.ts +6 -41
- package/src/session/session.ts +11 -1
- package/src/session/tools.ts +117 -0
- package/src/session/version-pin.ts +6 -0
- package/src/testing/index.ts +1 -0
- package/src/testing/logger.ts +1 -1
- package/src/testing/printer.ts +41 -0
- package/src/testing/query-promts.ts +1 -1
- package/src/testing/query.test.ts +1 -2
- package/src/testing/test-data.ts +1 -1
- package/src/typedefs.d.ts +8 -0
- package/dist/lib/browser/chunk-OLO6SVOL.mjs.map +0 -7
- package/dist/lib/node/chunk-CI5Q7FBG.cjs.map +0 -7
- package/dist/lib/node-esm/chunk-Y3SYOFFJ.mjs.map +0 -7
- package/dist/types/src/conversation/conversation.d.ts.map +0 -1
- package/dist/types/src/conversation/conversation.test.d.ts.map +0 -1
- package/dist/types/src/conversation/index.d.ts.map +0 -1
- package/dist/types/src/conversation/types.d.ts.map +0 -1
- package/dist/types/src/cypher/ast.d.ts.map +0 -1
- package/dist/types/src/cypher/combinators.d.ts.map +0 -1
- package/dist/types/src/cypher/combinators.test.d.ts.map +0 -1
- package/dist/types/src/cypher/echo-data-source.d.ts.map +0 -1
- package/dist/types/src/cypher/execution-plan.d.ts.map +0 -1
- package/dist/types/src/cypher/execution-plan.test.d.ts.map +0 -1
- package/dist/types/src/cypher/index.d.ts.map +0 -1
- package/dist/types/src/cypher/parjs.d.ts.map +0 -1
- package/dist/types/src/cypher/parser.d.ts.map +0 -1
- package/dist/types/src/cypher/query-executor.d.ts.map +0 -1
- package/dist/types/src/cypher/query-executor.test.d.ts.map +0 -1
- package/dist/types/src/cypher/schema.d.ts.map +0 -1
- package/dist/types/src/cypher/schema.test.d.ts.map +0 -1
- /package/dist/types/src/{conversation → experimental/conversation}/conversation.test.d.ts +0 -0
- /package/dist/types/src/{conversation → experimental/conversation}/index.d.ts +0 -0
- /package/dist/types/src/{conversation → experimental/conversation}/types.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/ast.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/combinators.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/combinators.test.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/echo-data-source.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/execution-plan.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/execution-plan.test.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/index.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/parjs.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/parser.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/query-executor.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/query-executor.test.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/schema.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/schema.test.d.ts +0 -0
- /package/src/{conversation → experimental/conversation}/index.ts +0 -0
- /package/src/{conversation → experimental/conversation}/types.ts +0 -0
- /package/src/{cypher → experimental/cypher}/ast.ts +0 -0
- /package/src/{cypher → experimental/cypher}/combinators.test.ts +0 -0
- /package/src/{cypher → experimental/cypher}/combinators.ts +0 -0
- /package/src/{cypher → experimental/cypher}/echo-data-source.ts +0 -0
- /package/src/{cypher → experimental/cypher}/execution-plan.test.ts +0 -0
- /package/src/{cypher → experimental/cypher}/execution-plan.ts +0 -0
- /package/src/{cypher → experimental/cypher}/index.ts +0 -0
- /package/src/{cypher → experimental/cypher}/parjs-shims.d.ts +0 -0
- /package/src/{cypher → experimental/cypher}/parjs.ts +0 -0
- /package/src/{cypher → experimental/cypher}/parser.ts +0 -0
- /package/src/{cypher → experimental/cypher}/query-executor.ts +0 -0
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
AIServiceEdgeClient,
|
|
3
|
+
AIServiecOverloadedError,
|
|
4
|
+
AISession,
|
|
3
5
|
DEFAULT_EDGE_MODEL,
|
|
4
6
|
DEFAULT_EDGE_MODELS,
|
|
5
7
|
DEFAULT_OLLAMA_ENDPOINT,
|
|
@@ -15,6 +17,7 @@ import {
|
|
|
15
17
|
OllamaClient,
|
|
16
18
|
StreamTransform,
|
|
17
19
|
ToolTypes,
|
|
20
|
+
VersionPin,
|
|
18
21
|
createArtifactElement,
|
|
19
22
|
createGenerationStream,
|
|
20
23
|
emitMessageAsEvents,
|
|
@@ -29,449 +32,7 @@ import {
|
|
|
29
32
|
parseCypherQuery,
|
|
30
33
|
runLLM,
|
|
31
34
|
runTools
|
|
32
|
-
} from "./chunk-
|
|
33
|
-
|
|
34
|
-
// packages/experimental/assistant/src/session/session.ts
|
|
35
|
-
import { Option, Schema as Schema2 } from "effect";
|
|
36
|
-
import { defineTool, Message, ToolResult } from "@dxos/artifact";
|
|
37
|
-
import { Event, synchronized } from "@dxos/async";
|
|
38
|
-
import { ObjectVersion } from "@dxos/echo-db";
|
|
39
|
-
import { create } from "@dxos/echo-schema";
|
|
40
|
-
import { invariant } from "@dxos/invariant";
|
|
41
|
-
import { log } from "@dxos/log";
|
|
42
|
-
|
|
43
|
-
// packages/experimental/assistant/src/session/version-pin.ts
|
|
44
|
-
import { Schema } from "effect";
|
|
45
|
-
import { getVersion } from "@dxos/echo-db";
|
|
46
|
-
import { ObjectId } from "@dxos/echo-schema";
|
|
47
|
-
var ObjectVersionSchema = Schema.Unknown;
|
|
48
|
-
var VersionPinSchema = Schema.Struct({
|
|
49
|
-
// TODO(dmaretskyi): Use Ref when those support encoding.
|
|
50
|
-
objectId: ObjectId,
|
|
51
|
-
// TODO(dmaretskyi): Could be opaque
|
|
52
|
-
version: ObjectVersionSchema
|
|
53
|
-
});
|
|
54
|
-
var VersionPin = class extends VersionPinSchema {
|
|
55
|
-
static {
|
|
56
|
-
this.DISPOSITION = "version-pin";
|
|
57
|
-
}
|
|
58
|
-
static fromObject(object) {
|
|
59
|
-
return VersionPin.make({
|
|
60
|
-
objectId: object.id,
|
|
61
|
-
version: getVersion(object)
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
static createBlock(pin) {
|
|
65
|
-
return {
|
|
66
|
-
type: "json",
|
|
67
|
-
disposition: VersionPin.DISPOSITION,
|
|
68
|
-
json: JSON.stringify(pin)
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
};
|
|
72
|
-
|
|
73
|
-
// packages/experimental/assistant/src/session/session.ts
|
|
74
|
-
function _ts_decorate(decorators, target, key, desc) {
|
|
75
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
76
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
77
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
78
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
79
|
-
}
|
|
80
|
-
var __dxlog_file = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/session/session.ts";
|
|
81
|
-
var AISession = class _AISession {
|
|
82
|
-
constructor(_options) {
|
|
83
|
-
this._options = _options;
|
|
84
|
-
this._parser = new MixedStreamParser();
|
|
85
|
-
this._pending = [];
|
|
86
|
-
this._history = [];
|
|
87
|
-
this.message = this._parser.message;
|
|
88
|
-
this.block = this._parser.block;
|
|
89
|
-
this.update = this._parser.update;
|
|
90
|
-
this.streamEvent = this._parser.streamEvent;
|
|
91
|
-
this.userMessage = new Event();
|
|
92
|
-
this._parser.message.on((message) => {
|
|
93
|
-
this._pending.push(message);
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
async run(options) {
|
|
97
|
-
const systemTools = [];
|
|
98
|
-
switch (this._options.operationModel) {
|
|
99
|
-
case "planning":
|
|
100
|
-
systemTools.push(this._createQueryArtifactsTool(options.artifacts), this._createPlanningTool(options));
|
|
101
|
-
break;
|
|
102
|
-
case "importing":
|
|
103
|
-
systemTools.push(this._createQueryArtifactsTool(options.artifacts), this._createRequireTool(options.artifacts, (artifactDefinitionIds) => {
|
|
104
|
-
for (const artifactDefinitionId of artifactDefinitionIds) {
|
|
105
|
-
requiredArtifactIds.add(artifactDefinitionId);
|
|
106
|
-
}
|
|
107
|
-
}));
|
|
108
|
-
break;
|
|
109
|
-
case "configured":
|
|
110
|
-
break;
|
|
111
|
-
default:
|
|
112
|
-
throw new TypeError(`Invalid operation model: ${this._options.operationModel}`);
|
|
113
|
-
}
|
|
114
|
-
this._history = [
|
|
115
|
-
...options.history
|
|
116
|
-
];
|
|
117
|
-
this._pending = [
|
|
118
|
-
await this._formatUserPrompt(options.artifactDiffResolver, options.prompt, options.history)
|
|
119
|
-
];
|
|
120
|
-
this.userMessage.emit(this._pending.at(-1));
|
|
121
|
-
this._stream = void 0;
|
|
122
|
-
let error;
|
|
123
|
-
const requiredArtifactIds = new Set(options.requiredArtifactIds ?? []);
|
|
124
|
-
try {
|
|
125
|
-
let more = false;
|
|
126
|
-
do {
|
|
127
|
-
const tools = [
|
|
128
|
-
...systemTools,
|
|
129
|
-
...options.tools,
|
|
130
|
-
...options.artifacts.filter((artifact) => requiredArtifactIds.has(artifact.id)).flatMap((artifact) => artifact.tools)
|
|
131
|
-
];
|
|
132
|
-
log("request", {
|
|
133
|
-
pending: this._pending.length,
|
|
134
|
-
history: this._history.length,
|
|
135
|
-
tools: tools.map((tool) => tool.name)
|
|
136
|
-
}, {
|
|
137
|
-
F: __dxlog_file,
|
|
138
|
-
L: 180,
|
|
139
|
-
S: this,
|
|
140
|
-
C: (f, a) => f(...a)
|
|
141
|
-
});
|
|
142
|
-
this._stream = await options.client.execStream({
|
|
143
|
-
...options.generationOptions ?? {},
|
|
144
|
-
// TODO(burdon): Rename messages or separate history/message.
|
|
145
|
-
history: [
|
|
146
|
-
...this._history,
|
|
147
|
-
...this._pending
|
|
148
|
-
],
|
|
149
|
-
tools,
|
|
150
|
-
systemPrompt: options.systemPrompt ?? createBaseInstructions({
|
|
151
|
-
availableArtifacts: Array.from(requiredArtifactIds),
|
|
152
|
-
operationModel: this._options.operationModel
|
|
153
|
-
})
|
|
154
|
-
});
|
|
155
|
-
await this._parser.parse(this._stream);
|
|
156
|
-
await this._stream.complete();
|
|
157
|
-
log("response", {
|
|
158
|
-
pending: this._pending
|
|
159
|
-
}, {
|
|
160
|
-
F: __dxlog_file,
|
|
161
|
-
L: 205,
|
|
162
|
-
S: this,
|
|
163
|
-
C: (f, a) => f(...a)
|
|
164
|
-
});
|
|
165
|
-
more = false;
|
|
166
|
-
const message = this._pending.at(-1);
|
|
167
|
-
invariant(message, void 0, {
|
|
168
|
-
F: __dxlog_file,
|
|
169
|
-
L: 210,
|
|
170
|
-
S: this,
|
|
171
|
-
A: [
|
|
172
|
-
"message",
|
|
173
|
-
""
|
|
174
|
-
]
|
|
175
|
-
});
|
|
176
|
-
if (isToolUse(message)) {
|
|
177
|
-
log("tool request...", void 0, {
|
|
178
|
-
F: __dxlog_file,
|
|
179
|
-
L: 212,
|
|
180
|
-
S: this,
|
|
181
|
-
C: (f, a) => f(...a)
|
|
182
|
-
});
|
|
183
|
-
const response = await runTools({
|
|
184
|
-
message: this._pending.at(-1),
|
|
185
|
-
tools,
|
|
186
|
-
extensions: options.extensions ?? {}
|
|
187
|
-
});
|
|
188
|
-
log("tool response", {
|
|
189
|
-
response
|
|
190
|
-
}, {
|
|
191
|
-
F: __dxlog_file,
|
|
192
|
-
L: 219,
|
|
193
|
-
S: this,
|
|
194
|
-
C: (f, a) => f(...a)
|
|
195
|
-
});
|
|
196
|
-
switch (response.type) {
|
|
197
|
-
case "continue": {
|
|
198
|
-
this._pending = [
|
|
199
|
-
...this._pending,
|
|
200
|
-
response.message
|
|
201
|
-
];
|
|
202
|
-
this.userMessage.emit(response.message);
|
|
203
|
-
more = true;
|
|
204
|
-
break;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
} while (more);
|
|
209
|
-
} catch (err) {
|
|
210
|
-
log.catch(err, void 0, {
|
|
211
|
-
F: __dxlog_file,
|
|
212
|
-
L: 231,
|
|
213
|
-
S: this,
|
|
214
|
-
C: (f, a) => f(...a)
|
|
215
|
-
});
|
|
216
|
-
if (err instanceof Error && err.message.includes("Overloaded")) {
|
|
217
|
-
error = new AIServiecOverloadedError("AI service overloaded", {
|
|
218
|
-
cause: err
|
|
219
|
-
});
|
|
220
|
-
} else {
|
|
221
|
-
error = new Error("AI service error", {
|
|
222
|
-
cause: err
|
|
223
|
-
});
|
|
224
|
-
}
|
|
225
|
-
} finally {
|
|
226
|
-
this._stream = void 0;
|
|
227
|
-
}
|
|
228
|
-
if (error) {
|
|
229
|
-
throw error;
|
|
230
|
-
}
|
|
231
|
-
return this._pending;
|
|
232
|
-
}
|
|
233
|
-
async _formatUserPrompt(artifactDiffResolver, prompt, history) {
|
|
234
|
-
const prelude = [];
|
|
235
|
-
if (artifactDiffResolver) {
|
|
236
|
-
const versions = gatherObjectVersions(history);
|
|
237
|
-
const artifactDiff = await artifactDiffResolver(Array.from(versions.entries()).map(([id, version]) => ({
|
|
238
|
-
id,
|
|
239
|
-
lastVersion: version
|
|
240
|
-
})));
|
|
241
|
-
log.info("vision", {
|
|
242
|
-
artifactDiff,
|
|
243
|
-
versions
|
|
244
|
-
}, {
|
|
245
|
-
F: __dxlog_file,
|
|
246
|
-
L: 262,
|
|
247
|
-
S: this,
|
|
248
|
-
C: (f, a) => f(...a)
|
|
249
|
-
});
|
|
250
|
-
for (const [id, { version }] of [
|
|
251
|
-
...artifactDiff.entries()
|
|
252
|
-
]) {
|
|
253
|
-
if (ObjectVersion.equals(version, versions.get(id))) {
|
|
254
|
-
artifactDiff.delete(id);
|
|
255
|
-
continue;
|
|
256
|
-
}
|
|
257
|
-
prelude.push(VersionPin.createBlock(VersionPin.make({
|
|
258
|
-
objectId: id,
|
|
259
|
-
version
|
|
260
|
-
})));
|
|
261
|
-
}
|
|
262
|
-
if (artifactDiff.size > 0) {
|
|
263
|
-
prelude.push(createArtifactUpdateBlock(artifactDiff));
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
return create(Message, {
|
|
267
|
-
role: "user",
|
|
268
|
-
content: [
|
|
269
|
-
...prelude,
|
|
270
|
-
{
|
|
271
|
-
type: "text",
|
|
272
|
-
text: prompt
|
|
273
|
-
}
|
|
274
|
-
]
|
|
275
|
-
});
|
|
276
|
-
}
|
|
277
|
-
_createQueryArtifactsTool(artifacts) {
|
|
278
|
-
return defineTool("system", {
|
|
279
|
-
name: "query_artifact_definitions",
|
|
280
|
-
description: "Query the available artifact definitions",
|
|
281
|
-
schema: Schema2.Struct({}),
|
|
282
|
-
execute: async () => {
|
|
283
|
-
return ToolResult.Success({
|
|
284
|
-
artifactDefinitions: artifacts.map((artifact) => ({
|
|
285
|
-
id: artifact.id,
|
|
286
|
-
name: artifact.name,
|
|
287
|
-
description: artifact.description
|
|
288
|
-
}))
|
|
289
|
-
});
|
|
290
|
-
}
|
|
291
|
-
});
|
|
292
|
-
}
|
|
293
|
-
_createRequireTool(artifacts, onRequire) {
|
|
294
|
-
return defineTool("system", {
|
|
295
|
-
name: "require_artifact_definitions",
|
|
296
|
-
description: "Require the use of specific artifact definitions. This will allow the model to interact with artifact definitions and use their tools.",
|
|
297
|
-
schema: Schema2.Struct({
|
|
298
|
-
artifactDefinitionIds: Schema2.Array(Schema2.String).annotations({
|
|
299
|
-
description: "The ids of the artifact definitions to require",
|
|
300
|
-
examples: [
|
|
301
|
-
[
|
|
302
|
-
"artifact:dxos.org/example/Test"
|
|
303
|
-
]
|
|
304
|
-
]
|
|
305
|
-
})
|
|
306
|
-
}),
|
|
307
|
-
execute: async ({ artifactDefinitionIds }) => {
|
|
308
|
-
const missingArtifactDefinitionIds = artifactDefinitionIds.filter((artifactId) => !artifacts.some((artifact) => artifact.id === artifactId));
|
|
309
|
-
if (missingArtifactDefinitionIds.length > 0) {
|
|
310
|
-
return ToolResult.Error(`One or more artifact definition ids are invalid: ${missingArtifactDefinitionIds.join(", ")}`);
|
|
311
|
-
}
|
|
312
|
-
onRequire(artifactDefinitionIds);
|
|
313
|
-
return ToolResult.Success({});
|
|
314
|
-
}
|
|
315
|
-
});
|
|
316
|
-
}
|
|
317
|
-
_createPlanningTool(options) {
|
|
318
|
-
return defineTool("system", {
|
|
319
|
-
name: "create_plan",
|
|
320
|
-
description: "Create a plan. Make sure that each step is independent and can be executed solely on the data returned by the previous step. The steps only share the data that is specified in the plan.",
|
|
321
|
-
schema: Schema2.Struct({
|
|
322
|
-
goal: Schema2.String.annotations({
|
|
323
|
-
description: "The goal that the plan will achieve."
|
|
324
|
-
}),
|
|
325
|
-
steps: Schema2.Array(Schema2.Struct({
|
|
326
|
-
action: Schema2.String.annotations({
|
|
327
|
-
description: "Complete, detailed action to perform."
|
|
328
|
-
}),
|
|
329
|
-
input: Schema2.String.annotations({
|
|
330
|
-
description: "The required input data for this step. First step must not require any data."
|
|
331
|
-
}),
|
|
332
|
-
output: Schema2.String.annotations({
|
|
333
|
-
description: "The output data from this step. This is passed to the next step as input."
|
|
334
|
-
}),
|
|
335
|
-
requiredArtifactIds: Schema2.Array(Schema2.String).annotations({
|
|
336
|
-
description: "The ids of the artifacts required to perform this step.",
|
|
337
|
-
examples: [
|
|
338
|
-
[
|
|
339
|
-
"artifact:dxos.org/example/Test"
|
|
340
|
-
]
|
|
341
|
-
]
|
|
342
|
-
})
|
|
343
|
-
})).annotations({
|
|
344
|
-
description: "Steps"
|
|
345
|
-
})
|
|
346
|
-
}),
|
|
347
|
-
execute: async ({ goal, steps }) => {
|
|
348
|
-
const missingArtifactIds = steps.flatMap((step) => step.requiredArtifactIds).filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
|
|
349
|
-
if (missingArtifactIds.length > 0) {
|
|
350
|
-
return ToolResult.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(", ")}`);
|
|
351
|
-
}
|
|
352
|
-
const stepResults = [];
|
|
353
|
-
for (const step of steps) {
|
|
354
|
-
log("executing step", {
|
|
355
|
-
action: step.action
|
|
356
|
-
}, {
|
|
357
|
-
F: __dxlog_file,
|
|
358
|
-
L: 369,
|
|
359
|
-
S: this,
|
|
360
|
-
C: (f, a) => f(...a)
|
|
361
|
-
});
|
|
362
|
-
const session = new _AISession({
|
|
363
|
-
operationModel: "importing"
|
|
364
|
-
});
|
|
365
|
-
session.message.on((ev) => this.message.emit(ev));
|
|
366
|
-
session.block.on((ev) => this.block.emit(ev));
|
|
367
|
-
session.update.on((ev) => this.update.emit(ev));
|
|
368
|
-
session.streamEvent.on((ev) => this.streamEvent.emit(ev));
|
|
369
|
-
session.userMessage.on((ev) => this.userMessage.emit(ev));
|
|
370
|
-
const messages = await session.run({
|
|
371
|
-
client: options.client,
|
|
372
|
-
artifacts: options.artifacts,
|
|
373
|
-
tools: options.tools,
|
|
374
|
-
history: options.history,
|
|
375
|
-
extensions: options.extensions,
|
|
376
|
-
generationOptions: options.generationOptions,
|
|
377
|
-
requiredArtifactIds: step.requiredArtifactIds.slice(),
|
|
378
|
-
artifactDiffResolver: options.artifactDiffResolver,
|
|
379
|
-
prompt: `
|
|
380
|
-
You are an agent that executes the subtask in a plan.
|
|
381
|
-
|
|
382
|
-
While you know the plan's goal only focus on your subtask
|
|
383
|
-
Use the data from the previous step to complete your task.
|
|
384
|
-
Return all of the data from "output" in your last message.
|
|
385
|
-
|
|
386
|
-
Current step (that you need to complete):
|
|
387
|
-
${JSON.stringify({
|
|
388
|
-
goal,
|
|
389
|
-
input: step.input,
|
|
390
|
-
output: step.output,
|
|
391
|
-
yourTask: step.action
|
|
392
|
-
}, null, 2)}
|
|
393
|
-
|
|
394
|
-
Previous step results:
|
|
395
|
-
${JSON.stringify(stepResults.at(-1))}.
|
|
396
|
-
`
|
|
397
|
-
});
|
|
398
|
-
const result = messages.at(-1);
|
|
399
|
-
stepResults.push(result);
|
|
400
|
-
}
|
|
401
|
-
return ToolResult.Success({
|
|
402
|
-
stepResults
|
|
403
|
-
});
|
|
404
|
-
}
|
|
405
|
-
});
|
|
406
|
-
}
|
|
407
|
-
abort() {
|
|
408
|
-
this._stream?.abort();
|
|
409
|
-
}
|
|
410
|
-
};
|
|
411
|
-
_ts_decorate([
|
|
412
|
-
synchronized
|
|
413
|
-
], AISession.prototype, "run", null);
|
|
414
|
-
var createBaseInstructions = ({ availableArtifacts, operationModel }) => `
|
|
415
|
-
You are a friendly, advanced AI assistant capable of creating and managing artifacts from available data and tools.
|
|
416
|
-
Your task is to process user commands and questions and decide how best to respond.
|
|
417
|
-
In some cases, you will need to create or reference data objects called artifacts.
|
|
418
|
-
|
|
419
|
-
Follow these guidelines carefully:
|
|
420
|
-
|
|
421
|
-
Decision-making:
|
|
422
|
-
|
|
423
|
-
- Analyze the structure and type of the content in the user's message.
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
${operationModel === "planning" ? `
|
|
427
|
-
- Can you complete the task using the available artifacts?
|
|
428
|
-
- If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
|
|
429
|
-
- Identify which artifacts are relevant to the user's request.
|
|
430
|
-
- Break down the user's request into a step-by-step plan that you will use to execute the user's request, the plan items should include artifacts which will be used to perform the actions.
|
|
431
|
-
` : ""}
|
|
432
|
-
${operationModel === "importing" ? `
|
|
433
|
-
- Can you complete the task using the available artifacts?
|
|
434
|
-
- If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
|
|
435
|
-
- Identify which artifacts are relevant to the user's request.
|
|
436
|
-
- Are the required artifacts already available?
|
|
437
|
-
- If not, select which artifact(s) will be the most relevant and require them using the require_artifacts tool.
|
|
438
|
-
- The require'd artifact tools will be available for use after require.
|
|
439
|
-
` : ""}
|
|
440
|
-
${operationModel === "configured" ? `
|
|
441
|
-
- Select the most relevant artifact(s) to complete the task.
|
|
442
|
-
- Call the appropriate tool to use the artifact(s).
|
|
443
|
-
` : ""}
|
|
444
|
-
|
|
445
|
-
${availableArtifacts.length > 0 ? `Artifacts already in context: ${availableArtifacts.join("\n")}` : ""}
|
|
446
|
-
`;
|
|
447
|
-
var AIServiecOverloadedError = class extends Schema2.TaggedError()("AIServiecOverloadedError", {}) {
|
|
448
|
-
};
|
|
449
|
-
var gatherObjectVersions = (messages) => {
|
|
450
|
-
const artifactIds = /* @__PURE__ */ new Map();
|
|
451
|
-
for (const message of messages) {
|
|
452
|
-
for (const block of message.content) {
|
|
453
|
-
if (block.type === "json" && block.disposition === VersionPin.DISPOSITION) {
|
|
454
|
-
const pin = VersionPin.pipe(Schema2.decodeOption)(JSON.parse(block.json)).pipe(Option.getOrUndefined);
|
|
455
|
-
if (!pin) {
|
|
456
|
-
continue;
|
|
457
|
-
}
|
|
458
|
-
artifactIds.set(pin.objectId, pin.version);
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
return artifactIds;
|
|
463
|
-
};
|
|
464
|
-
var createArtifactUpdateBlock = (artifactDiff) => {
|
|
465
|
-
return {
|
|
466
|
-
type: "text",
|
|
467
|
-
disposition: "artifact-update",
|
|
468
|
-
text: `
|
|
469
|
-
The following artifacts have been updated since the last message:
|
|
470
|
-
${Array.from(artifactDiff.entries()).map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `
|
|
471
|
-
${diff}` : ""}</changed-artifact>`).join("\n")}
|
|
472
|
-
`
|
|
473
|
-
};
|
|
474
|
-
};
|
|
35
|
+
} from "./chunk-YSYP7S4W.mjs";
|
|
475
36
|
export {
|
|
476
37
|
AIServiceEdgeClient,
|
|
477
38
|
AIServiecOverloadedError,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": [
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Option, Schema } from 'effect';\n\nimport {\n defineTool,\n Message,\n ToolResult,\n type ArtifactDefinition,\n type MessageContentBlock,\n type Tool,\n} from '@dxos/artifact';\nimport { Event, synchronized } from '@dxos/async';\nimport { ObjectVersion } from '@dxos/echo-db';\nimport { create, type ObjectId } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { VersionPin } from './version-pin';\nimport { MixedStreamParser, type AIServiceClient, type GenerateRequest, type GenerationStream } from '../ai-service';\nimport { isToolUse, runTools } from '../conversation';\n\n/**\n * Contains message history, tools, current context.\n * Current context means the state of the app, time of day, and other contextual information.\n * It makes requests to the model, its a state machine.\n * It keeps track of the current goal.\n * It manages the context window.\n * Tracks the success criteria of reaching the goal, exposing metrics (stretch)\n * Could be run locally in the app or remotely.\n * Could be personal or shared.\n */\n\n/**\n * Resolves artifact ids to their versions.\n * Used to give the model a sense of the changes to the artifacts made by users during the conversation.\n * The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,\n * a diff is inserted into the conversation.\n */\nexport type ArtifactDiffResolver = (artifacts: { id: ObjectId; lastVersion: ObjectVersion }[]) => Promise<\n Map<\n ObjectId,\n {\n version: ObjectVersion;\n diff?: string;\n }\n >\n>;\n\nexport type SessionRunOptions = {\n client: AIServiceClient;\n\n artifacts: ArtifactDefinition[];\n\n /**\n * Non-artifact specific tools.\n */\n tools: Tool[];\n\n history: Message[];\n\n prompt: string;\n\n generationOptions?: Pick<GenerateRequest, 'model'>;\n\n extensions?: ToolContextExtensions;\n\n systemPrompt?: string;\n\n /**\n * Pre-require artifacts.\n */\n requiredArtifactIds?: string[];\n\n /**\n * @see ArtifactDiffResolver\n */\n artifactDiffResolver?: ArtifactDiffResolver;\n};\n\ntype OperationModel = 'planning' | 'importing' | 'configured';\n\nexport type AiSessionOptions = {\n /**\n * Determines the agent's handling of the artifacts definitions:\n *\n * - `planning`: The model will create a plan with required artifacts for each step.\n * - `importing`: The model can query registry and only pull in the artifacts that are required to complete the task.\n * - `configured`: The available artifacts are pre-selected and the model cannot select additional artifacts.\n */\n operationModel: OperationModel;\n};\n\nexport class AISession {\n /** SSE stream parser. */\n private readonly _parser = new MixedStreamParser();\n\n /** Pending messages (incl. the current user request). */\n private _pending: Message[] = [];\n\n /** Current streaming response. */\n private _stream: GenerationStream | undefined;\n\n /** Prior history from queue. */\n private _history: Message[] = [];\n\n /**\n * New message.\n */\n public readonly message = this._parser.message;\n\n /**\n * Complete block added to Message.\n */\n public readonly block = this._parser.block;\n\n /**\n * Update partial block (while streaming).\n */\n public readonly update = this._parser.update;\n\n public readonly streamEvent = this._parser.streamEvent;\n\n /**\n * User prompt or tool result.\n */\n public readonly userMessage = new Event<Message>();\n\n constructor(private readonly _options: AiSessionOptions) {\n // Message complete.\n this._parser.message.on((message) => {\n this._pending.push(message);\n });\n }\n\n @synchronized\n async run(options: SessionRunOptions): Promise<Message[]> {\n const systemTools: Tool[] = [];\n switch (this._options.operationModel) {\n case 'planning':\n systemTools.push(this._createQueryArtifactsTool(options.artifacts), this._createPlanningTool(options));\n break;\n case 'importing':\n systemTools.push(\n this._createQueryArtifactsTool(options.artifacts),\n this._createRequireTool(options.artifacts, (artifactDefinitionIds) => {\n for (const artifactDefinitionId of artifactDefinitionIds) {\n requiredArtifactIds.add(artifactDefinitionId);\n }\n }),\n );\n break;\n case 'configured':\n // no system tools\n break;\n default:\n throw new TypeError(`Invalid operation model: ${this._options.operationModel}`);\n }\n\n this._history = [...options.history];\n this._pending = [await this._formatUserPrompt(options.artifactDiffResolver, options.prompt, options.history)];\n this.userMessage.emit(this._pending.at(-1)!);\n this._stream = undefined;\n let error: Error | undefined;\n\n const requiredArtifactIds = new Set<string>(options.requiredArtifactIds ?? []);\n try {\n let more = false;\n do {\n const tools = [\n ...systemTools,\n ...options.tools,\n ...options.artifacts\n .filter((artifact) => requiredArtifactIds.has(artifact.id))\n .flatMap((artifact) => artifact.tools),\n ];\n\n log('request', {\n pending: this._pending.length,\n history: this._history.length,\n tools: tools.map((tool) => tool.name),\n });\n\n // Open request stream.\n this._stream = await options.client.execStream({\n ...(options.generationOptions ?? {}),\n // TODO(burdon): Rename messages or separate history/message.\n history: [...this._history, ...this._pending],\n tools,\n systemPrompt:\n options.systemPrompt ??\n createBaseInstructions({\n availableArtifacts: Array.from(requiredArtifactIds),\n operationModel: this._options.operationModel,\n }),\n });\n\n // Wait until complete.\n await this._parser.parse(this._stream);\n await this._stream.complete();\n\n // Add messages.\n log('response', { pending: this._pending });\n\n // Resolve tool use locally.\n more = false;\n const message = this._pending.at(-1);\n invariant(message);\n if (isToolUse(message)) {\n log('tool request...');\n const response = await runTools({\n message: this._pending.at(-1)!,\n tools,\n extensions: options.extensions ?? {},\n });\n\n log('tool response', { response });\n switch (response.type) {\n case 'continue': {\n this._pending = [...this._pending, response.message];\n this.userMessage.emit(response.message);\n more = true;\n break;\n }\n }\n }\n } while (more);\n } catch (err) {\n log.catch(err);\n if (err instanceof Error && err.message.includes('Overloaded')) {\n error = new AIServiecOverloadedError('AI service overloaded', { cause: err } as any); // TODO(dmaretskyi): Schema errors cant have cause\n } else {\n error = new Error('AI service error', { cause: err });\n }\n } finally {\n this._stream = undefined;\n }\n\n if (error) {\n throw error;\n }\n\n return this._pending;\n }\n\n private async _formatUserPrompt(\n artifactDiffResolver: ArtifactDiffResolver | undefined,\n prompt: string,\n history: Message[],\n ) {\n const prelude: MessageContentBlock[] = [];\n\n if (artifactDiffResolver) {\n const versions = gatherObjectVersions(history);\n\n const artifactDiff = await artifactDiffResolver(\n Array.from(versions.entries()).map(([id, version]) => ({ id, lastVersion: version })),\n );\n\n log.info('vision', {\n artifactDiff,\n versions,\n });\n\n for (const [id, { version }] of [...artifactDiff.entries()]) {\n if (ObjectVersion.equals(version, versions.get(id)!)) {\n artifactDiff.delete(id);\n continue;\n }\n\n prelude.push(VersionPin.createBlock(VersionPin.make({ objectId: id, version })));\n }\n if (artifactDiff.size > 0) {\n prelude.push(createArtifactUpdateBlock(artifactDiff));\n }\n }\n\n return create(Message, {\n role: 'user',\n content: [...prelude, { type: 'text', text: prompt }],\n });\n }\n\n private _createQueryArtifactsTool(artifacts: ArtifactDefinition[]) {\n return defineTool('system', {\n name: 'query_artifact_definitions',\n description: 'Query the available artifact definitions',\n schema: Schema.Struct({}),\n execute: async () => {\n return ToolResult.Success({\n artifactDefinitions: artifacts.map((artifact) => ({\n id: artifact.id,\n name: artifact.name,\n description: artifact.description,\n })),\n });\n },\n });\n }\n\n private _createRequireTool(\n artifacts: ArtifactDefinition[],\n onRequire: (artifactDefinitionIds: readonly string[]) => void,\n ) {\n return defineTool('system', {\n name: 'require_artifact_definitions',\n description:\n 'Require the use of specific artifact definitions. This will allow the model to interact with artifact definitions and use their tools.',\n schema: Schema.Struct({\n artifactDefinitionIds: Schema.Array(Schema.String).annotations({\n description: 'The ids of the artifact definitions to require',\n examples: [['artifact:dxos.org/example/Test']],\n }),\n }),\n execute: async ({ artifactDefinitionIds }) => {\n const missingArtifactDefinitionIds = artifactDefinitionIds.filter(\n (artifactId) => !artifacts.some((artifact) => artifact.id === artifactId),\n );\n if (missingArtifactDefinitionIds.length > 0) {\n return ToolResult.Error(\n `One or more artifact definition ids are invalid: ${missingArtifactDefinitionIds.join(', ')}`,\n );\n }\n\n onRequire(artifactDefinitionIds);\n\n return ToolResult.Success({});\n },\n });\n }\n\n private _createPlanningTool(options: SessionRunOptions) {\n return defineTool('system', {\n name: 'create_plan',\n description:\n 'Create a plan. Make sure that each step is independent and can be executed solely on the data returned by the previous step. The steps only share the data that is specified in the plan.',\n schema: Schema.Struct({\n goal: Schema.String.annotations({ description: 'The goal that the plan will achieve.' }),\n steps: Schema.Array(\n Schema.Struct({\n action: Schema.String.annotations({\n description: 'Complete, detailed action to perform.',\n }),\n input: Schema.String.annotations({\n description: 'The required input data for this step. First step must not require any data.',\n }),\n output: Schema.String.annotations({\n description: 'The output data from this step. This is passed to the next step as input.',\n }),\n requiredArtifactIds: Schema.Array(Schema.String).annotations({\n description: 'The ids of the artifacts required to perform this step.',\n examples: [['artifact:dxos.org/example/Test']],\n }),\n }),\n ).annotations({ description: 'Steps' }),\n }),\n execute: async ({ goal, steps }) => {\n const missingArtifactIds = steps\n .flatMap((step) => step.requiredArtifactIds)\n .filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));\n if (missingArtifactIds.length > 0) {\n return ToolResult.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(', ')}`);\n }\n\n const stepResults: any[] = [];\n for (const step of steps) {\n log('executing step', { action: step.action });\n const session = new AISession({ operationModel: 'importing' });\n session.message.on((ev) => this.message.emit(ev));\n session.block.on((ev) => this.block.emit(ev));\n session.update.on((ev) => this.update.emit(ev));\n session.streamEvent.on((ev) => this.streamEvent.emit(ev));\n session.userMessage.on((ev) => this.userMessage.emit(ev));\n\n const messages = await session.run({\n client: options.client,\n artifacts: options.artifacts,\n tools: options.tools,\n history: options.history,\n extensions: options.extensions,\n generationOptions: options.generationOptions,\n requiredArtifactIds: step.requiredArtifactIds.slice(),\n artifactDiffResolver: options.artifactDiffResolver,\n prompt: `\n You are an agent that executes the subtask in a plan.\n \n While you know the plan's goal only focus on your subtask\n Use the data from the previous step to complete your task.\n Return all of the data from \"output\" in your last message.\n \n Current step (that you need to complete):\n ${JSON.stringify(\n {\n goal,\n input: step.input,\n output: step.output,\n yourTask: step.action,\n },\n null,\n 2,\n )}\n \n Previous step results:\n ${JSON.stringify(stepResults.at(-1))}.\n `,\n });\n const result = messages.at(-1);\n stepResults.push(result);\n }\n\n return ToolResult.Success({ stepResults });\n },\n });\n }\n\n abort() {\n this._stream?.abort();\n }\n}\n\n// TODO(burdon): Use handlebars template with effect-schema input.\nconst createBaseInstructions = ({\n availableArtifacts,\n operationModel,\n}: {\n availableArtifacts: string[];\n operationModel: OperationModel;\n}) => `\n You are a friendly, advanced AI assistant capable of creating and managing artifacts from available data and tools. \n Your task is to process user commands and questions and decide how best to respond.\n In some cases, you will need to create or reference data objects called artifacts.\n\n Follow these guidelines carefully:\n\n Decision-making:\n\n - Analyze the structure and type of the content in the user's message.\n \n \n ${\n operationModel === 'planning'\n ? `\n - Can you complete the task using the available artifacts?\n - If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.\n - Identify which artifacts are relevant to the user's request.\n - Break down the user's request into a step-by-step plan that you will use to execute the user's request, the plan items should include artifacts which will be used to perform the actions.\n `\n : ''\n }\n ${\n operationModel === 'importing'\n ? `\n - Can you complete the task using the available artifacts?\n - If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.\n - Identify which artifacts are relevant to the user's request.\n - Are the required artifacts already available?\n - If not, select which artifact(s) will be the most relevant and require them using the require_artifacts tool.\n - The require'd artifact tools will be available for use after require.\n `\n : ''\n }\n ${\n operationModel === 'configured'\n ? `\n - Select the most relevant artifact(s) to complete the task.\n - Call the appropriate tool to use the artifact(s).\n `\n : ''\n }\n\n ${availableArtifacts.length > 0 ? `Artifacts already in context: ${availableArtifacts.join('\\n')}` : ''}\n`;\n\nexport class AIServiecOverloadedError extends Schema.TaggedError<AIServiecOverloadedError>()(\n 'AIServiecOverloadedError',\n {},\n) {}\n\nconst gatherObjectVersions = (messages: Message[]): Map<ObjectId, ObjectVersion> => {\n const artifactIds = new Map<ObjectId, ObjectVersion>();\n for (const message of messages) {\n for (const block of message.content) {\n if (block.type === 'json' && block.disposition === VersionPin.DISPOSITION) {\n const pin = VersionPin.pipe(Schema.decodeOption)(JSON.parse(block.json)).pipe(Option.getOrUndefined);\n if (!pin) {\n continue;\n }\n artifactIds.set(pin.objectId, pin.version);\n }\n }\n }\n\n return artifactIds;\n};\n\nconst createArtifactUpdateBlock = (\n artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,\n): MessageContentBlock => {\n return {\n type: 'text',\n disposition: 'artifact-update',\n text: `\n The following artifacts have been updated since the last message:\n ${Array.from(artifactDiff.entries())\n .map(([id, { diff }]) => `<changed-artifact id=\"${id}\">${diff ? `\\n${diff}` : ''}</changed-artifact>`)\n .join('\\n')}\n `,\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport type { MessageContentBlock } from '@dxos/artifact';\nimport type { ObjectVersion } from '@dxos/echo-db';\nimport { getVersion } from '@dxos/echo-db';\nimport { ObjectId, type BaseEchoObject } from '@dxos/echo-schema';\n\n// TODO(dmaretskyi): Extract.\nconst ObjectVersionSchema = Schema.Unknown as Schema.Schema<ObjectVersion>;\n\nconst VersionPinSchema = Schema.Struct({\n // TODO(dmaretskyi): Use Ref when those support encoding.\n objectId: ObjectId,\n // TODO(dmaretskyi): Could be opaque\n version: ObjectVersionSchema,\n});\nexport interface VersionPin extends Schema.Schema.Type<typeof VersionPinSchema> {}\n\nexport const VersionPin: typeof VersionPinSchema & {\n DISPOSITION: 'version-pin';\n fromObject: (object: BaseEchoObject) => VersionPin;\n createBlock: (pin: VersionPin) => MessageContentBlock;\n} = class extends VersionPinSchema {\n static readonly DISPOSITION = 'version-pin';\n static fromObject(object: BaseEchoObject): VersionPin {\n return VersionPin.make({\n objectId: object.id,\n version: getVersion(object),\n });\n }\n\n static createBlock(pin: VersionPin): MessageContentBlock {\n return {\n type: 'json',\n disposition: VersionPin.DISPOSITION,\n json: JSON.stringify(pin),\n };\n }\n};\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": [
|
|
3
|
+
"sources": [],
|
|
4
|
+
"sourcesContent": [],
|
|
5
|
+
"mappings": "",
|
|
6
|
+
"names": []
|
|
7
7
|
}
|