@dxos/assistant 0.8.3 → 0.8.4-main.1da679c

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 (168) hide show
  1. package/dist/lib/browser/chunk-3K5SRE5A.mjs +404 -0
  2. package/dist/lib/browser/chunk-3K5SRE5A.mjs.map +7 -0
  3. package/dist/lib/browser/chunk-UB26N5UF.mjs +89 -0
  4. package/dist/lib/browser/chunk-UB26N5UF.mjs.map +7 -0
  5. package/dist/lib/browser/extraction/index.mjs +268 -0
  6. package/dist/lib/browser/extraction/index.mjs.map +7 -0
  7. package/dist/lib/browser/index.mjs +412 -2101
  8. package/dist/lib/browser/index.mjs.map +4 -4
  9. package/dist/lib/browser/meta.json +1 -1
  10. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs +13 -0
  11. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs.map +7 -0
  12. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs +91 -0
  13. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs.map +7 -0
  14. package/dist/lib/node-esm/chunk-W7AIB6DP.mjs +406 -0
  15. package/dist/lib/node-esm/chunk-W7AIB6DP.mjs.map +7 -0
  16. package/dist/lib/node-esm/extraction/index.mjs +269 -0
  17. package/dist/lib/node-esm/extraction/index.mjs.map +7 -0
  18. package/dist/lib/node-esm/index.mjs +412 -2102
  19. package/dist/lib/node-esm/index.mjs.map +4 -4
  20. package/dist/lib/node-esm/meta.json +1 -1
  21. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs +14 -0
  22. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs.map +7 -0
  23. package/dist/types/src/conversation/context.d.ts +96 -0
  24. package/dist/types/src/conversation/context.d.ts.map +1 -0
  25. package/dist/types/src/conversation/conversation.d.ts +42 -0
  26. package/dist/types/src/conversation/conversation.d.ts.map +1 -0
  27. package/dist/types/src/conversation/index.d.ts +3 -0
  28. package/dist/types/src/conversation/index.d.ts.map +1 -0
  29. package/dist/types/src/diff.d.ts +15 -0
  30. package/dist/types/src/diff.d.ts.map +1 -0
  31. package/dist/types/src/diff.test.d.ts +2 -0
  32. package/dist/types/src/diff.test.d.ts.map +1 -0
  33. package/dist/types/src/errors.d.ts +75 -0
  34. package/dist/types/src/errors.d.ts.map +1 -0
  35. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +1 -1
  36. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  37. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +177 -48
  38. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  39. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts +1 -1
  40. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  41. package/dist/types/src/extraction/extraction.d.ts +250 -162
  42. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  43. package/dist/types/src/functions/index.d.ts +2 -0
  44. package/dist/types/src/functions/index.d.ts.map +1 -0
  45. package/dist/types/src/functions/services.d.ts +7 -0
  46. package/dist/types/src/functions/services.d.ts.map +1 -0
  47. package/dist/types/src/index.d.ts +5 -3
  48. package/dist/types/src/index.d.ts.map +1 -1
  49. package/dist/types/src/session/artifact-diff.d.ts +27 -0
  50. package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
  51. package/dist/types/src/session/error-handling.d.ts +4 -0
  52. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  53. package/dist/types/src/session/format.d.ts +182 -0
  54. package/dist/types/src/session/format.d.ts.map +1 -0
  55. package/dist/types/src/session/format.test.d.ts +2 -0
  56. package/dist/types/src/session/format.test.d.ts.map +1 -0
  57. package/dist/types/src/session/index.d.ts +3 -0
  58. package/dist/types/src/session/index.d.ts.map +1 -1
  59. package/dist/types/src/session/observer.d.ts +22 -0
  60. package/dist/types/src/session/observer.d.ts.map +1 -0
  61. package/dist/types/src/session/session.d.ts +32 -246
  62. package/dist/types/src/session/session.d.ts.map +1 -1
  63. package/dist/types/src/session/toolkit.d.ts +14 -0
  64. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  65. package/dist/types/src/session/version-pin.d.ts +4 -4
  66. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  67. package/dist/types/src/templates/index.d.ts +2 -0
  68. package/dist/types/src/templates/index.d.ts.map +1 -0
  69. package/dist/types/src/templates/system.d.ts +18 -0
  70. package/dist/types/src/templates/system.d.ts.map +1 -0
  71. package/dist/types/src/types.d.ts +13 -0
  72. package/dist/types/src/types.d.ts.map +1 -1
  73. package/dist/types/tsconfig.tsbuildinfo +1 -1
  74. package/package.json +48 -32
  75. package/src/conversation/context.ts +154 -0
  76. package/src/conversation/conversation.ts +123 -0
  77. package/src/conversation/index.ts +6 -0
  78. package/src/diff.test.ts +43 -0
  79. package/src/diff.ts +79 -0
  80. package/src/errors.ts +15 -0
  81. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +13 -24
  82. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +25 -20
  83. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +9 -9
  84. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +15 -7
  85. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +2 -2
  86. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +3 -1
  87. package/src/extraction/quotes.test.ts +3 -3
  88. package/src/extraction/quotes.ts +2 -2
  89. package/src/functions/index.ts +5 -0
  90. package/src/functions/services.ts +119 -0
  91. package/src/index.ts +5 -3
  92. package/src/session/__snapshots__/session.test.ts.snap +32 -0
  93. package/src/session/artifact-diff.ts +41 -0
  94. package/src/session/error-handling.ts +39 -0
  95. package/src/session/format.test.ts +60 -0
  96. package/src/session/format.ts +139 -0
  97. package/src/session/index.ts +3 -0
  98. package/src/session/observer.ts +58 -0
  99. package/src/session/session.test.ts +98 -19
  100. package/src/session/session.ts +159 -507
  101. package/src/session/toolkit.ts +42 -0
  102. package/src/session/version-pin.test.ts +2 -21
  103. package/src/session/version-pin.ts +9 -9
  104. package/src/summarization/summarization.test.ts +82 -106
  105. package/src/templates/format.tpl +60 -0
  106. package/src/templates/index.ts +5 -0
  107. package/src/templates/system.tpl +48 -0
  108. package/src/templates/system.ts +41 -0
  109. package/src/types.ts +45 -1
  110. package/src/typings.d.ts +5 -0
  111. package/dist/lib/node/index.cjs +0 -2178
  112. package/dist/lib/node/index.cjs.map +0 -7
  113. package/dist/lib/node/meta.json +0 -1
  114. package/dist/types/bin/chat.d.ts +0 -2
  115. package/dist/types/bin/chat.d.ts.map +0 -1
  116. package/dist/types/src/blueprint/ai.test.d.ts +0 -2
  117. package/dist/types/src/blueprint/ai.test.d.ts.map +0 -1
  118. package/dist/types/src/blueprint/blueprint.d.ts +0 -55
  119. package/dist/types/src/blueprint/blueprint.d.ts.map +0 -1
  120. package/dist/types/src/blueprint/blueprint.test.d.ts +0 -2
  121. package/dist/types/src/blueprint/blueprint.test.d.ts.map +0 -1
  122. package/dist/types/src/blueprint/index.d.ts +0 -4
  123. package/dist/types/src/blueprint/index.d.ts.map +0 -1
  124. package/dist/types/src/blueprint/logger.d.ts +0 -25
  125. package/dist/types/src/blueprint/logger.d.ts.map +0 -1
  126. package/dist/types/src/blueprint/machine.d.ts +0 -143
  127. package/dist/types/src/blueprint/machine.d.ts.map +0 -1
  128. package/dist/types/src/blueprint/test-data.d.ts +0 -3
  129. package/dist/types/src/blueprint/test-data.d.ts.map +0 -1
  130. package/dist/types/src/research/exa.d.ts +0 -7
  131. package/dist/types/src/research/exa.d.ts.map +0 -1
  132. package/dist/types/src/research/graph.d.ts +0 -41
  133. package/dist/types/src/research/graph.d.ts.map +0 -1
  134. package/dist/types/src/research/graph.test.d.ts +0 -2
  135. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  136. package/dist/types/src/research/index.d.ts +0 -4
  137. package/dist/types/src/research/index.d.ts.map +0 -1
  138. package/dist/types/src/research/research.d.ts +0 -10
  139. package/dist/types/src/research/research.d.ts.map +0 -1
  140. package/dist/types/src/research/research.test.d.ts +0 -2
  141. package/dist/types/src/research/research.test.d.ts.map +0 -1
  142. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  143. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  144. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  145. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  146. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  147. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  148. package/dist/types/src/testing/index.d.ts +0 -3
  149. package/dist/types/src/testing/index.d.ts.map +0 -1
  150. package/src/blueprint/ai.test.ts +0 -156
  151. package/src/blueprint/blueprint.test.ts +0 -151
  152. package/src/blueprint/blueprint.ts +0 -75
  153. package/src/blueprint/index.ts +0 -7
  154. package/src/blueprint/logger.ts +0 -155
  155. package/src/blueprint/machine.ts +0 -251
  156. package/src/blueprint/test-data.ts +0 -55
  157. package/src/research/exa.ts +0 -100
  158. package/src/research/graph.test.ts +0 -15
  159. package/src/research/graph.ts +0 -337
  160. package/src/research/index.ts +0 -7
  161. package/src/research/instructions-research.tpl +0 -97
  162. package/src/research/research.test.ts +0 -190
  163. package/src/research/research.ts +0 -89
  164. package/src/testing/exa-search-1748337321991.ts +0 -131
  165. package/src/testing/exa-search-1748337331526.ts +0 -144
  166. package/src/testing/exa-search-1748337344119.ts +0 -133
  167. package/src/testing/index.ts +0 -11
  168. package/src/typedefs.d.ts +0 -8
