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

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 (149) hide show
  1. package/dist/lib/browser/chunk-5GJYG2ML.mjs +396 -0
  2. package/dist/lib/browser/chunk-5GJYG2ML.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 +295 -1657
  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-FLFCEB4P.mjs +398 -0
  15. package/dist/lib/node-esm/chunk-FLFCEB4P.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 +294 -1657
  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 +25 -21
  26. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  27. package/dist/types/src/conversation/index.d.ts +1 -0
  28. package/dist/types/src/conversation/index.d.ts.map +1 -1
  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 +41 -4
  34. package/dist/types/src/errors.d.ts.map +1 -1
  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 +65 -30
  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.map +1 -1
  40. package/dist/types/src/extraction/extraction.d.ts +246 -216
  41. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  42. package/dist/types/src/functions/services.d.ts +4 -3
  43. package/dist/types/src/functions/services.d.ts.map +1 -1
  44. package/dist/types/src/index.d.ts +2 -3
  45. package/dist/types/src/index.d.ts.map +1 -1
  46. package/dist/types/src/session/artifact-diff.d.ts +27 -0
  47. package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
  48. package/dist/types/src/session/error-handling.d.ts +4 -0
  49. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  50. package/dist/types/src/session/format.d.ts +182 -0
  51. package/dist/types/src/session/format.d.ts.map +1 -0
  52. package/dist/types/src/session/format.test.d.ts +2 -0
  53. package/dist/types/src/session/format.test.d.ts.map +1 -0
  54. package/dist/types/src/session/index.d.ts +3 -0
  55. package/dist/types/src/session/index.d.ts.map +1 -1
  56. package/dist/types/src/session/observer.d.ts +22 -0
  57. package/dist/types/src/session/observer.d.ts.map +1 -0
  58. package/dist/types/src/session/session.d.ts +23 -236
  59. package/dist/types/src/session/session.d.ts.map +1 -1
  60. package/dist/types/src/session/toolkit.d.ts +14 -0
  61. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  62. package/dist/types/src/session/version-pin.d.ts +2 -2
  63. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  64. package/dist/types/src/templates/index.d.ts +1 -1
  65. package/dist/types/src/templates/system.d.ts +18 -0
  66. package/dist/types/src/templates/system.d.ts.map +1 -0
  67. package/dist/types/src/types.d.ts +3 -0
  68. package/dist/types/src/types.d.ts.map +1 -1
  69. package/dist/types/tsconfig.tsbuildinfo +1 -1
  70. package/package.json +45 -28
  71. package/src/conversation/context.ts +154 -0
  72. package/src/conversation/conversation.ts +80 -53
  73. package/src/conversation/index.ts +1 -0
  74. package/src/diff.test.ts +43 -0
  75. package/src/diff.ts +79 -0
  76. package/src/errors.ts +5 -0
  77. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +8 -7
  78. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +10 -10
  79. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +9 -9
  80. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +12 -7
  81. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +2 -0
  82. package/src/extraction/quotes.test.ts +1 -1
  83. package/src/extraction/quotes.ts +1 -1
  84. package/src/functions/services.ts +57 -77
  85. package/src/index.ts +2 -3
  86. package/src/session/artifact-diff.ts +41 -0
  87. package/src/session/error-handling.ts +36 -0
  88. package/src/session/format.test.ts +60 -0
  89. package/src/session/format.ts +139 -0
  90. package/src/session/index.ts +3 -0
  91. package/src/session/observer.ts +58 -0
  92. package/src/session/session.test.ts +36 -38
  93. package/src/session/session.ts +113 -248
  94. package/src/session/toolkit.ts +42 -0
  95. package/src/session/version-pin.ts +4 -4
  96. package/src/summarization/summarization.test.ts +11 -22
  97. package/src/templates/format.tpl +60 -0
  98. package/src/templates/index.ts +1 -1
  99. package/src/templates/system.tpl +50 -0
  100. package/src/templates/system.ts +41 -0
  101. package/src/types.ts +10 -5
  102. package/src/typings.d.ts +5 -0
  103. package/dist/types/bin/chat.d.ts +0 -2
  104. package/dist/types/bin/chat.d.ts.map +0 -1
  105. package/dist/types/src/context/binder.d.ts +0 -34
  106. package/dist/types/src/context/binder.d.ts.map +0 -1
  107. package/dist/types/src/context/binding.d.ts +0 -56
  108. package/dist/types/src/context/binding.d.ts.map +0 -1
  109. package/dist/types/src/context/index.d.ts +0 -3
  110. package/dist/types/src/context/index.d.ts.map +0 -1
  111. package/dist/types/src/research/exa.d.ts +0 -12
  112. package/dist/types/src/research/exa.d.ts.map +0 -1
  113. package/dist/types/src/research/graph.d.ts +0 -51
  114. package/dist/types/src/research/graph.d.ts.map +0 -1
  115. package/dist/types/src/research/graph.test.d.ts +0 -2
  116. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  117. package/dist/types/src/research/index.d.ts +0 -4
  118. package/dist/types/src/research/index.d.ts.map +0 -1
  119. package/dist/types/src/research/research.d.ts +0 -10
  120. package/dist/types/src/research/research.d.ts.map +0 -1
  121. package/dist/types/src/research/research.test.d.ts +0 -2
  122. package/dist/types/src/research/research.test.d.ts.map +0 -1
  123. package/dist/types/src/templates/prompt.d.ts +0 -30
  124. package/dist/types/src/templates/prompt.d.ts.map +0 -1
  125. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  126. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  127. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  128. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  129. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  130. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  131. package/dist/types/src/testing/index.d.ts +0 -3
  132. package/dist/types/src/testing/index.d.ts.map +0 -1
  133. package/src/context/binder.ts +0 -103
  134. package/src/context/binding.ts +0 -32
  135. package/src/context/index.ts +0 -6
  136. package/src/research/exa.ts +0 -97
  137. package/src/research/graph.test.ts +0 -64
  138. package/src/research/graph.ts +0 -369
  139. package/src/research/index.ts +0 -7
  140. package/src/research/instructions-research.tpl +0 -98
  141. package/src/research/research.test.ts +0 -190
  142. package/src/research/research.ts +0 -87
  143. package/src/templates/assistant.tpl +0 -111
  144. package/src/templates/prompt.ts +0 -45
  145. package/src/testing/exa-search-1748337321991.ts +0 -131
  146. package/src/testing/exa-search-1748337331526.ts +0 -144
  147. package/src/testing/exa-search-1748337344119.ts +0 -133
  148. package/src/testing/index.ts +0 -11
  149. package/src/typedefs.d.ts +0 -8
