@dxos/assistant 0.8.4-main.7ace549 → 0.8.4-main.937b3ca

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 (84) hide show
  1. package/dist/lib/browser/chunk-7CDDG6LL.mjs +578 -0
  2. package/dist/lib/browser/chunk-7CDDG6LL.mjs.map +7 -0
  3. package/dist/lib/browser/extraction/index.mjs +3 -3
  4. package/dist/lib/browser/extraction/index.mjs.map +3 -3
  5. package/dist/lib/browser/index.mjs +239 -678
  6. package/dist/lib/browser/index.mjs.map +4 -4
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/browser/testing/index.mjs +32 -0
  9. package/dist/lib/browser/testing/index.mjs.map +7 -0
  10. package/dist/lib/node-esm/chunk-CC7ER6Q3.mjs +579 -0
  11. package/dist/lib/node-esm/chunk-CC7ER6Q3.mjs.map +7 -0
  12. package/dist/lib/node-esm/extraction/index.mjs +3 -3
  13. package/dist/lib/node-esm/extraction/index.mjs.map +3 -3
  14. package/dist/lib/node-esm/index.mjs +239 -678
  15. package/dist/lib/node-esm/index.mjs.map +4 -4
  16. package/dist/lib/node-esm/meta.json +1 -1
  17. package/dist/lib/node-esm/testing/index.mjs +33 -0
  18. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  19. package/dist/types/src/conversation/context.d.ts +74 -42
  20. package/dist/types/src/conversation/context.d.ts.map +1 -1
  21. package/dist/types/src/conversation/context.test.d.ts +2 -0
  22. package/dist/types/src/conversation/context.test.d.ts.map +1 -0
  23. package/dist/types/src/conversation/conversation.d.ts +14 -14
  24. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  25. package/dist/types/src/conversation/conversation.test.d.ts +2 -0
  26. package/dist/types/src/conversation/conversation.test.d.ts.map +1 -0
  27. package/dist/types/src/errors.d.ts +12 -16
  28. package/dist/types/src/errors.d.ts.map +1 -1
  29. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +179 -178
  30. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  31. package/dist/types/src/extraction/extraction.d.ts +285 -241
  32. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  33. package/dist/types/src/extraction/quotes.d.ts +2 -2
  34. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  35. package/dist/types/src/functions/services.d.ts +3 -3
  36. package/dist/types/src/functions/services.d.ts.map +1 -1
  37. package/dist/types/src/functions.test.d.ts +2 -0
  38. package/dist/types/src/functions.test.d.ts.map +1 -0
  39. package/dist/types/src/session/GenericToolkit.d.ts +1 -0
  40. package/dist/types/src/session/GenericToolkit.d.ts.map +1 -1
  41. package/dist/types/src/session/format.d.ts +3 -3
  42. package/dist/types/src/session/format.d.ts.map +1 -1
  43. package/dist/types/src/session/observer.d.ts +4 -3
  44. package/dist/types/src/session/observer.d.ts.map +1 -1
  45. package/dist/types/src/session/session.d.ts +14 -9
  46. package/dist/types/src/session/session.d.ts.map +1 -1
  47. package/dist/types/src/session/toolkit.d.ts +5 -6
  48. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  49. package/dist/types/src/session/version-pin.d.ts +1 -1
  50. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  51. package/dist/types/src/testing/index.d.ts +2 -0
  52. package/dist/types/src/testing/index.d.ts.map +1 -0
  53. package/dist/types/src/testing/layer.d.ts +21 -0
  54. package/dist/types/src/testing/layer.d.ts.map +1 -0
  55. package/dist/types/src/types/artifact.d.ts +12 -3
  56. package/dist/types/src/types/artifact.d.ts.map +1 -1
  57. package/dist/types/tsconfig.tsbuildinfo +1 -1
  58. package/package.json +38 -29
  59. package/src/conversation/context.test.ts +46 -0
  60. package/src/conversation/context.ts +183 -65
  61. package/src/conversation/conversation.test.ts +65 -0
  62. package/src/conversation/conversation.ts +46 -49
  63. package/src/diff.test.ts +1 -1
  64. package/src/errors.ts +2 -2
  65. package/src/execution-graph.ts +2 -2
  66. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +3 -3
  67. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +1 -1
  68. package/src/extraction/extraction.ts +3 -3
  69. package/src/extraction/quotes.ts +3 -4
  70. package/src/functions/services.ts +28 -10
  71. package/src/functions.conversations.json +1 -0
  72. package/src/functions.test.ts +74 -0
  73. package/src/session/GenericToolkit.ts +1 -0
  74. package/src/session/format.test.ts +101 -38
  75. package/src/session/format.ts +11 -12
  76. package/src/session/observer.ts +3 -1
  77. package/src/session/session.conversations.json +1 -1
  78. package/src/session/session.test.ts +7 -13
  79. package/src/session/session.ts +33 -12
  80. package/src/session/toolkit.ts +13 -22
  81. package/src/session/version-pin.ts +2 -2
  82. package/src/testing/index.ts +5 -0
  83. package/src/testing/layer.ts +78 -0
  84. package/src/types/artifact.ts +18 -6
