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

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 (89) hide show
  1. package/dist/lib/browser/{chunk-5GJYG2ML.mjs → chunk-CWGVG235.mjs} +65 -81
  2. package/dist/lib/browser/chunk-CWGVG235.mjs.map +7 -0
  3. package/dist/lib/browser/extraction/index.mjs +18 -14
  4. package/dist/lib/browser/extraction/index.mjs.map +4 -4
  5. package/dist/lib/browser/index.mjs +552 -88
  6. package/dist/lib/browser/index.mjs.map +4 -4
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/node-esm/{chunk-FLFCEB4P.mjs → chunk-OV5PMQPB.mjs} +65 -81
  9. package/dist/lib/node-esm/chunk-OV5PMQPB.mjs.map +7 -0
  10. package/dist/lib/node-esm/extraction/index.mjs +18 -14
  11. package/dist/lib/node-esm/extraction/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/index.mjs +552 -88
  13. package/dist/lib/node-esm/index.mjs.map +4 -4
  14. package/dist/lib/node-esm/meta.json +1 -1
  15. package/dist/types/src/conversation/context.d.ts +14 -7
  16. package/dist/types/src/conversation/context.d.ts.map +1 -1
  17. package/dist/types/src/conversation/conversation.d.ts +9 -10
  18. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  19. package/dist/types/src/errors.d.ts +38 -38
  20. package/dist/types/src/errors.d.ts.map +1 -1
  21. package/dist/types/src/execution-graph.d.ts +82 -0
  22. package/dist/types/src/execution-graph.d.ts.map +1 -0
  23. package/dist/types/src/execution-graph.test.d.ts +2 -0
  24. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  25. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  26. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +61 -57
  27. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  28. package/dist/types/src/extraction/extraction.d.ts +10 -6
  29. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  30. package/dist/types/src/extraction/quotes.d.ts +1 -1
  31. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  32. package/dist/types/src/functions/services.d.ts +17 -5
  33. package/dist/types/src/functions/services.d.ts.map +1 -1
  34. package/dist/types/src/index.d.ts +2 -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 +34 -32
  41. package/dist/types/src/session/format.d.ts.map +1 -1
  42. package/dist/types/src/session/observer.d.ts +1 -1
  43. package/dist/types/src/session/observer.d.ts.map +1 -1
  44. package/dist/types/src/session/session.d.ts +13 -9
  45. package/dist/types/src/session/session.d.ts.map +1 -1
  46. package/dist/types/src/session/toolkit.d.ts +7 -6
  47. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  48. package/dist/types/src/session/version-pin.d.ts +2 -2
  49. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  50. package/dist/types/src/{types.d.ts → types/artifact.d.ts} +3 -3
  51. package/dist/types/src/types/artifact.d.ts.map +1 -0
  52. package/dist/types/src/types/index.d.ts +2 -0
  53. package/dist/types/src/types/index.d.ts.map +1 -0
  54. package/dist/types/tsconfig.tsbuildinfo +1 -1
  55. package/package.json +26 -31
  56. package/src/conversation/context.ts +49 -17
  57. package/src/conversation/conversation.ts +23 -18
  58. package/src/errors.ts +4 -4
  59. package/src/execution-graph.test.ts +738 -0
  60. package/src/execution-graph.ts +500 -0
  61. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +3 -1
  62. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +3 -1
  63. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +2 -1
  64. package/src/extraction/extraction.ts +2 -2
  65. package/src/extraction/quotes.test.ts +2 -2
  66. package/src/extraction/quotes.ts +3 -3
  67. package/src/functions/services.ts +85 -46
  68. package/src/index.ts +2 -1
  69. package/src/session/artifact-diff.ts +2 -2
  70. package/src/session/error-handling.ts +11 -6
  71. package/src/session/format.test.ts +1 -1
  72. package/src/session/format.ts +9 -6
  73. package/src/session/observer.ts +2 -1
  74. package/src/session/session.conversations.json +1 -0
  75. package/src/session/session.test.ts +50 -209
  76. package/src/session/session.ts +31 -20
  77. package/src/session/toolkit.ts +19 -13
  78. package/src/session/version-pin.ts +2 -2
  79. package/src/summarization/summarization.test.ts +8 -3
  80. package/src/templates/system.tpl +10 -12
  81. package/src/{types.ts → types/artifact.ts} +2 -2
  82. package/src/types/index.ts +5 -0
  83. package/dist/lib/browser/chunk-5GJYG2ML.mjs.map +0 -7
  84. package/dist/lib/node-esm/chunk-FLFCEB4P.mjs.map +0 -7
  85. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  86. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  87. package/dist/types/src/types.d.ts.map +0 -1
  88. package/src/session/__snapshots__/session.test.ts.snap +0 -32
  89. package/src/session/version-pin.test.ts +0 -7
@@ -1,10 +1,11 @@
1
1
  // src/session/artifact-diff.ts
2
- import { Context } from "effect";
2
+ import * as Context from "effect/Context";
3
3
  var ArtifactDiffResolver = class extends Context.Tag("@dxos/assistant/ArtifactDiffResolver")() {
4
4
  };
5
5
 
6
6
  // src/session/observer.ts
