@dxos/assistant 0.8.2-main.f081794 → 0.8.2-main.f11618f

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.
Files changed (39) hide show
  1. package/dist/lib/browser/index.mjs +270 -150
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/browser/testing/index.mjs +7 -7
  5. package/dist/lib/browser/testing/index.mjs.map +3 -3
  6. package/dist/lib/node/index.cjs +266 -149
  7. package/dist/lib/node/index.cjs.map +4 -4
  8. package/dist/lib/node/meta.json +1 -1
  9. package/dist/lib/node/testing/index.cjs +8 -8
  10. package/dist/lib/node/testing/index.cjs.map +3 -3
  11. package/dist/lib/node-esm/index.mjs +270 -150
  12. package/dist/lib/node-esm/index.mjs.map +4 -4
  13. package/dist/lib/node-esm/meta.json +1 -1
  14. package/dist/lib/node-esm/testing/index.mjs +7 -7
  15. package/dist/lib/node-esm/testing/index.mjs.map +3 -3
  16. package/dist/types/src/session/index.d.ts +1 -0
  17. package/dist/types/src/session/index.d.ts.map +1 -1
  18. package/dist/types/src/session/session.d.ts +29 -4
  19. package/dist/types/src/session/session.d.ts.map +1 -1
  20. package/dist/types/src/session/version-pin.d.ts +17 -0
  21. package/dist/types/src/session/version-pin.d.ts.map +1 -0
  22. package/dist/types/src/session/version-pin.test.d.ts +2 -0
  23. package/dist/types/src/session/version-pin.test.d.ts.map +1 -0
  24. package/dist/types/src/testing/test-schema.d.ts +2 -2
  25. package/dist/types/src/testing/test-schema.d.ts.map +1 -1
  26. package/package.json +13 -13
  27. package/src/bin/chat.ts +2 -2
  28. package/src/cypher/combinators.test.ts +4 -4
  29. package/src/cypher/execution-plan.test.ts +1 -1
  30. package/src/cypher/query-executor.test.ts +1 -1
  31. package/src/cypher/schema.test.ts +3 -3
  32. package/src/session/index.ts +1 -0
  33. package/src/session/session.test.ts +2 -1
  34. package/src/session/session.ts +283 -147
  35. package/src/session/version-pin.test.ts +26 -0
  36. package/src/session/version-pin.ts +43 -0
  37. package/src/testing/query.test.ts +3 -3
  38. package/src/testing/test-data.ts +5 -5
  39. package/src/testing/test-schema.ts +3 -3
@@ -32,12 +32,45 @@ import {
32
32
  } from "./chunk-DEIGOD4U.mjs";
33
33
 
34
34
  // packages/experimental/assistant/src/session/session.ts
35
- import { Schema as S } from "effect";
35
+ import { Option, Schema as S } from "effect";
36
36
  import { defineTool, Message, ToolResult } from "@dxos/artifact";
37
37
  import { Event, synchronized } from "@dxos/async";
38
+ import { ObjectVersion } from "@dxos/echo-db";
38
39
  import { create } from "@dxos/echo-schema";
39
40
  import { invariant } from "@dxos/invariant";
40
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
41
74
  function _ts_decorate(decorators, target, key, desc) {
42
75
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
43
76
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -61,152 +94,28 @@ var AISession = class _AISession {
61
94
  });
62
95
  }