@@ -3,14 +3,13 @@
3
3
  //
4
4
 
5
5
  import type * as Toolkit from '@effect/ai/Toolkit';
6
- import * as Array from 'effect/Array';
6
+ import type { Registry } from '@effect-atom/atom-react';
7
7
  import * as Effect from 'effect/Effect';
8
- import * as Option from 'effect/Option';
9
8
 
10
9
  import { Resource } from '@dxos/context';
11
10
  import { Obj } from '@dxos/echo';
12
11
  import { type Queue } from '@dxos/echo-db';
13
- import { DatabaseService } from '@dxos/echo-db';
12
+ import { invariant } from '@dxos/invariant';
14
13
  import { log } from '@dxos/log';
15
14
  import { Message } from '@dxos/types';
16
15
 
@@ -24,49 +23,48 @@ import {
24
23
 
25
24
  import { AiContextBinder, AiContextService, type ContextBinding } from './context';
26
25
 
27
- export interface AiConversationRunParams {
26
+ export interface AiConversationRunProps {
28
27
  prompt: string;
29
28
  system?: string;
30
29
  observer?: GenerationObserver;
31
30
  }
32
31
 
32
+ export type AiConversationOptions = {
33
+ queue: Queue<Message.Message | ContextBinding>;
34
+ toolkit?: Toolkit.Any;
35
+ registry?: Registry.Registry;
36
+ };
37
+
33
38
  /**
34
39
  * Durable conversation state (initiated by users and agents) backed by a Queue.
35
40
  * Executes tools based on AI responses and supports cancellation of in-progress requests.
36
41
  */
37
42
  export class AiConversation extends Resource {
38
43
  /**
39
- * Message and binding queue.
44
+ * Blueprints and objects bound to the conversation.
40
45
  */
46
+ private readonly _binder: AiContextBinder;
41
47
  private readonly _queue: Queue<Message.Message | ContextBinding>;
48
+ private readonly _toolkit?: Toolkit.Any;
42
49
 
43
- /**
44
- * Blueprints bound to the conversation.
45
- */
46
- private readonly _context: AiContextBinder;
47
-
48
- /**
49
- * Toolkit from the current session request.
50
- */
51
- private _toolkit: Toolkit.WithHandler<any> | undefined;
52
-
53
- public constructor(queue: Queue<Message.Message | ContextBinding>) {
50
+ public constructor(options: AiConversationOptions) {
54
51
  super();
55
- this._queue = queue;
56
- this._context = new AiContextBinder(this._queue);
52
+ this._queue = options.queue;
53
+ this._toolkit = options.toolkit;
54
+ invariant(this._queue);
55
+ this._binder = new AiContextBinder({ queue: this._queue, registry: options.registry });
57
56
  }
58
57
 
59
58
  protected override async _open(): Promise<void> {
60
- // TODO(wittjosiah): Pass in parent context?
61
- await this._context.open();
59
+ await this._binder.open(this._ctx);
62
60
  }
63
61
 
64
- protected override async _close(): Promise<void> {
65
- await this._context.close();
62
+ public get queue() {
63
+ return this._queue;
66
64
  }
67
65
 
68
66
  public get context() {
69
- return this._context;
67
+ return this._binder;
70
68
  }
71
69
 
72
70
  public get toolkit() {
@@ -74,55 +72,54 @@ export class AiConversation extends Resource {
74
72
  }
75
73
 
76
74
  public async getHistory(): Promise<Message.Message[]> {
77
- const queueItems = await this._queue.queryObjects();
75
+ const queueItems = await this._queue.queryObjects(); // TODO(burdon): Update.
78
76
  return queueItems.filter(Obj.instanceOf(Message.Message));
79
77
  }
80
78
 
81
79
  /**
82
80
  * Creates a new cancelable request effect.
83
81
  */
84
- createRequest(
85
- params: AiConversationRunParams,
82
+ public createRequest(
83
+ params: AiConversationRunProps,
86
84
  ): Effect.Effect<Message.Message[], AiSessionRunError, AiSessionRunRequirements> {
87
- return Effect.gen(this, function* () {
88
- const session = new AiSession();
89
- const history = yield* Effect.promise(() => this.getHistory());
90
-
91
- // Get context objects.
92
- const context = yield* Effect.promise(() => this.context.query());
93
- const blueprints = yield* Effect.forEach(context.blueprints.values(), DatabaseService.loadOption).pipe(
94
- Effect.map(Array.filter(Option.isSome)),
95
- Effect.map(Array.map((option) => option.value)),
96
- );
97
- const objects = yield* Effect.forEach(context.objects.values(), DatabaseService.loadOption).pipe(
98
- Effect.map(Array.filter(Option.isSome)),
99
- Effect.map(Array.map((option) => option.value)),
100
- );
85
+ const self = this;
86
+ return Effect.gen(function* () {
87
+ const history = yield* Effect.promise(() => self.getHistory());
101
88
 
102
89
  // Create toolkit.
103
- const toolkit = yield* createToolkit({ blueprints });
104
- this._toolkit = toolkit;
90
+ const blueprints = self.context.getBlueprints();
91
+ const toolkit = yield* createToolkit({
92
+ toolkit: self._toolkit,
93
+ blueprints,
94
+ });
95
+
96
+ // Context objects.
97
+ const objects = self.context.getObjects();
105
98
 
106
- const start = Date.now();
107
99
  log('run', {
108
100
  history: history.length,
109
101
  blueprints: blueprints.length,
102
+ tools: Object.keys(toolkit.tools).length,
110
103
  objects: objects.length,
111
- tools: this._toolkit?.tools.length ?? 0,
112
104
  });
113
105
 
114
106
  // Process request.
115
- const messages = yield* session.run({ history, blueprints, objects, toolkit, ...params }).pipe(
107
+ const session = new AiSession();
108
+ const messages = yield* session.run({ history, blueprints, toolkit, objects, ...params }).pipe(
116
109
  Effect.provideService(AiContextService, {
117
- binder: this.context,
110
+ binder: self.context,
118
111
  }),
119
112
  );
120
113
 
121
- log('result', { messages: messages.length, duration: Date.now() - start });
114
+ log('result', {
115
+ messages: messages.length,
116
+ duration: session.duration,
117
+ toolCalls: session.toolCalls,
118
+ });
122
119
 
123
120
  // Append to queue.
124
- yield* Effect.promise(() => this._queue.append(messages));
121
+ yield* Effect.promise(() => self._queue.append(messages));
125
122
  return messages;
126
- }).pipe(Effect.withSpan('AiConversation.request'));
123
+ });
127
124
  }
128
125
  }
package/src/diff.test.ts CHANGED
@@ -15,7 +15,7 @@ describe('diff', () => {
15
15
  it('should apply diffs', async () => {
16
16
  const builder = new EchoTestBuilder();
17
17
  const { db, graph } = await builder.createDatabase();
18
- graph.schemaRegistry.addSchema([Text.Text]);
18
+ await graph.schemaRegistry.register([Text.Text]);
19
19
 
20
20
  const document = trim`
21
21
  # Hello World
package/src/errors.ts CHANGED
@@ -7,9 +7,9 @@ import { BaseError } from '@dxos/errors';
7
7
  /**
8
8
  * Generic error from AI model.
9
9
  */
10
- export class AiModelError extends BaseError.extend('AI_MODEL_ERROR', 'AI model error') {}
10
+ export class AiModelError extends BaseError.extend('AiModelError', 'AI model error') {}
11
11
 
12
12
  /**
13
13
  * Generic error for AI agent execution.
14
14
  */
15
- export class AiAssistantError extends BaseError.extend('AI_ASSISTANT_ERROR', 'AI assistant error') {}
15
+ export class AiAssistantError extends BaseError.extend('AiAssistantError', 'AI assistant error') {}
@@ -496,7 +496,7 @@ const getParentId = (message: Message.Message) => {
496
496
  }
497
497
  };
498
498
 
499
- const stringifyRef = (ref: Ref.Any) => {
499
+ const stringifyRef = (ref: Ref.Unknown) => {
500
500
  if (ref.target) {
501
501
  return stringifyObject(ref.target);
502
502
  }
@@ -504,6 +504,6 @@ const stringifyRef = (ref: Ref.Any) => {
504
504
  return ref.dxn.asEchoDXN()?.echoId ?? ref.dxn.asQueueDXN()?.objectId ?? '';
505
505
  };
506
506
 
507
- const stringifyObject = (obj: Obj.Any) => {
507
+ const stringifyObject = (obj: Obj.Unknown) => {
508
508
  return Obj.getLabel(obj) ?? Obj.getTypename(obj) ?? obj.id;
509
509
  };
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { beforeAll, describe, test } from 'vitest';
6
6
 
7
- import { type EchoDatabase } from '@dxos/echo-db';
7
+ import { type Database } from '@dxos/echo';
8
8
  import { EchoTestBuilder } from '@dxos/echo-db/testing';
9
9
  import { FunctionExecutor, ServiceContainer } from '@dxos/functions-runtime';
10
10
  import { log } from '@dxos/log';
@@ -19,7 +19,7 @@ import { extractionNerFunction } from './extraction-ner-function';
19
19
 
20
20
  describe.skip('NER EntityExtraction', () => {
21
21
  let builder: EchoTestBuilder;
22
- let db: EchoDatabase;
22
+ let db: Database.Database;
23
23
  let executor: FunctionExecutor;
24
24
  let testData: {
25
25
  transcriptJosiah: Message.Message[];
@@ -37,7 +37,7 @@ describe.skip('NER EntityExtraction', () => {
37
37
  builder = await new EchoTestBuilder().open();
38
38
  const { db: db1 } = await builder.createDatabase({ indexing: { vector: true } });
39
39
  db = db1;
40
- db.graph.schemaRegistry.addSchema(TYPES);
40
+ await db.graph.schemaRegistry.register(TYPES);
41
41
  const data = createTestData();
42
42
  testData = {
43
43
  transcriptJosiah: data.transcriptJosiah,
@@ -20,7 +20,7 @@ export const extractionNerFunction = defineFunction({
20
20
  throw new Error('not implemented');
21
21
  // log.info('input', { message, options });
22
22
  // const startTime = performance.now();
23
- // const { db } = context.getService(DatabaseService);
23
+ // const { db } = context.getService(Database.Service);
24
24
  // const { extractFullEntities } = await import('./named-entity-recognition');
25
25
 
26
26
  // const entitiesPromise = Promise.all(
@@ -13,7 +13,7 @@ import { Message } from '@dxos/types';
13
13
 
14
14
  export const ExtractionInput = Schema.Struct({
15
15
  message: Message.Message,
16
- objects: Schema.optional(Schema.Array(Type.Expando)),
16
+ objects: Schema.optional(Schema.Array(Type.Obj)),
17
17
  options: Schema.optional(
18
18
  Schema.Struct({
19
19
  timeout: Schema.optional(Schema.Number),
@@ -29,7 +29,7 @@ export const ExtractionOutput = Schema.Struct({
29
29
  });
30
30
  export interface ExtractionOutput extends Schema.Schema.Type<typeof ExtractionOutput> {}
31
31
 
32
- export type ProcessTranscriptMessageParams = {
32
+ export type ProcessTranscriptMessageProps = {
33
33
  input: ExtractionInput;
34
34
  function: FunctionDefinition<ExtractionInput, ExtractionOutput>;
35
35
  executor: FunctionExecutor;
@@ -55,7 +55,7 @@ export type ExtractionFunction = FunctionDefinition<ExtractionInput, ExtractionO
55
55
  * Extract entities from the transcript message and add them to the message.
56
56
  */
57
57
  // TODO(dmaretskyi): Move context to a vector search index.
58
- export const processTranscriptMessage = async (params: ProcessTranscriptMessageParams): Promise<ExtractionOutput> => {
58
+ export const processTranscriptMessage = async (params: ProcessTranscriptMessageProps): Promise<ExtractionOutput> => {
59
59
  try {
60
60
  if (params.options?.timeout && params.options.timeout > 0) {
61
61
  return await asyncTimeout(params.executor.invoke(params.function, params.input), params.options.timeout);
@@ -4,8 +4,7 @@
4
4
 
5
5
  import * as Schema from 'effect/Schema';
6
6
 
7
- import { Filter, Query } from '@dxos/echo';
8
- import { type EchoDatabase } from '@dxos/echo-db';
7
+ import { type Database, Filter, Query } from '@dxos/echo';
9
8
  import { ObjectId } from '@dxos/keys';
10
9
  import { DXN } from '@dxos/keys';
11
10
  import { log } from '@dxos/log';
@@ -28,10 +27,10 @@ export const ReferencedQuotes = Schema.Struct({
28
27
  });
29
28
  export type ReferencedQuotes = Schema.Schema.Type<typeof ReferencedQuotes>;
30
29
 
31
- export const findQuotes = async (quotes: string[], db: EchoDatabase): Promise<ReferencedQuotes> => {
30
+ export const findQuotes = async (quotes: string[], db: Database.Database): Promise<ReferencedQuotes> => {
32
31
  const references = await Promise.all(
33
32
  quotes.map(async (quote) => {
34
- const { objects } = await db.query(Query.select(Filter.text(quote, { type: 'vector' }))).run();
33
+ const objects = await db.query(Query.select(Filter.text(quote, { type: 'vector' }))).run();
35
34
  log.info('found quotes in vector index', { objects, quote });
36
35
  return objects.length > 0 ? [{ id: objects[0].id.toString(), quote }] : [];
37
36
  }),
@@ -9,14 +9,17 @@ import * as Effect from 'effect/Effect';
9
9
  import * as Layer from 'effect/Layer';
10
10
  import * as Record from 'effect/Record';
11
11
  import * as Schema from 'effect/Schema';
12
+ import type * as SchemaAST from 'effect/SchemaAST';
12
13
 
13
14
  import { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from '@dxos/ai';
14
15
  import { todo } from '@dxos/debug';
15
- import { Query } from '@dxos/echo';
16
- import { DatabaseService } from '@dxos/echo-db';
16
+ import { Query, Type } from '@dxos/echo';
17
+ import { Database } from '@dxos/echo';
17
18
  import { Function, FunctionDefinition, FunctionInvocationService } from '@dxos/functions';
18
19
  import { invariant } from '@dxos/invariant';
19
20
 
21
+ import { RefFromLLM } from '../types';
22
+
20
23
  /**
21
24
  * Constructs a `ToolResolverService` whose `resolve(id)` looks up tools in the following order:
22
25
  * 1. Toolkit: return an existing tool from the provided `toolkit` if one is present under `id`.
@@ -26,27 +29,27 @@ import { invariant } from '@dxos/invariant';
26
29
  *
27
30
  * If none of the above yield a match, the effect fails with `AiToolNotFoundError`.
28
31
  *
29
- * Requires `DatabaseService` in the environment.
32
+ * Requires `Database.Service` in the environment.
30
33
  */
31
34
  export const makeToolResolverFromFunctions = (
32
35
  functions: FunctionDefinition.Any[],
33
36
  toolkit: Toolkit.Toolkit<any>,
34
- ): Layer.Layer<ToolResolverService, never, DatabaseService> => {
37
+ ): Layer.Layer<ToolResolverService, never, Database.Service> => {
35
38
  return Layer.effect(
36
39
  ToolResolverService,
37
40
  Effect.gen(function* () {
38
- const dbService = yield* DatabaseService;
41
+ const dbService = yield* Database.Service;
39
42
  return {
40
43
  resolve: (id): Effect.Effect<Tool.Any, AiToolNotFoundError> =>
41
44
  Effect.gen(function* () {
45
+ // TODO(dmaretskyi): Use FunctionInvocationService.resolveFunction().
46
+
42
47
  const tool = toolkit.tools[id];
43
48
  if (tool) {
44
49
  return tool;
45
50
  }
46
51
 
47
- const {
48
- objects: [dbFunction],
49
- } = yield* DatabaseService.runQuery(Query.type(Function.Function, { key: id }));
52
+ const [dbFunction] = yield* Database.Service.runQuery(Query.type(Function.Function, { key: id }));
50
53
 
51
54
  const functionDef = dbFunction
52
55
  ? FunctionDefinition.deserialize(dbFunction)
@@ -57,7 +60,7 @@ export const makeToolResolverFromFunctions = (
57
60
  }
58
61
 
59
62
  return projectFunctionToTool(functionDef);
60
- }).pipe(Effect.provideService(DatabaseService, dbService)),
63
+ }).pipe(Effect.provideService(Database.Service, dbService)),
61
64
  } satisfies Context.Tag.Service<ToolResolverService>;
62
65
  }),
63
66
  );
@@ -82,6 +85,7 @@ export const makeToolExecutionServiceFromFunctions = (
82
85
  if (Tool.isProviderDefined(tool)) {
83
86
  throw new Error('Attempted to call a provider-defined tool');
84
87
  }
88
+
85
89
  // TODO(wittjosiah): Everything is `never` here.
86
90
  const { result } = yield* (toolkitHandler.handle as any)(tool.name, input);
87
91
  return result;
@@ -149,7 +153,9 @@ const makeToolName = (name: string) => {
149
153
  const createStructFieldsFromSchema = (schema: Schema.Schema<any, any>): Record<string, Schema.Schema<any, any>> => {
150
154
  switch (schema.ast._tag) {
151
155
  case 'TypeLiteral':
152
- return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [prop.name, Schema.make(prop.type)]));
156
+ return Object.fromEntries(
157
+ schema.ast.propertySignatures.map((prop) => [prop.name, Schema.make(mapSchemaTypeForLLM(prop.type))]),
158
+ );
153
159
  case 'VoidKeyword':
154
160
  return {};
155
161
  default:
@@ -157,6 +163,18 @@ const createStructFieldsFromSchema = (schema: Schema.Schema<any, any>): Record<s
157
163
  }
158
164
  };
159
165
 
166
+ /**
167
+ * Picks an LLM-friendly schema type for the given schema AST.
168
+ * The picked schema type decodes to the original schema type.
169
+ */
170
+ const mapSchemaTypeForLLM = (ast: SchemaAST.AST): SchemaAST.AST => {
171
+ if (Type.Ref.isRefSchemaAST(ast)) {
172
+ return RefFromLLM.ast;
173
+ }
174
+
175
+ return ast;
176
+ };
177
+
160
178
  const isHandlerLike = (value: unknown): value is Toolkit.WithHandler<Record<string, Tool.Any>> => {
161
179
  return typeof (value as any).tools === 'object' && typeof (value as any).handle === 'function';
162
180
  };