@dxos/assistant 0.8.4-main.ae835ea → 0.8.4-main.bc2380dfbc

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 (172) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +2 -1
  3. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
  4. package/dist/lib/neutral/extraction/index.mjs +204 -0
  5. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  6. package/dist/lib/neutral/index.mjs +1755 -0
  7. package/dist/lib/neutral/index.mjs.map +7 -0
  8. package/dist/lib/neutral/meta.json +1 -0
  9. package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
  10. package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
  11. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  12. package/dist/types/src/extraction/extraction.d.ts +1065 -312
  13. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  14. package/dist/types/src/extraction/index.d.ts +0 -1
  15. package/dist/types/src/extraction/index.d.ts.map +1 -1
  16. package/dist/types/src/extraction/quotes.d.ts +2 -2
  17. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  18. package/dist/types/src/functions/services.d.ts +13 -15
  19. package/dist/types/src/functions/services.d.ts.map +1 -1
  20. package/dist/types/src/index.d.ts +2 -5
  21. package/dist/types/src/index.d.ts.map +1 -1
  22. package/dist/types/src/request/AiRequest.d.ts +104 -0
  23. package/dist/types/src/request/AiRequest.d.ts.map +1 -0
  24. package/dist/types/src/{session → request}/artifact-diff.d.ts +1 -1
  25. package/dist/types/src/request/artifact-diff.d.ts.map +1 -0
  26. package/dist/types/src/request/format.d.ts +15 -0
  27. package/dist/types/src/request/format.d.ts.map +1 -0
  28. package/dist/types/src/request/index.d.ts +4 -0
  29. package/dist/types/src/request/index.d.ts.map +1 -0
  30. package/dist/types/src/{session → request}/observer.d.ts +6 -5
  31. package/dist/types/src/request/observer.d.ts.map +1 -0
  32. package/dist/types/src/{session → request}/version-pin.d.ts +3 -3
  33. package/dist/types/src/request/version-pin.d.ts.map +1 -0
  34. package/dist/types/src/session/AiContext.d.ts +154 -0
  35. package/dist/types/src/session/AiContext.d.ts.map +1 -0
  36. package/dist/types/src/session/AiContext.test.d.ts +2 -0
  37. package/dist/types/src/session/AiContext.test.d.ts.map +1 -0
  38. package/dist/types/src/session/AiSession.d.ts +73 -0
  39. package/dist/types/src/session/AiSession.d.ts.map +1 -0
  40. package/dist/types/src/session/index.d.ts +2 -4
  41. package/dist/types/src/session/index.d.ts.map +1 -1
  42. package/dist/types/src/session/toolkit.d.ts +10 -9
  43. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  44. package/dist/types/src/templates/system.d.ts +1 -2
  45. package/dist/types/src/templates/system.d.ts.map +1 -1
  46. package/dist/types/src/util/artifact.d.ts +27 -0
  47. package/dist/types/src/util/artifact.d.ts.map +1 -0
  48. package/dist/types/src/{diff.d.ts → util/diff.d.ts} +3 -1
  49. package/dist/types/src/util/diff.d.ts.map +1 -0
  50. package/dist/types/src/{diff.test.d.ts.map → util/diff.test.d.ts.map} +1 -1
  51. package/dist/types/src/util/error-handling.d.ts.map +1 -0
  52. package/dist/types/src/{errors.d.ts → util/errors.d.ts} +32 -40
  53. package/dist/types/src/util/errors.d.ts.map +1 -0
  54. package/dist/types/src/{execution-graph.d.ts → util/execution-graph.d.ts} +5 -2
  55. package/dist/types/src/util/execution-graph.d.ts.map +1 -0
  56. package/dist/types/src/util/execution-graph.test.d.ts.map +1 -0
  57. package/dist/types/src/util/index.d.ts +7 -0
  58. package/dist/types/src/util/index.d.ts.map +1 -0
  59. package/dist/types/src/util/tracing.d.ts +233 -0
  60. package/dist/types/src/util/tracing.d.ts.map +1 -0
  61. package/dist/types/tsconfig.tsbuildinfo +1 -1
  62. package/package.json +36 -42
  63. package/src/extraction/extraction-ner-function/index.ts +0 -1
  64. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +10 -5
  65. package/src/extraction/extraction.ts +43 -14
  66. package/src/extraction/index.ts +0 -1
  67. package/src/extraction/quotes.ts +4 -5
  68. package/src/functions/services.ts +119 -63
  69. package/src/index.ts +2 -5
  70. package/src/request/AiRequest.ts +348 -0
  71. package/src/{session → request}/artifact-diff.ts +1 -1
  72. package/src/{session → request}/format.ts +29 -24
  73. package/src/request/index.ts +8 -0
  74. package/src/{session → request}/observer.ts +6 -3
  75. package/src/{session → request}/version-pin.ts +6 -6
  76. package/src/session/AiContext.test.ts +53 -0
  77. package/src/session/AiContext.ts +403 -0
  78. package/src/session/AiSession.ts +324 -0
  79. package/src/session/index.ts +3 -4
  80. package/src/session/toolkit.ts +27 -28
  81. package/src/templates/{format.tpl → instructions/format.tpl} +1 -4
  82. package/src/templates/{system.tpl → instructions/system.tpl} +50 -2
  83. package/src/templates/system.ts +9 -8
  84. package/src/{types → util}/artifact.ts +42 -6
  85. package/src/util/diff.test.ts +74 -0
  86. package/src/{diff.ts → util/diff.ts} +13 -4
  87. package/src/{session → util}/error-handling.ts +3 -2
  88. package/src/util/errors.ts +15 -0
  89. package/src/{execution-graph.test.ts → util/execution-graph.test.ts} +47 -45
  90. package/src/{execution-graph.ts → util/execution-graph.ts} +41 -22
  91. package/src/util/index.ts +10 -0
  92. package/src/util/tracing.ts +57 -0
  93. package/dist/lib/browser/chunk-4VIJTKPM.mjs +0 -354
  94. package/dist/lib/browser/chunk-4VIJTKPM.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 -272
  98. package/dist/lib/browser/extraction/index.mjs.map +0 -7
  99. package/dist/lib/browser/index.mjs +0 -900
  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/node-esm/chunk-AUUC7II4.mjs +0 -356
  104. package/dist/lib/node-esm/chunk-AUUC7II4.mjs.map +0 -7
  105. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs +0 -91
  106. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs.map +0 -7
  107. package/dist/lib/node-esm/extraction/index.mjs +0 -273
  108. package/dist/lib/node-esm/extraction/index.mjs.map +0 -7
  109. package/dist/lib/node-esm/index.mjs +0 -901
  110. package/dist/lib/node-esm/index.mjs.map +0 -7
  111. package/dist/lib/node-esm/meta.json +0 -1
  112. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs +0 -14
  113. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs.map +0 -7
  114. package/dist/types/src/conversation/context.d.ts +0 -103
  115. package/dist/types/src/conversation/context.d.ts.map +0 -1
  116. package/dist/types/src/conversation/conversation.d.ts +0 -41
  117. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  118. package/dist/types/src/conversation/index.d.ts +0 -3
  119. package/dist/types/src/conversation/index.d.ts.map +0 -1
  120. package/dist/types/src/diff.d.ts.map +0 -1
  121. package/dist/types/src/errors.d.ts.map +0 -1
  122. package/dist/types/src/execution-graph.d.ts.map +0 -1
  123. package/dist/types/src/execution-graph.test.d.ts.map +0 -1
  124. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
  125. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
  126. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
  127. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
  128. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
  129. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
  130. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -345
  131. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
  132. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
  133. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
  134. package/dist/types/src/session/artifact-diff.d.ts.map +0 -1
  135. package/dist/types/src/session/error-handling.d.ts.map +0 -1
  136. package/dist/types/src/session/format.d.ts +0 -186
  137. package/dist/types/src/session/format.d.ts.map +0 -1
  138. package/dist/types/src/session/format.test.d.ts +0 -2
  139. package/dist/types/src/session/format.test.d.ts.map +0 -1
  140. package/dist/types/src/session/observer.d.ts.map +0 -1
  141. package/dist/types/src/session/session.d.ts +0 -51
  142. package/dist/types/src/session/session.d.ts.map +0 -1
  143. package/dist/types/src/session/session.test.d.ts +0 -2
  144. package/dist/types/src/session/session.test.d.ts.map +0 -1
  145. package/dist/types/src/session/version-pin.d.ts.map +0 -1
  146. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  147. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  148. package/dist/types/src/types/artifact.d.ts +0 -16
  149. package/dist/types/src/types/artifact.d.ts.map +0 -1
  150. package/dist/types/src/types/index.d.ts +0 -2
  151. package/dist/types/src/types/index.d.ts.map +0 -1
  152. package/src/conversation/context.ts +0 -186
  153. package/src/conversation/conversation.ts +0 -128
  154. package/src/conversation/index.ts +0 -6
  155. package/src/diff.test.ts +0 -43
  156. package/src/errors.ts +0 -15
  157. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -84
  158. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -72
  159. package/src/extraction/extraction-llm-function/index.ts +0 -5
  160. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -115
  161. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -64
  162. package/src/session/format.test.ts +0 -60
  163. package/src/session/session.conversations.json +0 -1
  164. package/src/session/session.test.ts +0 -149
  165. package/src/session/session.ts +0 -213
  166. package/src/summarization/summarization.test.ts +0 -202
  167. package/src/types/index.ts +0 -5
  168. /package/dist/lib/{browser/named-entity-recognition-QPYHML66.mjs.map → neutral/chunk-J5LGTIGS.mjs.map} +0 -0
  169. /package/dist/types/src/{diff.test.d.ts → util/diff.test.d.ts} +0 -0
  170. /package/dist/types/src/{session → util}/error-handling.d.ts +0 -0
  171. /package/dist/types/src/{execution-graph.test.d.ts → util/execution-graph.test.d.ts} +0 -0
  172. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -0,0 +1,324 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import { type Registry } from '@effect-atom/atom-react';