63
96
  async run(options) {
64
- const systemTools = [
65
- defineTool("system", {
66
- name: "query_artifact_definitions",
67
- description: "Query the available artifact definitions",
68
- schema: S.Struct({}),
69
- execute: async () => {
70
- return ToolResult.Success({
71
- artifactDefinitions: options.artifacts.map((artifact) => ({
72
- id: artifact.id,
73
- name: artifact.name,
74
- description: artifact.description
75
- }))
76
- });
77
- }
78
- })
79
- ];
97
+ const systemTools = [];
80
98
  switch (this._options.operationModel) {
81
99
  case "planning":
82
- systemTools.push(defineTool("system", {
83
- name: "create_plan",
84
- 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.",
85
- schema: S.Struct({
86
- goal: S.String.annotations({
87
- description: "The goal that the plan will achieve."
88
- }),
89
- steps: S.Array(S.Struct({
90
- action: S.String.annotations({
91
- description: "Complete, detailed action to perform."
92
- }),
93
- input: S.String.annotations({
94
- description: "The required input data for this step. First step must not require any data."
95
- }),
96
- output: S.String.annotations({
97
- description: "The output data from this step. This is passed to the next step as input."
98
- }),
99
- requiredArtifactIds: S.Array(S.String).annotations({
100
- description: "The ids of the artifacts required to perform this step.",
101
- examples: [
102
- [
103
- "artifact:dxos.org/example/Test"
104
- ]
105
- ]
106
- })
107
- })).annotations({
108
- description: "Steps"
109
- })
110
- }),
111
- execute: async ({ goal, steps }) => {
112
- const missingArtifactIds = steps.flatMap((step) => step.requiredArtifactIds).filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
113
- if (missingArtifactIds.length > 0) {
114
- return ToolResult.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(", ")}`);
115
- }
116
- const stepResults = [];
117
- for (const step of steps) {
118
- log("executing step", {
119
- action: step.action
120
- }, {
121
- F: __dxlog_file,
122
- L: 160,
123
- S: this,
124
- C: (f, a) => f(...a)
125
- });
126
- const session = new _AISession({
127
- operationModel: "immediate"
128
- });
129
- session.message.on((ev) => this.message.emit(ev));
130
- session.block.on((ev) => this.block.emit(ev));
131
- session.update.on((ev) => this.update.emit(ev));
132
- session.streamEvent.on((ev) => this.streamEvent.emit(ev));
133
- session.userMessage.on((ev) => this.userMessage.emit(ev));
134
- const messages = await session.run({
135
- client: options.client,
136
- artifacts: options.artifacts,
137
- tools: options.tools,
138
- history: options.history,
139
- extensions: options.extensions,
140
- generationOptions: options.generationOptions,
141
- requiredArtifactIds: step.requiredArtifactIds.slice(),
142
- prompt: `
143
- You are an agent that executes the subtask in a plan.
144
-
145
- While you know the plan's goal only focus on your subtask
146
- Use the data from the previous step to complete your task.
147
- Return all of the data from "output" in your last message.
148
-
149
- Current step (that you need to complete):
150
- ${JSON.stringify({
151
- goal,
152
- input: step.input,
153
- output: step.output,
154
- yourTask: step.action
155
- }, null, 2)}
156
-
157
- Previous step results:
158
- ${JSON.stringify(stepResults.at(-1))}.
159
- `
160
- });
161
- const result = messages.at(-1);
162
- stepResults.push(result);
163
- }
164
- return ToolResult.Success({
165
- stepResults
166
- });
167
- }
168
- }));
100
+ systemTools.push(this._createQueryArtifactsTool(options.artifacts), this._createPlanningTool(options));
169
101
  break;
170
- case "immediate":
171
- systemTools.push(defineTool("system", {
172
- name: "require_artifact_definitions",
173
- description: "Require the use of specific artifact definitions. This will allow the model to interact with artifact definitions and use their tools.",
174
- schema: S.Struct({
175
- artifactDefinitionIds: S.Array(S.String).annotations({
176
- description: "The ids of the artifact definitions to require",
177
- examples: [
178
- [
179
- "artifact:dxos.org/example/Test"
180
- ]
181
- ]
182
- })
183
- }),
184
- execute: async ({ artifactDefinitionIds }) => {
185
- const missingArtifactDefinitionIds = artifactDefinitionIds.filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
186
- if (missingArtifactDefinitionIds.length > 0) {
187
- return ToolResult.Error(`One or more artifact definition ids are invalid: ${missingArtifactDefinitionIds.join(", ")}`);
188
- }
189
- for (const artifactDefinitionId of artifactDefinitionIds) {
190
- requiredArtifactIds.add(artifactDefinitionId);
191
- }
192
- return ToolResult.Success({});
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);
193
106
  }
194
107
  }));
195
108
  break;
109
+ case "configured":
110
+ break;
111
+ default:
112
+ throw new TypeError(`Invalid operation model: ${this._options.operationModel}`);
196
113
  }
197
114
  this._history = [
198
115
  ...options.history
199
116
  ];
200
117
  this._pending = [
201
- create(Message, {
202
- role: "user",
203
- content: [
204
- {
205
- type: "text",
206
- text: options.prompt
207
- }
208
- ]
209
- })
118
+ await this._formatUserPrompt(options.artifactDiffResolver, options.prompt, options.history)
210
119
  ];
211
120
  this.userMessage.emit(this._pending.at(-1));
212
121
  this._stream = void 0;
@@ -226,7 +135,7 @@ var AISession = class _AISession {
226
135
  tools: tools.map((tool) => tool.name)
227
136
  }, {
228
137
  F: __dxlog_file,
229
- L: 264,
138
+ L: 180,
230
139
  S: this,
231
140
  C: (f, a) => f(...a)
232
141
  });
@@ -249,7 +158,7 @@ var AISession = class _AISession {
249
158
  pending: this._pending
250
159
  }, {
251
160
  F: __dxlog_file,
252
- L: 289,
161
+ L: 205,
253
162
  S: this,
254
163
  C: (f, a) => f(...a)
255
164
  });
@@ -257,7 +166,7 @@ var AISession = class _AISession {
257
166
  const message = this._pending.at(-1);
258
167
  invariant(message, void 0, {
259
168
  F: __dxlog_file,
260
- L: 294,
169
+ L: 210,
261
170
  S: this,
262
171
  A: [
263
172
  "message",
@@ -267,7 +176,7 @@ var AISession = class _AISession {
267
176
  if (isToolUse(message)) {
268
177
  log("tool request...", void 0, {
269
178
  F: __dxlog_file,
270
- L: 296,
179
+ L: 212,
271
180
  S: this,
272
181
  C: (f, a) => f(...a)
273
182
  });
@@ -280,7 +189,7 @@ var AISession = class _AISession {
280
189
  response
281
190
  }, {
282
191
  F: __dxlog_file,
283
- L: 303,
192
+ L: 219,
284
193
  S: this,
285
194
  C: (f, a) => f(...a)
286
195
  });
@@ -300,7 +209,7 @@ var AISession = class _AISession {
300
209
  } catch (err) {
301
210
  log.catch(err, void 0, {
302
211
  F: __dxlog_file,
303
- L: 315,
212
+ L: 231,
304
213
  S: this,
305
214
  C: (f, a) => f(...a)
306
215
  });
@@ -321,6 +230,180 @@ var AISession = class _AISession {
321
230
  }
322
231
  return this._pending;
323
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: S.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: S.Struct({
298
+ artifactDefinitionIds: S.Array(S.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: S.Struct({
322
+ goal: S.String.annotations({
323
+ description: "The goal that the plan will achieve."
324
+ }),
325
+ steps: S.Array(S.Struct({
326
+ action: S.String.annotations({
327
+ description: "Complete, detailed action to perform."
328
+ }),
329
+ input: S.String.annotations({
330
+ description: "The required input data for this step. First step must not require any data."
331
+ }),
332
+ output: S.String.annotations({
333
+ description: "The output data from this step. This is passed to the next step as input."
334
+ }),
335
+ requiredArtifactIds: S.Array(S.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
+ }
324
407
  abort() {
325
408
  this._stream?.abort();
326
409
  }
@@ -338,21 +421,57 @@ var createBaseInstructions = ({ availableArtifacts, operationModel }) => `
338
421
  Decision-making:
339
422
 
340
423
  - Analyze the structure and type of the content in the user's message.
341
- - Can you complete the task using the available artifacts?
342
- - If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
343
- - Identify which artifacts are relevant to the user's request.
424
+
425
+
344
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.
345
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.
346
- ` : `
347
- - Are the required artifacts already available?
348
- - If not, select which artifact(s) will be the most relevant and require them using the require_artifacts tool.
349
- - The require'd artifact tools will be available for use after require.
350
- `}
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
+ ` : ""}
351
444
 
352
445
  ${availableArtifacts.length > 0 ? `Artifacts already in context: ${availableArtifacts.join("\n")}` : ""}
353
446
  `;
354
447
  var AIServiecOverloadedError = class extends S.TaggedError()("AIServiecOverloadedError", {}) {
355
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(S.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
+ };
356
475
  export {
357
476
  AIServiceEdgeClient,
358
477
  AIServiecOverloadedError,
@@ -372,6 +491,7 @@ export {
372
491
  OllamaClient,
373
492
  StreamTransform,
374
493
  ToolTypes,
494
+ VersionPin,
375
495
  createArtifactElement,
376
496
  createGenerationStream,
377
497
  emitMessageAsEvents,