@dxos/assistant 0.8.4-main.f9ba587 → 0.8.4-main.fcfe5033a5

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 (233) hide show
  1. package/README.md +1 -0
  2. package/dist/lib/neutral/chunk-2TBLG3XY.mjs +1793 -0
  3. package/dist/lib/neutral/chunk-2TBLG3XY.mjs.map +7 -0
  4. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
  5. package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +7 -0
  6. package/dist/lib/neutral/extraction/index.mjs +219 -0
  7. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  8. package/dist/lib/neutral/index.mjs +537 -0
  9. package/dist/lib/neutral/index.mjs.map +7 -0
  10. package/dist/lib/neutral/meta.json +1 -0
  11. package/dist/lib/neutral/testing/index.mjs +111 -0
  12. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  13. package/dist/types/src/conversation/context.d.ts +155 -0
  14. package/dist/types/src/conversation/context.d.ts.map +1 -0
  15. package/dist/types/src/conversation/context.test.d.ts +2 -0
  16. package/dist/types/src/conversation/context.test.d.ts.map +1 -0
  17. package/dist/types/src/conversation/index.d.ts +2 -1
  18. package/dist/types/src/conversation/index.d.ts.map +1 -1
  19. package/dist/types/src/conversation/session.d.ts +78 -0
  20. package/dist/types/src/conversation/session.d.ts.map +1 -0
  21. package/dist/types/src/conversation/session.test.d.ts.map +1 -0
  22. package/dist/types/src/diff.d.ts +17 -0
  23. package/dist/types/src/diff.d.ts.map +1 -0
  24. package/dist/types/src/diff.test.d.ts +2 -0
  25. package/dist/types/src/diff.test.d.ts.map +1 -0
  26. package/dist/types/src/errors.d.ts +67 -0
  27. package/dist/types/src/errors.d.ts.map +1 -0
  28. package/dist/types/src/execution-graph.d.ts +85 -0
  29. package/dist/types/src/execution-graph.d.ts.map +1 -0
  30. package/dist/types/src/execution-graph.test.d.ts +2 -0
  31. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  32. package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
  33. package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
  34. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts +1 -1
  35. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  36. package/dist/types/src/extraction/extraction.d.ts +1066 -215
  37. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  38. package/dist/types/src/extraction/index.d.ts +0 -1
  39. package/dist/types/src/extraction/index.d.ts.map +1 -1
  40. package/dist/types/src/extraction/quotes.d.ts +3 -3
  41. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  42. package/dist/types/src/functions/index.d.ts +2 -0
  43. package/dist/types/src/functions/index.d.ts.map +1 -0
  44. package/dist/types/src/functions/services.d.ts +17 -0
  45. package/dist/types/src/functions/services.d.ts.map +1 -0
  46. package/dist/types/src/functions.test.d.ts +2 -0
  47. package/dist/types/src/functions.test.d.ts.map +1 -0
  48. package/dist/types/src/index.d.ts +7 -5
  49. package/dist/types/src/index.d.ts.map +1 -1
  50. package/dist/types/src/service/AgentService.d.ts +75 -0
  51. package/dist/types/src/service/AgentService.d.ts.map +1 -0
  52. package/dist/types/src/service/AgentService.test.d.ts +2 -0
  53. package/dist/types/src/service/AgentService.test.d.ts.map +1 -0
  54. package/dist/types/src/service/agent-process.d.ts +21 -0
  55. package/dist/types/src/service/agent-process.d.ts.map +1 -0
  56. package/dist/types/src/service/index.d.ts +3 -0
  57. package/dist/types/src/service/index.d.ts.map +1 -0
  58. package/dist/types/src/session/artifact-diff.d.ts +27 -0
  59. package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
  60. package/dist/types/src/session/error-handling.d.ts +4 -0
  61. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  62. package/dist/types/src/session/format.d.ts +16 -0
  63. package/dist/types/src/session/format.d.ts.map +1 -0
  64. package/dist/types/src/session/format.test.d.ts +2 -0
  65. package/dist/types/src/session/format.test.d.ts.map +1 -0
  66. package/dist/types/src/session/index.d.ts +5 -1
  67. package/dist/types/src/session/index.d.ts.map +1 -1
  68. package/dist/types/src/session/observer.d.ts +23 -0
  69. package/dist/types/src/session/observer.d.ts.map +1 -0
  70. package/dist/types/src/session/request.d.ts +106 -0
  71. package/dist/types/src/session/request.d.ts.map +1 -0
  72. package/dist/types/src/session/request.test.d.ts +2 -0
  73. package/dist/types/src/session/request.test.d.ts.map +1 -0
  74. package/dist/types/src/session/session-ollama.test.d.ts +2 -0
  75. package/dist/types/src/session/session-ollama.test.d.ts.map +1 -0
  76. package/dist/types/src/session/toolkit.d.ts +16 -0
  77. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  78. package/dist/types/src/session/version-pin.d.ts +5 -5
  79. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  80. package/dist/types/src/templates/index.d.ts +2 -0
  81. package/dist/types/src/templates/index.d.ts.map +1 -0
  82. package/dist/types/src/templates/system.d.ts +17 -0
  83. package/dist/types/src/templates/system.d.ts.map +1 -0
  84. package/dist/types/src/testing/index.d.ts +1 -2
  85. package/dist/types/src/testing/index.d.ts.map +1 -1
  86. package/dist/types/src/testing/layer.d.ts +40 -0
  87. package/dist/types/src/testing/layer.d.ts.map +1 -0
  88. package/dist/types/src/tracing.d.ts +223 -0
  89. package/dist/types/src/tracing.d.ts.map +1 -0
  90. package/dist/types/src/types/artifact.d.ts +28 -0
  91. package/dist/types/src/types/artifact.d.ts.map +1 -0
  92. package/dist/types/src/types/index.d.ts +2 -0
  93. package/dist/types/src/types/index.d.ts.map +1 -0
  94. package/dist/types/tsconfig.tsbuildinfo +1 -1
  95. package/package.json +60 -29
  96. package/src/conversation/context.test.ts +52 -0
  97. package/src/conversation/context.ts +403 -0
  98. package/src/conversation/index.ts +2 -1
  99. package/src/conversation/session.test.ts +58 -0
  100. package/src/conversation/session.ts +300 -0
  101. package/src/diff.test.ts +74 -0
  102. package/src/diff.ts +93 -0
  103. package/src/errors.ts +15 -0
  104. package/src/execution-graph.test.ts +740 -0
  105. package/src/execution-graph.ts +509 -0
  106. package/src/extraction/extraction-ner-function/index.ts +0 -1
  107. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  108. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +3 -1
  109. package/src/extraction/extraction.ts +44 -15
  110. package/src/extraction/index.ts +0 -1
  111. package/src/extraction/quotes.test.ts +3 -3
  112. package/src/extraction/quotes.ts +6 -7
  113. package/src/functions/index.ts +5 -0
  114. package/src/functions/services.ts +214 -0
  115. package/src/functions.conversations.json +1 -0
  116. package/src/functions.test.ts +88 -0
  117. package/src/index.ts +7 -5
  118. package/src/service/AgentService.conversations.json +1 -0
  119. package/src/service/AgentService.test.ts +169 -0
  120. package/src/service/AgentService.ts +184 -0
  121. package/src/service/agent-process.ts +364 -0
  122. package/src/service/index.ts +6 -0
  123. package/src/session/artifact-diff.ts +41 -0
  124. package/src/session/error-handling.ts +41 -0
  125. package/src/session/format.test.ts +132 -0
  126. package/src/session/format.ts +149 -0
  127. package/src/session/index.ts +5 -1
  128. package/src/session/observer.ts +62 -0
  129. package/src/session/request.conversations.json +1 -0
  130. package/src/session/request.test.ts +195 -0
  131. package/src/session/request.ts +344 -0
  132. package/src/session/session-ollama.test.ts +81 -0
  133. package/src/session/toolkit.ts +47 -0
  134. package/src/session/version-pin.ts +12 -12
  135. package/src/templates/index.ts +5 -0
  136. package/src/templates/instructions/format.tpl +57 -0
  137. package/src/templates/instructions/system.tpl +85 -0
  138. package/src/templates/system.ts +42 -0
  139. package/src/testing/index.ts +2 -8
  140. package/src/testing/layer.ts +236 -0
  141. package/src/tracing.ts +43 -0
  142. package/src/types/artifact.ts +89 -0
  143. package/src/types/index.ts +5 -0
  144. package/src/typings.d.ts +5 -0
  145. package/dist/lib/browser/index.mjs +0 -2019
  146. package/dist/lib/browser/index.mjs.map +0 -7
  147. package/dist/lib/browser/meta.json +0 -1
  148. package/dist/lib/node-esm/index.mjs +0 -2021
  149. package/dist/lib/node-esm/index.mjs.map +0 -7
  150. package/dist/lib/node-esm/meta.json +0 -1
  151. package/dist/types/bin/chat.d.ts +0 -2
  152. package/dist/types/bin/chat.d.ts.map +0 -1
  153. package/dist/types/src/blueprint/blueprint.d.ts +0 -41
  154. package/dist/types/src/blueprint/blueprint.d.ts.map +0 -1
  155. package/dist/types/src/blueprint/index.d.ts +0 -3
  156. package/dist/types/src/blueprint/index.d.ts.map +0 -1
  157. package/dist/types/src/blueprint/registry.d.ts +0 -7
  158. package/dist/types/src/blueprint/registry.d.ts.map +0 -1
  159. package/dist/types/src/context/binder.d.ts +0 -34
  160. package/dist/types/src/context/binder.d.ts.map +0 -1
  161. package/dist/types/src/context/binding.d.ts +0 -38
  162. package/dist/types/src/context/binding.d.ts.map +0 -1
  163. package/dist/types/src/context/index.d.ts +0 -3
  164. package/dist/types/src/context/index.d.ts.map +0 -1
  165. package/dist/types/src/conversation/conversation.d.ts +0 -44
  166. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  167. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
  168. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
  169. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
  170. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
  171. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
  172. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
  173. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -208
  174. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
  175. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
  176. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
  177. package/dist/types/src/research/exa.d.ts +0 -7
  178. package/dist/types/src/research/exa.d.ts.map +0 -1
  179. package/dist/types/src/research/graph.d.ts +0 -41
  180. package/dist/types/src/research/graph.d.ts.map +0 -1
  181. package/dist/types/src/research/graph.test.d.ts +0 -2
  182. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  183. package/dist/types/src/research/index.d.ts +0 -4
  184. package/dist/types/src/research/index.d.ts.map +0 -1
  185. package/dist/types/src/research/research.d.ts +0 -10
  186. package/dist/types/src/research/research.d.ts.map +0 -1
  187. package/dist/types/src/research/research.test.d.ts +0 -2
  188. package/dist/types/src/research/research.test.d.ts.map +0 -1
  189. package/dist/types/src/session/session.d.ts +0 -283
  190. package/dist/types/src/session/session.d.ts.map +0 -1
  191. package/dist/types/src/session/session.test.d.ts.map +0 -1
  192. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  193. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  194. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  195. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  196. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  197. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  198. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  199. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  200. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  201. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  202. package/dist/types/src/types.d.ts +0 -3
  203. package/dist/types/src/types.d.ts.map +0 -1
  204. package/src/blueprint/blueprint.ts +0 -75
  205. package/src/blueprint/index.ts +0 -6
  206. package/src/blueprint/registry.ts +0 -15
  207. package/src/context/binder.ts +0 -101
  208. package/src/context/binding.ts +0 -31
  209. package/src/context/index.ts +0 -6
  210. package/src/conversation/conversation.ts +0 -103
  211. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -95
  212. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -66
  213. package/src/extraction/extraction-llm-function/index.ts +0 -5
  214. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -115
  215. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -54
  216. package/src/research/exa.ts +0 -100
  217. package/src/research/graph.test.ts +0 -15
  218. package/src/research/graph.ts +0 -337
  219. package/src/research/index.ts +0 -7
  220. package/src/research/instructions-research.tpl +0 -97
  221. package/src/research/research.test.ts +0 -190
  222. package/src/research/research.ts +0 -90
  223. package/src/session/session.test.ts +0 -275
  224. package/src/session/session.ts +0 -582
  225. package/src/session/version-pin.test.ts +0 -26
  226. package/src/summarization/summarization.test.ts +0 -221
  227. package/src/testing/exa-search-1748337321991.ts +0 -131
  228. package/src/testing/exa-search-1748337331526.ts +0 -144
  229. package/src/testing/exa-search-1748337344119.ts +0 -133
  230. package/src/typedefs.d.ts +0 -8
  231. package/src/types.ts +0 -8
  232. /package/dist/types/src/{session → conversation}/session.test.d.ts +0 -0
  233. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -0,0 +1,300 @@
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 } from '@dxos/blueprints';
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 { Operation, type OperationRegistry } from '@dxos/operation';
24
+ import { Message } from '@dxos/types';
25
+
26
+ import { ToolExecutionServices } from '../functions';
27
+ import {
28
+ AiRequest,
29
+ type AiRequestRunError,
30
+ type AiRequestRunRequirements,
31
+ type GenerationObserver,
32
+ createToolkit,
33
+ formatSystemPrompt,
34
+ } from '../session';
35
+ import { AiContextBinder, AiContextService } from './context';
36
+
37
+ export interface McpServerConfig {
38
+ url: string;
39
+ protocol: 'sse' | 'http';
40
+ apiKey?: string;
41
+ }
42
+
43
+ export interface AiSessionRunProps<R = never> {
44
+ prompt: string;
45
+ system?: string;
46
+ observer?: GenerationObserver;
47
+ toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
48
+
49
+ /**
50
+ * Space-level MCP servers to connect alongside blueprint-defined ones.
51
+ */
52
+ mcpServers?: readonly McpServerConfig[];
53
+ }
54
+
55
+ export type AiSessionOptions = {
56
+ feed: Feed.Feed;
57
+ runtime: Runtime.Runtime<Feed.FeedService>;
58
+ registry?: Registry.Registry;
59
+ };
60
+
61
+ // TODO(dmaretskyi): Take from model characteristics. opus has 200k max tokens.
62
+ /**
63
+ * Summarization threshold in tokens.
64
+ */
65
+ const SUMMARY_THRESHOLD = 80_000;
66
+
67
+ /**
68
+ * Durable conversation state (initiated by users and agents) backed by a Feed.
69
+ * Executes tools based on AI responses and supports cancellation of in-progress requests.
70
+ */
71
+ export class AiSession extends Resource {
72
+ /**
73
+ * Blueprints and objects bound to the conversation.
74
+ */
75
+ private readonly _binder: AiContextBinder;
76
+ private readonly _feed: Feed.Feed;
77
+ private readonly _runtime: Runtime.Runtime<Feed.FeedService>;
78
+
79
+ public constructor(options: AiSessionOptions) {
80
+ super();
81
+ this._feed = options.feed;
82
+ this._runtime = options.runtime;
83
+ invariant(this._feed);
84
+ invariant(this._runtime);
85
+ this._binder = new AiContextBinder({ feed: this._feed, runtime: this._runtime, registry: options.registry });
86
+ }
87
+
88
+ protected override async _open(): Promise<void> {
89
+ await this._binder.open(this._ctx);
90
+ }
91
+
92
+ public get feed() {
93
+ return this._feed;
94
+ }
95
+
96
+ public get context() {
97
+ return this._binder;
98
+ }
99
+
100
+ public async getHistory(): Promise<Message.Message[]> {
101
+ const queryResult = await Runtime.runPromise(this._runtime)(Feed.query(this._feed, Filter.type(Message.Message)));
102
+ const items = await queryResult.run();
103
+ return items.filter(Obj.instanceOf(Message.Message));
104
+ }
105
+
106
+ getTools(): Effect.Effect<
107
+ Record<string, import('@effect/ai/Tool').Any>,
108
+ never,
109
+ ToolExecutionService | ToolResolverService
110
+ > {
111
+ return Effect.gen(this, function* () {
112
+ const toolkit = yield* createToolkit({ blueprints: this.context.getBlueprints() });
113
+ return toolkit.toolkit.tools;
114
+ }).pipe(Effect.orDie);
115
+ }
116
+
117
+ /**
118
+ * Not provided by default, since users might want to override them.
119
+ */
120
+ makeToolExecutionServices(): Layer.Layer<
121
+ ToolExecutionService | ToolResolverService,
122
+ never,
123
+ OpaqueToolkit.OpaqueToolkitProvider | Operation.Service | OperationRegistry.Service
124
+ > {
125
+ return ToolExecutionServices.pipe(
126
+ Layer.provide(Operation.withInvocationOptions({ conversation: Obj.getDXN(this._feed).toString() })),
127
+ );
128
+ }
129
+ /**
130
+ * Creates a new cancelable request effect.
131
+ */
132
+ public createRequest<R = never>(
133
+ params: AiSessionRunProps<R>,
134
+ ): Effect.Effect<Message.Message[], AiRequestRunError, AiRequestRunRequirements | R> {
135
+ return Effect.gen(this, function* () {
136
+ const history = yield* Effect.promise(() => this.getHistory());
137
+ const blueprints = this.context.getBlueprints();
138
+ const objects = this.context.getObjects();
139
+
140
+ log('run', {
141
+ history: history.length,
142
+ blueprints: blueprints.length,
143
+ objects: objects.length,
144
+ });
145
+
146
+ const request = new AiRequest({
147
+ summarizationThreshold: SUMMARY_THRESHOLD,
148
+ observer: params.observer,
149
+ onOutput: (message) =>
150
+ Effect.promise(() => Runtime.runPromise(this._runtime)(Feed.append(this._feed, [message]))),
151
+ });
152
+
153
+ yield* request.begin({
154
+ history,
155
+ blueprints,
156
+ objects,
157
+ prompt: params.prompt,
158
+ system: params.system,
159
+ });
160
+
161
+ // Turn loop: recompute toolkit and system prompt between turns to pick up dynamically enabled blueprints.
162
+ do {
163
+ yield* Effect.promise(() => this.context.sync());
164
+ const currentBlueprints = this.context.getBlueprints();
165
+ const mcps = yield* connectMcpServers(currentBlueprints, params.mcpServers);
166
+ const toolkit = yield* createToolkit({
167
+ toolkit: params.toolkit,
168
+ blueprints: currentBlueprints,
169
+ opaqueToolkits: mcps,
170
+ });
171
+
172
+ log('toolkit', { tools: Record.keys(toolkit.toolkit.tools) });
173
+ const system = yield* formatSystemPrompt({
174
+ system: params.system,
175
+ blueprints: currentBlueprints,
176
+ objects: this.context.getObjects(),
177
+ }).pipe(Effect.orDie);
178
+
179
+ const { done } = yield* request.runAgentTurn({ system, toolkit });
180
+ if (done) {
181
+ break;
182
+ }
183
+
184
+ yield* request.runTools({ toolkit });
185
+ } while (true);
186
+
187
+ log('result', {
188
+ messages: request.pending.length,
189
+ duration: request.duration,
190
+ toolCalls: request.toolCalls,
191
+ });
192
+
193
+ return [...request.pending];
194
+ }).pipe(
195
+ Effect.provide(
196
+ Layer.mergeAll(
197
+ Layer.succeed(AiContextService, {
198
+ binder: this.context,
199
+ }),
200
+ Layer.succeed(AiSessionService, this),
201
+ Operation.withInvocationOptions({ conversation: Obj.getDXN(this._feed).toString() }),
202
+ ),
203
+ ),
204
+ Effect.withSpan('AiSession.createRequest'),
205
+ );
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Gives access to the ai session.
211
+ */
212
+ export class AiSessionService extends Context.Tag('@dxos/assistant/AiSessionService')<AiSessionService, AiSession>() {
213
+ /**
214
+ * Create a new session layer from options.
215
+ */
216
+ static layer = (options: AiSessionOptions): Layer.Layer<AiSessionService | AiContextService> =>
217
+ aiContextFromSession.pipe(
218
+ Layer.provideMerge(
219
+ Layer.scoped(
220
+ AiSessionService,
221
+ Effect.gen(function* () {
222
+ const session = yield* acquireReleaseResource(() => new AiSession(options));
223
+ return session;
224
+ }),
225
+ ),
226
+ ),
227
+ );
228
+
229
+ /**
230
+ * Create a new session with a new feed.
231
+ */
232
+ static layerNewFeed = (
233
+ options?: Omit<AiSessionOptions, 'feed' | 'runtime'>,
234
+ ): Layer.Layer<AiSessionService | AiContextService, never, Database.Service | Feed.FeedService> =>
235
+ Layer.unwrapScoped(
236
+ Effect.gen(function* () {
237
+ const feed = Feed.make();
238
+ yield* Database.add(feed);
239
+ const runtime = yield* Effect.runtime<Feed.FeedService>();
240
+ return AiSessionService.layer({
241
+ ...options,
242
+ feed,
243
+ runtime,
244
+ });
245
+ }),
246
+ );
247
+
248
+ /**
249
+ * Run a prompt in the current session.
250
+ */
251
+ static run = <R = never>(
252
+ params: AiSessionRunProps<R>,
253
+ ): Effect.Effect<Message.Message[], AiRequestRunError, AiRequestRunRequirements | AiSessionService | R> =>
254
+ Effect.gen(function* () {
255
+ const session = yield* AiSessionService;
256
+ return yield* session.createRequest(params);
257
+ });
258
+ }
259
+
260
+ const aiContextFromSession = Layer.effect(
261
+ AiContextService,
262
+ Effect.gen(function* () {
263
+ const session = yield* AiSessionService;
264
+ return {
265
+ binder: session.context,
266
+ };
267
+ }),
268
+ );
269
+
270
+ const connectMcpServers = (
271
+ blueprints: readonly Blueprint.Blueprint[],
272
+ spaceMcpServers: readonly McpServerConfig[] = [],
273
+ ): Effect.Effect<OpaqueToolkit.OpaqueToolkit[]> => {
274
+ const blueprintServers: McpToolkit.McpToolkitOptions[] = pipe(
275
+ blueprints,
276
+ Array.flatMap((_) => _.mcpServers ?? []),
277
+ Array.map(({ url, protocol }) => ({ url, kind: protocol })),
278
+ );
279
+ const spaceServers: McpToolkit.McpToolkitOptions[] = spaceMcpServers.map(({ url, protocol, apiKey }) => ({
280
+ url,
281
+ kind: protocol,
282
+ apiKey,
283
+ }));
284
+ const allServers = [...blueprintServers, ...spaceServers];
285
+
286
+ return pipe(
287
+ allServers,
288
+ Effect.forEach((options) =>
289
+ McpToolkit.make(options).pipe(
290
+ // NOTE: Type-inference fails here without explicit void return.
291
+ Effect.tap((toolkit): void =>
292
+ log.info('Connected to MCP server', { url: options.url, tools: Object.keys(toolkit.toolkit.tools).length }),
293
+ ),
294
+ Effect.tapDefect((error) => Effect.sync(() => log.warn('Failed to connect to MCP server', { error }))),
295
+ Effect.either,
296
+ ),
297
+ ),
298
+ Effect.map(Array.filterMap((_) => Either.getRight(_))),
299
+ );
300
+ };
@@ -0,0 +1,74 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
6
+
7
+ import { createDocAccessor } from '@dxos/echo-db';
8
+ import { EchoTestBuilder } from '@dxos/echo-db/testing';
9
+ import { Text } from '@dxos/schema';
10
+ import { trim } from '@dxos/util';
11
+
12
+ import { applyDiffs } from './diff';
13
+
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
+
24
+ it('should apply diffs', async () => {
25
+ const { db } = await builder.createDatabase({ types: [Text.Text] });
26
+
27
+ const document = trim`
28
+ # Hello World
29
+ There'z a typo in this sentence.
30
+ And another oon here.
31
+ But not this one.
32
+ `;
33
+
34
+ const text = db.add(Text.make({ content: document }));
35
+ const accessor = createDocAccessor(text, ['content']);
36
+ const result = applyDiffs(accessor, [
37
+ `- There'z a typo in this sentence.`,
38
+ `+ There is a typo in this sentence.`,
39
+ `- And another oon here.`,
40
+ `+ And another one here.`,
41
+ ]);
42
+
43
+ expect(result).toBe(trim`
44
+ # Hello World
45
+ There is a typo in this sentence.
46
+ And another one here.
47
+ But not this one.
48
+ `);
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
+ });
74
+ });
package/src/diff.ts ADDED
@@ -0,0 +1,93 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { next as A, type Doc } from '@automerge/automerge';
6
+
7
+ import { DocAccessor, toCursorRange } from '@dxos/echo-db';
8
+ import { log } from '@dxos/log';
9
+ import { isNonNullable } from '@dxos/util';
10
+
11
+ // Relevant info:
12
+ // https://github.com/Minahil-official/GPT-4.1-Promting-Guide?tab=readme-ov-file#-apply-patch-tool-format-v4a-diff
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
+
19
+ // TOOD(burdon): Support append to end (no "-").
20
+
21
+ export type Diff = {
22
+ match: string;
23
+ replace: string;
24
+ };
25
+
26
+ /**
27
+ * Convert a list of diffs into a list of operations.
28
+ */
29
+ export const reduceDiffs = (diffs: readonly string[]): Diff[] => {
30
+ return diffs.reduce<Diff[]>((acc, diff) => {
31
+ const current = acc[acc.length - 1];
32
+ const [op, ...rest] = diff.split(' ');
33
+ switch (op) {
34
+ case '-': {
35
+ if (current && !current.match) {
36
+ current.match += rest.join(' ');
37
+ } else {
38
+ acc.push({ match: rest.join(' '), replace: '' });
39
+ }
40
+ return acc;
41
+ }
42
+ case '+': {
43
+ if (current && !current.replace) {
44
+ current.replace += rest.join(' ');
45
+ } else {
46
+ acc.push({ match: '', replace: rest.join(' ') });
47
+ }
48
+ return acc;
49
+ }
50
+ default: {
51
+ throw new Error(`Invalid diff format: each line must start with "- " or "+ ", got: ${JSON.stringify(diff)}`);
52
+ }
53
+ }
54
+ }, []);
55
+ };
56
+
57
+ export const computeDiffsWithCursors = <T>(accessor: DocAccessor<T>, diffs: readonly string[]) => {
58
+ return reduceDiffs(diffs)
59
+ .map((diff) => {
60
+ const text = DocAccessor.getValue<string>(accessor);
61
+ const idx = text.indexOf(diff.match);
62
+ if (idx !== -1) {
63
+ return { cursor: toCursorRange(accessor, idx, idx + diff.match.length), text: diff.replace };
64
+ }
65
+ })
66
+ .filter(isNonNullable);
67
+ };
68
+
69
+ export const applyDiffs = <T>(
70
+ accessor: DocAccessor<T>,
71
+ diffs: readonly string[],
72
+ { errorOnNotFound = false }: { errorOnNotFound?: boolean } = {},
73
+ ): string => {
74
+ for (const diff of reduceDiffs(diffs)) {
75
+ accessor.handle.change((doc: Doc<T>) => {
76
+ const text = DocAccessor.getValue<string>(accessor);
77
+ const idx = text.indexOf(diff.match);
78
+ if (idx !== -1) {
79
+ // TODO(burdon): Replace smallest substring.
80
+ // NOTE: This only replaces the first match.
81
+ A.splice(doc, accessor.path as A.Prop[], idx, diff.match.length, diff.replace);
82
+ } else {
83
+ if (errorOnNotFound) {
84
+ throw new Error(`Diff not found: ${diff.match}`);
85
+ } else {
86
+ log.warn('diff not found', diff);
87
+ }
88
+ }
89
+ });
90
+ }
91
+
92
+ return DocAccessor.getValue<string>(accessor);
93
+ };
package/src/errors.ts ADDED
@@ -0,0 +1,15 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { BaseError } from '@dxos/errors';
6
+
7
+ /**
8
+ * Generic error from AI model.
9
+ */
10
+ export class AiModelError extends BaseError.extend('AiModelError', 'AI model error') {}
11
+
12
+ /**
13
+ * Generic error for AI agent execution.
14
+ */
15
+ export class AiAssistantError extends BaseError.extend('AiAssistantError', 'AI assistant error') {}