@dxos/assistant 0.8.4-main.dedc0f3 → 0.8.4-main.dfabb4ec29

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 (152) hide show
  1. package/README.md +1 -0
  2. package/dist/lib/neutral/extraction/index.mjs +202 -0
  3. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  4. package/dist/lib/neutral/index.mjs +1736 -0
  5. package/dist/lib/neutral/index.mjs.map +7 -0
  6. package/dist/lib/neutral/meta.json +1 -0
  7. package/dist/types/src/conversation/context.d.ts +124 -64
  8. package/dist/types/src/conversation/context.d.ts.map +1 -1
  9. package/dist/types/src/conversation/context.test.d.ts +2 -0
  10. package/dist/types/src/conversation/context.test.d.ts.map +1 -0
  11. package/dist/types/src/conversation/index.d.ts +1 -1
  12. package/dist/types/src/conversation/index.d.ts.map +1 -1
  13. package/dist/types/src/conversation/session.d.ts +73 -0
  14. package/dist/types/src/conversation/session.d.ts.map +1 -0
  15. package/dist/types/src/diff.d.ts +3 -1
  16. package/dist/types/src/diff.d.ts.map +1 -1
  17. package/dist/types/src/errors.d.ts +40 -48
  18. package/dist/types/src/errors.d.ts.map +1 -1
  19. package/dist/types/src/execution-graph.d.ts +85 -0
  20. package/dist/types/src/execution-graph.d.ts.map +1 -0
  21. package/dist/types/src/execution-graph.test.d.ts +2 -0
  22. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  23. package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
  24. package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
  25. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  26. package/dist/types/src/extraction/extraction.d.ts +1066 -303
  27. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  28. package/dist/types/src/extraction/index.d.ts +0 -1
  29. package/dist/types/src/extraction/index.d.ts.map +1 -1
  30. package/dist/types/src/extraction/quotes.d.ts +3 -3
  31. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  32. package/dist/types/src/functions/services.d.ts +15 -5
  33. package/dist/types/src/functions/services.d.ts.map +1 -1
  34. package/dist/types/src/index.d.ts +3 -1
  35. package/dist/types/src/index.d.ts.map +1 -1
  36. package/dist/types/src/session/artifact-diff.d.ts +2 -2
  37. package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
  38. package/dist/types/src/session/error-handling.d.ts +2 -2
  39. package/dist/types/src/session/error-handling.d.ts.map +1 -1
  40. package/dist/types/src/session/format.d.ts +8 -175
  41. package/dist/types/src/session/format.d.ts.map +1 -1
  42. package/dist/types/src/session/index.d.ts +2 -1
  43. package/dist/types/src/session/index.d.ts.map +1 -1
  44. package/dist/types/src/session/observer.d.ts +7 -6
  45. package/dist/types/src/session/observer.d.ts.map +1 -1
  46. package/dist/types/src/session/request.d.ts +104 -0
  47. package/dist/types/src/session/request.d.ts.map +1 -0
  48. package/dist/types/src/session/toolkit.d.ts +11 -9
  49. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  50. package/dist/types/src/session/version-pin.d.ts +4 -4
  51. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  52. package/dist/types/src/templates/system.d.ts +1 -2
  53. package/dist/types/src/templates/system.d.ts.map +1 -1
  54. package/dist/types/src/tracing.d.ts +233 -0
  55. package/dist/types/src/tracing.d.ts.map +1 -0
  56. package/dist/types/src/types/artifact.d.ts +28 -0
  57. package/dist/types/src/types/artifact.d.ts.map +1 -0
  58. package/dist/types/src/types/index.d.ts +2 -0
  59. package/dist/types/src/types/index.d.ts.map +1 -0
  60. package/dist/types/tsconfig.tsbuildinfo +1 -1
  61. package/package.json +35 -46
  62. package/src/conversation/context.test.ts +52 -0
  63. package/src/conversation/context.ts +324 -75
  64. package/src/conversation/index.ts +1 -1
  65. package/src/conversation/session.ts +323 -0
  66. package/src/diff.test.ts +37 -6
  67. package/src/diff.ts +18 -4
  68. package/src/errors.ts +4 -4
  69. package/src/execution-graph.test.ts +740 -0
  70. package/src/execution-graph.ts +519 -0
  71. package/src/extraction/extraction-ner-function/index.ts +0 -1
  72. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  73. package/src/extraction/extraction.ts +44 -15
  74. package/src/extraction/index.ts +0 -1
  75. package/src/extraction/quotes.test.ts +2 -2
  76. package/src/extraction/quotes.ts +6 -7
  77. package/src/functions/services.ts +156 -61
  78. package/src/index.ts +3 -1
  79. package/src/session/artifact-diff.ts +2 -2
  80. package/src/session/error-handling.ts +11 -6
  81. package/src/session/format.ts +35 -27
  82. package/src/session/index.ts +2 -1
  83. package/src/session/observer.ts +8 -4
  84. package/src/session/request.ts +347 -0
  85. package/src/session/toolkit.ts +32 -27
  86. package/src/session/version-pin.ts +7 -7
  87. package/src/templates/{format.tpl → instructions/format.tpl} +1 -4
  88. package/src/templates/instructions/system.tpl +96 -0
  89. package/src/templates/system.ts +9 -8
  90. package/src/tracing.ts +57 -0
  91. package/src/{types.ts → types/artifact.ts} +44 -7
  92. package/src/types/index.ts +5 -0
  93. package/dist/lib/browser/chunk-5GJYG2ML.mjs +0 -396
  94. package/dist/lib/browser/chunk-5GJYG2ML.mjs.map +0 -7
  95. package/dist/lib/browser/chunk-UB26N5UF.mjs +0 -89
  96. package/dist/lib/browser/chunk-UB26N5UF.mjs.map +0 -7
  97. package/dist/lib/browser/extraction/index.mjs +0 -268
  98. package/dist/lib/browser/extraction/index.mjs.map +0 -7
  99. package/dist/lib/browser/index.mjs +0 -469
  100. package/dist/lib/browser/index.mjs.map +0 -7
  101. package/dist/lib/browser/meta.json +0 -1
  102. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs +0 -13
  103. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs.map +0 -7
  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-FLFCEB4P.mjs +0 -398
  107. package/dist/lib/node-esm/chunk-FLFCEB4P.mjs.map +0 -7
  108. package/dist/lib/node-esm/extraction/index.mjs +0 -269
  109. package/dist/lib/node-esm/extraction/index.mjs.map +0 -7
  110. package/dist/lib/node-esm/index.mjs +0 -470
  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/conversation/conversation.d.ts +0 -42
  116. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  117. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
  118. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
  119. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
  120. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
  121. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
  122. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
  123. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -337
  124. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
  125. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
  126. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
  127. package/dist/types/src/session/format.test.d.ts +0 -2
  128. package/dist/types/src/session/format.test.d.ts.map +0 -1
  129. package/dist/types/src/session/session.d.ts +0 -47
  130. package/dist/types/src/session/session.d.ts.map +0 -1
  131. package/dist/types/src/session/session.test.d.ts +0 -2
  132. package/dist/types/src/session/session.test.d.ts.map +0 -1
  133. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  134. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  135. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  136. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  137. package/dist/types/src/types.d.ts +0 -16
  138. package/dist/types/src/types.d.ts.map +0 -1
  139. package/src/conversation/conversation.ts +0 -123
  140. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -84
  141. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -70
  142. package/src/extraction/extraction-llm-function/index.ts +0 -5
  143. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -115
  144. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -62
  145. package/src/session/__snapshots__/session.test.ts.snap +0 -32
  146. package/src/session/format.test.ts +0 -60
  147. package/src/session/session.test.ts +0 -308
  148. package/src/session/session.ts +0 -201
  149. package/src/session/version-pin.test.ts +0 -7
  150. package/src/summarization/summarization.test.ts +0 -197
  151. package/src/templates/system.tpl +0 -50
  152. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -0,0 +1,323 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import type { Registry } from '@effect-atom/atom-react';
