@dxos/assistant 0.8.4-main.5ea62a8 → 0.8.4-main.72ec0f3

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 (117) hide show
  1. package/dist/lib/browser/chunk-J5LGTIGS.mjs +10 -0
  2. package/dist/lib/browser/extraction/index.mjs +121 -164
  3. package/dist/lib/browser/extraction/index.mjs.map +4 -4
  4. package/dist/lib/browser/index.mjs +978 -157
  5. package/dist/lib/browser/index.mjs.map +4 -4
  6. package/dist/lib/browser/meta.json +1 -1
  7. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  8. package/dist/lib/node-esm/extraction/index.mjs +121 -164
  9. package/dist/lib/node-esm/extraction/index.mjs.map +4 -4
  10. package/dist/lib/node-esm/index.mjs +978 -157
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/types/src/conversation/context.d.ts +14 -7
  14. package/dist/types/src/conversation/context.d.ts.map +1 -1
  15. package/dist/types/src/conversation/conversation.d.ts +11 -12
  16. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  17. package/dist/types/src/diff.d.ts.map +1 -1
  18. package/dist/types/src/errors.d.ts +38 -42
  19. package/dist/types/src/errors.d.ts.map +1 -1
  20. package/dist/types/src/execution-graph.d.ts +85 -0
  21. package/dist/types/src/execution-graph.d.ts.map +1 -0
  22. package/dist/types/src/execution-graph.test.d.ts +2 -0
  23. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  24. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +1 -1
  25. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  26. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +64 -53
  27. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  28. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  29. package/dist/types/src/extraction/extraction.d.ts +24 -13
  30. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  31. package/dist/types/src/extraction/quotes.d.ts +1 -1
  32. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  33. package/dist/types/src/functions/services.d.ts +18 -5
  34. package/dist/types/src/functions/services.d.ts.map +1 -1
  35. package/dist/types/src/index.d.ts +2 -1
  36. package/dist/types/src/index.d.ts.map +1 -1
  37. package/dist/types/src/session/GenericToolkit.d.ts +84 -0
  38. package/dist/types/src/session/GenericToolkit.d.ts.map +1 -0
  39. package/dist/types/src/session/artifact-diff.d.ts +2 -2
  40. package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
  41. package/dist/types/src/session/error-handling.d.ts +2 -2
  42. package/dist/types/src/session/error-handling.d.ts.map +1 -1
  43. package/dist/types/src/session/format.d.ts +4 -174
  44. package/dist/types/src/session/format.d.ts.map +1 -1
  45. package/dist/types/src/session/index.d.ts +1 -0
  46. package/dist/types/src/session/index.d.ts.map +1 -1
  47. package/dist/types/src/session/observer.d.ts +3 -3
  48. package/dist/types/src/session/observer.d.ts.map +1 -1
  49. package/dist/types/src/session/session.d.ts +15 -11
  50. package/dist/types/src/session/session.d.ts.map +1 -1
  51. package/dist/types/src/session/toolkit.d.ts +7 -6
  52. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  53. package/dist/types/src/session/version-pin.d.ts +3 -3
  54. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  55. package/dist/types/src/types/artifact.d.ts +20 -0
  56. package/dist/types/src/types/artifact.d.ts.map +1 -0
  57. package/dist/types/src/types/index.d.ts +2 -0
  58. package/dist/types/src/types/index.d.ts.map +1 -0
  59. package/dist/types/tsconfig.tsbuildinfo +1 -1
  60. package/package.json +29 -32
  61. package/src/conversation/context.ts +49 -17
  62. package/src/conversation/conversation.ts +30 -25
  63. package/src/diff.test.ts +3 -3
  64. package/src/diff.ts +7 -0
  65. package/src/errors.ts +4 -4
  66. package/src/execution-graph.test.ts +740 -0
  67. package/src/execution-graph.ts +509 -0
  68. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +9 -9
  69. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +47 -55
  70. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +16 -16
  71. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +42 -43
  72. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  73. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +2 -0
  74. package/src/extraction/extraction.ts +7 -6
  75. package/src/extraction/quotes.test.ts +2 -2
  76. package/src/extraction/quotes.ts +3 -3
  77. package/src/functions/services.ts +93 -50
  78. package/src/index.ts +2 -1
  79. package/src/session/GenericToolkit.ts +130 -0
  80. package/src/session/artifact-diff.ts +2 -2
  81. package/src/session/error-handling.ts +11 -6
  82. package/src/session/format.test.ts +5 -4
  83. package/src/session/format.ts +19 -14
  84. package/src/session/index.ts +2 -0
  85. package/src/session/observer.ts +4 -3
  86. package/src/session/session.conversations.json +1 -0
  87. package/src/session/session.test.ts +51 -210
  88. package/src/session/session.ts +41 -29
  89. package/src/session/toolkit.ts +19 -13
  90. package/src/session/version-pin.ts +4 -5
  91. package/src/templates/{format.tpl → instructions/format.tpl} +4 -2
  92. package/src/templates/{system.tpl → instructions/system.tpl} +10 -12
  93. package/src/templates/system.ts +2 -2
  94. package/src/{types.ts → types/artifact.ts} +22 -3
  95. package/src/types/index.ts +5 -0
  96. package/dist/lib/browser/chunk-6WRGDEMH.mjs +0 -89
  97. package/dist/lib/browser/chunk-6WRGDEMH.mjs.map +0 -7
  98. package/dist/lib/browser/chunk-N4O3C3T5.mjs +0 -396
  99. package/dist/lib/browser/chunk-N4O3C3T5.mjs.map +0 -7
  100. package/dist/lib/browser/named-entity-recognition-O46UTCLR.mjs +0 -13
  101. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs +0 -91
  102. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs.map +0 -7
  103. package/dist/lib/node-esm/chunk-QVJ7EAM2.mjs +0 -398
  104. package/dist/lib/node-esm/chunk-QVJ7EAM2.mjs.map +0 -7
  105. package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs +0 -14
  106. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  107. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  108. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  109. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  110. package/dist/types/src/types.d.ts +0 -16
  111. package/dist/types/src/types.d.ts.map +0 -1
  112. package/src/session/__snapshots__/session.test.ts.snap +0 -32
  113. package/src/session/version-pin.test.ts +0 -7
  114. package/src/summarization/summarization.test.ts +0 -197
  115. /package/dist/lib/browser/{named-entity-recognition-O46UTCLR.mjs.map → chunk-J5LGTIGS.mjs.map} +0 -0
  116. /package/dist/lib/node-esm/{named-entity-recognition-W4VMRCH6.mjs.map → chunk-HSLMI22Q.mjs.map} +0 -0
  117. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -2,14 +2,20 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { type AiError, AiLanguageModel, type AiTool, type AiToolkit } from '@effect/ai';