7
- import { Effect, Function } from "effect";
7
+ import * as Effect from "effect/Effect";
8
+ import * as Function from "effect/Function";
8
9
  var GenerationObserver = Object.freeze({
9
10
  make: ({ onBegin = Function.constant(Effect.void), onPart = Function.constant(Effect.void), onBlock = Function.constant(Effect.void), onEnd = Function.constant(Effect.void), onMessage = Function.constant(Effect.void) } = {}) => ({
10
11
  onBegin,
@@ -35,14 +36,16 @@ var GenerationObserver = Object.freeze({
35
36
 
36
37
  // src/errors.ts
37
38
  import { BaseError } from "@dxos/errors";
38
- var AiAssistantError = class extends BaseError.extend("AI_ASSISTANT_ERROR") {
39
+ var AiModelError = class extends BaseError.extend("AI_MODEL_ERROR", "AI model error") {
39
40
  };
40
- var AnthropicError = class extends BaseError.extend("ANTHROPIC_ERROR") {
41
+ var AiAssistantError = class extends BaseError.extend("AI_ASSISTANT_ERROR", "AI assistant error") {
41
42
  };
42
43
 
43
44
  // src/session/session.ts
44
- import { AiLanguageModel } from "@effect/ai";
45
- import { Chunk, Effect as Effect4, Stream } from "effect";
45
+ import * as LanguageModel from "@effect/ai/LanguageModel";
46
+ import * as Chunk from "effect/Chunk";
47
+ import * as Effect3 from "effect/Effect";
48
+ import * as Stream from "effect/Stream";
46
49
  import { AiParser, AiPreprocessor, callTool, getToolCalls } from "@dxos/ai";
47
50
  import { todo } from "@dxos/debug";
48
51
  import { Obj as Obj2 } from "@dxos/echo";
@@ -50,36 +53,11 @@ import { TracingService } from "@dxos/functions";
50
53
  import { log as log2 } from "@dxos/log";
51
54
  import { DataType as DataType2 } from "@dxos/schema";
52
55
 
53
- // src/session/error-handling.ts
54
- import { AiError } from "@effect/ai";
55
- import { HttpClientError } from "@effect/platform";
56
- import { Effect as Effect2, Schema } from "effect";
57
- var AnthropicErrorResponse = Schema.Struct({
58
- type: Schema.Literal("error"),
59
- error: Schema.Struct({
60
- type: Schema.String,
61
- message: Schema.String
62
- })
63
- });
64
- var mapAiError = (err) => Effect2.gen(function* () {
65
- const cause = err.cause;
66
- if (HttpClientError.isHttpClientError(cause) && cause.reason === "StatusCode") {
67
- const body = yield* cause.response.json.pipe(Effect2.flatMap(Schema.decodeUnknown(AnthropicErrorResponse, {
68
- exact: false
69
- })));
70
- const parsedCause = new AnthropicError(`${body.error.type}: ${body.error.message}`);
71
- return new AiError.AiError({
72
- description: body.error.message,
73
- module: err.module,
74
- method: err.method,
75
- cause: parsedCause
76
- });
77
- }
78
- return err;
79
- }).pipe(Effect2.catchAll(() => Effect2.succeed(err)));
80
-
81
56
  // src/session/format.ts
82
- import { Array, Effect as Effect3, Option, pipe } from "effect";
57
+ import * as Array from "effect/Array";
58
+ import * as Effect2 from "effect/Effect";
59
+ import * as Function2 from "effect/Function";
60
+ import * as Option from "effect/Option";
83
61
  import { Template } from "@dxos/blueprints";
84
62
  import { Obj } from "@dxos/echo";
85
63
  import { ObjectVersion } from "@dxos/echo-db";
@@ -88,50 +66,52 @@ import { log } from "@dxos/log";
88
66
  import { DataType } from "@dxos/schema";
89
67
  import { trim } from "@dxos/util";
90
68
  var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/session/format.ts";
91
- var formatSystemPrompt = ({ system, blueprints = [], objects = [] }) => Effect3.gen(function* () {
92
- const blueprintDefs = yield* pipe(blueprints, Effect3.forEach((blueprint) => Effect3.succeed(blueprint.instructions)), Effect3.flatMap(Effect3.forEach((template) => DatabaseService.loadOption(template.source))), Effect3.map(Array.filter(Option.isSome)), Effect3.map(Array.map((template) => trim`
69
+ var formatSystemPrompt = ({ system, blueprints = [], objects = [] }) => Effect2.gen(function* () {
70
+ const blueprintDefs = yield* Function2.pipe(blueprints, Effect2.forEach((blueprint) => Effect2.succeed(blueprint.instructions)), Effect2.flatMap(Effect2.forEach((template) => DatabaseService.loadOption(template.source))), Effect2.map(Array.filter(Option.isSome)), Effect2.map(Array.map((template) => trim`
93
71
  <blueprint>
94
72
  ${Template.process(template.value.content)}
95
73
  </blueprint>
96
- `)), Effect3.map((blueprints2) => blueprints2.length > 0 ? [
74
+ `)), Effect2.map((blueprints2) => blueprints2.length > 0 ? [
97
75
  "## Blueprints Definitions",
98
76
  ...blueprints2
99
77
  ].join("\n\n") : void 0));
100
- const objectDefs = yield* pipe(objects, Effect3.forEach((object) => Effect3.succeed(trim`
78
+ const objectDefs = yield* Function2.pipe(objects, Effect2.forEach((object) => Effect2.succeed(trim`
101
79
  <object>
102
80
  <dxn>${Obj.getDXN(object)}</dxn>
103
81
  <typename>${Obj.getTypename(object)}</typename>
104
82
  </object>
105
- `)), Effect3.map((objects2) => objects2.length > 0 ? [
83
+ `)), Effect2.map((objects2) => objects2.length > 0 ? [
106
84
  "## Context Objects",
107
85
  ...objects2
108
86
  ].join("\n\n") : void 0));
109
- return yield* pipe(Effect3.succeed([
87
+ return yield* Function2.pipe(Effect2.succeed([
110
88
  system,
111
89
  blueprintDefs,
112
90
  objectDefs
113
- ].filter((def) => def !== void 0)), Effect3.map((parts) => parts.join("\n\n")));
91
+ ].filter((def) => def !== void 0)), Effect2.map((parts) => parts.join("\n\n")));
114
92
  });
115
- var formatUserPrompt = ({ prompt, history = [] }) => Effect3.gen(function* () {
93
+ var formatUserPrompt = ({ prompt, history = [] }) => Effect2.gen(function* () {
116
94
  const blocks = [];
117
- const artifactDiffResolver = yield* Effect3.serviceOption(ArtifactDiffResolver);
95
+ const artifactDiffResolver = yield* Effect2.serviceOption(ArtifactDiffResolver);
118
96
  if (Option.isSome(artifactDiffResolver)) {
119
97
  const versions = gatherObjectVersions(history);
120
- const artifactDiff = yield* Effect3.tryPromise({
98
+ const artifactDiff = yield* Effect2.tryPromise({
121
99
  try: () => artifactDiffResolver.value.resolve([
122
100
  ...versions.entries()
123
101
  ].map(([id, version]) => ({
124
102
  id,
125
103
  lastVersion: version
126
104
  }))),
127
- catch: AiAssistantError.wrap("Artifact diff resolution error")
105
+ catch: AiAssistantError.wrap({
106
+ message: "Artifact diff resolution error"
107
+ })
128
108
  });
129
109
  log("version", {
130
110
  artifactDiff,
131
111
  versions
132
112
  }, {
133
113
  F: __dxlog_file,
134
- L: 90,
114
+ L: 93,
135
115
  S: this,
136
116
  C: (f, a) => f(...a)
137
117
  });
@@ -222,16 +202,16 @@ var AiSession = class {
222
202
  _define_property(this, "_pending", void 0);
223
203
  _define_property(this, "run", void 0);
224
204
  this._options = _options;
225
- this._semaphore = Effect4.runSync(Effect4.makeSemaphore(1));
205
+ this._semaphore = Effect3.runSync(Effect3.makeSemaphore(1));
226
206
  this._history = [];
227
207
  this._pending = [];
228
- this.run = ({ prompt, system: systemTemplate, history = [], objects = [], blueprints = [], toolkit, observer = GenerationObserver.noop() }) => Effect4.gen(this, function* () {
208
+ this.run = ({ prompt, system: systemTemplate, history = [], objects = [], blueprints = [], toolkit, observer = GenerationObserver.noop() }) => Effect3.gen(this, function* () {
229
209
  this._history = [
230
210
  ...history
231
211
  ];
232
212
  this._pending = [];
233
213
  const pending = this._pending;
234
- const submitMessage = Effect4.fnUntraced(function* (message) {
214
+ const submitMessage = Effect3.fnUntraced(function* (message) {
235
215
  pending.push(message);
236
216
  yield* observer.onMessage(message);
237
217
  yield* TracingService.emitConverationMessage(message);
@@ -258,27 +238,31 @@ var AiSession = class {
258
238
  objects: objects?.length ?? 0
259
239
  }, {
260
240
  F: __dxlog_file2,
261
- L: 104,
241
+ L: 109,
262
242
  S: this,
263
243
  C: (f, a) => f(...a)
264
244
  });
265
- const prompt2 = yield* AiPreprocessor.preprocessAiInput([
245
+ const prompt2 = yield* AiPreprocessor.preprocessPrompt([
266
246
  ...this._history,
267
247
  ...this._pending
268
- ]);
269
- const blocks = yield* AiLanguageModel.streamText({
248
+ ], {
249
+ system
250
+ });
251
+ const blocks = yield* LanguageModel.streamText({
270
252
  prompt: prompt2,
271
- system,
272
253
  toolkit,
273
254
  disableToolCallResolution: true
274
- }).pipe(Stream.catchTag("AiError", Effect4.fnUntraced(function* (err) {
275
- return yield* Effect4.fail(yield* mapAiError(err));
276
- })), AiParser.parseResponse({
277
- onBegin: () => observer.onBegin(),
278
- onBlock: (block) => observer.onBlock(block),
279
- onPart: (part) => observer.onPart(part),
280
- onEnd: (summary) => observer.onEnd(summary)
281
- }), Stream.runCollect, Effect4.map(Chunk.toArray));
255
+ }).pipe(
256
+ // TOOD(dmaretskyi): Error mapping.
257
+ AiParser.parseResponse({
258
+ onBegin: () => observer.onBegin(),
259
+ onBlock: (block) => observer.onBlock(block),
260
+ onPart: (part) => observer.onPart(part),
261
+ onEnd: (summary) => observer.onEnd(summary)
262
+ }),
263
+ Stream.runCollect,
264
+ Effect3.map(Chunk.toArray)
265
+ );
282
266
  const response = yield* submitMessage(Obj2.make(DataType2.Message, {
283
267
  created: (/* @__PURE__ */ new Date()).toISOString(),
284
268
  sender: {
@@ -292,8 +276,8 @@ var AiSession = class {
292
276
  } else if (!toolkit) {
293
277
  throw new Error("No toolkit provided");
294
278
  }
295
- const toolResults = yield* Effect4.forEach(toolCalls, (toolCall) => {
296
- return callTool(toolkit, toolCall).pipe(Effect4.provide(TracingService.layerSubframe((context) => ({
279
+ const toolResults = yield* Effect3.forEach(toolCalls, (toolCall) => {
280
+ return callTool(toolkit, toolCall).pipe(Effect3.provide(TracingService.layerSubframe((context) => ({
297
281
  ...context,
298
282
  parentMessage: response.id,
299
283
  toolCallId: toolCall.toolCallId
@@ -302,7 +286,7 @@ var AiSession = class {
302
286
  yield* submitMessage(Obj2.make(DataType2.Message, {
303
287
  created: (/* @__PURE__ */ new Date()).toISOString(),
304
288
  sender: {
305
- role: "user"
289
+ role: "tool"
306
290
  },
307
291
  blocks: toolResults
308
292
  }));
@@ -311,12 +295,12 @@ var AiSession = class {
311
295
  pending: this._pending.length
312
296
  }, {
313
297
  F: __dxlog_file2,
314
- L: 178,
298
+ L: 180,
315
299
  S: this,
316
300
  C: (f, a) => f(...a)
317
301
  });
318
302
  return this._pending;
319
- }).pipe(this._semaphore.withPermits(1), Effect4.withSpan("AiSession.run"));
303
+ }).pipe(this._semaphore.withPermits(1), Effect3.withSpan("AiSession.run"));
320
304
  }
321
305
  };
322
306
  var createSnippet = (text, len = 32) => text.length <= len * 2 ? text : [
@@ -326,27 +310,27 @@ var createSnippet = (text, len = 32) => text.length <= len * 2 ? text : [
326
310
  ].join("");
327
311
 
328
312
  // src/session/toolkit.ts
329
- import { AiToolkit } from "@effect/ai";
330
- import { Effect as Effect5 } from "effect";
313
+ import * as Toolkit from "@effect/ai/Toolkit";
314
+ import * as Effect4 from "effect/Effect";
331
315
  import { ToolExecutionService, ToolResolverService } from "@dxos/ai";
332
- import { isNotFalsy } from "@dxos/util";
333
- var createToolkit = ({ toolkit: toolkitParam, toolIds = [], blueprints = [] }) => Effect5.gen(function* () {
316
+ import { isTruthy } from "@dxos/util";
317
+ var createToolkit = ({ toolkit: toolkitParam, toolIds = [], blueprints = [] }) => Effect4.gen(function* () {
334
318
  const blueprintToolkit = yield* ToolResolverService.resolveToolkit([
335
319
  ...blueprints.flatMap(({ tools }) => tools),
336
320
  ...toolIds
337
321
  ]);
338
322
  const blueprintToolkitHandler = yield* blueprintToolkit.toContext(ToolExecutionService.handlersFor(blueprintToolkit));
339
- const toolkit = AiToolkit.merge(...[
323
+ const toolkit = Toolkit.merge(...[
340
324
  toolkitParam,
341
325
  blueprintToolkit
342
- ].filter(isNotFalsy));
343
- return yield* toolkit.pipe(Effect5.provide(blueprintToolkitHandler));
326
+ ].filter(isTruthy));
327
+ return yield* toolkit.pipe(Effect4.provide(blueprintToolkitHandler));
344
328
  });
345
329
 
346
330
  // src/session/version-pin.ts
347
- import { Schema as Schema2 } from "effect";
331
+ import * as Schema from "effect/Schema";
332
+ import { ObjectId } from "@dxos/echo/internal";
348
333
  import { getVersion } from "@dxos/echo-db";
349
- import { ObjectId } from "@dxos/echo-schema";
350
334
  function _define_property2(obj, key, value) {
351
335
  if (key in obj) {
352
336
  Object.defineProperty(obj, key, {
@@ -361,8 +345,8 @@ function _define_property2(obj, key, value) {
361
345
  return obj;
362
346
  }
363
347
  var _class;
364
- var ObjectVersionSchema = Schema2.Unknown;
365
- var VersionPinSchema = Schema2.Struct({
348
+ var ObjectVersionSchema = Schema.Unknown;
349
+ var VersionPinSchema = Schema.Struct({
366
350
  // TODO(dmaretskyi): Use Ref when those support encoding.
367
351
  objectId: ObjectId,
368
352
  // TODO(dmaretskyi): Could be opaque.
@@ -387,10 +371,10 @@ var VersionPin = (_class = class extends VersionPinSchema {
387
371
  export {
388
372
  ArtifactDiffResolver,
389
373
  GenerationObserver,
374
+ AiModelError,
390
375
  AiAssistantError,
391
- AnthropicError,
392
376
  AiSession,
393
377
  createToolkit,
394
378
  VersionPin
395
379
  };
396
- //# sourceMappingURL=chunk-5GJYG2ML.mjs.map
380
+ //# sourceMappingURL=chunk-CWGVG235.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/session/artifact-diff.ts", "../../../src/session/observer.ts", "../../../src/errors.ts", "../../../src/session/session.ts", "../../../src/session/format.ts", "../../../src/session/toolkit.ts", "../../../src/session/version-pin.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Context from 'effect/Context';\n\nimport { type ObjectId } from '@dxos/echo/internal';\nimport { type ObjectVersion } from '@dxos/echo-db';\n\n/**\n * Resolves artifact ids to their versions.\n * Used to give the model a sense of the changes to the artifacts made by users during the conversation.\n * The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,\n * a diff is inserted into the conversation.\n *\n * Can be optionally provided to the session run call.\n */\n// TODO(dmaretskyi): Convert to Context.Reference\nexport class ArtifactDiffResolver extends Context.Tag('@dxos/assistant/ArtifactDiffResolver')<\n ArtifactDiffResolver,\n ArtifactDiffResolver.Service\n>() {}\n\nexport namespace ArtifactDiffResolver {\n export type Service = {\n resolve: (\n artifacts: {\n id: ObjectId;\n lastVersion: ObjectVersion;\n }[],\n ) => Promise<\n Map<\n ObjectId,\n {\n version: ObjectVersion;\n diff?: string;\n }\n >\n >;\n };\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Function from 'effect/Function';\n\nimport { type AiParser, type ConsolePrinter } from '@dxos/ai';\nimport { type DataType } from '@dxos/schema';\n\n/**\n * Live observer of the generation process.\n */\nexport interface GenerationObserver extends AiParser.ParseResponseCallbacks {\n /**\n * Complete messages fired during the session, both from the model and from the user.\n * This message will contain all message blocks emitted through the `onBlock` callback.\n */\n onMessage: (message: DataType.Message) => Effect.Effect<void>;\n}\n\nexport const GenerationObserver = Object.freeze({\n make: ({\n onBegin = Function.constant(Effect.void),\n onPart = Function.constant(Effect.void),\n onBlock = Function.constant(Effect.void),\n onEnd = Function.constant(Effect.void),\n onMessage = Function.constant(Effect.void),\n }: Partial<GenerationObserver> = {}): GenerationObserver => ({\n onBegin,\n onPart,\n onBlock,\n onEnd,\n onMessage,\n }),\n\n noop: () => GenerationObserver.make(),\n\n /**\n * Debug printer to be used in unit-tests and browser devtools.\n */\n fromPrinter: (printer: ConsolePrinter) =>\n GenerationObserver.make({\n onBlock: (block) =>\n Effect.sync(() => {\n if (block.pending) {\n return; // Only prints full blocks (better for unit-tests and browser devtools).\n }\n printer.printContentBlock(block);\n }),\n onMessage: (message) =>\n Effect.sync(() => {\n if (message.sender.role === 'assistant') {\n return; // Skip assistant messages since they are printed in the `onBlock` callback.\n }\n printer.printMessage(message);\n }),\n }),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { BaseError } from '@dxos/errors';\n\n/**\n * Generic error from AI model.\n */\nexport class AiModelError extends BaseError.extend('AI_MODEL_ERROR', 'AI model error') {}\n\n/**\n * Generic error for AI agent execution.\n */\nexport class AiAssistantError extends BaseError.extend('AI_ASSISTANT_ERROR', 'AI assistant error') {}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as AiError from '@effect/ai/AiError';\nimport * as LanguageModel from '@effect/ai/LanguageModel';\nimport type * as Tool from '@effect/ai/Tool';\nimport type * as Toolkit from '@effect/ai/Toolkit';\nimport * as Chunk from 'effect/Chunk';\nimport * as Effect from 'effect/Effect';\nimport type * as Schema from 'effect/Schema';\nimport * as Stream from 'effect/Stream';\n\nimport {\n AiParser,\n AiPreprocessor,\n type AiToolNotFoundError,\n type PromptPreprocessingError,\n type ToolExecutionService,\n type ToolResolverService,\n callTool,\n getToolCalls,\n} from '@dxos/ai';\nimport { type Blueprint } from '@dxos/blueprints';\nimport { todo } from '@dxos/debug';\nimport { Obj } from '@dxos/echo';\nimport { TracingService } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nimport { type AiAssistantError } from '../errors';\n\nimport { formatSystemPrompt, formatUserPrompt } from './format';\nimport { GenerationObserver } from './observer';\n\nexport type AiSessionRunError = AiError.AiError | PromptPreprocessingError | AiToolNotFoundError | AiAssistantError;\n\nexport type AiSessionRunRequirements =\n | LanguageModel.LanguageModel\n | ToolExecutionService\n | ToolResolverService\n | TracingService;\n\nexport type AiSessionRunParams<Tools extends Record<string, Tool.Any>> = {\n prompt: string;\n system?: string;\n history?: DataType.Message[];\n objects?: Obj.Any[];\n blueprints?: Blueprint.Blueprint[];\n toolkit?: Toolkit.WithHandler<Tools>;\n observer?: GenerationObserver;\n};\n\nexport type AiSessionOptions = {};\n\n/**\n * Contains message history, tools, current context.\n * Current context means the state of the app, time of day, and other contextual information.\n * It makes requests to the model, its a state machine.\n * It keeps track of the current goal.\n * It manages the context window.\n * Tracks the success criteria of reaching the goal, exposing metrics (stretch).\n * Could be run locally in the app or remotely.\n * Could be personal or shared.\n */\nexport class AiSession {\n /** Prevents concurrent execution of session. */\n private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));\n\n /** Message history from queue. */\n // TODO(burdon): Evolve into supporting a git-like graph of messages.\n private _history: DataType.Message[] = [];\n\n /** Pending messages for this session (incl. the current prompt). */\n private _pending: DataType.Message[] = [];\n\n constructor(private readonly _options: AiSessionOptions = {}) {}\n\n run = <Tools extends Record<string, Tool.Any>>({\n prompt,\n system: systemTemplate,\n history = [],\n objects = [],\n blueprints = [],\n toolkit,\n observer = GenerationObserver.noop(),\n }: AiSessionRunParams<Tools>): Effect.Effect<DataType.Message[], AiSessionRunError, AiSessionRunRequirements> =>\n Effect.gen(this, function* () {\n this._history = [...history];\n this._pending = [];\n const pending = this._pending;\n\n const submitMessage = Effect.fnUntraced(function* (message: DataType.Message) {\n pending.push(message);\n yield* observer.onMessage(message);\n yield* TracingService.emitConverationMessage(message);\n return message;\n });\n\n // Submit the prompt.\n // TODO(burdon): Remove if cancelled?\n const promptMessage = yield* submitMessage(yield* formatUserPrompt({ prompt, history }));\n\n // Generate system and prompt messages.\n const system = yield* formatSystemPrompt({ system: systemTemplate, blueprints, objects });\n\n // Tool call loop.\n do {\n log('request', {\n prompt: promptMessage,\n system: { snippet: createSnippet(system), length: system.length },\n pending: this._pending.length,\n history: this._history.length,\n objects: objects?.length ?? 0,\n });\n\n const prompt = yield* AiPreprocessor.preprocessPrompt([...this._history, ...this._pending], { system });\n\n // Execute the stream request.\n // logDump('prompt', Prompt.Prompt.pipe(Schema.encodeSync)(prompt));\n const blocks = yield* LanguageModel.streamText({\n prompt,\n toolkit,\n disableToolCallResolution: true,\n }).pipe(\n // TOOD(dmaretskyi): Error mapping.\n AiParser.parseResponse({\n onBegin: () => observer.onBegin(),\n onBlock: (block) => observer.onBlock(block),\n onPart: (part) => observer.onPart(part),\n onEnd: (summary) => observer.onEnd(summary),\n }),\n Stream.runCollect,\n Effect.map(Chunk.toArray),\n );\n\n // Create the response message.\n const response = yield* submitMessage(\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'assistant' },\n blocks,\n }),\n );\n\n // Parse the response for tool calls.\n const toolCalls = getToolCalls(response);\n if (toolCalls.length === 0) {\n break;\n } else if (!toolkit) {\n throw new Error('No toolkit provided'); // TODO(burdon): Throw user error?\n }\n\n // Execute the tool calls.\n // TODO(burdon): Retry errors? Write result when each completes individually?\n const toolResults = yield* Effect.forEach(toolCalls, (toolCall) => {\n return callTool(toolkit, toolCall).pipe(\n Effect.provide(\n TracingService.layerSubframe((context) => ({\n ...context,\n parentMessage: response.id,\n toolCallId: toolCall.toolCallId,\n })),\n ),\n );\n });\n\n // Add to queue and continue loop.\n // TODO(wittjosiah): Sometimes tool error results are added to the queue before the tool agent statuses.\n // This results in a broken execution graph.\n yield* submitMessage(\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'tool' },\n blocks: toolResults,\n }),\n );\n } while (true);\n\n log('done', { pending: this._pending.length });\n return this._pending;\n }).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiSession.run'));\n\n /**\n * @deprecated\n */\n // TODO(burdon): Implement or remove.\n async runStructured<S extends Schema.Schema.AnyNoContext>(\n _schema: S,\n _options: AiSessionRunParams<any>,\n ): Promise<Schema.Schema.Type<S>> {\n return todo();\n // const parser = structuredOutputParser(schema);\n // const result = await this.run({\n // ...options,\n // executableTools: [...(options.executableTools ?? []), parser.tool],\n // });\n // return parser.getResult(result);\n }\n}\n\nconst createSnippet = (text: string, len = 32) =>\n text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');\n\n// TODO(dmaretskyi): Extract as a general util.\nconst logDump = (message: string, data: unknown) => {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { writeFileSync } = require('node:fs');\n const path = `/tmp/log-data-${Date.now()}.json`;\n writeFileSync(path, JSON.stringify(data, null, 2));\n log.info(message, { path });\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Array from 'effect/Array';\nimport * as Effect from 'effect/Effect';\nimport * as Function from 'effect/Function';\nimport * as Option from 'effect/Option';\n\nimport { Template } from '@dxos/blueprints';\nimport { Obj } from '@dxos/echo';\nimport { type ObjectId } from '@dxos/echo/internal';\nimport { ObjectVersion } from '@dxos/echo-db';\nimport { DatabaseService } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { type ContentBlock, DataType } from '@dxos/schema';\nimport { trim } from '@dxos/util';\n\nimport { AiAssistantError } from '../errors';\n\nimport { ArtifactDiffResolver } from './artifact-diff';\nimport { type AiSessionRunParams } from './session';\n\n/**\n * Formats the system prompt.\n */\n// TODO(burdon): Move to AiPreprocessor.\nexport const formatSystemPrompt = ({\n system,\n blueprints = [],\n objects = [],\n}: Pick<AiSessionRunParams<any>, 'system' | 'blueprints' | 'objects'>) =>\n Effect.gen(function* () {\n const blueprintDefs = yield* Function.pipe(\n blueprints,\n Effect.forEach((blueprint) => Effect.succeed(blueprint.instructions)),\n Effect.flatMap(Effect.forEach((template) => DatabaseService.loadOption(template.source))),\n Effect.map(Array.filter(Option.isSome)),\n Effect.map(\n Array.map(\n (template) => trim`\n <blueprint>\n ${Template.process(template.value.content)}\n </blueprint>\n `,\n ),\n ),\n Effect.map((blueprints) =>\n blueprints.length > 0 ? ['## Blueprints Definitions', ...blueprints].join('\\n\\n') : undefined,\n ),\n );\n\n const objectDefs = yield* Function.pipe(\n objects,\n Effect.forEach((object) =>\n Effect.succeed(trim`\n <object>\n <dxn>${Obj.getDXN(object)}</dxn>\n <typename>${Obj.getTypename(object)}</typename>\n </object>\n `),\n ),\n Effect.map((objects) => (objects.length > 0 ? ['## Context Objects', ...objects].join('\\n\\n') : undefined)),\n );\n\n return yield* Function.pipe(\n Effect.succeed([system, blueprintDefs, objectDefs].filter((def): def is string => def !== undefined)),\n Effect.map((parts) => parts.join('\\n\\n')),\n );\n });\n\n/**\n * Formats the user prompt.\n */\n// TODO(burdon): Move to AiPreprocessor.\n// TODO(burdon): Convert util below to `Effect.fn` (to preserve stack info)\nexport const formatUserPrompt = ({ prompt, history = [] }: Pick<AiSessionRunParams<any>, 'prompt' | 'history'>) =>\n Effect.gen(function* () {\n const blocks: ContentBlock.Any[] = [];\n\n // TODO(dmaretskyi): Evaluate other approaches as `serviceOption` isn't represented in the type system.\n const artifactDiffResolver = yield* Effect.serviceOption(ArtifactDiffResolver);\n if (Option.isSome(artifactDiffResolver)) {\n const versions = gatherObjectVersions(history);\n const artifactDiff = yield* Effect.tryPromise({\n try: () =>\n artifactDiffResolver.value.resolve(\n [...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),\n ),\n catch: AiAssistantError.wrap({ message: 'Artifact diff resolution error' }),\n });\n\n log('version', { artifactDiff, versions });\n for (const [id, { version }] of [...artifactDiff.entries()]) {\n if (ObjectVersion.equals(version, versions.get(id)!)) {\n artifactDiff.delete(id);\n continue;\n }\n\n blocks.push({ _tag: 'anchor', objectId: id, version });\n }\n\n if (artifactDiff.size > 0) {\n blocks.push(createArtifactUpdateBlock(artifactDiff));\n }\n }\n\n return Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: [...blocks, { _tag: 'text', text: prompt }],\n });\n });\n\nconst gatherObjectVersions = (messages: DataType.Message[]): Map<ObjectId, ObjectVersion> => {\n const artifactIds = new Map<ObjectId, ObjectVersion>();\n for (const message of messages) {\n for (const block of message.blocks) {\n if (block._tag === 'anchor') {\n artifactIds.set(block.objectId, block.version as ObjectVersion);\n }\n }\n }\n\n return artifactIds;\n};\n\nconst createArtifactUpdateBlock = (\n artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,\n): ContentBlock.Any => {\n return {\n _tag: 'text',\n // TODO(dmaretskyi): Does this need to be a special content-block?\n disposition: 'artifact-update',\n text: trim`\n The following artifacts have been updated since the last message:\n ${[...artifactDiff.entries()]\n .map(([id, { diff }]) => `<changed-artifact id=\"${id}\">${diff ? `\\n${diff}` : ''}</changed-artifact>`)\n .join('\\n')}\n `,\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as Tool from '@effect/ai/Tool';\nimport * as Toolkit from '@effect/ai/Toolkit';\nimport type * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\n\nimport { type AiToolNotFoundError, ToolExecutionService, type ToolId, ToolResolverService } from '@dxos/ai';\nimport { type Blueprint } from '@dxos/blueprints';\nimport { isTruthy } from '@dxos/util';\n\nexport type ToolkitParams<Tools extends Record<string, Tool.Any>> = {\n toolkit?: Toolkit.Toolkit<Tools>;\n toolIds?: ToolId[];\n blueprints?: Blueprint.Blueprint[];\n};\n\n/**\n * Build a combined toolkit from the blueprint tools and the provided toolkit.\n */\nexport const createToolkit = <Tools extends Record<string, Tool.Any> = {}>({\n toolkit: toolkitParam,\n toolIds = [],\n blueprints = [],\n}: ToolkitParams<Tools>): Effect.Effect<\n Toolkit.WithHandler<any>,\n AiToolNotFoundError,\n ToolResolverService | ToolExecutionService | Tool.HandlersFor<Tools>\n> =>\n Effect.gen(function* () {\n const blueprintToolkit = yield* ToolResolverService.resolveToolkit([\n ...blueprints.flatMap(({ tools }) => tools),\n ...toolIds,\n ]);\n\n const blueprintToolkitHandler: Context.Context<Tool.HandlersFor<any>> = yield* blueprintToolkit.toContext(\n ToolExecutionService.handlersFor(blueprintToolkit),\n );\n\n const toolkit = Toolkit.merge(...[toolkitParam, blueprintToolkit].filter(isTruthy));\n return yield* toolkit.pipe(Effect.provide(blueprintToolkitHandler)) as any as Effect.Effect<\n Toolkit.WithHandler<any>,\n never,\n Tool.HandlersFor<Tools>\n >;\n });\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { type AnyEchoObject, ObjectId } from '@dxos/echo/internal';\nimport { type ObjectVersion } from '@dxos/echo-db';\nimport { getVersion } from '@dxos/echo-db';\nimport { type ContentBlock } from '@dxos/schema';\n\n// TODO(dmaretskyi): Extract.\nconst ObjectVersionSchema = Schema.Unknown as Schema.Schema<ObjectVersion>;\n\nconst VersionPinSchema = Schema.Struct({\n // TODO(dmaretskyi): Use Ref when those support encoding.\n objectId: ObjectId,\n // TODO(dmaretskyi): Could be opaque.\n version: ObjectVersionSchema,\n});\n\n/**\n * Used to pin a specific version of an object during the course of a conversation.\n * This allows us to detect when the object changes during the course of the conversation.\n */\nexport interface VersionPin extends Schema.Schema.Type<typeof VersionPinSchema> {}\n\nexport const VersionPin: typeof VersionPinSchema & {\n DISPOSITION: 'version-pin';\n fromObject: (object: AnyEchoObject) => VersionPin;\n createBlock: (pin: VersionPin) => ContentBlock.Any;\n} = class extends VersionPinSchema {\n static readonly DISPOSITION = 'version-pin';\n static fromObject(object: AnyEchoObject): VersionPin {\n return VersionPin.make({\n objectId: object.id,\n version: getVersion(object),\n });\n }\n\n static createBlock(pin: VersionPin): ContentBlock.Any {\n return {\n _tag: 'json',\n disposition: VersionPin.DISPOSITION,\n data: JSON.stringify(pin),\n };\n }\n};\n"],
5
+ "mappings": ";AAIA,YAAYA,aA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mBAA0BC,cAAO;;EAErCC,UAAUC;;EAEVC,SAASN;AACX,CAAA;AAQO,IAAMO,cAAAA,SAIT,cAAcL,iBAAAA;EAEhB,OAAOM,WAAWC,QAAmC;AACnD,WAAOF,WAAWG,KAAK;MACrBN,UAAUK,OAAOE;MACjBL,SAASM,WAAWH,MAAAA;IACtB,CAAA;EACF;EAEA,OAAOI,YAAYC,KAAmC;AACpD,WAAO;MACLC,MAAM;MACNC,aAAaT,WAAWU;MACxBC,MAAMC,KAAKC,UAAUN,GAAAA;IACvB;EACF;AACF,GAfEO,kBAAA,QAAgBJ,eAAc,aAAA,GAAA;",
6
+ "names": ["Context", "ArtifactDiffResolver", "Tag", "Effect", "Function", "GenerationObserver", "Object", "freeze", "make", "onBegin", "constant", "void", "onPart", "onBlock", "onEnd", "onMessage", "noop", "fromPrinter", "printer", "block", "sync", "pending", "printContentBlock", "message", "sender", "role", "printMessage", "BaseError", "AiModelError", "BaseError", "extend", "AiAssistantError", "LanguageModel", "Chunk", "Effect", "Stream", "AiParser", "AiPreprocessor", "callTool", "getToolCalls", "todo", "Obj", "TracingService", "log", "DataType", "Array", "Effect", "Function", "Option", "Template", "Obj", "ObjectVersion", "DatabaseService", "log", "DataType", "trim", "formatSystemPrompt", "system", "blueprints", "objects", "gen", "blueprintDefs", "pipe", "forEach", "blueprint", "succeed", "instructions", "flatMap", "template", "DatabaseService", "loadOption", "source", "map", "filter", "isSome", "trim", "Template", "process", "value", "content", "length", "join", "undefined", "objectDefs", "object", "Obj", "getDXN", "getTypename", "def", "parts", "formatUserPrompt", "prompt", "history", "blocks", "artifactDiffResolver", "serviceOption", "ArtifactDiffResolver", "versions", "gatherObjectVersions", "artifactDiff", "tryPromise", "try", "resolve", "entries", "id", "version", "lastVersion", "catch", "AiAssistantError", "wrap", "message", "log", "ObjectVersion", "equals", "get", "delete", "push", "_tag", "objectId", "size", "createArtifactUpdateBlock", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "text", "messages", "artifactIds", "Map", "block", "set", "disposition", "diff", "AiSession", "runStructured", "_schema", "_options", "todo", "_semaphore", "_history", "_pending", "run", "runSync", "makeSemaphore", "prompt", "system", "systemTemplate", "history", "objects", "blueprints", "toolkit", "observer", "GenerationObserver", "noop", "gen", "pending", "submitMessage", "fnUntraced", "message", "push", "onMessage", "TracingService", "emitConverationMessage", "promptMessage", "formatUserPrompt", "formatSystemPrompt", "log", "snippet", "createSnippet", "length", "AiPreprocessor", "preprocessPrompt", "blocks", "streamText", "disableToolCallResolution", "pipe", "AiParser", "parseResponse", "onBegin", "onBlock", "block", "onPart", "part", "onEnd", "summary", "runCollect", "map", "toArray", "response", "Obj", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "toolCalls", "getToolCalls", "Error", "toolResults", "forEach", "toolCall", "callTool", "provide", "layerSubframe", "context", "parentMessage", "id", "toolCallId", "withPermits", "withSpan", "text", "len", "slice", "join", "Toolkit", "Effect", "ToolExecutionService", "ToolResolverService", "isTruthy", "createToolkit", "toolkit", "toolkitParam", "toolIds", "blueprints", "gen", "blueprintToolkit", "ToolResolverService", "resolveToolkit", "flatMap", "tools", "blueprintToolkitHandler", "toContext", "ToolExecutionService", "handlersFor", "merge", "filter", "isTruthy", "pipe", "provide", "Schema", "ObjectId", "getVersion", "ObjectVersionSchema", "Unknown", "VersionPinSchema", "Struct", "objectId", "ObjectId", "version", "VersionPin", "fromObject", "object", "make", "id", "getVersion", "createBlock", "pin", "_tag", "disposition", "DISPOSITION", "data", "JSON", "stringify", "_define_property"]
7
+ }
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  AiSession
3
- } from "../chunk-5GJYG2ML.mjs";
3
+ } from "../chunk-CWGVG235.mjs";
4
4
  import {
5
5
  combineNerTokens,
6
6
  createTokenGroups,
@@ -9,9 +9,9 @@ import {
9
9
  } from "../chunk-UB26N5UF.mjs";
10
10
 
11
11
  // src/extraction/extraction.ts
12
- import { Schema } from "effect";
12
+ import * as Schema from "effect/Schema";
13
13
  import { asyncTimeout } from "@dxos/async";
14
- import { Expando } from "@dxos/echo-schema";
14
+ import { Expando } from "@dxos/echo/internal";
15
15
  import { log } from "@dxos/log";
16
16
  import { DataType } from "@dxos/schema";
17
17
  var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction.ts";
@@ -57,14 +57,14 @@ var processTranscriptMessage = async (params) => {
57
57
  // src/extraction/extraction-llm-function/extraction-llm-function.ts
58
58
  import { AiService } from "@dxos/ai";
59
59
  import { Obj } from "@dxos/echo";
60
- import { create } from "@dxos/echo-schema";
60
+ import { create } from "@dxos/echo/internal";
61
61
  import { defineFunction } from "@dxos/functions";
62
62
  import { DataType as DataType2 } from "@dxos/schema";
63
63
 
64
64
  // src/extraction/quotes.ts
65
- import { Schema as Schema2 } from "effect";
65
+ import * as Schema2 from "effect/Schema";
66
66
  import { Filter, Query } from "@dxos/echo";
67
- import { ObjectId } from "@dxos/echo-schema";
67
+ import { ObjectId } from "@dxos/echo/internal";
68
68
  import { DXN } from "@dxos/keys";
69
69
  import { log as log2 } from "@dxos/log";
70
70
  var __dxlog_file2 = "/__w/dxos/dxos/packages/core/assistant/src/extraction/quotes.ts";
@@ -111,16 +111,18 @@ var insertReferences = (text, quotes) => {
111
111
  continue;
112
112
  }
113
113
  const regex = new RegExp(quote.quote.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "gi");
114
- text = text.replace(regex, `[${quote.quote}][${DXN.fromLocalObjectId(quote.id).toString()}]`);
114
+ text = text.replace(regex, `[${quote.quote}](${DXN.fromLocalObjectId(quote.id).toString()})`);
115
115
  }
116
116
  return text;
117
117
  };
118
118
 
119
- // raw-loader:./instructions.tpl?raw
119
+ // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction-llm-function/instructions.tpl?raw
120
120
  var instructions_default = 'You are an AI assistant specialized in processing and enhancing transcripts with contextual information.\nYour task is to analyze a given transcript and extract references to the context objects.\n\nThe context and transcript are provided in the user message in `context` and `transcript` XML tags.\n\nHere are your instructions:\n\n1. Read the transcript and context information provided above.\n\n2. Process each segment of the transcript separately.\n\n3. For each segment:\n a. Analyze the content and identify relevant information from the context.\n b. Extract a number of references to the context objects that are mentioned in the segment.\n c. Output the references in the format `{ "quote": "earnings report", "id": "01JT0JP9AX0XKGZX4MV4B69VT6" }`.\n d. If there are no references, just output an empty array.\n\n4. Maintain the exact order and structure of the original transcript segments.\n\nOutput Format:\nYou have been provided with a tool that specifies output format\n\nRemember:\n- Only quote the text that is in the transcript.\n- Analyze each segment carefully before processing it.\n- Only reference objects that appear in the context and exactly by their id, If the object is not in the context, do not insert a reference. \n\nNow, process the transcript and context provided below according to these instructions.';
121
121
 
122
122
  // src/extraction/extraction-llm-function/extraction-llm-function.ts
123
123
  var extractionAnthropicFunction = defineFunction({
124
+ key: "dxos.org/function/extraction/extract-entities",
125
+ name: "Extract Entities",
124
126
  description: "Extract entities from the transcript message and add them to the message.",
125
127
  inputSchema: ExtractionInput,
126
128
  outputSchema: ExtractionOutput,
@@ -173,13 +175,15 @@ var extractionAnthropicFunction = defineFunction({
173
175
 
174
176
  // src/extraction/extraction-ner-function/extraction-ner-function.ts
175
177
  import { asyncTimeout as asyncTimeout2 } from "@dxos/async";
176
- import { create as create2 } from "@dxos/echo-schema";
178
+ import { create as create2 } from "@dxos/echo/internal";
177
179
  import { DatabaseService, defineFunction as defineFunction2 } from "@dxos/functions";
178
180
  import { invariant } from "@dxos/invariant";
179
181
  import { log as log3 } from "@dxos/log";
180
182
  import { DataType as DataType3 } from "@dxos/schema";
181
183
  var __dxlog_file3 = "/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction-ner-function/extraction-ner-function.ts";
182
184
  var extractionNerFunction = defineFunction2({
185
+ key: "dxos.org/function/extraction/extract-entities",
186
+ name: "Extract Entities",
183
187
  description: "Extracts named entities from a text",
184
188
  inputSchema: ExtractionInput,
185
189
  outputSchema: ExtractionOutput,
@@ -189,7 +193,7 @@ var extractionNerFunction = defineFunction2({
189
193
  options
190
194
  }, {
191
195
  F: __dxlog_file3,
192
- L: 27,
196
+ L: 29,
193
197
  S: void 0,
194
198
  C: (f, a) => f(...a)
195
199
  });
@@ -199,7 +203,7 @@ var extractionNerFunction = defineFunction2({
199
203
  const entitiesPromise = Promise.all(message.blocks.map(async (block) => {
200
204
  invariant(block._tag === "transcript" || block._tag === "text", void 0, {
201
205
  F: __dxlog_file3,
202
- L: 34,
206
+ L: 36,
203
207
  S: void 0,
204
208
  A: [
205
209
  "block._tag === 'transcript' || block._tag === 'text'",
@@ -213,7 +217,7 @@ var extractionNerFunction = defineFunction2({
213
217
  entities
214
218
  }, {
215
219
  F: __dxlog_file3,
216
- L: 40,
220
+ L: 42,
217
221
  S: void 0,
218
222
  C: (f, a) => f(...a)
219
223
  });
@@ -221,7 +225,7 @@ var extractionNerFunction = defineFunction2({
221
225
  const blocksWithReferences = message.blocks.map((block) => {
222
226
  invariant(block._tag === "transcript" || block._tag === "text", void 0, {
223
227
  F: __dxlog_file3,
224
- L: 47,
228
+ L: 49,
225
229
  S: void 0,
226
230
  A: [
227
231
  "block._tag === 'transcript' || block._tag === 'text'",
@@ -241,7 +245,7 @@ var extractionNerFunction = defineFunction2({
241
245
  messageWithReferences
242
246
  }, {
243
247
  F: __dxlog_file3,
244
- L: 56,
248
+ L: 58,
245
249
  S: void 0,
246
250
  C: (f, a) => f(...a)
247
251
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../../src/extraction/extraction.ts", "../../../../src/extraction/extraction-llm-function/extraction-llm-function.ts", "../../../../src/extraction/quotes.ts", "raw-loader:./instructions.tpl?raw", "../../../../src/extraction/extraction-ner-function/extraction-ner-function.ts"],
4
- "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { asyncTimeout } from '@dxos/async';\nimport { Expando } from '@dxos/echo-schema';\nimport { type FunctionDefinition, type FunctionExecutor } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nexport const ExtractionInput = Schema.Struct({\n message: DataType.Message,\n objects: Schema.optional(Schema.Array(Expando)),\n options: Schema.optional(\n Schema.Struct({\n timeout: Schema.optional(Schema.Number),\n fallbackToRaw: Schema.optional(Schema.Boolean),\n }),\n ),\n});\nexport interface ExtractionInput extends Schema.Schema.Type<typeof ExtractionInput> {}\n\nexport const ExtractionOutput = Schema.Struct({\n message: DataType.Message,\n timeElapsed: Schema.Number,\n});\nexport interface ExtractionOutput extends Schema.Schema.Type<typeof ExtractionOutput> {}\n\nexport type ProcessTranscriptMessageParams = {\n input: ExtractionInput;\n function: FunctionDefinition<ExtractionInput, ExtractionOutput>;\n executor: FunctionExecutor;\n\n options?: {\n /**\n * Timeout for the entity extraction.\n */\n timeout?: number;\n\n /**\n * Fallback to raw text if the entity extraction fails.\n * Otherwise the function will throw an error.\n * @default false\n */\n fallbackToRaw?: boolean;\n };\n};\n\nexport type ExtractionFunction = FunctionDefinition<ExtractionInput, ExtractionOutput>;\n\n/**\n * Extract entities from the transcript message and add them to the message.\n */\n// TODO(dmaretskyi): Move context to a vector search index.\nexport const processTranscriptMessage = async (params: ProcessTranscriptMessageParams): Promise<ExtractionOutput> => {\n try {\n if (params.options?.timeout && params.options.timeout > 0) {\n return await asyncTimeout(params.executor.invoke(params.function, params.input), params.options.timeout);\n } else {\n return await params.executor.invoke(params.function, params.input);\n }\n } catch (error) {\n if (params.options?.fallbackToRaw) {\n log.warn('failed to process message, falling back to raw text', { error });\n return {\n message: params.input.message,\n timeElapsed: 0,\n };\n } else {\n throw error;\n }\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// ISSUE(burdon): defineFunction\n// @ts-nocheck\n\nimport { AiService } from '@dxos/ai';\nimport { Obj } from '@dxos/echo';\nimport { create } from '@dxos/echo-schema';\nimport { type FunctionDefinition, defineFunction } from '@dxos/functions';\nimport { type ContentBlock, DataType } from '@dxos/schema';\n\nimport { AiSession } from '../../session';\nimport { ExtractionInput, ExtractionOutput } from '../extraction';\nimport { ReferencedQuotes, insertReferences } from '../quotes';\n\nimport PROMPT from './instructions.tpl?raw';\n\nexport const extractionAnthropicFunction: FunctionDefinition<ExtractionInput, ExtractionOutput> = defineFunction({\n description: 'Extract entities from the transcript message and add them to the message.',\n inputSchema: ExtractionInput,\n outputSchema: ExtractionOutput,\n handler: async ({ data: { message, objects }, context }) => {\n const startTime = performance.now();\n const ai = context.getService(AiService.AiService);\n const session = new AiSession({ operationModel: 'configured' });\n const result = await session.runStructured(ReferencedQuotes, {\n generationOptions: {\n model: '@anthropic/claude-3-5-haiku-20241022',\n },\n client: ai.client,\n systemPrompt: PROMPT,\n history: [\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: [\n {\n _tag: 'text',\n text: `<context>${JSON.stringify(objects)}</context>`,\n } satisfies ContentBlock.Text,\n {\n _tag: 'text',\n text: `<transcript>${JSON.stringify(message.blocks)}</transcript>`,\n } satisfies ContentBlock.Text,\n ],\n }),\n ],\n artifacts: [],\n prompt: '',\n tools: [],\n } as any); // TODO(burdon): Rewrite test.\n\n return {\n timeElapsed: performance.now() - startTime,\n message: create(DataType.Message, {\n ...message,\n blocks: message.blocks.map((block) =>\n block._tag !== 'transcript'\n ? block\n : {\n ...block,\n text: insertReferences(block.text, result),\n },\n ),\n }),\n };\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { Filter, Query } from '@dxos/echo';\nimport { type EchoDatabase } from '@dxos/echo-db';\nimport { ObjectId } from '@dxos/echo-schema';\nimport { DXN } from '@dxos/keys';\nimport { log } from '@dxos/log';\n\nexport const ReferencedQuotes = Schema.Struct({\n references: Schema.Array(\n Schema.Struct({\n id: Schema.String,\n quote: Schema.String, // TODO(burdon): Quote?\n }),\n )\n .pipe(Schema.mutable)\n .annotations({\n // TODO(burdon): Does this description make sense?\n description: `\n The references to the context objects that are mentioned in the transcript. \n Quote should match the original transcript text exactly, while id is the id of the context object.\n `,\n }),\n});\nexport type ReferencedQuotes = Schema.Schema.Type<typeof ReferencedQuotes>;\n\nexport const findQuotes = async (quotes: string[], db: EchoDatabase): Promise<ReferencedQuotes> => {\n const references = await Promise.all(\n quotes.map(async (quote) => {\n const { objects } = await db.query(Query.select(Filter.text(quote, { type: 'vector' }))).run();\n log.info('found quotes in vector index', { objects, quote });\n return objects.length > 0 ? [{ id: objects[0].id.toString(), quote }] : [];\n }),\n );\n return { references: references.flat() };\n};\n\n/**\n * Finds and replaces all quotes with DXNs references.\n */\n// TODO(dmaretskyi): Lookup and verifiy ids from provided context.\nexport const insertReferences = (text: string, quotes: ReferencedQuotes) => {\n for (const quote of quotes.references) {\n if (!ObjectId.isValid(quote.id)) {\n continue;\n }\n\n // Use a case-insensitive regular expression to replace the quote.\n const regex = new RegExp(quote.quote.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'gi');\n text = text.replace(regex, `[${quote.quote}][${DXN.fromLocalObjectId(quote.id).toString()}]`);\n }\n\n return text;\n};\n", "You are an AI assistant specialized in processing and enhancing transcripts with contextual information.\nYour task is to analyze a given transcript and extract references to the context objects.\n\nThe context and transcript are provided in the user message in `context` and `transcript` XML tags.\n\nHere are your instructions:\n\n1. Read the transcript and context information provided above.\n\n2. Process each segment of the transcript separately.\n\n3. For each segment:\n a. Analyze the content and identify relevant information from the context.\n b. Extract a number of references to the context objects that are mentioned in the segment.\n c. Output the references in the format `{ \"quote\": \"earnings report\", \"id\": \"01JT0JP9AX0XKGZX4MV4B69VT6\" }`.\n d. If there are no references, just output an empty array.\n\n4. Maintain the exact order and structure of the original transcript segments.\n\nOutput Format:\nYou have been provided with a tool that specifies output format\n\nRemember:\n- Only quote the text that is in the transcript.\n- Analyze each segment carefully before processing it.\n- Only reference objects that appear in the context and exactly by their id, If the object is not in the context, do not insert a reference. \n\nNow, process the transcript and context provided below according to these instructions.", "//\n// Copyright 2025 DXOS.org\n//\n\n// ISSUE(burdon): defineFunction\n// @ts-nocheck\n\nimport { asyncTimeout } from '@dxos/async';\nimport { create } from '@dxos/echo-schema';\nimport { DatabaseService, defineFunction } from '@dxos/functions';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nimport { ExtractionInput, ExtractionOutput } from '../extraction';\nimport { findQuotes, insertReferences } from '../quotes';\n\n/**\n * Named Entity Recognition model\n */\n// TODO(mykola): Make it use vector index to query objects and not pass objects as input.\nexport const extractionNerFunction = defineFunction({\n description: 'Extracts named entities from a text',\n inputSchema: ExtractionInput,\n outputSchema: ExtractionOutput,\n handler: async ({ data: { message, options }, context }) => {\n log.info('input', { message, options });\n const startTime = performance.now();\n const { db } = context.getService(DatabaseService);\n const { extractFullEntities } = await import('./named-entity-recognition');\n\n const entitiesPromise = Promise.all(\n message.blocks.map(async (block) => {\n invariant(block._tag === 'transcript' || block._tag === 'text');\n return extractFullEntities(block.text);\n }),\n ).then((entities) => entities.flat());\n const entities = options?.timeout ? await asyncTimeout(entitiesPromise, options.timeout) : await entitiesPromise;\n\n log.info('entities', { entities });\n const quoteReferences = await findQuotes(\n entities.map((entity) => entity.word),\n db,\n );\n\n const blocksWithReferences = message.blocks.map((block) => {\n invariant(block._tag === 'transcript' || block._tag === 'text');\n return { ...block, text: insertReferences(block._tag, quoteReferences) };\n });\n\n const messageWithReferences = create(DataType.Message, {\n ...message,\n blocks: blocksWithReferences,\n });\n\n log.info('output', { messageWithReferences });\n return {\n message: messageWithReferences,\n timeElapsed: performance.now() - startTime,\n };\n },\n});\n"],
5
- "mappings": ";;;;;;;;;;;AAIA,SAASA,cAAc;AAEvB,SAASC,oBAAoB;AAC7B,SAASC,eAAe;AAExB,SAASC,WAAW;AACpB,SAASC,gBAAgB;;AAElB,IAAMC,kBAAkBL,OAAOM,OAAO;EAC3CC,SAASH,SAASI;EAClBC,SAAST,OAAOU,SAASV,OAAOW,MAAMT,OAAAA,CAAAA;EACtCU,SAASZ,OAAOU,SACdV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,QAAQe,OAAOC,IAAI,OAAOC,UAAAA;AACxBC,gBAAUD,MAAME,SAAS,gBAAgBF,MAAME,SAAS,QAAA,QAAA;;;;;;;;;AACxD,aAAOR,qBAAoBM,MAAMG,IAAI;IACvC,CAAA,CAAA,EACAC,KAAK,CAACC,cAAaA,UAASC,KAAI,CAAA;AAClC,UAAMD,WAAWrB,SAASuB,UAAU,MAAMC,cAAab,iBAAiBX,QAAQuB,OAAO,IAAI,MAAMZ;AAEjGT,IAAAA,KAAIC,KAAK,YAAY;MAAEkB;IAAS,GAAA;;;;;;AAChC,UAAMI,kBAAkB,MAAMC,WAC5BL,SAASN,IAAI,CAACY,WAAWA,OAAOC,IAAI,GACpCrB,EAAAA;AAGF,UAAMsB,uBAAuB9B,QAAQe,OAAOC,IAAI,CAACC,UAAAA;AAC/CC,gBAAUD,MAAME,SAAS,gBAAgBF,MAAME,SAAS,QAAA,QAAA;;;;;;;;;AACxD,aAAO;QAAE,GAAGF;QAAOG,MAAMW,iBAAiBd,MAAME,MAAMO,eAAAA;MAAiB;IACzE,CAAA;AAEA,UAAMM,wBAAwBC,QAAOC,UAASC,SAAS;MACrD,GAAGnC;MACHe,QAAQe;IACV,CAAA;AAEA3B,IAAAA,KAAIC,KAAK,UAAU;MAAE4B;IAAsB,GAAA;;;;;;AAC3C,WAAO;MACLhC,SAASgC;MACTI,aAAa9B,YAAYC,IAAG,IAAKF;IACnC;EACF;AACF,CAAA;",
6
- "names": ["Schema", "asyncTimeout", "Expando", "log", "DataType", "ExtractionInput", "Struct", "message", "Message", "objects", "optional", "Array", "options", "timeout", "Number", "fallbackToRaw", "Boolean", "ExtractionOutput", "timeElapsed", "processTranscriptMessage", "params", "executor", "invoke", "function", "input", "error", "warn", "AiService", "Obj", "create", "defineFunction", "DataType", "Schema", "Filter", "Query", "ObjectId", "DXN", "log", "ReferencedQuotes", "Struct", "references", "Array", "id", "String", "quote", "pipe", "mutable", "annotations", "description", "findQuotes", "quotes", "db", "Promise", "all", "map", "objects", "query", "select", "text", "type", "run", "info", "length", "toString", "flat", "insertReferences", "isValid", "regex", "RegExp", "replace", "fromLocalObjectId", "extractionAnthropicFunction", "defineFunction", "description", "inputSchema", "ExtractionInput", "outputSchema", "ExtractionOutput", "handler", "data", "message", "objects", "context", "startTime", "performance", "now", "ai", "getService", "AiService", "session", "AiSession", "operationModel", "result", "runStructured", "ReferencedQuotes", "generationOptions", "model", "client", "systemPrompt", "PROMPT", "history", "Obj", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "blocks", "_tag", "text", "JSON", "stringify", "artifacts", "prompt", "tools", "timeElapsed", "create", "map", "block", "insertReferences", "asyncTimeout", "create", "DatabaseService", "defineFunction", "invariant", "log", "DataType", "extractionNerFunction", "defineFunction", "description", "inputSchema", "ExtractionInput", "outputSchema", "ExtractionOutput", "handler", "data", "message", "options", "context", "log", "info", "startTime", "performance", "now", "db", "getService", "DatabaseService", "extractFullEntities", "entitiesPromise", "Promise", "all", "blocks", "map", "block", "invariant", "_tag", "text", "then", "entities", "flat", "timeout", "asyncTimeout", "quoteReferences", "findQuotes", "entity", "word", "blocksWithReferences", "insertReferences", "messageWithReferences", "create", "DataType", "Message", "timeElapsed"]
3
+ "sources": ["../../../../src/extraction/extraction.ts", "../../../../src/extraction/extraction-llm-function/extraction-llm-function.ts", "../../../../src/extraction/quotes.ts", "raw-loader:/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction-llm-function/instructions.tpl?raw", "../../../../src/extraction/extraction-ner-function/extraction-ner-function.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { asyncTimeout } from '@dxos/async';\nimport { Expando } from '@dxos/echo/internal';\nimport { type FunctionDefinition, type FunctionExecutor } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nexport const ExtractionInput = Schema.Struct({\n message: DataType.Message,\n objects: Schema.optional(Schema.Array(Expando)),\n options: Schema.optional(\n Schema.Struct({\n timeout: Schema.optional(Schema.Number),\n fallbackToRaw: Schema.optional(Schema.Boolean),\n }),\n ),\n});\nexport interface ExtractionInput extends Schema.Schema.Type<typeof ExtractionInput> {}\n\nexport const ExtractionOutput = Schema.Struct({\n message: DataType.Message,\n timeElapsed: Schema.Number,\n});\nexport interface ExtractionOutput extends Schema.Schema.Type<typeof ExtractionOutput> {}\n\nexport type ProcessTranscriptMessageParams = {\n input: ExtractionInput;\n function: FunctionDefinition<ExtractionInput, ExtractionOutput>;\n executor: FunctionExecutor;\n\n options?: {\n /**\n * Timeout for the entity extraction.\n */\n timeout?: number;\n\n /**\n * Fallback to raw text if the entity extraction fails.\n * Otherwise the function will throw an error.\n * @default false\n */\n fallbackToRaw?: boolean;\n };\n};\n\nexport type ExtractionFunction = FunctionDefinition<ExtractionInput, ExtractionOutput>;\n\n/**\n * Extract entities from the transcript message and add them to the message.\n */\n// TODO(dmaretskyi): Move context to a vector search index.\nexport const processTranscriptMessage = async (params: ProcessTranscriptMessageParams): Promise<ExtractionOutput> => {\n try {\n if (params.options?.timeout && params.options.timeout > 0) {\n return await asyncTimeout(params.executor.invoke(params.function, params.input), params.options.timeout);\n } else {\n return await params.executor.invoke(params.function, params.input);\n }\n } catch (error) {\n if (params.options?.fallbackToRaw) {\n log.warn('failed to process message, falling back to raw text', { error });\n return {\n message: params.input.message,\n timeElapsed: 0,\n };\n } else {\n throw error;\n }\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// ISSUE(burdon): defineFunction\n// @ts-nocheck\n\nimport { AiService } from '@dxos/ai';\nimport { Obj } from '@dxos/echo';\nimport { create } from '@dxos/echo/internal';\nimport { type FunctionDefinition, defineFunction } from '@dxos/functions';\nimport { type ContentBlock, DataType } from '@dxos/schema';\n\nimport { AiSession } from '../../session';\nimport { ExtractionInput, ExtractionOutput } from '../extraction';\nimport { ReferencedQuotes, insertReferences } from '../quotes';\n\nimport PROMPT from './instructions.tpl?raw';\n\nexport const extractionAnthropicFunction: FunctionDefinition<ExtractionInput, ExtractionOutput> = defineFunction({\n key: 'dxos.org/function/extraction/extract-entities',\n name: 'Extract Entities',\n description: 'Extract entities from the transcript message and add them to the message.',\n inputSchema: ExtractionInput,\n outputSchema: ExtractionOutput,\n handler: async ({ data: { message, objects }, context }) => {\n const startTime = performance.now();\n const ai = context.getService(AiService.AiService);\n const session = new AiSession({ operationModel: 'configured' });\n const result = await session.runStructured(ReferencedQuotes, {\n generationOptions: {\n model: '@anthropic/claude-3-5-haiku-20241022',\n },\n client: ai.client,\n systemPrompt: PROMPT,\n history: [\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: [\n {\n _tag: 'text',\n text: `<context>${JSON.stringify(objects)}</context>`,\n } satisfies ContentBlock.Text,\n {\n _tag: 'text',\n text: `<transcript>${JSON.stringify(message.blocks)}</transcript>`,\n } satisfies ContentBlock.Text,\n ],\n }),\n ],\n artifacts: [],\n prompt: '',\n tools: [],\n } as any); // TODO(burdon): Rewrite test.\n\n return {\n timeElapsed: performance.now() - startTime,\n message: create(DataType.Message, {\n ...message,\n blocks: message.blocks.map((block) =>\n block._tag !== 'transcript'\n ? block\n : {\n ...block,\n text: insertReferences(block.text, result),\n },\n ),\n }),\n };\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { Filter, Query } from '@dxos/echo';\nimport { ObjectId } from '@dxos/echo/internal';\nimport { type EchoDatabase } from '@dxos/echo-db';\nimport { DXN } from '@dxos/keys';\nimport { log } from '@dxos/log';\n\nexport const ReferencedQuotes = Schema.Struct({\n references: Schema.Array(\n Schema.Struct({\n id: Schema.String,\n quote: Schema.String, // TODO(burdon): Quote?\n }),\n )\n .pipe(Schema.mutable)\n .annotations({\n // TODO(burdon): Does this description make sense?\n description: `\n The references to the context objects that are mentioned in the transcript. \n Quote should match the original transcript text exactly, while id is the id of the context object.\n `,\n }),\n});\nexport type ReferencedQuotes = Schema.Schema.Type<typeof ReferencedQuotes>;\n\nexport const findQuotes = async (quotes: string[], db: EchoDatabase): Promise<ReferencedQuotes> => {\n const references = await Promise.all(\n quotes.map(async (quote) => {\n const { objects } = await db.query(Query.select(Filter.text(quote, { type: 'vector' }))).run();\n log.info('found quotes in vector index', { objects, quote });\n return objects.length > 0 ? [{ id: objects[0].id.toString(), quote }] : [];\n }),\n );\n return { references: references.flat() };\n};\n\n/**\n * Finds and replaces all quotes with DXNs references.\n */\n// TODO(dmaretskyi): Lookup and verifiy ids from provided context.\nexport const insertReferences = (text: string, quotes: ReferencedQuotes) => {\n for (const quote of quotes.references) {\n if (!ObjectId.isValid(quote.id)) {\n continue;\n }\n\n // Use a case-insensitive regular expression to replace the quote.\n const regex = new RegExp(quote.quote.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'gi');\n text = text.replace(regex, `[${quote.quote}](${DXN.fromLocalObjectId(quote.id).toString()})`);\n }\n\n return text;\n};\n", "You are an AI assistant specialized in processing and enhancing transcripts with contextual information.\nYour task is to analyze a given transcript and extract references to the context objects.\n\nThe context and transcript are provided in the user message in `context` and `transcript` XML tags.\n\nHere are your instructions:\n\n1. Read the transcript and context information provided above.\n\n2. Process each segment of the transcript separately.\n\n3. For each segment:\n a. Analyze the content and identify relevant information from the context.\n b. Extract a number of references to the context objects that are mentioned in the segment.\n c. Output the references in the format `{ \"quote\": \"earnings report\", \"id\": \"01JT0JP9AX0XKGZX4MV4B69VT6\" }`.\n d. If there are no references, just output an empty array.\n\n4. Maintain the exact order and structure of the original transcript segments.\n\nOutput Format:\nYou have been provided with a tool that specifies output format\n\nRemember:\n- Only quote the text that is in the transcript.\n- Analyze each segment carefully before processing it.\n- Only reference objects that appear in the context and exactly by their id, If the object is not in the context, do not insert a reference. \n\nNow, process the transcript and context provided below according to these instructions.", "//\n// Copyright 2025 DXOS.org\n//\n\n// ISSUE(burdon): defineFunction\n// @ts-nocheck\n\nimport { asyncTimeout } from '@dxos/async';\nimport { create } from '@dxos/echo/internal';\nimport { DatabaseService, defineFunction } from '@dxos/functions';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nimport { ExtractionInput, ExtractionOutput } from '../extraction';\nimport { findQuotes, insertReferences } from '../quotes';\n\n/**\n * Named Entity Recognition model\n */\n// TODO(mykola): Make it use vector index to query objects and not pass objects as input.\nexport const extractionNerFunction = defineFunction({\n key: 'dxos.org/function/extraction/extract-entities',\n name: 'Extract Entities',\n description: 'Extracts named entities from a text',\n inputSchema: ExtractionInput,\n outputSchema: ExtractionOutput,\n handler: async ({ data: { message, options }, context }) => {\n log.info('input', { message, options });\n const startTime = performance.now();\n const { db } = context.getService(DatabaseService);\n const { extractFullEntities } = await import('./named-entity-recognition');\n\n const entitiesPromise = Promise.all(\n message.blocks.map(async (block) => {\n invariant(block._tag === 'transcript' || block._tag === 'text');\n return extractFullEntities(block.text);\n }),\n ).then((entities) => entities.flat());\n const entities = options?.timeout ? await asyncTimeout(entitiesPromise, options.timeout) : await entitiesPromise;\n\n log.info('entities', { entities });\n const quoteReferences = await findQuotes(\n entities.map((entity) => entity.word),\n db,\n );\n\n const blocksWithReferences = message.blocks.map((block) => {\n invariant(block._tag === 'transcript' || block._tag === 'text');\n return { ...block, text: insertReferences(block._tag, quoteReferences) };\n });\n\n const messageWithReferences = create(DataType.Message, {\n ...message,\n blocks: blocksWithReferences,\n });\n\n log.info('output', { messageWithReferences });\n return {\n message: messageWithReferences,\n timeElapsed: performance.now() - startTime,\n };\n },\n});\n"],
5
+ "mappings": ";;;;;;;;;;;AAIA,YAAYA,YAAY;AAExB,SAASC,oBAAoB;AAC7B,SAASC,eAAe;AAExB,SAASC,WAAW;AACpB,SAASC,gBAAgB;;AAElB,IAAMC,kBAAyBC,cAAO;EAC3CC,SAASH,SAASI;EAClBC,SAAgBC,gBAAgBC,aAAMT,OAAAA,CAAAA;EACtCU,SAAgBF,gBACPJ,cAAO;IACZO,SAAgBH,g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gBAAgBF,MAAME,SAAS,QAAA,QAAA;;;;;;;;;AACxD,aAAOR,qBAAoBM,MAAMG,IAAI;IACvC,CAAA,CAAA,EACAC,KAAK,CAACC,cAAaA,UAASC,KAAI,CAAA;AAClC,UAAMD,WAAWrB,SAASuB,UAAU,MAAMC,cAAab,iBAAiBX,QAAQuB,OAAO,IAAI,MAAMZ;AAEjGT,IAAAA,KAAIC,KAAK,YAAY;MAAEkB;IAAS,GAAA;;;;;;AAChC,UAAMI,kBAAkB,MAAMC,WAC5BL,SAASN,IAAI,CAACY,WAAWA,OAAOC,IAAI,GACpCrB,EAAAA;AAGF,UAAMsB,uBAAuB9B,QAAQe,OAAOC,IAAI,CAACC,UAAAA;AAC/CC,gBAAUD,MAAME,SAAS,gBAAgBF,MAAME,SAAS,QAAA,QAAA;;;;;;;;;AACxD,aAAO;QAAE,GAAGF;QAAOG,MAAMW,iBAAiBd,MAAME,MAAMO,eAAAA;MAAiB;IACzE,CAAA;AAEA,UAAMM,wBAAwBC,QAAOC,UAASC,SAAS;MACrD,GAAGnC;MACHe,QAAQe;IACV,CAAA;AAEA3B,IAAAA,KAAIC,KAAK,UAAU;MAAE4B;IAAsB,GAAA;;;;;;AAC3C,WAAO;MACLhC,SAASgC;MACTI,aAAa9B,YAAYC,IAAG,IAAKF;IACnC;EACF;AACF,CAAA;",
6
+ "names": ["Schema", "asyncTimeout", "Expando", "log", "DataType", "ExtractionInput", "Struct", "message", "Message", "objects", "optional", "Array", "options", "timeout", "Number", "fallbackToRaw", "Boolean", "ExtractionOutput", "timeElapsed", "processTranscriptMessage", "params", "executor", "invoke", "function", "input", "error", "warn", "AiService", "Obj", "create", "defineFunction", "DataType", "Schema", "Filter", "Query", "ObjectId", "DXN", "log", "ReferencedQuotes", "Struct", "references", "Array", "id", "String", "quote", "pipe", "mutable", "annotations", "description", "findQuotes", "quotes", "db", "Promise", "all", "map", "objects", "query", "select", "text", "type", "run", "info", "length", "toString", "flat", "insertReferences", "isValid", "regex", "RegExp", "replace", "fromLocalObjectId", "extractionAnthropicFunction", "defineFunction", "key", "name", "description", "inputSchema", "ExtractionInput", "outputSchema", "ExtractionOutput", "handler", "data", "message", "objects", "context", "startTime", "performance", "now", "ai", "getService", "AiService", "session", "AiSession", "operationModel", "result", "runStructured", "ReferencedQuotes", "generationOptions", "model", "client", "systemPrompt", "PROMPT", "history", "Obj", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "blocks", "_tag", "text", "JSON", "stringify", "artifacts", "prompt", "tools", "timeElapsed", "create", "map", "block", "insertReferences", "asyncTimeout", "create", "DatabaseService", "defineFunction", "invariant", "log", "DataType", "extractionNerFunction", "defineFunction", "key", "name", "description", "inputSchema", "ExtractionInput", "outputSchema", "ExtractionOutput", "handler", "data", "message", "options", "context", "log", "info", "startTime", "performance", "now", "db", "getService", "DatabaseService", "extractFullEntities", "entitiesPromise", "Promise", "all", "blocks", "map", "block", "invariant", "_tag", "text", "then", "entities", "flat", "timeout", "asyncTimeout", "quoteReferences", "findQuotes", "entity", "word", "blocksWithReferences", "insertReferences", "messageWithReferences", "create", "DataType", "Message", "timeElapsed"]
7
7
  }