8
+ import * as Array from 'effect/Array';
9
+ import * as Context from 'effect/Context';
10
+ import * as Effect from 'effect/Effect';
11
+ import * as Either from 'effect/Either';
12
+ import { pipe } from 'effect/Function';
13
+ import * as Layer from 'effect/Layer';
14
+ import * as Record from 'effect/Record';
15
+ import * as Runtime from 'effect/Runtime';
16
+
17
+ import { type OpaqueToolkit, type ToolExecutionService, type ToolResolverService } from '@dxos/ai';
18
+ import { type Blueprint, type OperationRegistry, McpServer, Operation, Trace } from '@dxos/compute';
19
+ import { Resource } from '@dxos/context';
20
+ import { Database, Feed, Filter, Obj } from '@dxos/echo';
21
+ import { acquireReleaseResource } from '@dxos/effect';
22
+ import { invariant } from '@dxos/invariant';
23
+ import { log } from '@dxos/log';
24
+ import { McpToolkit } from '@dxos/mcp-client';
25
+ import { Message, type ContentBlock } from '@dxos/types';
26
+
27
+ import { ToolExecutionServices } from '../functions';
28
+ import { AiRequest, type GenerationObserver, formatSystemPrompt } from '../request';
29
+ import { McpServerError } from '../util';
30
+ import * as AiContext from './AiContext';
31
+ import { createToolkit } from './toolkit';
32
+
33
+ export type RunProps<R = never> = {
34
+ prompt: string | ContentBlock.Any[];
35
+ system?: string;
36
+ observer?: GenerationObserver;
37
+ toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
38
+
39
+ /**
40
+ * Space-level MCP servers to connect alongside blueprint-defined ones.
41
+ */
42
+ mcpServers?: readonly McpServer.McpServer[];
43
+ };
44
+
45
+ export type Options = {
46
+ feed: Feed.Feed;
47
+ runtime: Runtime.Runtime<Feed.FeedService>;
48
+ registry?: Registry.Registry;
49
+ };
50
+
51
+ /**
52
+ * Summarization threshold in tokens.
53
+ */
54
+ // TODO(dmaretskyi): Take from model characteristics. opus has 200k max tokens.
55
+ const SUMMARY_THRESHOLD = 80_000;
56
+
57
+ /**
58
+ * Durable conversation state (initiated by users and agents) backed by a Feed.
59
+ * Executes tools based on AI responses and supports cancellation of in-progress requests.
60
+ */
61
+ export class Session extends Resource {
62
+ /**
63
+ * Blueprints and objects bound to the session.
64
+ */
65
+ private readonly _binder: AiContext.Binder;
66
+ private readonly _feed: Feed.Feed;
67
+ private readonly _runtime: Runtime.Runtime<Feed.FeedService>;
68
+
69
+ public constructor(options: Options) {
70
+ super();
71
+ this._feed = options.feed;
72
+ this._runtime = options.runtime;
73
+ invariant(this._feed);
74
+ invariant(this._runtime);
75
+ this._binder = new AiContext.Binder({
76
+ feed: this._feed,
77
+ runtime: this._runtime,
78
+ registry: options.registry,
79
+ });
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
+ /**
125
+ * Creates a new cancelable request effect.
126
+ */
127
+ public createRequest<R = never>(
128
+ params: RunProps<R>,
129
+ ): Effect.Effect<Message.Message[], AiRequest.RunError, AiRequest.RunRequirements | R> {
130
+ return Effect.gen(this, function* () {
131
+ const history = yield* Effect.promise(() => this.getHistory());
132
+ const blueprints = this.context.getBlueprints();
133
+ const objects = this.context.getObjects();
134
+
135
+ log('run', {
136
+ history: history.length,
137
+ blueprints: blueprints.length,
138
+ objects: objects.length,
139
+ });
140
+
141
+ const request = new AiRequest.Request({
142
+ summarizationThreshold: SUMMARY_THRESHOLD,
143
+ observer: params.observer,
144
+ onOutput: (message) =>
145
+ Effect.promise(() => Runtime.runPromise(this._runtime)(Feed.append(this._feed, [message]))),
146
+ });
147
+
148
+ yield* request.begin({
149
+ history,
150
+ blueprints,
151
+ objects,
152
+ prompt: params.prompt,
153
+ system: params.system,
154
+ });
155
+
156
+ // Turn loop: recompute toolkit and system prompt between turns to pick up dynamically enabled blueprints.
157
+ do {
158
+ yield* Effect.promise(() => this.context.sync());
159
+ const currentBlueprints = this.context.getBlueprints();
160
+ const mcps = yield* connectMcpServers(currentBlueprints, params.mcpServers);
161
+ const toolkit = yield* createToolkit({
162
+ toolkit: params.toolkit,
163
+ blueprints: currentBlueprints,
164
+ opaqueToolkits: mcps,
165
+ });
166
+
167
+ log('toolkit', { tools: Record.keys(toolkit.toolkit.tools) });
168
+ const system = yield* formatSystemPrompt({
169
+ system: params.system,
170
+ blueprints: currentBlueprints,
171
+ objects: this.context.getObjects(),
172
+ }).pipe(Effect.orDie);
173
+
174
+ const { done } = yield* request.runAgentTurn({ system, toolkit });
175
+ if (done) {
176
+ break;
177
+ }
178
+
179
+ yield* request.runTools({ toolkit });
180
+ } while (true);
181
+
182
+ log('result', {
183
+ messages: request.pending.length,
184
+ duration: request.duration,
185
+ toolCalls: request.toolCalls,
186
+ });
187
+
188
+ return [...request.pending];
189
+ }).pipe(
190
+ Effect.provide(
191
+ Layer.mergeAll(
192
+ Layer.succeed(AiContext.Service, {
193
+ binder: this.context,
194
+ }),
195
+ Layer.succeed(Service, this),
196
+ Operation.withInvocationOptions({ conversation: Obj.getDXN(this._feed).toString() }),
197
+ ),
198
+ ),
199
+ Effect.withSpan('AiSession.createRequest'),
200
+ );
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Gives access to the ai session.
206
+ */
207
+ export class Service extends Context.Tag('@dxos/assistant/AiSessionService')<Service, Session>() {
208
+ /**
209
+ * Create a new session layer from options.
210
+ */
211
+ static layer = (options: Options): Layer.Layer<Service | AiContext.Service> =>
212
+ aiContextFromSession.pipe(
213
+ Layer.provideMerge(
214
+ Layer.scoped(
215
+ Service,
216
+ Effect.gen(function* () {
217
+ const session = yield* acquireReleaseResource(() => new Session(options));
218
+ return session;
219
+ }),
220
+ ),
221
+ ),
222
+ );
223
+
224
+ /**
225
+ * Create a new session with a new feed.
226
+ */
227
+ static layerNewFeed = (
228
+ options?: Omit<Options, 'feed' | 'runtime'>,
229
+ ): Layer.Layer<Service | AiContext.Service, never, Database.Service | Feed.FeedService> =>
230
+ Layer.unwrapScoped(
231
+ Effect.gen(function* () {
232
+ const feed = yield* Database.add(Feed.make());
233
+ const runtime = yield* Effect.runtime<Feed.FeedService>();
234
+ return Service.layer({ ...options, feed, runtime });
235
+ }),
236
+ );
237
+
238
+ /**
239
+ * Run a prompt in the current session.
240
+ */
241
+ static run = <R = never>(
242
+ params: RunProps<R>,
243
+ ): Effect.Effect<Message.Message[], AiRequest.RunError, AiRequest.RunRequirements | Service | R> =>
244
+ Effect.gen(function* () {
245
+ const session = yield* Service;
246
+ return yield* session.createRequest(params);
247
+ });
248
+ }
249
+
250
+ const aiContextFromSession = Layer.effect(
251
+ AiContext.Service,
252
+ Effect.gen(function* () {
253
+ const session = yield* Service;
254
+ return {
255
+ binder: session.context,
256
+ };
257
+ }),
258
+ );
259
+
260
+ const connectMcpServers = (
261
+ blueprints: readonly Blueprint.Blueprint[],
262
+ spaceMcpServers: readonly McpServer.McpServer[] = [],
263
+ ): Effect.Effect<OpaqueToolkit.OpaqueToolkit[], never, Trace.TraceService> => {
264
+ const blueprintServers: McpToolkit.McpToolkitOptions[] = pipe(
265
+ blueprints,
266
+ Array.flatMap((_) => _.mcpServers ?? []),
267
+ Array.map(({ url, protocol, apiKey }) => ({ url, protocol, apiKey })),
268
+ );
269
+ const spaceServers: McpToolkit.McpToolkitOptions[] = spaceMcpServers.map(({ url, protocol, apiKey }) => ({
270
+ url,
271
+ protocol,
272
+ apiKey,
273
+ }));
274
+ const allServers = [...blueprintServers, ...spaceServers];
275
+
276
+ return pipe(
277
+ allServers,
278
+ Effect.forEach((options) =>
279
+ McpToolkit.make(options).pipe(
280
+ // NOTE: Type-inference fails here without explicit void return.
281
+ Effect.tap((toolkit): void =>
282
+ log.info('Connected to MCP server', { url: options.url, tools: Object.keys(toolkit.toolkit.tools).length }),
283
+ ),
284
+ // Surface typed connection failures via ephemeral trace + warn log, then drop the server.
285
+ Effect.tapError((error) =>
286
+ Effect.gen(function* () {
287
+ log.warn('Failed to connect to MCP server', {
288
+ url: error.url,
289
+ protocol: error.protocol,
290
+ message: error.message,
291
+ });
292
+ yield* Trace.write(McpServerError, {
293
+ url: error.url,
294
+ protocol: error.protocol,
295
+ message: error.message,
296
+ });
297
+ }),
298
+ ),
299
+ // Catch unexpected defects too (e.g. malformed tool schemas) so a single broken
300
+ // server can never abort the whole turn — surface them through the same channel.
301
+ Effect.catchAllDefect((defect) =>
302
+ Effect.gen(function* () {
303
+ const message = defect instanceof Error ? defect.message : String(defect);
304
+ log.warn('Unexpected MCP defect', { url: options.url, message });
305
+ yield* Trace.write(McpServerError, {
306
+ url: options.url,
307
+ protocol: options.protocol,
308
+ message: `Unexpected MCP failure: ${message}`,
309
+ });
310
+ return yield* Effect.fail(
311
+ new McpToolkit.McpConnectionError({
312
+ url: options.url,
313
+ protocol: options.protocol,
314
+ message,
315
+ }),
316
+ );
317
+ }),
318
+ ),
319
+ Effect.either,
320
+ ),
321
+ ),
322
+ Effect.map(Array.filterMap((_) => Either.getRight(_))),
323
+ );
324
+ };
@@ -2,8 +2,7 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- export * from './artifact-diff';
6
- export * from './observer';
7
- export * from './session';
8
5
  export * from './toolkit';
9
- export * from './version-pin';
6
+
7
+ export * as AiContext from './AiContext';
8
+ export * as AiSession from './AiSession';
@@ -2,47 +2,46 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import type * as Tool from '@effect/ai/Tool';
6
5
  import * as Toolkit from '@effect/ai/Toolkit';
7
- import type * as Context from 'effect/Context';
8
6
  import * as Effect from 'effect/Effect';
7
+ import * as Layer from 'effect/Layer';
9
8
 
10
- import { type AiToolNotFoundError, ToolExecutionService, type ToolId, ToolResolverService } from '@dxos/ai';
11
- import { type Blueprint } from '@dxos/blueprints';
9
+ import { type AiToolNotFoundError, OpaqueToolkit, ToolExecutionService, ToolResolverService } from '@dxos/ai';
10
+ import { type Blueprint } from '@dxos/compute';
12
11
  import { isTruthy } from '@dxos/util';
13
12
 
14
- export type ToolkitParams<Tools extends Record<string, Tool.Any>> = {
15
- toolkit?: Toolkit.Toolkit<Tools>;
16
- toolIds?: ToolId[];
17
- blueprints?: Blueprint.Blueprint[];
13
+ export type CreateToolkitProps = {
14
+ toolkit?: OpaqueToolkit.Any;
15
+ blueprints?: readonly Blueprint.Blueprint[];
16
+ /**
17
+ * Self-contained with handlers toolkits.
18
+ */
19
+ opaqueToolkits?: readonly OpaqueToolkit.Any[];
18
20
  };
19
21
 
20
22
  /**
21
23
  * Build a combined toolkit from the blueprint tools and the provided toolkit.
22
24
  */
23
- export const createToolkit = <Tools extends Record<string, Tool.Any> = {}>({
24
- toolkit: toolkitParam,
25
- toolIds = [],
25
+ export const createToolkit = ({
26
+ toolkit: toolkitProp,
26
27
  blueprints = [],
27
- }: ToolkitParams<Tools>): Effect.Effect<
28
- Toolkit.WithHandler<any>,
28
+ opaqueToolkits = [],
29
+ }: CreateToolkitProps): Effect.Effect<
30
+ OpaqueToolkit.OpaqueToolkit,
29
31
  AiToolNotFoundError,
30
- ToolResolverService | ToolExecutionService | Tool.HandlersFor<Tools>
32
+ ToolResolverService | ToolExecutionService
31
33
  > =>
32
34
  Effect.gen(function* () {
33
- const blueprintToolkit = yield* ToolResolverService.resolveToolkit([
34
- ...blueprints.flatMap(({ tools }) => tools),
35
- ...toolIds,
36
- ]);
35
+ const blueprintToolkit = yield* ToolResolverService.resolveToolkit(blueprints.flatMap(({ tools }) => tools));
36
+ const blueprintToolHandler = yield* blueprintToolkit.toContext(ToolExecutionService.handlersFor(blueprintToolkit));
37
+ const opaqueToolkit = OpaqueToolkit.merge(...opaqueToolkits);
37
38
 
38
- const blueprintToolkitHandler: Context.Context<Tool.HandlersFor<any>> = yield* blueprintToolkit.toContext(
39
- ToolExecutionService.handlersFor(blueprintToolkit),
39
+ const toolkitDefs = [toolkitProp?.toolkit, blueprintToolkit, opaqueToolkit.toolkit].filter(isTruthy);
40
+ const mergedToolkit = Toolkit.merge(...toolkitDefs);
41
+ const combinedHandlerLayer = Layer.mergeAll(
42
+ Layer.succeedContext(blueprintToolHandler),
43
+ toolkitProp?.layer ?? OpaqueToolkit.empty.layer,
44
+ opaqueToolkit.layer,
40
45
  );
41
-
42
- const toolkit = Toolkit.merge(...[toolkitParam, blueprintToolkit].filter(isTruthy));
43
- return yield* toolkit.pipe(Effect.provide(blueprintToolkitHandler)) as any as Effect.Effect<
44
- Toolkit.WithHandler<any>,
45
- never,
46
- Tool.HandlersFor<Tools>
47
- >;
48
- });
46
+ return OpaqueToolkit.make(mergedToolkit, combinedHandlerLayer as any) as OpaqueToolkit.OpaqueToolkit;
47
+ }) as Effect.Effect<OpaqueToolkit.OpaqueToolkit, AiToolNotFoundError, ToolResolverService | ToolExecutionService>;
@@ -45,16 +45,13 @@ You can reply with a block reference for objects if you have the DXN. For exampl
45
45
 
46
46
  Each suggestion must in the form of a proposed action enclosed in a <suggestion> tag.
47
47
  Example: <suggestion>Show on a map</suggestion>
48
+ Do not use bullets when listing suggestions.
48
49
 
49
50
  ### Multiple choice questions
50
51
 
51
52
  You may ask multiple choice questions by wrapping consise options inside <option> tags inside a well formed <select> tag.
52
53
  Example: <select><option>Yes</option><option>No</option></select>
53
54
 
54
- ## Toolkit
55
-
56
- If the user asks for a list of tools, then just emit a single self-closing <toolkit/> tag instead of listing the tools.
57
-
58
55
  ## Context
59
56
 
60
57
  The current date and time is {{DATETIME}}.
@@ -43,6 +43,54 @@
43
43
  - Suggested actions could include actions that create artifacts.
44
44
  - After creating an artifact use a tool to add it to the chat context.
45
45
 
46
- ## Context
46
+ ## Navigation
47
47
 
48
- Today is {{DATETIME}}.
48
+ - When the user asks to open, go to, navigate to, or show a specific document, page, or object, use the navigation tools instead of loading content inline.
49
+ - First, call the Resolve navigation targets tool to find the navigation path for the requested item.
50
+ - Without arguments, it returns available pages that can be navigated to.
51
+ - With a DXN in the query, it resolves that specific object to a navigation path.
52
+ - If you know the object's DXN (e.g. from a database query or context objects), pass it in the query to get the exact navigation path.
53
+ - Then, call the Open tool with the resolved navigation path(s) in the subject array to navigate the user to that item.
54
+ - Do not respond with the document's content when the user asks to open it — open it in the main content area instead.
55
+ - If multiple targets match, present the options to the user and let them choose which to open.
56
+
57
+ ## Response format
58
+
59
+ - NEVER output narration text outside `<status>` tags or the final user-facing answer. Any progress update, transition sentence, or "let me…" lead-in MUST be wrapped in `<status>...</status>`. Violating this is an error.
60
+ - When updating the user about the progress of the work you are doing, put the update in a <status> XML tag.
61
+ - Only when you need to show the result to the user or ask a question use a text block without status tags.
62
+ - After a `</status>` tag, the next output must be either another `<status>` tag, a tool call, or the final user-facing answer — never a transition sentence.
63
+
64
+ <example>
65
+ // reasoning...
66
+ <status>Looking for emails from Depot</status>
67
+ // tool call..
68
+ <status>Found 2 emails from Depot.</status>
69
+ <status>Loading email details</status>
70
+ // tool call
71
+ <status>Located mailbox</status>
72
+ I found **2 emails from Depot**:
73
+ </example>
74
+
75
+ Do not do (no status tags):
76
+
77
+ <incorrect_example>
78
+ // reasoning...
79
+ // tool call..
80
+ I found 2 emails from Depot. Let me load their details:
81
+ // tool call
82
+ I found **2 emails from Depot**:
83
+ </incorrect_example>
84
+
85
+ Do not do (transition sentence after a status tag, before tool calls):
86
+
87
+ <incorrect_example>
88
+ <status>Doing X</status>
89
+ Let me start by doing X:
90
+ // tool call
91
+ </incorrect_example>
92
+
93
+ - NEVER write a lead-in sentence before a tool call. Use a `<status>` tag instead.
94
+ - Avoid using plain text to tell the user what you are about to do; instead, use status blocks.
95
+ - WRONG: Let me get...
96
+ - CORRECT: <status>Getting...</status>
@@ -5,10 +5,10 @@
5
5
  import defaultsDeep from 'lodash.defaultsdeep';
6
6
 
7
7
  import { type ModelCapabilities } from '@dxos/ai';
8
- import { Template } from '@dxos/blueprints';
8
+ import { Template } from '@dxos/compute';
9
9
 
10
- import FORMAT from './format.tpl?raw';
11
- import SYSTEM from './system.tpl?raw';
10
+ import FORMAT from './instructions/format.tpl?raw';
11
+ import SYSTEM from './instructions/system.tpl?raw';
12
12
 
13
13
  /**
14
14
  * System template variables.
@@ -29,13 +29,14 @@ export const createSystemPrompt = (options: Partial<SystemPromptOptions> = {}) =
29
29
  }),
30
30
  );
31
31
 
32
+ /**
33
+ * NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.
34
+ */
35
+ const SYSTEM_ID = '01K2J2FZWH39F55CS7B26GP1Q3';
36
+
32
37
  export const templates = {
33
- /** Editable system prompt.*/
34
38
  system: Template.make({
35
- /**
36
- * NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.
37
- */
38
- id: '01K2J2FZWH39F55CS7B26GP1Q3',
39
+ id: SYSTEM_ID,
39
40
  source: SYSTEM,
40
41
  }),
41
42
  };
@@ -2,10 +2,12 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ import type * as Effect from 'effect/Effect';
5
6
  import * as Schema from 'effect/Schema';
6
7
 
7
- import { type ObjectId } from '@dxos/echo/internal';
8
- import { DXN, LOCAL_SPACE_TAG, type SpaceId } from '@dxos/keys';
8
+ import { Database, type Err, Obj, Ref, type Type } from '@dxos/echo';
9
+ import { EncodedReference } from '@dxos/echo-protocol';
10
+ import { DXN, LOCAL_SPACE_TAG, type ObjectId, type SpaceId } from '@dxos/keys';
9
11
  import { trim } from '@dxos/util';
10
12
 
11
13
  /**
@@ -16,18 +18,30 @@ export const createArtifactElement = (id: ObjectId) => `<artifact id=${id} />`;
16
18
  /**
17
19
  * A model-friendly way to reference an object.
18
20
  * Supports vairous formats that will be normalized to a DXN.
21
+ *
22
+ * @deprecated Use `Ref.Ref(XXX)` instead.
19
23
  */
20
- // TODO(burdon): Rename ObjectReference?
24
+ // TODO(burdon): Rename RefFromLLM?
21
25
  export const ArtifactId: Schema.Schema<string> & {
22
26
  toDXN: (reference: ArtifactId, owningSpaceId?: SpaceId) => DXN;
27
+ resolve: <S extends Type.AnyEntity>(
28
+ schema: S,
29
+ ref: ArtifactId,
30
+ ) => Effect.Effect<Schema.Schema.Type<S>, Err.ObjectNotFoundError, Database.Service>;
23
31
  } = class extends Schema.String.annotations({
32
+ // TODO(dmaretskyi): This section gets overriden.
24
33
  description: trim`
25
34
  The ID of the referenced object. Formats accepted:
26
- - DXN (dxn:echo:@:XXXXX). DXNs can be prepended with an @ symbol for compatibility with in-text references.
35
+ - DXN (dxn:echo:@:01KG7R1ZXWFMWQ4DA1Q6TN1DG4). DXNs can be prepended with an @ symbol for compatibility with in-text references.
27
36
  - space ID, object ID tuple (spaceID:objectID)
28
- - Only object ID that is assumed to be in the current space (XXXXX)
37
+ - Only object ID that is assumed to be in the current space (01KG7R1ZXWFMWQ4DA1Q6TN1DG4)
29
38
  `,
30
- examples: ['dxn:echo:@:XXXXX', '@dxn:echo:@:XXXXX', 'spaceID:objectID', 'XXXXX'],
39
+ examples: [
40
+ 'dxn:echo:@:01KG7R1ZXWFMWQ4DA1Q6TN1DG4',
41
+ '@dxn:echo:@:01KG7R1ZXWFMWQ4DA1Q6TN1DG4',
42
+ 'BM3FSHFOMJCHCG5QW7JTVKGYABD2GAA7G:01KG7R1ZXWFMWQ4DA1Q6TN1DG4',
43
+ '01KG7R1ZXWFMWQ4DA1Q6TN1DG4',
44
+ ],
31
45
  }) {
32
46
  static toDXN(reference: ArtifactId, owningSpaceId?: SpaceId): DXN {
33
47
  // Allow @dxn: prefix for compatibility with in-text references.
@@ -47,6 +61,28 @@ export const ArtifactId: Schema.Schema<string> & {
47
61
  throw new Error(`Unable to parse object reference: ${reference}`);
48
62
  }
49
63
  }
64
+
65
+ /**
66
+ * Resolves an artifact ID to an object.
67
+ */
68
+ static resolve<S extends Type.AnyEntity>(
69
+ schema: S,
70
+ ref: ArtifactId,
71
+ ): Effect.Effect<Schema.Schema.Type<S>, Err.ObjectNotFoundError, Database.Service> {
72
+ const dxn = ArtifactId.toDXN(ref);
73
+ return Database.resolve(dxn, schema);
74
+ }
50
75
  };
51
76
 
52
77
  export type ArtifactId = Schema.Schema.Type<typeof ArtifactId>;
78
+
79
+ /**
80
+ * Schema that decodes ECHO reference object from an LLM-friendly input.
81
+ */
82
+ export const RefFromLLM = Schema.transform(ArtifactId, Ref.Ref(Obj.Unknown), {
83
+ decode: (fromA, fromI) => EncodedReference.fromDXN(ArtifactId.toDXN(fromA)),
84
+ encode: (toI, toA) => EncodedReference.toDXN(toI).toString(),
85
+ strict: false,
86
+ }).annotations({
87
+ description: ArtifactId.ast.annotations.description as string,
88
+ });
@@ -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
+ });