6
- import { Chunk, Effect, type Schema, Stream } from 'effect';
5
+ import type * as AiError from '@effect/ai/AiError';
6
+ import * as LanguageModel from '@effect/ai/LanguageModel';
7
+ import type * as Tool from '@effect/ai/Tool';
8
+ import type * as Toolkit from '@effect/ai/Toolkit';
9
+ import * as Chunk from 'effect/Chunk';
10
+ import * as Effect from 'effect/Effect';
11
+ import type * as Schema from 'effect/Schema';
12
+ import * as Stream from 'effect/Stream';
7
13
 
8
14
  import {
9
- type AiInputPreprocessingError,
10
15
  AiParser,
11
16
  AiPreprocessor,
12
17
  type AiToolNotFoundError,
18
+ type PromptPreprocessingError,
13
19
  type ToolExecutionService,
14
20
  type ToolResolverService,
15
21
  callTool,
@@ -20,29 +26,29 @@ import { todo } from '@dxos/debug';
20
26
  import { Obj } from '@dxos/echo';
21
27
  import { TracingService } from '@dxos/functions';
22
28
  import { log } from '@dxos/log';
23
- import { DataType } from '@dxos/schema';
29
+ import { Message } from '@dxos/types';
24
30
 
25
31
  import { type AiAssistantError } from '../errors';
26
32
 
27
- import { mapAiError } from './error-handling';
28
33
  import { formatSystemPrompt, formatUserPrompt } from './format';
29
34
  import { GenerationObserver } from './observer';
30
35
 
31
- export type AiSessionRunError = AiError.AiError | AiInputPreprocessingError | AiToolNotFoundError | AiAssistantError;
36
+ export type AiSessionRunError = AiError.AiError | PromptPreprocessingError | AiToolNotFoundError | AiAssistantError;
32
37
 
33
38
  export type AiSessionRunRequirements =
34
- | AiLanguageModel.AiLanguageModel
39
+ | LanguageModel.LanguageModel
35
40
  | ToolExecutionService
36
41
  | ToolResolverService
37
42
  | TracingService;
38
43
 
39
- export type AiSessionRunParams<Tools extends AiTool.Any> = {
44
+ export type AiSessionRunParams<Tools extends Record<string, Tool.Any>> = {
40
45
  prompt: string;
46
+ // TODO(wittjosiah): Rename to systemPrompt.
41
47
  system?: string;
42
- history?: DataType.Message[];
48
+ history?: Message.Message[];
43
49
  objects?: Obj.Any[];
44
50
  blueprints?: Blueprint.Blueprint[];
45
- toolkit?: AiToolkit.ToHandler<Tools>;
51
+ toolkit?: Toolkit.WithHandler<Tools>;
46
52
  observer?: GenerationObserver;
47
53
  };
48
54
 
@@ -64,14 +70,14 @@ export class AiSession {
64
70
 
65
71
  /** Message history from queue. */
66
72
  // TODO(burdon): Evolve into supporting a git-like graph of messages.
67
- private _history: DataType.Message[] = [];
73
+ private _history: Message.Message[] = [];
68
74
 
69
75
  /** Pending messages for this session (incl. the current prompt). */
70
- private _pending: DataType.Message[] = [];
76
+ private _pending: Message.Message[] = [];
71
77
 
72
78
  constructor(private readonly _options: AiSessionOptions = {}) {}
73
79
 
74
- run = <Tools extends AiTool.Any>({
80
+ run = <Tools extends Record<string, Tool.Any>>({
75
81
  prompt,
76
82
  system: systemTemplate,
77
83
  history = [],
@@ -79,13 +85,13 @@ export class AiSession {
79
85
  blueprints = [],
80
86
  toolkit,
81
87
  observer = GenerationObserver.noop(),
82
- }: AiSessionRunParams<Tools>): Effect.Effect<DataType.Message[], AiSessionRunError, AiSessionRunRequirements> =>
88
+ }: AiSessionRunParams<Tools>): Effect.Effect<Message.Message[], AiSessionRunError, AiSessionRunRequirements> =>
83
89
  Effect.gen(this, function* () {
84
90
  this._history = [...history];
85
91
  this._pending = [];
86
92
  const pending = this._pending;
87
93
 
88
- const submitMessage = Effect.fnUntraced(function* (message: DataType.Message) {
94
+ const submitMessage = Effect.fnUntraced(function* (message: Message.Message) {
89
95
  pending.push(message);
90
96
  yield* observer.onMessage(message);
91
97
  yield* TracingService.emitConverationMessage(message);
@@ -101,7 +107,7 @@ export class AiSession {
101
107
 
102
108
  // Tool call loop.
103
109
  do {
104
- log.info('request', {
110
+ log('request', {
105
111
  prompt: promptMessage,
106
112
  system: { snippet: createSnippet(system), length: system.length },
107
113
  pending: this._pending.length,
@@ -109,21 +115,16 @@ export class AiSession {
109
115
  objects: objects?.length ?? 0,
110
116
  });
111
117
 
112
- const prompt = yield* AiPreprocessor.preprocessAiInput([...this._history, ...this._pending]);
118
+ const prompt = yield* AiPreprocessor.preprocessPrompt([...this._history, ...this._pending], { system });
113
119
 
114
120
  // Execute the stream request.
115
- const blocks = yield* AiLanguageModel.streamText({
121
+ // logDump('prompt', Prompt.Prompt.pipe(Schema.encodeSync)(prompt));
122
+ const blocks = yield* LanguageModel.streamText({
116
123
  prompt,
117
- system,
118
124
  toolkit,
119
125
  disableToolCallResolution: true,
120
126
  }).pipe(
121
- Stream.catchTag(
122
- 'AiError',
123
- Effect.fnUntraced(function* (err) {
124
- return yield* Effect.fail(yield* mapAiError(err));
125
- }),
126
- ),
127
+ // TOOD(dmaretskyi): Error mapping.
127
128
  AiParser.parseResponse({
128
129
  onBegin: () => observer.onBegin(),
129
130
  onBlock: (block) => observer.onBlock(block),
@@ -136,7 +137,7 @@ export class AiSession {
136
137
 
137
138
  // Create the response message.
138
139
  const response = yield* submitMessage(
139
- Obj.make(DataType.Message, {
140
+ Obj.make(Message.Message, {
140
141
  created: new Date().toISOString(),
141
142
  sender: { role: 'assistant' },
142
143
  blocks,
@@ -166,10 +167,12 @@ export class AiSession {
166
167
  });
167
168
 
168
169
  // Add to queue and continue loop.
170
+ // TODO(wittjosiah): Sometimes tool error results are added to the queue before the tool agent statuses.
171
+ // This results in a broken execution graph.
169
172
  yield* submitMessage(
170
- Obj.make(DataType.Message, {
173
+ Obj.make(Message.Message, {
171
174
  created: new Date().toISOString(),
172
- sender: { role: 'user' },
175
+ sender: { role: 'tool' },
173
176
  blocks: toolResults,
174
177
  }),
175
178
  );
@@ -185,7 +188,7 @@ export class AiSession {
185
188
  // TODO(burdon): Implement or remove.
186
189
  async runStructured<S extends Schema.Schema.AnyNoContext>(
187
190
  _schema: S,
188
- _options: AiSessionRunParams<AiTool.Any>,
191
+ _options: AiSessionRunParams<any>,
189
192
  ): Promise<Schema.Schema.Type<S>> {
190
193
  return todo();
191
194
  // const parser = structuredOutputParser(schema);
@@ -199,3 +202,12 @@ export class AiSession {
199
202
 
200
203
  const createSnippet = (text: string, len = 32) =>
201
204
  text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');
205
+
206
+ // TODO(dmaretskyi): Extract as a general util.
207
+ const logDump = (message: string, data: unknown) => {
208
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
209
+ const { writeFileSync } = require('node:fs');
210
+ const path = `/tmp/log-data-${Date.now()}.json`;
211
+ writeFileSync(path, JSON.stringify(data, null, 2));
212
+ log.info(message, { path });
213
+ };
@@ -2,15 +2,17 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { type AiTool, AiToolkit } from '@effect/ai';
6
- import { type Context, Effect } from 'effect';
5
+ import type * as Tool from '@effect/ai/Tool';
6
+ import * as Toolkit from '@effect/ai/Toolkit';
7
+ import type * as Context from 'effect/Context';
8
+ import * as Effect from 'effect/Effect';
7
9
 
8
- import { ToolExecutionService, type ToolId, ToolResolverService } from '@dxos/ai';
10
+ import { type AiToolNotFoundError, ToolExecutionService, type ToolId, ToolResolverService } from '@dxos/ai';
9
11
  import { type Blueprint } from '@dxos/blueprints';
10
- import { isNotFalsy } from '@dxos/util';
12
+ import { isTruthy } from '@dxos/util';
11
13
 
12
- export type ToolkitParams<Tools extends AiTool.Any> = {
13
- toolkit?: AiToolkit.AiToolkit<Tools>;
14
+ export type ToolkitParams<Tools extends Record<string, Tool.Any>> = {
15
+ toolkit?: Toolkit.Toolkit<Tools>;
14
16
  toolIds?: ToolId[];
15
17
  blueprints?: Blueprint.Blueprint[];
16
18
  };
@@ -18,25 +20,29 @@ export type ToolkitParams<Tools extends AiTool.Any> = {
18
20
  /**
19
21
  * Build a combined toolkit from the blueprint tools and the provided toolkit.
20
22
  */
21
- export const createToolkit = <Tools extends AiTool.Any>({
23
+ export const createToolkit = <Tools extends Record<string, Tool.Any> = {}>({
22
24
  toolkit: toolkitParam,
23
25
  toolIds = [],
24
26
  blueprints = [],
25
- }: ToolkitParams<Tools>) =>
27
+ }: ToolkitParams<Tools>): Effect.Effect<
28
+ Toolkit.WithHandler<any>,
29
+ AiToolNotFoundError,
30
+ ToolResolverService | ToolExecutionService | Tool.HandlersFor<Tools>
31
+ > =>
26
32
  Effect.gen(function* () {
27
33
  const blueprintToolkit = yield* ToolResolverService.resolveToolkit([
28
34
  ...blueprints.flatMap(({ tools }) => tools),
29
35
  ...toolIds,
30
36
  ]);
31
37
 
32
- const blueprintToolkitHandler: Context.Context<AiTool.ToHandler<AiTool.Any>> = yield* blueprintToolkit.toContext(
38
+ const blueprintToolkitHandler: Context.Context<Tool.HandlersFor<any>> = yield* blueprintToolkit.toContext(
33
39
  ToolExecutionService.handlersFor(blueprintToolkit),
34
40
  );
35
41
 
36
- const toolkit = AiToolkit.merge(...[toolkitParam, blueprintToolkit].filter(isNotFalsy));
37
- return yield* toolkit.pipe(Effect.provide(blueprintToolkitHandler)) as Effect.Effect<
38
- AiToolkit.ToHandler<any>,
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>,
39
45
  never,
40
- AiTool.ToHandler<Tools>
46
+ Tool.HandlersFor<Tools>
41
47
  >;
42
48
  });
@@ -2,12 +2,11 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Schema } from 'effect';
5
+ import * as Schema from 'effect/Schema';
6
6
 
7
- import { type ObjectVersion } from '@dxos/echo-db';
8
- import { getVersion } from '@dxos/echo-db';
9
- import { type AnyEchoObject, ObjectId } from '@dxos/echo-schema';
10
- import { type ContentBlock } from '@dxos/schema';
7
+ import { type AnyEchoObject, ObjectId } from '@dxos/echo/internal';
8
+ import { type ObjectVersion, getVersion } from '@dxos/echo-db';
9
+ import { type ContentBlock } from '@dxos/types';
11
10
 
12
11
  // TODO(dmaretskyi): Extract.
13
12
  const ObjectVersionSchema = Schema.Unknown as Schema.Schema<ObjectVersion>;
@@ -23,6 +23,7 @@ The <typename> element is the type of the object.
23
23
  It is very important to respond in the correct format.
24
24
  You response must be valid Markdown.
25
25
  In some cases you should respond with well-formed XML tags along with the content.
26
+ Code snippets should use 2-space indents.
26
27
 
27
28
  {{#if cot}}
28
29
  Before responding, explain your reasoning and include your detailed chain-of-thought enclosed in a <cot> tag.
@@ -42,8 +43,9 @@ You can reply with a block reference for objects if you have the DXN. For exampl
42
43
 
43
44
  ### Suggestions
44
45
 
45
- Each suggestion must in the form of a proposed action enclosed in a <suggest> tag.
46
- Example: <suggest>Show on a map</suggest>
46
+ Each suggestion must in the form of a proposed action enclosed in a <suggestion> tag.
47
+ Example: <suggestion>Show on a map</suggestion>
48
+ Do not use bullets when listing suggestions.
47
49
 
48
50
  ### Multiple choice questions
49
51
 
@@ -1,17 +1,15 @@
1
1
  {{! System Prompt }}
2
2
 
3
- You are a helpful assistant called Kai.
4
- Your name is Kai and you are powered by different language models.
5
- You were created by DXOS and operate in Composer and on the DXOS EDGE network.
6
- In your initial greeting state your name and make some suggestions based on the current context objects.
3
+ - You are a helpful assistant called Kai.
4
+ - Your name is Kai and you are powered by different language models.
5
+ - You were created by DXOS and operate inside of Composer and on the DXOS EDGE network.
6
+ - In your initial greeting state your name and make some suggestions based on the current context objects.
7
+ - You are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.
8
+ - Your task is to process user commands and questions and decide how best to respond.
9
+ - In general be concise and direct.
10
+ - Follow all instructions carefully.
7
11
 
8
- You are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.
9
- Your task is to process user commands and questions and decide how best to respond.
10
- In general be concise and direct.
11
-
12
- Follow these instructions carefully.
13
-
14
- ## Include the following steps
12
+ ## Planning
15
13
 
16
14
  - Analyze the structure and type of the content in the user's message.
17
15
  - Determine if you complete the task using the available blueprint definitions?
@@ -27,7 +25,7 @@ Follow these instructions carefully.
27
25
  - Call the show tool to show the artifact to the user.
28
26
  - Your reasoning must include: whether to use artifacts or not, to create one or query, whether to show the artifact to the user, and how to structure the response.
29
27
 
30
- ## Blueprints
28
+ ## Blueprints and Artifacts
31
29
 
32
30
  - Determine if the interaction involves an artifact. Prefer artifacts for tables, lists, spreadsheets, kanbans, games, images, and other structured data.
33
31
  - Determine if the user is explicitly talking about creating a new artifact, or wants to use an existing artifact.
@@ -7,8 +7,8 @@ import defaultsDeep from 'lodash.defaultsdeep';
7
7
  import { type ModelCapabilities } from '@dxos/ai';
8
8
  import { Template } from '@dxos/blueprints';
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.
@@ -2,9 +2,12 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Schema } from 'effect';
5
+ import type * as Effect from 'effect/Effect';
6
+ import * as Schema from 'effect/Schema';
6
7
 
7
- import { type ObjectId } from '@dxos/echo-schema';
8
+ import { type ObjectNotFoundError, type Type } from '@dxos/echo';
9
+ import { type ObjectId } from '@dxos/echo/internal';
10
+ import { DatabaseService } from '@dxos/echo-db';
8
11
  import { DXN, LOCAL_SPACE_TAG, type SpaceId } from '@dxos/keys';
9
12
  import { trim } from '@dxos/util';
10
13
 
@@ -17,10 +20,15 @@ export const createArtifactElement = (id: ObjectId) => `<artifact id=${id} />`;
17
20
  * A model-friendly way to reference an object.
18
21
  * Supports vairous formats that will be normalized to a DXN.
19
22
  */
20
- // TODO(burdon): Rename ObjectReference?
23
+ // TODO(burdon): Rename RefFromLLM?
21
24
  export const ArtifactId: Schema.Schema<string> & {
22
25
  toDXN: (reference: ArtifactId, owningSpaceId?: SpaceId) => DXN;
26
+ resolve: <S extends Type.Obj.Any | Type.Relation.Any>(
27
+ schema: S,
28
+ ref: ArtifactId,
29
+ ) => Effect.Effect<Schema.Schema.Type<S>, ObjectNotFoundError, DatabaseService>;
23
30
  } = class extends Schema.String.annotations({
31
+ // TODO(dmaretskyi): This section gets overriden.
24
32
  description: trim`
25
33
  The ID of the referenced object. Formats accepted:
26
34
  - DXN (dxn:echo:@:XXXXX). DXNs can be prepended with an @ symbol for compatibility with in-text references.
@@ -47,6 +55,17 @@ export const ArtifactId: Schema.Schema<string> & {
47
55
  throw new Error(`Unable to parse object reference: ${reference}`);
48
56
  }
49
57
  }
58
+
59
+ /**
60
+ * Resolves an artifact ID to an object.
61
+ */
62
+ static resolve<S extends Type.Obj.Any | Type.Relation.Any>(
63
+ schema: S,
64
+ ref: ArtifactId,
65
+ ): Effect.Effect<Schema.Schema.Type<S>, ObjectNotFoundError, DatabaseService> {
66
+ const dxn = ArtifactId.toDXN(ref);
67
+ return DatabaseService.resolve(dxn, schema);
68
+ }
50
69
  };
51
70
 
52
71
  export type ArtifactId = Schema.Schema.Type<typeof ArtifactId>;
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ export * from './artifact';
@@ -1,89 +0,0 @@
1
- // src/extraction/extraction-ner-function/named-entity-recognition.ts
2
- import { pipeline } from "@xenova/transformers";
3
- import { log } from "@dxos/log";
4
- var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction-ner-function/named-entity-recognition.ts";
5
- var _ner;
6
- var getNer = () => {
7
- if (!_ner) {
8
- _ner = pipeline("ner", "Xenova/bert-base-NER").then((ner) => {
9
- log.info("NER model is ready", void 0, {
10
- F: __dxlog_file,
11
- L: 23,
12
- S: void 0,
13
- C: (f, a) => f(...a)
14
- });
15
- return ner;
16
- });
17
- }
18
- return _ner;
19
- };
20
- var extractFullEntities = async (text) => {
21
- const ner = await getNer();
22
- const entities = await ner(text);
23
- const tokenGroups = createTokenGroups(entities);
24
- const combinedEntities = tokenGroups.map(combineNerTokens);
25
- return combinedEntities;
26
- };
27
- var createTokenGroups = (tokens) => {
28
- const tokenGroups = [];
29
- const canBeCombined = (prevToken, currentToken) => {
30
- const [currentState, currentEntity] = currentToken.entity.split("-");
31
- const [prevState, prevEntity] = prevToken.entity.split("-");
32
- if (prevEntity !== currentEntity) {
33
- return false;
34
- }
35
- if (prevState === "O") {
36
- return false;
37
- }
38
- if (currentState === "I") {
39
- return true;
40
- }
41
- if ((prevState === "B" || prevState === "I") && currentState === "B") {
42
- return currentToken.word.startsWith("#");
43
- }
44
- return false;
45
- };
46
- for (const token of tokens) {
47
- if (tokenGroups.length === 0) {
48
- tokenGroups.push([
49
- token
50
- ]);
51
- continue;
52
- }
53
- const lastTokenGroup = tokenGroups.at(-1);
54
- if (canBeCombined(lastTokenGroup.at(-1), token)) {
55
- lastTokenGroup.push(token);
56
- continue;
57
- }
58
- tokenGroups.push([
59
- token
60
- ]);
61
- }
62
- return tokenGroups;
63
- };
64
- var combineNerTokens = (group) => {
65
- const combinedToken = {
66
- entity: group.at(0).entity.split("-")[1],
67
- score: group.reduce((acc, token) => acc + token.score, 0) / group.length,
68
- index: group.at(0).index,
69
- word: group.at(0).word,
70
- start: group.at(0).start,
71
- end: group.at(-1).end
72
- };
73
- for (const token of group.slice(1)) {
74
- if (token.word.startsWith("#")) {
75
- combinedToken.word += token.word.replace(/^#+/, "");
76
- } else {
77
- combinedToken.word += " " + token.word;
78
- }
79
- }
80
- return combinedToken;
81
- };
82
-
83
- export {
84
- getNer,
85
- extractFullEntities,
86
- createTokenGroups,
87
- combineNerTokens
88
- };
89
- //# sourceMappingURL=chunk-6WRGDEMH.mjs.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/extraction/extraction-ner-function/named-entity-recognition.ts"],
4
- "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport {\n type TokenClassificationOutput,\n type TokenClassificationPipelineType,\n type TokenClassificationSingle,\n pipeline,\n} from '@xenova/transformers';\n\nimport { log } from '@dxos/log';\n\nlet _ner: Promise<TokenClassificationPipelineType>;\n/**\n * Named Entity Recognition pipeline.\n * Initializes the pipeline on first call.\n * @returns The singleton promise that resolves to a token classification pipeline.\n */\nexport const getNer = () => {\n if (!_ner) {\n _ner = pipeline('ner', 'Xenova/bert-base-NER').then((ner) => {\n log.info('NER model is ready');\n return ner;\n });\n }\n return _ner;\n};\n\n/**\n * Extracts entities from text using the named entity recognition pipeline and does simple grouping of tokens.\n */\nexport const extractFullEntities = async (text: string): Promise<TokenClassificationSingle[]> => {\n const ner = await getNer();\n const entities = (await ner(text)) as TokenClassificationOutput;\n const tokenGroups = createTokenGroups(entities);\n const combinedEntities = tokenGroups.map(combineNerTokens);\n return combinedEntities;\n};\n\nexport const createTokenGroups = (tokens: TokenClassificationSingle[]): TokenClassificationSingle[][] => {\n const tokenGroups: TokenClassificationSingle[][] = [];\n\n const canBeCombined = (prevToken: TokenClassificationSingle, currentToken: TokenClassificationSingle) => {\n const [currentState, currentEntity] = currentToken.entity.split('-'); // B, I, O\n const [prevState, prevEntity] = prevToken.entity.split('-'); // B, I, O\n if (prevEntity !== currentEntity) {\n return false;\n }\n if (prevState === 'O') {\n return false;\n }\n if (currentState === 'I') {\n return true;\n }\n if ((prevState === 'B' || prevState === 'I') && currentState === 'B') {\n return currentToken.word.startsWith('#');\n }\n return false;\n };\n\n for (const token of tokens) {\n if (tokenGroups.length === 0) {\n tokenGroups.push([token]);\n continue;\n }\n const lastTokenGroup = tokenGroups.at(-1)!;\n if (canBeCombined(lastTokenGroup.at(-1)!, token)) {\n lastTokenGroup.push(token);\n continue;\n }\n tokenGroups.push([token]);\n }\n\n return tokenGroups;\n};\n\nexport const combineNerTokens = (group: TokenClassificationSingle[]): TokenClassificationSingle => {\n const combinedToken: TokenClassificationSingle = {\n entity: group.at(0)!.entity.split('-')[1],\n score: group.reduce((acc, token) => acc + token.score, 0) / group.length,\n index: group.at(0)!.index,\n word: group.at(0)!.word,\n start: group.at(0)!.start,\n end: group.at(-1)!.end,\n };\n\n for (const token of group.slice(1)) {\n if (token.word.startsWith('#')) {\n combinedToken.word += token.word.replace(/^#+/, '');\n } else {\n combinedToken.word += ' ' + token.word;\n }\n }\n\n return combinedToken;\n};\n"],
5
- "mappings": ";AAIA,SAIEA,gBACK;AAEP,SAASC,WAAW;;AAEpB,IAAIC;AAMG,IAAMC,SAAS,MAAA;AACpB,MAAI,CAACD,MAAM;AACTA,WAAOF,SAAS,OAAO,sBAAA,EAAwBI,KAAK,CAACC,QAAAA;AACnDJ,UAAIK,KAAK,sBAAA,QAAA;;;;;;AACT,aAAOD;IACT,CAAA;EACF;AACA,SAAOH;AACT;AAKO,IAAMK,sBAAsB,OAAOC,SAAAA;AACxC,QAAMH,MAAM,MAAMF,OAAAA;AAClB,QAAMM,WAAY,MAAMJ,IAAIG,IAAAA;AAC5B,QAAME,cAAcC,kBAAkBF,QAAAA;AACtC,QAAMG,mBAAmBF,YAAYG,IAAIC,gBAAAA;AACzC,SAAOF;AACT;AAEO,IAAMD,oBAAoB,CAACI,WAAAA;AAChC,QAAML,cAA6C,CAAA;AAEnD,QAAMM,gBAAgB,CAACC,WAAsCC,iBAAAA;AAC3D,UAAM,CAACC,cAAcC,aAAAA,IAAiBF,aAAaG,OAAOC,MAAM,GAAA;AAChE,UAAM,CAACC,WAAWC,UAAAA,IAAcP,UAAUI,OAAOC,MAAM,GAAA;AACvD,QAAIE,eAAeJ,eAAe;AAChC,aAAO;IACT;AACA,QAAIG,cAAc,KAAK;AACrB,aAAO;IACT;AACA,QAAIJ,iBAAiB,KAAK;AACxB,aAAO;IACT;AACA,SAAKI,cAAc,OAAOA,cAAc,QAAQJ,iBAAiB,KAAK;AACpE,aAAOD,aAAaO,KAAKC,WAAW,GAAA;IACtC;AACA,WAAO;EACT;AAEA,aAAWC,SAASZ,QAAQ;AAC1B,QAAIL,YAAYkB,WAAW,GAAG;AAC5BlB,kBAAYmB,KAAK;QAACF;OAAM;AACxB;IACF;AACA,UAAMG,iBAAiBpB,YAAYqB,GAAG,EAAC;AACvC,QAAIf,cAAcc,eAAeC,GAAG,EAAC,GAAKJ,KAAAA,GAAQ;AAChDG,qBAAeD,KAAKF,KAAAA;AACpB;IACF;AACAjB,gBAAYmB,KAAK;MAACF;KAAM;EAC1B;AAEA,SAAOjB;AACT;AAEO,IAAMI,mBAAmB,CAACkB,UAAAA;AAC/B,QAAMC,gBAA2C;IAC/CZ,QAAQW,MAAMD,GAAG,CAAA,EAAIV,OAAOC,MAAM,GAAA,EAAK,CAAA;IACvCY,OAAOF,MAAMG,OAAO,CAACC,KAAKT,UAAUS,MAAMT,MAAMO,OAAO,CAAA,IAAKF,MAAMJ;IAClES,OAAOL,MAAMD,GAAG,CAAA,EAAIM;IACpBZ,MAAMO,MAAMD,GAAG,CAAA,EAAIN;IACnBa,OAAON,MAAMD,GAAG,CAAA,EAAIO;IACpBC,KAAKP,MAAMD,GAAG,EAAC,EAAIQ;EACrB;AAEA,aAAWZ,SAASK,MAAMQ,MAAM,CAAA,GAAI;AAClC,QAAIb,MAAMF,KAAKC,WAAW,GAAA,GAAM;AAC9BO,oBAAcR,QAAQE,MAAMF,KAAKgB,QAAQ,OAAO,EAAA;IAClD,OAAO;AACLR,oBAAcR,QAAQ,MAAME,MAAMF;IACpC;EACF;AAEA,SAAOQ;AACT;",
6
- "names": ["pipeline", "log", "_ner", "getNer", "then", "ner", "info", "extractFullEntities", "text", "entities", "tokenGroups", "createTokenGroups", "combinedEntities", "map", "combineNerTokens", "tokens", "canBeCombined", "prevToken", "currentToken", "currentState", "currentEntity", "entity", "split", "prevState", "prevEntity", "word", "startsWith", "token", "length", "push", "lastTokenGroup", "at", "group", "combinedToken", "score", "reduce", "acc", "index", "start", "end", "slice", "replace"]
7
- }