6
+ import * as Array from 'effect/Array';
7
+ import * as Context from 'effect/Context';
8
+ import * as Effect from 'effect/Effect';
9
+ import * as Either from 'effect/Either';
10
+ import { pipe } from 'effect/Function';
11
+ import * as Layer from 'effect/Layer';
12
+ import * as Record from 'effect/Record';
13
+ import * as Runtime from 'effect/Runtime';
14
+
15
+ import { type OpaqueToolkit, type ToolExecutionService, type ToolResolverService } from '@dxos/ai';
16
+ import { type Blueprint, type OperationRegistry, McpServer, Operation, Trace } from '@dxos/compute';
17
+ import { Resource } from '@dxos/context';
18
+ import { Database, Feed, Filter, Obj } from '@dxos/echo';
19
+ import { acquireReleaseResource } from '@dxos/effect';
20
+ import { invariant } from '@dxos/invariant';
21
+ import { log } from '@dxos/log';
22
+ import { McpToolkit } from '@dxos/mcp-client';
23
+ import { Message, type ContentBlock } from '@dxos/types';
24
+
25
+ import { ToolExecutionServices } from '../functions';
26
+ import {
27
+ AiRequest,
28
+ type AiRequestRunError,
29
+ type AiRequestRunRequirements,
30
+ type GenerationObserver,
31
+ createToolkit,
32
+ formatSystemPrompt,
33
+ } from '../session';
34
+ import { McpServerError } from '../tracing';
35
+ import { AiContextBinder, AiContextService } from './context';
36
+
37
+ export interface AiSessionRunProps<R = never> {
38
+ prompt: string | ContentBlock.Any[];
39
+ system?: string;
40
+ observer?: GenerationObserver;
41
+ toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
42
+
43
+ /**
44
+ * Space-level MCP servers to connect alongside blueprint-defined ones.
45
+ */
46
+ mcpServers?: readonly McpServer.McpServer[];
47
+ }
48
+
49
+ export type AiSessionOptions = {
50
+ feed: Feed.Feed;
51
+ runtime: Runtime.Runtime<Feed.FeedService>;
52
+ registry?: Registry.Registry;
53
+ };
54
+
55
+ // TODO(dmaretskyi): Take from model characteristics. opus has 200k max tokens.
56
+ /**
57
+ * Summarization threshold in tokens.
58
+ */
59
+ const SUMMARY_THRESHOLD = 80_000;
60
+
61
+ /**
62
+ * Durable conversation state (initiated by users and agents) backed by a Feed.
63
+ * Executes tools based on AI responses and supports cancellation of in-progress requests.
64
+ */
65
+ export class AiSession extends Resource {
66
+ /**
67
+ * Blueprints and objects bound to the session.
68
+ */
69
+ private readonly _binder: AiContextBinder;
70
+ private readonly _feed: Feed.Feed;
71
+ private readonly _runtime: Runtime.Runtime<Feed.FeedService>;
72
+
73
+ public constructor(options: AiSessionOptions) {
74
+ super();
75
+ this._feed = options.feed;
76
+ this._runtime = options.runtime;
77
+ invariant(this._feed);
78
+ invariant(this._runtime);
79
+ this._binder = new AiContextBinder({ feed: this._feed, runtime: this._runtime, registry: options.registry });
80
+ }
81
+
82
+ protected override async _open(): Promise<void> {
83
+ await this._binder.open(this._ctx);
84
+ }
85
+
86
+ public get feed() {
87
+ return this._feed;
88
+ }
89
+
90
+ public get context() {
91
+ return this._binder;
92
+ }
93
+
94
+ public async getHistory(): Promise<Message.Message[]> {
95
+ const queryResult = await Runtime.runPromise(this._runtime)(Feed.query(this._feed, Filter.type(Message.Message)));
96
+ const items = await queryResult.run();
97
+ return items.filter(Obj.instanceOf(Message.Message));
98
+ }
99
+
100
+ getTools(): Effect.Effect<
101
+ Record<string, import('@effect/ai/Tool').Any>,
102
+ never,
103
+ ToolExecutionService | ToolResolverService
104
+ > {
105
+ return Effect.gen(this, function* () {
106
+ const toolkit = yield* createToolkit({ blueprints: this.context.getBlueprints() });
107
+ return toolkit.toolkit.tools;
108
+ }).pipe(Effect.orDie);
109
+ }
110
+
111
+ /**
112
+ * Not provided by default, since users might want to override them.
113
+ */
114
+ makeToolExecutionServices(): Layer.Layer<
115
+ ToolExecutionService | ToolResolverService,
116
+ never,
117
+ OpaqueToolkit.OpaqueToolkitProvider | Operation.Service | OperationRegistry.Service
118
+ > {
119
+ return ToolExecutionServices.pipe(
120
+ Layer.provide(Operation.withInvocationOptions({ conversation: Obj.getDXN(this._feed).toString() })),
121
+ );
122
+ }
123
+ /**
124
+ * Creates a new cancelable request effect.
125
+ */
126
+ public createRequest<R = never>(
127
+ params: AiSessionRunProps<R>,
128
+ ): Effect.Effect<Message.Message[], AiRequestRunError, AiRequestRunRequirements | R> {
129
+ return Effect.gen(this, function* () {
130
+ const history = yield* Effect.promise(() => this.getHistory());
131
+ const blueprints = this.context.getBlueprints();
132
+ const objects = this.context.getObjects();
133
+
134
+ log('run', {
135
+ history: history.length,
136
+ blueprints: blueprints.length,
137
+ objects: objects.length,
138
+ });
139
+
140
+ const request = new AiRequest({
141
+ summarizationThreshold: SUMMARY_THRESHOLD,
142
+ observer: params.observer,
143
+ onOutput: (message) =>
144
+ Effect.promise(() => Runtime.runPromise(this._runtime)(Feed.append(this._feed, [message]))),
145
+ });
146
+
147
+ yield* request.begin({
148
+ history,
149
+ blueprints,
150
+ objects,
151
+ prompt: params.prompt,
152
+ system: params.system,
153
+ });
154
+
155
+ // Turn loop: recompute toolkit and system prompt between turns to pick up dynamically enabled blueprints.
156
+ do {
157
+ yield* Effect.promise(() => this.context.sync());
158
+ const currentBlueprints = this.context.getBlueprints();
159
+ const mcps = yield* connectMcpServers(currentBlueprints, params.mcpServers);
160
+ const toolkit = yield* createToolkit({
161
+ toolkit: params.toolkit,
162
+ blueprints: currentBlueprints,
163
+ opaqueToolkits: mcps,
164
+ });
165
+
166
+ log('toolkit', { tools: Record.keys(toolkit.toolkit.tools) });
167
+ const system = yield* formatSystemPrompt({
168
+ system: params.system,
169
+ blueprints: currentBlueprints,
170
+ objects: this.context.getObjects(),
171
+ }).pipe(Effect.orDie);
172
+
173
+ const { done } = yield* request.runAgentTurn({ system, toolkit });
174
+ if (done) {
175
+ break;
176
+ }
177
+
178
+ yield* request.runTools({ toolkit });
179
+ } while (true);
180
+
181
+ log('result', {
182
+ messages: request.pending.length,
183
+ duration: request.duration,
184
+ toolCalls: request.toolCalls,
185
+ });
186
+
187
+ return [...request.pending];
188
+ }).pipe(
189
+ Effect.provide(
190
+ Layer.mergeAll(
191
+ Layer.succeed(AiContextService, {
192
+ binder: this.context,
193
+ }),
194
+ Layer.succeed(AiSessionService, this),
195
+ Operation.withInvocationOptions({ conversation: Obj.getDXN(this._feed).toString() }),
196
+ ),
197
+ ),
198
+ Effect.withSpan('AiSession.createRequest'),
199
+ );
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Gives access to the ai session.
205
+ */
206
+ export class AiSessionService extends Context.Tag('@dxos/assistant/AiSessionService')<AiSessionService, AiSession>() {
207
+ /**
208
+ * Create a new session layer from options.
209
+ */
210
+ static layer = (options: AiSessionOptions): Layer.Layer<AiSessionService | AiContextService> =>
211
+ aiContextFromSession.pipe(
212
+ Layer.provideMerge(
213
+ Layer.scoped(
214
+ AiSessionService,
215
+ Effect.gen(function* () {
216
+ const session = yield* acquireReleaseResource(() => new AiSession(options));
217
+ return session;
218
+ }),
219
+ ),
220
+ ),
221
+ );
222
+
223
+ /**
224
+ * Create a new session with a new feed.
225
+ */
226
+ static layerNewFeed = (
227
+ options?: Omit<AiSessionOptions, 'feed' | 'runtime'>,
228
+ ): Layer.Layer<AiSessionService | AiContextService, never, Database.Service | Feed.FeedService> =>
229
+ Layer.unwrapScoped(
230
+ Effect.gen(function* () {
231
+ const feed = yield* Database.add(Feed.make());
232
+ const runtime = yield* Effect.runtime<Feed.FeedService>();
233
+ return AiSessionService.layer({ ...options, feed, runtime });
234
+ }),
235
+ );
236
+
237
+ /**
238
+ * Run a prompt in the current session.
239
+ */
240
+ static run = <R = never>(
241
+ params: AiSessionRunProps<R>,
242
+ ): Effect.Effect<Message.Message[], AiRequestRunError, AiRequestRunRequirements | AiSessionService | R> =>
243
+ Effect.gen(function* () {
244
+ const session = yield* AiSessionService;
245
+ return yield* session.createRequest(params);
246
+ });
247
+ }
248
+
249
+ const aiContextFromSession = Layer.effect(
250
+ AiContextService,
251
+ Effect.gen(function* () {
252
+ const session = yield* AiSessionService;
253
+ return {
254
+ binder: session.context,
255
+ };
256
+ }),
257
+ );
258
+
259
+ const connectMcpServers = (
260
+ blueprints: readonly Blueprint.Blueprint[],
261
+ spaceMcpServers: readonly McpServer.McpServer[] = [],
262
+ ): Effect.Effect<OpaqueToolkit.OpaqueToolkit[], never, Trace.TraceService> => {
263
+ const blueprintServers: McpToolkit.McpToolkitOptions[] = pipe(
264
+ blueprints,
265
+ Array.flatMap((_) => _.mcpServers ?? []),
266
+ Array.map(({ url, protocol, apiKey }) => ({ url, protocol, apiKey })),
267
+ );
268
+ const spaceServers: McpToolkit.McpToolkitOptions[] = spaceMcpServers.map(({ url, protocol, apiKey }) => ({
269
+ url,
270
+ protocol,
271
+ apiKey,
272
+ }));
273
+ const allServers = [...blueprintServers, ...spaceServers];
274
+
275
+ return pipe(
276
+ allServers,
277
+ Effect.forEach((options) =>
278
+ McpToolkit.make(options).pipe(
279
+ // NOTE: Type-inference fails here without explicit void return.
280
+ Effect.tap((toolkit): void =>
281
+ log.info('Connected to MCP server', { url: options.url, tools: Object.keys(toolkit.toolkit.tools).length }),
282
+ ),
283
+ // Surface typed connection failures via ephemeral trace + warn log, then drop the server.
284
+ Effect.tapError((error) =>
285
+ Effect.gen(function* () {
286
+ log.warn('Failed to connect to MCP server', {
287
+ url: error.url,
288
+ protocol: error.protocol,
289
+ message: error.message,
290
+ });
291
+ yield* Trace.write(McpServerError, {
292
+ url: error.url,
293
+ protocol: error.protocol,
294
+ message: error.message,
295
+ });
296
+ }),
297
+ ),
298
+ // Catch unexpected defects too (e.g. malformed tool schemas) so a single broken
299
+ // server can never abort the whole turn — surface them through the same channel.
300
+ Effect.catchAllDefect((defect) =>
301
+ Effect.gen(function* () {
302
+ const message = defect instanceof Error ? defect.message : String(defect);
303
+ log.warn('Unexpected MCP defect', { url: options.url, message });
304
+ yield* Trace.write(McpServerError, {
305
+ url: options.url,
306
+ protocol: options.protocol,
307
+ message: `Unexpected MCP failure: ${message}`,
308
+ });
309
+ return yield* Effect.fail(
310
+ new McpToolkit.McpConnectionError({
311
+ url: options.url,
312
+ protocol: options.protocol,
313
+ message,
314
+ }),
315
+ );
316
+ }),
317
+ ),
318
+ Effect.either,
319
+ ),
320
+ ),
321
+ Effect.map(Array.filterMap((_) => Either.getRight(_))),
322
+ );
323
+ };
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({ content: 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({ content: 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({ content: '' }));
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
@@ -5,11 +5,11 @@
5
5
  import { BaseError } from '@dxos/errors';
6
6
 
7
7
  /**
8
- * Generic error for AI agent execution.
8
+ * Generic error from AI model.
9
9
  */
10
- export class AiAssistantError extends BaseError.extend('AI_ASSISTANT_ERROR') {}
10
+ export class AiModelError extends BaseError.extend('AiModelError', 'AI model error') {}
11
11
 
12
12
  /**
13
- * Parsed error from the anthropic API.
13
+ * Generic error for AI agent execution.
14
14
  */
15
- export class AnthropicError extends BaseError.extend('ANTHROPIC_ERROR') {}
15
+ export class AiAssistantError extends BaseError.extend('AiAssistantError', 'AI assistant error') {}