@@ -2,27 +2,28 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- // TODO(burdon): Fix.
5
+ // ISSUE(burdon): defineFunction
6
6
  // @ts-nocheck
7
7
 
8
- import { ToolRegistry, AiService } from '@dxos/ai';
8
+ import { AiService } from '@dxos/ai';
9
9
  import { Obj } from '@dxos/echo';
10
10
  import { create } from '@dxos/echo-schema';
11
- import { defineFunction, type FunctionDefinition } from '@dxos/functions';
11
+ import { type FunctionDefinition, defineFunction } from '@dxos/functions';
12
12
  import { type ContentBlock, DataType } from '@dxos/schema';
13
13
 
14
- import PROMPT from './instructions.tpl?raw';
15
14
  import { AiSession } from '../../session';
16
15
  import { ExtractionInput, ExtractionOutput } from '../extraction';
17
- import { insertReferences, ReferencedQuotes } from '../quotes';
16
+ import { ReferencedQuotes, insertReferences } from '../quotes';
17
+
18
+ import PROMPT from './instructions.tpl?raw';
18
19
 
19
- export const extractionAnthropicFn: FunctionDefinition<ExtractionInput, ExtractionOutput> = defineFunction({
20
+ export const extractionAnthropicFunction: FunctionDefinition<ExtractionInput, ExtractionOutput> = defineFunction({
20
21
  description: 'Extract entities from the transcript message and add them to the message.',
21
22
  inputSchema: ExtractionInput,
22
23
  outputSchema: ExtractionOutput,
23
24
  handler: async ({ data: { message, objects }, context }) => {
24
25
  const startTime = performance.now();
25
- const ai = context.getService(AiService);
26
+ const ai = context.getService(AiService.AiService);
26
27
  const session = new AiSession({ operationModel: 'configured' });
27
28
  const result = await session.runStructured(ReferencedQuotes, {
28
29
  generationOptions: {
@@ -49,13 +50,13 @@ export const extractionAnthropicFn: FunctionDefinition<ExtractionInput, Extracti
49
50
  artifacts: [],
50
51
  prompt: '',
51
52
  tools: [],
52
- toolResolver: new ToolRegistry([]),
53
53
  } as any); // TODO(burdon): Rewrite test.
54
54
 
55
55
  return {
56
+ timeElapsed: performance.now() - startTime,
56
57
  message: create(DataType.Message, {
57
58
  ...message,
58
- blocks: message.blocks.map((block, i) =>
59
+ blocks: message.blocks.map((block) =>
59
60
  block._tag !== 'transcript'
60
61
  ? block
61
62
  : {
@@ -64,7 +65,6 @@ export const extractionAnthropicFn: FunctionDefinition<ExtractionInput, Extracti
64
65
  },
65
66
  ),
66
67
  }),
67
- timeElapsed: performance.now() - startTime,
68
68
  };
69
69
  },
70
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,7 +2,7 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- // TODO(burdon): Fix.
5
+ // ISSUE(burdon): defineFunction
6
6
  // @ts-nocheck
7
7
 
8
8
  import { asyncTimeout } from '@dxos/async';
@@ -12,12 +12,14 @@ import { invariant } from '@dxos/invariant';
12
12
  import { log } from '@dxos/log';
13
13
  import { DataType } from '@dxos/schema';
14
14
 
15
- import { extractFullEntities } from './named-entity-recognition';
16
15
  import { ExtractionInput, ExtractionOutput } from '../extraction';
17
16
  import { findQuotes, insertReferences } from '../quotes';
18
17
 
18
+ /**
19
+ * Named Entity Recognition model
20
+ */
19
21
  // TODO(mykola): Make it use vector index to query objects and not pass objects as input.
20
- export const extractionNerFn = defineFunction({
22
+ export const extractionNerFunction = defineFunction({
21
23
  description: 'Extracts named entities from a text',
22
24
  inputSchema: ExtractionInput,
23
25
  outputSchema: ExtractionOutput,
@@ -25,30 +27,33 @@ export const extractionNerFn = defineFunction({
25
27
  log.info('input', { message, options });
26
28
  const startTime = performance.now();
27
29
  const { db } = context.getService(DatabaseService);
30
+ const { extractFullEntities } = await import('./named-entity-recognition');
28
31
 
29
32
  const entitiesPromise = Promise.all(
30
33
  message.blocks.map(async (block) => {
31
- invariant(block._tag === 'transcript' || block._tag === 'text', 'Block must have text');
34
+ invariant(block._tag === 'transcript' || block._tag === 'text');
32
35
  return extractFullEntities(block.text);
33
36
  }),
34
37
  ).then((entities) => entities.flat());
35
38
  const entities = options?.timeout ? await asyncTimeout(entitiesPromise, options.timeout) : await entitiesPromise;
39
+
36
40
  log.info('entities', { entities });
37
41
  const quoteReferences = await findQuotes(
38
42
  entities.map((entity) => entity.word),
39
43
  db,
40
44
  );
41
- const blocksWithReferences = message.blocks.map((block, i) => {
42
- invariant(block._tag === 'transcript' || block._tag === 'text', 'Block must have text');
45
+
46
+ const blocksWithReferences = message.blocks.map((block) => {
47
+ invariant(block._tag === 'transcript' || block._tag === 'text');
43
48
  return { ...block, text: insertReferences(block._tag, quoteReferences) };
44
49
  });
50
+
45
51
  const messageWithReferences = create(DataType.Message, {
46
52
  ...message,
47
53
  blocks: blocksWithReferences,
48
54
  });
49
55
 
50
56
  log.info('output', { messageWithReferences });
51
-
52
57
  return {
53
58
  message: messageWithReferences,
54
59
  timeElapsed: performance.now() - startTime,
@@ -12,6 +12,7 @@ import {
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
 
@@ -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';
@@ -2,49 +2,72 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { AiTool } from '@effect/ai';
6
- import { Context, Effect, Layer, Match, Predicate, Record, Schema } from 'effect';
5
+ import { AiTool, type AiToolkit } from '@effect/ai';
6
+ import { Context, Effect, Layer, Record, Schema } from 'effect';
7
7
 
8
8
  import { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from '@dxos/ai';
9
9
  import { todo } from '@dxos/debug';
10
- import { FunctionError, type FunctionContext, type FunctionDefinition, type Services } from '@dxos/functions';
10
+ import { type FunctionDefinition, LocalFunctionExecutionService } from '@dxos/functions';
11
11
  import { invariant } from '@dxos/invariant';
12
12
 
13
13
  export const makeToolResolverFromFunctions = (
14
14
  functions: FunctionDefinition<any, any>[],
15
+ toolkit: AiToolkit.Any,
15
16
  ): Layer.Layer<ToolResolverService> => {
16
17
  return Layer.succeed(ToolResolverService, {
17
18
  resolve: Effect.fn('resolveTool')(function* (id) {
18
- const fn = functions.find((f) => f.name === id);
19
- if (!fn) {
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) {
20
26
  return yield* Effect.fail(new AiToolNotFoundError(id));
21
27
  }
22
28
 
23
- return projectFunctionToTool(fn);
29
+ return projectFunctionToTool(functionDef);
24
30
  }),
25
31
  });
26
32
  };
27
33
 
28
34
  export const makeToolExecutionServiceFromFunctions = (
29
35
  functions: FunctionDefinition<any, any>[],
30
- ): Layer.Layer<ToolExecutionService> => {
31
- return Layer.succeed(ToolExecutionService, {
32
- handlersFor: (toolkit) => {
33
- const makeHandler = (tool: AiTool.Any): ((params: unknown) => Effect.Effect<unknown, any, any>) => {
34
- return Effect.fn('toolFunctionHandler')(function* (input: any) {
35
- const { functionName } = Context.get(FunctionToolAnnotation)(tool.annotations as any);
36
- const fnDef = functions.find((f) => f.name === functionName);
37
- if (!fnDef) {
38
- return yield* Effect.fail(new AiToolNotFoundError(tool.name));
39
- }
40
-
41
- return yield* invokeFunction(fnDef, input).pipe(Effect.catchAllDefect((defect) => Effect.fail(defect)));
42
- });
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
+ },
43
68
  };
44
-
45
- return toolkit.of(Record.map(toolkit.tools, (tool, name) => makeHandler(tool)) as any) as any;
46
- },
47
- });
69
+ }),
70
+ );
48
71
  };
49
72
 
50
73
  /**
@@ -58,10 +81,12 @@ class FunctionToolAnnotation extends Context.Tag('@dxos/assisatnt/FunctionToolAn
58
81
  >() {}
59
82
 
60
83
  const toolCache = new WeakMap<FunctionDefinition<any, any>, AiTool.Any>();
84
+
61
85
  const projectFunctionToTool = (fn: FunctionDefinition<any, any>): AiTool.Any => {
62
86
  if (toolCache.has(fn)) {
63
87
  return toolCache.get(fn)!;
64
88
  }
89
+
65
90
  const tool = AiTool.make(makeToolName(fn.name), {
66
91
  description: fn.description,
67
92
  parameters: createStructFieldsFromSchema(fn.inputSchema),
@@ -76,64 +101,19 @@ const projectFunctionToTool = (fn: FunctionDefinition<any, any>): AiTool.Any =>
76
101
  * @returns Tool name produced from function name by escaping invalid characters.
77
102
  */
78
103
  const makeToolName = (name: string) => {
79
- const toolName = name.replace(/[^a-zA-Z0-9]/g, '');
104
+ const toolName = name.replace(/[^a-zA-Z0-9]/g, '_');
80
105
  invariant(toolName.match(/^[a-zA-Z_][a-zA-Z0-9-_]*$/));
81
106
  return toolName;
82
107
  };
83
108
 
84
109
  // TODO(dmaretskyi): Factor out.
85
110
  const createStructFieldsFromSchema = (schema: Schema.Schema<any, any>): Record<string, Schema.Schema<any, any>> => {
86
- return Match.value(schema.ast).pipe(
87
- Match.when(Predicate.isTagged('TypeLiteral'), (ast) => {
88
- return Object.fromEntries(ast.propertySignatures.map((prop) => [prop.name, Schema.make(prop.type)]));
89
- }),
90
- Match.orElseAbsurd,
91
- );
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
+ }
92
119
  };
93
-
94
- // TODO(dmaretskyi): Factor out.
95
- const invokeFunction = (fnDef: FunctionDefinition<any, any>, input: any): Effect.Effect<unknown, never, Services> =>
96
- Effect.gen(function* () {
97
- // Assert input matches schema
98
- const assertInput = fnDef.inputSchema.pipe(Schema.asserts);
99
- (assertInput as any)(input);
100
-
101
- const context: FunctionContext = {
102
- getService: () => todo(),
103
- getSpace: async (_spaceId: any) => {
104
- throw new Error('Not available. Use the database service instead.');
105
- },
106
- space: undefined,
107
- get ai(): never {
108
- throw new Error('Not available. Use the ai service instead.');
109
- },
110
- };
111
-
112
- // TODO(dmaretskyi): This should be delegated to a function invoker service.
113
- const data = yield* Effect.gen(function* () {
114
- const result = fnDef.handler({ context, data: input });
115
- if (Effect.isEffect(result)) {
116
- return yield* (result as Effect.Effect<unknown, unknown, Services>).pipe(Effect.orDie);
117
- } else if (
118
- typeof result === 'object' &&
119
- result !== null &&
120
- 'then' in result &&
121
- typeof result.then === 'function'
122
- ) {
123
- return yield* Effect.promise(() => result);
124
- } else {
125
- return result;
126
- }
127
- }).pipe(
128
- Effect.orDie,
129
- Effect.catchAllDefect((defect) =>
130
- Effect.die(new FunctionError('Error running function', { context: { name: fnDef.name }, cause: defect })),
131
- ),
132
- );
133
-
134
- // Assert output matches schema
135
- const assertOutput = fnDef.outputSchema?.pipe(Schema.asserts);
136
- (assertOutput as any)(data);
137
-
138
- return data;
139
- }).pipe(Effect.withSpan('invokeFunction', { attributes: { name: fnDef.name } }));
package/src/index.ts CHANGED
@@ -2,11 +2,10 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- export * from './context';
6
5
  export * from './conversation';
7
- export * from './extraction';
6
+ export * from './diff';
8
7
  export * from './functions';
9
- export * from './research';
10
8
  export * from './session';
11
9
  export * from './templates';
12
10
  export * from './types';
11
+ export * from './errors';
@@ -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,36 @@
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 { AnthropicError } 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 AnthropicError(`${body.error.type}: ${body.error.message}`);
28
+ return new AiError.AiError({
29
+ description: body.error.message,
30
+ module: err.module,
31
+ method: err.method,
32
+ cause: parsedCause,
33
+ });
34
+ }
35
+ return err;
36
+ }).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
+ });