@dxos/assistant 0.8.4-main.ead640a → 0.8.4-main.ef1bc66f44

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 (120) hide show
  1. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
  2. package/dist/lib/neutral/chunk-ZPC54VRM.mjs +596 -0
  3. package/dist/lib/neutral/chunk-ZPC54VRM.mjs.map +7 -0
  4. package/dist/lib/neutral/extraction/index.mjs +225 -0
  5. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  6. package/dist/lib/{browser → neutral}/index.mjs +346 -350
  7. package/dist/lib/neutral/index.mjs.map +7 -0
  8. package/dist/lib/neutral/meta.json +1 -0
  9. package/dist/lib/neutral/testing/index.mjs +38 -0
  10. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  11. package/dist/types/src/conversation/context.d.ts +97 -62
  12. package/dist/types/src/conversation/context.d.ts.map +1 -1
  13. package/dist/types/src/conversation/context.test.d.ts +2 -0
  14. package/dist/types/src/conversation/context.test.d.ts.map +1 -0
  15. package/dist/types/src/conversation/conversation.d.ts +41 -16
  16. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  17. package/dist/types/src/conversation/conversation.test.d.ts +2 -0
  18. package/dist/types/src/conversation/conversation.test.d.ts.map +1 -0
  19. package/dist/types/src/diff.d.ts +3 -1
  20. package/dist/types/src/diff.d.ts.map +1 -1
  21. package/dist/types/src/errors.d.ts +22 -30
  22. package/dist/types/src/errors.d.ts.map +1 -1
  23. package/dist/types/src/execution-graph.d.ts +5 -2
  24. package/dist/types/src/execution-graph.d.ts.map +1 -1
  25. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  26. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +254 -248
  27. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  28. package/dist/types/src/extraction/extraction.d.ts +344 -303
  29. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  30. package/dist/types/src/extraction/quotes.d.ts +2 -2
  31. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  32. package/dist/types/src/functions/services.d.ts +6 -6
  33. package/dist/types/src/functions/services.d.ts.map +1 -1
  34. package/dist/types/src/functions.test.d.ts +2 -0
  35. package/dist/types/src/functions.test.d.ts.map +1 -0
  36. package/dist/types/src/session/GenericToolkit.d.ts +107 -0
  37. package/dist/types/src/session/GenericToolkit.d.ts.map +1 -0
  38. package/dist/types/src/session/artifact-diff.d.ts +1 -1
  39. package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
  40. package/dist/types/src/session/format.d.ts +4 -176
  41. package/dist/types/src/session/format.d.ts.map +1 -1
  42. package/dist/types/src/session/index.d.ts +2 -0
  43. package/dist/types/src/session/index.d.ts.map +1 -1
  44. package/dist/types/src/session/observer.d.ts +6 -5
  45. package/dist/types/src/session/observer.d.ts.map +1 -1
  46. package/dist/types/src/session/session.d.ts +16 -11
  47. package/dist/types/src/session/session.d.ts.map +1 -1
  48. package/dist/types/src/session/toolkit.d.ts +5 -6
  49. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  50. package/dist/types/src/session/version-pin.d.ts +3 -3
  51. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  52. package/dist/types/src/testing/index.d.ts +2 -0
  53. package/dist/types/src/testing/index.d.ts.map +1 -0
  54. package/dist/types/src/testing/layer.d.ts +22 -0
  55. package/dist/types/src/testing/layer.d.ts.map +1 -0
  56. package/dist/types/src/types/artifact.d.ts +14 -2
  57. package/dist/types/src/types/artifact.d.ts.map +1 -1
  58. package/dist/types/tsconfig.tsbuildinfo +1 -1
  59. package/package.json +40 -31
  60. package/src/conversation/context.test.ts +46 -0
  61. package/src/conversation/context.ts +211 -67
  62. package/src/conversation/conversation.test.ts +65 -0
  63. package/src/conversation/conversation.ts +128 -53
  64. package/src/diff.test.ts +37 -6
  65. package/src/diff.ts +18 -4
  66. package/src/errors.ts +2 -2
  67. package/src/execution-graph.test.ts +45 -43
  68. package/src/execution-graph.ts +23 -14
  69. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +2 -2
  70. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +44 -54
  71. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +15 -14
  72. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +36 -44
  73. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +10 -5
  74. package/src/extraction/extraction.ts +9 -8
  75. package/src/extraction/quotes.ts +4 -5
  76. package/src/functions/services.ts +66 -37
  77. package/src/functions.conversations.json +1 -0
  78. package/src/functions.test.ts +74 -0
  79. package/src/session/GenericToolkit.ts +160 -0
  80. package/src/session/artifact-diff.ts +1 -1
  81. package/src/session/format.test.ts +103 -39
  82. package/src/session/format.ts +17 -16
  83. package/src/session/index.ts +3 -0
  84. package/src/session/observer.ts +5 -3
  85. package/src/session/session.conversations.json +1 -1
  86. package/src/session/session.test.ts +28 -15
  87. package/src/session/session.ts +44 -21
  88. package/src/session/toolkit.ts +13 -22
  89. package/src/session/version-pin.ts +6 -6
  90. package/src/templates/{format.tpl → instructions/format.tpl} +1 -4
  91. package/src/templates/system.ts +2 -2
  92. package/src/testing/index.ts +5 -0
  93. package/src/testing/layer.ts +84 -0
  94. package/src/types/artifact.ts +43 -6
  95. package/dist/lib/browser/chunk-CWGVG235.mjs +0 -380
  96. package/dist/lib/browser/chunk-CWGVG235.mjs.map +0 -7
  97. package/dist/lib/browser/chunk-UB26N5UF.mjs +0 -89
  98. package/dist/lib/browser/chunk-UB26N5UF.mjs.map +0 -7
  99. package/dist/lib/browser/extraction/index.mjs +0 -272
  100. package/dist/lib/browser/extraction/index.mjs.map +0 -7
  101. package/dist/lib/browser/index.mjs.map +0 -7
  102. package/dist/lib/browser/meta.json +0 -1
  103. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs +0 -13
  104. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs +0 -91
  105. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs.map +0 -7
  106. package/dist/lib/node-esm/chunk-OV5PMQPB.mjs +0 -382
  107. package/dist/lib/node-esm/chunk-OV5PMQPB.mjs.map +0 -7
  108. package/dist/lib/node-esm/extraction/index.mjs +0 -273
  109. package/dist/lib/node-esm/extraction/index.mjs.map +0 -7
  110. package/dist/lib/node-esm/index.mjs +0 -934
  111. package/dist/lib/node-esm/index.mjs.map +0 -7
  112. package/dist/lib/node-esm/meta.json +0 -1
  113. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs +0 -14
  114. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs.map +0 -7
  115. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  116. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  117. package/src/summarization/summarization.test.ts +0 -202
  118. /package/dist/lib/{browser/named-entity-recognition-QPYHML66.mjs.map → neutral/chunk-J5LGTIGS.mjs.map} +0 -0
  119. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
  120. /package/src/templates/{system.tpl → instructions/system.tpl} +0 -0