@@ -2,25 +2,29 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Message } from '@dxos/ai';
5
+ // ISSUE(burdon): defineFunction
6
+ // @ts-nocheck
7
+
8
+ import { AiService } from '@dxos/ai';
6
9
  import { Obj } from '@dxos/echo';
7
10
  import { create } from '@dxos/echo-schema';
8
- import { AiService, defineFunction, type FunctionDefinition } from '@dxos/functions';
9
- import { DataType } from '@dxos/schema';
11
+ import { type FunctionDefinition, defineFunction } from '@dxos/functions';
12
+ import { type ContentBlock, DataType } from '@dxos/schema';
10
13
 
11
- import PROMPT from './instructions.tpl?raw';
12
- import { AISession } from '../../session';
14
+ import { AiSession } from '../../session';
13
15
  import { ExtractionInput, ExtractionOutput } from '../extraction';
14
- import { insertReferences, ReferencedQuotes } from '../quotes';
16
+ import { ReferencedQuotes, insertReferences } from '../quotes';
17
+
18
+ import PROMPT from './instructions.tpl?raw';
15
19
 
16
- export const extractionAnthropicFn: FunctionDefinition<ExtractionInput, ExtractionOutput> = defineFunction({
20
+ export const extractionAnthropicFunction: FunctionDefinition<ExtractionInput, ExtractionOutput> = defineFunction({
17
21
  description: 'Extract entities from the transcript message and add them to the message.',
18
22
  inputSchema: ExtractionInput,
19
23
  outputSchema: ExtractionOutput,
20
24
  handler: async ({ data: { message, objects }, context }) => {
21
25
  const startTime = performance.now();
22
- const ai = context.getService(AiService);
23
- const session = new AISession({ operationModel: 'configured' });
26
+ const ai = context.getService(AiService.AiService);
27
+ const session = new AiSession({ operationModel: 'configured' });
24
28
  const result = await session.runStructured(ReferencedQuotes, {
25
29
  generationOptions: {
26
30
  model: '@anthropic/claude-3-5-haiku-20241022',
@@ -28,30 +32,32 @@ export const extractionAnthropicFn: FunctionDefinition<ExtractionInput, Extracti
28
32
  client: ai.client,
29
33
  systemPrompt: PROMPT,
30
34
  history: [
31
- Obj.make(Message, {
32
- role: 'user',
33
- content: [
35
+ Obj.make(DataType.Message, {
36
+ created: new Date().toISOString(),
37
+ sender: { role: 'user' },
38
+ blocks: [
34
39
  {
35
- type: 'text',
40
+ _tag: 'text',
36
41
  text: `<context>${JSON.stringify(objects)}</context>`,
37
- },
42
+ } satisfies ContentBlock.Text,
38
43
  {
39
- type: 'text',
44
+ _tag: 'text',
40
45
  text: `<transcript>${JSON.stringify(message.blocks)}</transcript>`,
41
- },
46
+ } satisfies ContentBlock.Text,
42
47
  ],
43
48
  }),
44
49
  ],
45
50
  artifacts: [],
46
51
  prompt: '',
47
52
  tools: [],
48
- });
53
+ } as any); // TODO(burdon): Rewrite test.
49
54
 
50
55
  return {
56
+ timeElapsed: performance.now() - startTime,
51
57
  message: create(DataType.Message, {
52
58
  ...message,
53
- blocks: message.blocks.map((block, i) =>
54
- block.type !== 'transcription'
59
+ blocks: message.blocks.map((block) =>
60
+ block._tag !== 'transcript'
55
61
  ? block
56
62
  : {
57
63
  ...block,
@@ -59,7 +65,6 @@ export const extractionAnthropicFn: FunctionDefinition<ExtractionInput, Extracti
59
65
  },
60
66
  ),
61
67
  }),
62
- timeElapsed: performance.now() - startTime,
63
68
  };
64
69
  },
65
70
  });
@@ -2,19 +2,20 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { describe, test, beforeAll } from 'vitest';
5
+ import { beforeAll, describe, test } from 'vitest';
6
6
 
7
7
  import { type EchoDatabase } from '@dxos/echo-db';
8
8
  import { EchoTestBuilder } from '@dxos/echo-db/testing';
9
9
  import { FunctionExecutor, ServiceContainer } from '@dxos/functions';
10
10
  import { log } from '@dxos/log';
11
11
  import { DataType } from '@dxos/schema';
12
- import { createTestData, Testing } from '@dxos/schema/testing';
12
+ import { Testing, createTestData } from '@dxos/schema/testing';
13
13
  import { range } from '@dxos/util';
14
14
 
15
- import { extractionNerFn } from './extraction-ner-function';
16
15
  import { processTranscriptMessage } from '../extraction';
17
16
 
17
+ import { extractionNerFunction } from './extraction-ner-function';
18
+
18
19
  describe.skip('NER EntityExtraction', () => {
19
20
  let builder: EchoTestBuilder;
20
21
  let db: EchoDatabase;
@@ -27,6 +28,7 @@ describe.skip('NER EntityExtraction', () => {
27
28
  contacts: Record<string, DataType.Person>;
28
29
  organizations: Record<string, DataType.Organization>;
29
30
  };
31
+
30
32
  const TYPES = [DataType.Organization, DataType.Person, Testing.Contact, Testing.DocumentType];
31
33
 
32
34
  beforeAll(async () => {
@@ -44,8 +46,8 @@ describe.skip('NER EntityExtraction', () => {
44
46
  contacts: Object.fromEntries(Object.entries(data.contacts).map(([key, value]) => [key, db.add(value)])),
45
47
  organizations: Object.fromEntries(Object.entries(data.organizations).map(([key, value]) => [key, db.add(value)])),
46
48
  };
47
- await db.flush();
48
49
 
50
+ await db.flush();
49
51
  executor = new FunctionExecutor(
50
52
  new ServiceContainer().setServices({
51
53
  database: { db },
@@ -64,7 +66,7 @@ describe.skip('NER EntityExtraction', () => {
64
66
  message,
65
67
  objects: [...documents, ...Object.values(contacts)],
66
68
  },
67
- function: extractionNerFn,
69
+ function: extractionNerFunction,
68
70
  executor,
69
71
  });
70
72
  log.info('output', enhancedMessage);
@@ -73,7 +75,6 @@ describe.skip('NER EntityExtraction', () => {
73
75
 
74
76
  test('computational irreducibility', async () => {
75
77
  const { transcriptWoflram, documents, contacts } = testData;
76
-
77
78
  log.info('context', { documents, contacts });
78
79
  const message = transcriptWoflram[0];
79
80
  log.info('input', message);
@@ -85,7 +86,7 @@ describe.skip('NER EntityExtraction', () => {
85
86
  message,
86
87
  objects: [...documents, ...Object.values(contacts)],
87
88
  },
88
- function: extractionNerFn,
89
+ function: extractionNerFunction,
89
90
  executor,
90
91
  });
91
92
  log.info('output', { message: enhancedMessage.blocks[0], timeElapsed });
@@ -95,7 +96,6 @@ describe.skip('NER EntityExtraction', () => {
95
96
 
96
97
  test('org and document linking', async () => {
97
98
  const { transcriptJosiah, documents, contacts, organizations } = testData;
98
-
99
99
  log.info('context', { contacts, organizations, documents });
100
100
 
101
101
  for (const message of transcriptJosiah) {
@@ -106,7 +106,7 @@ describe.skip('NER EntityExtraction', () => {
106
106
  message,
107
107
  objects: [...documents, ...Object.values(contacts), ...Object.values(organizations)],
108
108
  },
109
- function: extractionNerFn,
109
+ function: extractionNerFunction,
110
110
  executor,
111
111
  });
112
112
  log.info('output', enhancedMessage);
@@ -2,6 +2,9 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ // ISSUE(burdon): defineFunction
6
+ // @ts-nocheck
7
+
5
8
  import { asyncTimeout } from '@dxos/async';
6
9
  import { create } from '@dxos/echo-schema';
7
10
  import { DatabaseService, defineFunction } from '@dxos/functions';
@@ -9,12 +12,14 @@ import { invariant } from '@dxos/invariant';
9
12
  import { log } from '@dxos/log';
10
13
  import { DataType } from '@dxos/schema';
11
14
 
12
- import { extractFullEntities } from './named-entity-recognition';
13
15
  import { ExtractionInput, ExtractionOutput } from '../extraction';
14
16
  import { findQuotes, insertReferences } from '../quotes';
15
17
 
18
+ /**
19
+ * Named Entity Recognition model
20
+ */
16
21
  // TODO(mykola): Make it use vector index to query objects and not pass objects as input.
17
- export const extractionNerFn = defineFunction({
22
+ export const extractionNerFunction = defineFunction({
18
23
  description: 'Extracts named entities from a text',
19
24
  inputSchema: ExtractionInput,
20
25
  outputSchema: ExtractionOutput,
@@ -22,30 +27,33 @@ export const extractionNerFn = defineFunction({
22
27
  log.info('input', { message, options });
23
28
  const startTime = performance.now();
24
29
  const { db } = context.getService(DatabaseService);
30
+ const { extractFullEntities } = await import('./named-entity-recognition');
25
31
 
26
32
  const entitiesPromise = Promise.all(
27
33
  message.blocks.map(async (block) => {
28
- invariant(block.type === 'transcription' || block.type === 'text', 'Block must have text');
34
+ invariant(block._tag === 'transcript' || block._tag === 'text');
29
35
  return extractFullEntities(block.text);
30
36
  }),
31
37
  ).then((entities) => entities.flat());
32
38
  const entities = options?.timeout ? await asyncTimeout(entitiesPromise, options.timeout) : await entitiesPromise;
39
+
33
40
  log.info('entities', { entities });
34
41
  const quoteReferences = await findQuotes(
35
42
  entities.map((entity) => entity.word),
36
43
  db,
37
44
  );
38
- const blocksWithReferences = message.blocks.map((block, i) => {
39
- invariant(block.type === 'transcription' || block.type === 'text', 'Block must have text');
40
- return { ...block, text: insertReferences(block.text, quoteReferences) };
45
+
46
+ const blocksWithReferences = message.blocks.map((block) => {
47
+ invariant(block._tag === 'transcript' || block._tag === 'text');
48
+ return { ...block, text: insertReferences(block._tag, quoteReferences) };
41
49
  });
50
+
42
51
  const messageWithReferences = create(DataType.Message, {
43
52
  ...message,
44
53
  blocks: blocksWithReferences,
45
54
  });
46
55
 
47
56
  log.info('output', { messageWithReferences });
48
-
49
57
  return {
50
58
  message: messageWithReferences,
51
59
  timeElapsed: performance.now() - startTime,
@@ -57,7 +57,7 @@ describe('NamedEntityRecognition', () => {
57
57
  const { transcriptWoflram, transcriptJosiah } = await createTestData();
58
58
 
59
59
  const blocks = [...transcriptWoflram, ...transcriptJosiah].flatMap((message) =>
60
- message.blocks.flatMap((block) => (block.type === 'transcription' ? [block.text] : [])),
60
+ message.blocks.flatMap((block) => (block._tag === 'transcript' ? [block.text] : [])),
61
61
  );
62
62
 
63
63
  for (const block of blocks) {
@@ -70,7 +70,7 @@ describe('NamedEntityRecognition', () => {
70
70
  const { transcriptMessages } = await createTestData();
71
71
 
72
72
  const blocks = transcriptMessages.flatMap((message) =>
73
- message.blocks.flatMap((block) => (block.type === 'transcription' ? [block.text] : [])),
73
+ message.blocks.flatMap((block) => (block._tag === 'transcript' ? [block.text] : [])),
74
74
  );
75
75
 
76
76
  for (const block of blocks) {
@@ -4,14 +4,15 @@
4
4
 
5
5
  import {
6
6
  type TokenClassificationOutput,
7
+ type TokenClassificationPipelineType,
7
8
  type TokenClassificationSingle,
8
9
  pipeline,
9
- type TokenClassificationPipelineType,
10
10
  } from '@xenova/transformers';
11
11
 
12
12
  import { log } from '@dxos/log';
13
13
 
14
14
  let _ner: Promise<TokenClassificationPipelineType>;
15
+
15
16
  /**
16
17
  * Named Entity Recognition pipeline.
17
18
  * Initializes the pipeline on first call.
@@ -24,6 +25,7 @@ export const getNer = () => {
24
25
  return ner;
25
26
  });
26
27
  }
28
+
27
29
  return _ner;
28
30
  };
29
31
 
@@ -2,7 +2,7 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { describe, test, expect } from 'vitest';
5
+ import { describe, expect, test } from 'vitest';
6
6
 
7
7
  import { insertReferences } from './quotes';
8
8
 
@@ -13,7 +13,7 @@ describe('insertReferences', () => {
13
13
  };
14
14
 
15
15
  expect(insertReferences('This is a computational irreducibility test.', quotes)).toBe(
16
- 'This is a [computational irreducibility][dxn:echo:@:01JTG9JW11XGWJZ32AW8ET93D1] test.',
16
+ 'This is a [computational irreducibility](dxn:echo:@:01JTG9JW11XGWJZ32AW8ET93D1) test.',
17
17
  );
18
18
  expect(
19
19
  insertReferences(
@@ -21,7 +21,7 @@ describe('insertReferences', () => {
21
21
  quotes,
22
22
  ),
23
23
  ).toBe(
24
- "And what I'd like to talk today about is Steven Wolfram's concept of a [computational irreducibility][dxn:echo:@:01JTG9JW11XGWJZ32AW8ET93D1].",
24
+ "And what I'd like to talk today about is Steven Wolfram's concept of a [computational irreducibility](dxn:echo:@:01JTG9JW11XGWJZ32AW8ET93D1).",
25
25
  );
26
26
  });
27
27
  });
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { Schema } from 'effect';
6
6
 
7
- import { Query, Filter } from '@dxos/echo';
7
+ import { Filter, Query } from '@dxos/echo';
8
8
  import { type EchoDatabase } from '@dxos/echo-db';
9
9
  import { ObjectId } from '@dxos/echo-schema';
10
10
  import { DXN } from '@dxos/keys';
@@ -51,7 +51,7 @@ export const insertReferences = (text: string, quotes: ReferencedQuotes) => {
51
51
 
52
52
  // Use a case-insensitive regular expression to replace the quote.
53
53
  const regex = new RegExp(quote.quote.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
54
- text = text.replace(regex, `[${quote.quote}][${DXN.fromLocalObjectId(quote.id).toString()}]`);
54
+ text = text.replace(regex, `[${quote.quote}](${DXN.fromLocalObjectId(quote.id).toString()})`);
55
55
  }
56
56
 
57
57
  return text;
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ export * from './services';
@@ -0,0 +1,119 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { AiTool, type AiToolkit } from '@effect/ai';
6
+ import { Context, Effect, Layer, Record, Schema } from 'effect';
7
+
8
+ import { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from '@dxos/ai';
9
+ import { todo } from '@dxos/debug';
10
+ import { type FunctionDefinition, LocalFunctionExecutionService } from '@dxos/functions';
11
+ import { invariant } from '@dxos/invariant';
12
+
13
+ export const makeToolResolverFromFunctions = (
14
+ functions: FunctionDefinition<any, any>[],
15
+ toolkit: AiToolkit.Any,
16
+ ): Layer.Layer<ToolResolverService> => {
17
+ return Layer.succeed(ToolResolverService, {
18
+ resolve: Effect.fn('resolveTool')(function* (id) {
19
+ const tool = toolkit.tools[id];
20
+ if (tool) {
21
+ return tool;
22
+ }
23
+
24
+ const functionDef = functions.find((fn) => fn.name === id);
25
+ if (!functionDef) {
26
+ return yield* Effect.fail(new AiToolNotFoundError(id));
27
+ }
28
+
29
+ return projectFunctionToTool(functionDef);
30
+ }),
31
+ });
32
+ };
33
+
34
+ export const makeToolExecutionServiceFromFunctions = (
35
+ functions: FunctionDefinition<any, any>[],
36
+ toolkit: AiToolkit.AiToolkit<AiTool.Any>,
37
+ handlersLayer: Layer.Layer<AiTool.ToHandler<AiTool.AiTool<any>>, never, never>,
38
+ ): Layer.Layer<ToolExecutionService, never, LocalFunctionExecutionService> => {
39
+ return Layer.effect(
40
+ ToolExecutionService,
41
+ Effect.gen(function* () {
42
+ const toolkitHandler = yield* toolkit.pipe(Effect.provide(handlersLayer));
43
+ const localFunctionExecutionService = yield* LocalFunctionExecutionService;
44
+
45
+ return {
46
+ handlersFor: (toolkit) => {
47
+ const makeHandler = (tool: AiTool.Any): ((params: unknown) => Effect.Effect<unknown, any, any>) => {
48
+ return Effect.fn('toolFunctionHandler')(function* (input: any) {
49
+ if (toolkitHandler.tools.find((t: AiTool.Any) => t.name === tool.name)) {
50
+ // TODO(wittjosiah): Everything is `never` here.
51
+ return yield* (toolkitHandler.handle as any)(tool.name, input);
52
+ }
53
+
54
+ const { functionName } = Context.get(FunctionToolAnnotation)(tool.annotations as any);
55
+ const functionDef = functions.find((fn) => fn.name === functionName);
56
+ if (!functionDef) {
57
+ return yield* Effect.fail(new AiToolNotFoundError(tool.name));
58
+ }
59
+
60
+ return yield* localFunctionExecutionService
61
+ .invokeFunction(functionDef, input)
62
+ .pipe(Effect.catchAllDefect((defect) => Effect.fail(defect)));
63
+ });
64
+ };
65
+
66
+ return toolkit.of(Record.map(toolkit.tools, (tool, _name) => makeHandler(tool)) as any) as any;
67
+ },
68
+ };
69
+ }),
70
+ );
71
+ };
72
+
73
+ /**
74
+ * Tools that are projected from functions have this annotation.
75
+ */
76
+ class FunctionToolAnnotation extends Context.Tag('@dxos/assisatnt/FunctionToolAnnotation')<
77
+ FunctionToolAnnotation,
78
+ {
79
+ functionName: string;
80
+ }
81
+ >() {}
82
+
83
+ const toolCache = new WeakMap<FunctionDefinition<any, any>, AiTool.Any>();
84
+
85
+ const projectFunctionToTool = (fn: FunctionDefinition<any, any>): AiTool.Any => {
86
+ if (toolCache.has(fn)) {
87
+ return toolCache.get(fn)!;
88
+ }
89
+
90
+ const tool = AiTool.make(makeToolName(fn.name), {
91
+ description: fn.description,
92
+ parameters: createStructFieldsFromSchema(fn.inputSchema),
93
+ // TODO(dmaretskyi): Include output schema.
94
+ failure: Schema.Any, // TODO(dmaretskyi): Better type for the failure?
95
+ }).annotate(FunctionToolAnnotation, { functionName: fn.name });
96
+ toolCache.set(fn, tool);
97
+ return tool;
98
+ };
99
+
100
+ /**
101
+ * @returns Tool name produced from function name by escaping invalid characters.
102
+ */
103
+ const makeToolName = (name: string) => {
104
+ const toolName = name.replace(/[^a-zA-Z0-9]/g, '_');
105
+ invariant(toolName.match(/^[a-zA-Z_][a-zA-Z0-9-_]*$/));
106
+ return toolName;
107
+ };
108
+
109
+ // TODO(dmaretskyi): Factor out.
110
+ const createStructFieldsFromSchema = (schema: Schema.Schema<any, any>): Record<string, Schema.Schema<any, any>> => {
111
+ switch (schema.ast._tag) {
112
+ case 'TypeLiteral':
113
+ return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [prop.name, Schema.make(prop.type)]));
114
+ case 'VoidKeyword':
115
+ return {};
116
+ default:
117
+ return todo(`Unsupported schema AST: ${schema.ast._tag}`);
118
+ }
119
+ };
package/src/index.ts CHANGED
@@ -2,8 +2,10 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- export * from './extraction';
6
- export * from './research';
5
+ export * from './conversation';
6
+ export * from './diff';
7
+ export * from './functions';
7
8
  export * from './session';
9
+ export * from './templates';
8
10
  export * from './types';
9
- export * from './blueprint';
11
+ export * from './errors';
@@ -0,0 +1,32 @@
1
+ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
2
+
3
+ exports[`AiSession > no tools 1`] = `
4
+ [
5
+ {
6
+ "blocks": ReactiveArray [
7
+ {
8
+ "_tag": "text",
9
+ "text": "Hello world!",
10
+ },
11
+ ],
12
+ "created": "Sun, 20 Jul 2025 10:54:08 GMT",
13
+ "id": "01K0KQGFTFV3GBKGEWZW67K8HK",
14
+ "sender": {
15
+ "role": "user",
16
+ },
17
+ },
18
+ {
19
+ "blocks": ReactiveArray [
20
+ {
21
+ "_tag": "text",
22
+ "text": "Hi there! How can I help you today?",
23
+ },
24
+ ],
25
+ "created": "2025-07-20T10:54:10.801Z",
26
+ "id": "01K0KQGHVHJ37D4YG45WG090WV",
27
+ "sender": {
28
+ "role": "assistant",
29
+ },
30
+ },
31
+ ]
32
+ `;
@@ -0,0 +1,41 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Context } from 'effect';
6
+
7
+ import { type ObjectVersion } from '@dxos/echo-db';
8
+ import { type ObjectId } from '@dxos/echo-schema';
9
+
10
+ /**
11
+ * Resolves artifact ids to their versions.
12
+ * Used to give the model a sense of the changes to the artifacts made by users during the conversation.
13
+ * The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,
14
+ * a diff is inserted into the conversation.
15
+ *
16
+ * Can be optionally provided to the session run call.
17
+ */
18
+ // TODO(dmaretskyi): Convert to Context.Reference
19
+ export class ArtifactDiffResolver extends Context.Tag('@dxos/assistant/ArtifactDiffResolver')<
20
+ ArtifactDiffResolver,
21
+ ArtifactDiffResolver.Service
22
+ >() {}
23
+
24
+ export namespace ArtifactDiffResolver {
25
+ export type Service = {
26
+ resolve: (
27
+ artifacts: {
28
+ id: ObjectId;
29
+ lastVersion: ObjectVersion;
30
+ }[],
31
+ ) => Promise<
32
+ Map<
33
+ ObjectId,
34
+ {
35
+ version: ObjectVersion;
36
+ diff?: string;
37
+ }
38
+ >
39
+ >;
40
+ };
41
+ }
@@ -0,0 +1,39 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { AiError } from '@effect/ai';
6
+ import { HttpClientError } from '@effect/platform';
7
+ import { Effect, Schema } from 'effect';
8
+
9
+ import { AiModelError } from '../errors';
10
+
11
+ const AnthropicErrorResponse = Schema.Struct({
12
+ type: Schema.Literal('error'),
13
+ error: Schema.Struct({
14
+ type: Schema.String,
15
+ message: Schema.String,
16
+ }),
17
+ });
18
+
19
+ export const mapAiError = (err: AiError.AiError): Effect.Effect<AiError.AiError> =>
20
+ Effect.gen(function* () {
21
+ const cause = err.cause;
22
+ if (HttpClientError.isHttpClientError(cause) && cause.reason === 'StatusCode') {
23
+ const body = yield* cause.response.json.pipe(
24
+ Effect.flatMap(Schema.decodeUnknown(AnthropicErrorResponse, { exact: false })),
25
+ );
26
+
27
+ const parsedCause = new AiModelError({
28
+ message: body.error.message,
29
+ context: { model: 'anthropic', type: body.error.type },
30
+ });
31
+ return new AiError.AiError({
32
+ description: body.error.message,
33
+ module: err.module,
34
+ method: err.method,
35
+ cause: parsedCause,
36
+ });
37
+ }
38
+ return err;
39
+ }).pipe(Effect.catchAll(() => Effect.succeed(err)));
@@ -0,0 +1,60 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { beforeAll, describe, it } from '@effect/vitest';
6
+ import { Effect } from 'effect';
7
+
8
+ import { Blueprint, Template } from '@dxos/blueprints';
9
+ import { Obj } from '@dxos/echo';
10
+ import { type EchoDatabase } from '@dxos/echo-db';
11
+ import { EchoTestBuilder } from '@dxos/echo-db/testing';
12
+ import { DataType } from '@dxos/schema';
13
+ import { trim } from '@dxos/util';
14
+
15
+ import { createSystemPrompt } from '../templates/system';
16
+
17
+ import { formatSystemPrompt } from './format';
18
+
19
+ describe('format', () => {
20
+ let db: EchoDatabase;
21
+ beforeAll(async () => {
22
+ const builder = await new EchoTestBuilder().open();
23
+ ({ db } = await builder.createDatabase({
24
+ types: [DataType.Text, DataType.Organization, Blueprint.Blueprint],
25
+ }));
26
+ });
27
+
28
+ it.effect(
29
+ 'should format',
30
+ Effect.fn(function* () {
31
+ const object = db.add(
32
+ Obj.make(DataType.Organization, {
33
+ name: 'Test',
34
+ website: 'https://www.test.com',
35
+ }),
36
+ );
37
+
38
+ const blueprint = db.add(
39
+ Blueprint.make({
40
+ key: 'example.com/blueprint/test',
41
+ name: 'Test',
42
+ instructions: Template.make({
43
+ source: trim`
44
+ Test
45
+ This is the test blueprint.
46
+ `,
47
+ }),
48
+ }),
49
+ );
50
+
51
+ const output = yield* formatSystemPrompt({
52
+ system: createSystemPrompt({}),
53
+ blueprints: [blueprint, blueprint],
54
+ objects: [object, object],
55
+ });
56
+
57
+ console.log(output);
58
+ }),
59
+ );
60
+ });