@@ -2,17 +2,22 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ import type * as Tool from '@effect/ai/Tool';
5
6
  import type * as Toolkit from '@effect/ai/Toolkit';
6
- import * as Array from 'effect/Array';
7
+ import type { Registry } from '@effect-atom/atom-react';
8
+ import * as Context from 'effect/Context';
7
9
  import * as Effect from 'effect/Effect';
8
- import * as Option from 'effect/Option';
10
+ import * as Layer from 'effect/Layer';
9
11
 
12
+ import { type ToolExecutionService, type ToolResolverService } from '@dxos/ai';
10
13
  import { Resource } from '@dxos/context';
11
14
  import { Obj } from '@dxos/echo';
12
15
  import { type Queue } from '@dxos/echo-db';
13
- import { DatabaseService } from '@dxos/functions';
16
+ import { acquireReleaseResource } from '@dxos/effect';
17
+ import { QueueService } from '@dxos/functions';
18
+ import { invariant } from '@dxos/invariant';
14
19
  import { log } from '@dxos/log';
15
- import { DataType } from '@dxos/schema';
20
+ import { Message } from '@dxos/types';
16
21
 
17
22
  import {
18
23
  AiSession,
@@ -24,105 +29,175 @@ import {
24
29
 
25
30
  import { AiContextBinder, AiContextService, type ContextBinding } from './context';
26
31
 
27
- export interface AiConversationRunParams {
32
+ export interface AiConversationRunProps {
28
33
  prompt: string;
29
34
  system?: string;
30
35
  observer?: GenerationObserver;
31
36
  }
32
37
 
38
+ export type AiConversationOptions = {
39
+ queue: Queue<Message.Message | ContextBinding>;
40
+ toolkit?: Toolkit.Any;
41
+ registry?: Registry.Registry;
42
+ };
43
+
33
44
  /**
34
45
  * Durable conversation state (initiated by users and agents) backed by a Queue.
35
46
  * Executes tools based on AI responses and supports cancellation of in-progress requests.
36
47
  */
37
48
  export class AiConversation extends Resource {
38
49
  /**
39
- * Message and binding queue.
40
- */
41
- private readonly _queue: Queue<DataType.Message | ContextBinding>;
42
-
43
- /**
44
- * Blueprints bound to the conversation.
50
+ * Blueprints and objects bound to the conversation.
45
51
  */
46
- private readonly _context: AiContextBinder;
52
+ private readonly _binder: AiContextBinder;
53
+ private readonly _queue: Queue<Message.Message | ContextBinding>;
54
+ private readonly _toolkit?: Toolkit.Any;
47
55
 
48
- /**
49
- * Toolkit from the current session request.
50
- */
51
- private _toolkit: Toolkit.WithHandler<any> | undefined;
52
-
53
- public constructor(queue: Queue<DataType.Message | ContextBinding>) {
56
+ public constructor(options: AiConversationOptions) {
54
57
  super();
55
- this._queue = queue;
56
- this._context = new AiContextBinder(this._queue);
58
+ this._queue = options.queue;
59
+ this._toolkit = options.toolkit;
60
+ invariant(this._queue);
61
+ this._binder = new AiContextBinder({ queue: this._queue, registry: options.registry });
57
62
  }
58
63
 
59
64
  protected override async _open(): Promise<void> {
60
- // TODO(wittjosiah): Pass in parent context?
61
- await this._context.open();
65
+ await this._binder.open(this._ctx);
62
66
  }
63
67
 
64
- protected override async _close(): Promise<void> {
65
- await this._context.close();
68
+ public get queue() {
69
+ return this._queue;
66
70
  }
67
71
 
68
72
  public get context() {
69
- return this._context;
73
+ return this._binder;
70
74
  }
71
75
 
72
76
  public get toolkit() {
73
77
  return this._toolkit;
74
78
  }
75
79
 
76
- public async getHistory(): Promise<DataType.Message[]> {
77
- const queueItems = await this._queue.queryObjects();
78
- return queueItems.filter(Obj.instanceOf(DataType.Message));
80
+ public async getHistory(): Promise<Message.Message[]> {
81
+ const queueItems = await this._queue.queryObjects(); // TODO(burdon): Update.
82
+ return queueItems.filter(Obj.instanceOf(Message.Message));
83
+ }
84
+
85
+ getTools(): Effect.Effect<Record<string, Tool.Any>, never, ToolExecutionService | ToolResolverService> {
86
+ return Effect.gen(this, function* () {
87
+ const blueprints = this.context.getBlueprints();
88
+ const tookit = yield* createToolkit({ toolkit: this._toolkit, blueprints });
89
+ return tookit.tools;
90
+ }).pipe(Effect.orDie);
79
91
  }
80
92
 
81
93
  /**
82
94
  * Creates a new cancelable request effect.
83
95
  */
84
- createRequest(
85
- params: AiConversationRunParams,
86
- ): Effect.Effect<DataType.Message[], AiSessionRunError, AiSessionRunRequirements> {
96
+ public createRequest(
97
+ params: AiConversationRunProps,
98
+ ): Effect.Effect<Message.Message[], AiSessionRunError, AiSessionRunRequirements> {
87
99
  return Effect.gen(this, function* () {
88
- const session = new AiSession();
89
100
  const history = yield* Effect.promise(() => this.getHistory());
90
101
 
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
- );
101
-
102
102
  // Create toolkit.
103
- const toolkit = yield* createToolkit({ blueprints });
104
- this._toolkit = toolkit;
103
+ const blueprints = this.context.getBlueprints();
104
+ const toolkit = yield* createToolkit({
105
+ toolkit: this._toolkit,
106
+ blueprints,
107
+ });
108
+
109
+ // Context objects.
110
+ const objects = this.context.getObjects();
105
111
 
106
- const start = Date.now();
107
112
  log('run', {
108
113
  history: history.length,
109
114
  blueprints: blueprints.length,
115
+ tools: Object.keys(toolkit.tools).length,
110
116
  objects: objects.length,
111
- tools: this._toolkit?.tools.length ?? 0,
112
117
  });
113
118
 
114
119
  // Process request.
115
- const messages = yield* session.run({ history, blueprints, objects, toolkit, ...params }).pipe(
116
- Effect.provideService(AiContextService, {
117
- binder: this.context,
118
- }),
120
+ const session = new AiSession();
121
+ const messages = yield* session.run({ history, blueprints, toolkit, objects, ...params }).pipe(
122
+ Effect.provide(
123
+ Layer.mergeAll(
124
+ Layer.succeed(AiContextService, {
125
+ binder: this.context,
126
+ }),
127
+ Layer.succeed(AiConversationService, this),
128
+ ),
129
+ ),
119
130
  );
120
131
 
121
- log('result', { messages: messages.length, duration: Date.now() - start });
132
+ log('result', {
133
+ messages: messages.length,
134
+ duration: session.duration,
135
+ toolCalls: session.toolCalls,
136
+ });
122
137
 
123
138
  // Append to queue.
124
139
  yield* Effect.promise(() => this._queue.append(messages));
125
140
  return messages;
126
- }).pipe(Effect.withSpan('AiConversation.request'));
141
+ });
127
142
  }
128
143
  }
144
+
145
+ /**
146
+ * Gives access to the ai conversation.
147
+ */
148
+ export class AiConversationService extends Context.Tag('@dxos/assistant/AiConversationService')<
149
+ AiConversationService,
150
+ AiConversation
151
+ >() {
152
+ /**
153
+ * Create a new conversation layer from options.
154
+ */
155
+ static layer = (options: AiConversationOptions): Layer.Layer<AiConversationService | AiContextService> =>
156
+ aiContextFromConversation.pipe(
157
+ Layer.provideMerge(
158
+ Layer.scoped(
159
+ AiConversationService,
160
+ Effect.gen(function* () {
161
+ const conversation = yield* acquireReleaseResource(() => new AiConversation(options));
162
+ return conversation;
163
+ }),
164
+ ),
165
+ ),
166
+ );
167
+
168
+ /**
169
+ * Create a new conversation with a new queue.
170
+ */
171
+ static layerNewQueue = (
172
+ options?: Omit<AiConversationOptions, 'queue'>,
173
+ ): Layer.Layer<AiConversationService | AiContextService, never, QueueService> =>
174
+ Layer.unwrapScoped(
175
+ Effect.gen(function* () {
176
+ return AiConversationService.layer({
177
+ ...options,
178
+ queue: yield* QueueService.createQueue<Message.Message | ContextBinding>(),
179
+ });
180
+ }),
181
+ );
182
+
183
+ /**
184
+ * Run a prompt in the current conversation.
185
+ */
186
+ static run = (
187
+ params: AiConversationRunProps,
188
+ ): Effect.Effect<Message.Message[], AiSessionRunError, AiSessionRunRequirements | AiConversationService> =>
189
+ Effect.gen(function* () {
190
+ const conversation = yield* AiConversationService;
191
+ return yield* conversation.createRequest(params);
192
+ });
193
+ }
194
+
195
+ const aiContextFromConversation = Layer.effect(
196
+ AiContextService,
197
+ Effect.gen(function* () {
198
+ const conversation = yield* AiConversationService;
199
+ return {
200
+ binder: conversation.context,
201
+ };
202
+ }),
203
+ );
package/src/diff.test.ts CHANGED
@@ -2,20 +2,27 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { describe, expect, it } from 'vitest';
5
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
6
6
 
7
7
  import { createDocAccessor } from '@dxos/echo-db';
8
8
  import { EchoTestBuilder } from '@dxos/echo-db/testing';
9
- import { DataType } from '@dxos/schema';
9
+ import { Text } from '@dxos/schema';
10
10
  import { trim } from '@dxos/util';
11
11
 
12
12
  import { applyDiffs } from './diff';
13
13
 
14
14
  describe('diff', () => {
15
+ let builder: EchoTestBuilder;
16
+ beforeEach(async () => {
17
+ builder = await new EchoTestBuilder().open();
18
+ });
19
+
20
+ afterEach(async () => {
21
+ await builder.close();
22
+ });
23
+
15
24
  it('should apply diffs', async () => {
16
- const builder = new EchoTestBuilder();
17
- const { db, graph } = await builder.createDatabase();
18
- graph.schemaRegistry.addSchema([DataType.Text]);
25
+ const { db } = await builder.createDatabase({ types: [Text.Text] });
19
26
 
20
27
  const document = trim`
21
28
  # Hello World
@@ -24,7 +31,7 @@ describe('diff', () => {
24
31
  But not this one.
25
32
  `;
26
33
 
27
- const text = db.add(DataType.makeText(document));
34
+ const text = db.add(Text.make(document));
28
35
  const accessor = createDocAccessor(text, ['content']);
29
36
  const result = applyDiffs(accessor, [
30
37
  `- There'z a typo in this sentence.`,
@@ -40,4 +47,28 @@ describe('diff', () => {
40
47
  But not this one.
41
48
  `);
42
49
  });
50
+
51
+ it('should apply diffs that append content at the end', async () => {
52
+ const { db } = await builder.createDatabase({ types: [Text.Text] });
53
+
54
+ const document = '# Shopping list';
55
+
56
+ const text = db.add(Text.make(document));
57
+ const accessor = createDocAccessor(text, ['content']);
58
+ const result = applyDiffs(accessor, ['- # Shopping list', '+ # Shopping list\n- Milk']);
59
+
60
+ expect(result).toBe('# Shopping list\n- Milk');
61
+ });
62
+
63
+ it('should append text to an empty document', async () => {
64
+ const builder = new EchoTestBuilder();
65
+ const { db, graph } = await builder.createDatabase();
66
+ await graph.schemaRegistry.register([Text.Text]);
67
+
68
+ const text = db.add(Text.make(''));
69
+ const accessor = createDocAccessor(text, ['content']);
70
+ const result = applyDiffs(accessor, ['+ # Shopping list']);
71
+
72
+ expect(result).toBe('# Shopping list');
73
+ });
43
74
  });
package/src/diff.ts CHANGED
@@ -11,6 +11,11 @@ import { isNonNullable } from '@dxos/util';
11
11
  // Relevant info:
12
12
  // https://github.com/Minahil-official/GPT-4.1-Promting-Guide?tab=readme-ov-file#-apply-patch-tool-format-v4a-diff
13
13
 
14
+ // TODO(burdon): Anthropic only.
15
+ // https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/text-editor-tool#example-str-replace-command
16
+ // AI_TOOL_NOT_FOUND: str_replace_based_edit_tool
17
+ // 'str_replace_based_edit_tool',
18
+
14
19
  // TOOD(burdon): Support append to end (no "-").
15
20
 
16
21
  export type Diff = {
@@ -42,9 +47,10 @@ export const reduceDiffs = (diffs: readonly string[]): Diff[] => {
42
47
  }
43
48
  return acc;
44
49
  }
50
+ default: {
51
+ throw new Error(`Invalid diff format: each line must start with "- " or "+ ", got: ${JSON.stringify(diff)}`);
52
+ }
45
53
  }
46
-
47
- return acc;
48
54
  }, []);
49
55
  };
50
56
 
@@ -60,7 +66,11 @@ export const computeDiffsWithCursors = <T>(accessor: DocAccessor<T>, diffs: read
60
66
  .filter(isNonNullable);
61
67
  };
62
68
 
63
- export const applyDiffs = <T>(accessor: DocAccessor<T>, diffs: readonly string[]): string => {
69
+ export const applyDiffs = <T>(
70
+ accessor: DocAccessor<T>,
71
+ diffs: readonly string[],
72
+ { errorOnNotFound = false }: { errorOnNotFound?: boolean } = {},
73
+ ): string => {
64
74
  for (const diff of reduceDiffs(diffs)) {
65
75
  accessor.handle.change((doc: Doc<T>) => {
66
76
  const text = DocAccessor.getValue<string>(accessor);
@@ -70,7 +80,11 @@ export const applyDiffs = <T>(accessor: DocAccessor<T>, diffs: readonly string[]
70
80
  // NOTE: This only replaces the first match.
71
81
  A.splice(doc, accessor.path as A.Prop[], idx, diff.match.length, diff.replace);
72
82
  } else {
73
- log.warn('diff not found', diff);
83
+ if (errorOnNotFound) {
84
+ throw new Error(`Diff not found: ${diff.match}`);
85
+ } else {
86
+ log.warn('diff not found', diff);
87
+ }
74
88
  }
75
89
  });
76
90
  }
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') {}