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

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 (164) hide show
  1. package/dist/lib/browser/chunk-CWGVG235.mjs +380 -0
  2. package/dist/lib/browser/chunk-CWGVG235.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 +272 -0
  6. package/dist/lib/browser/extraction/index.mjs.map +7 -0
  7. package/dist/lib/browser/index.mjs +687 -1649
  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-OV5PMQPB.mjs +382 -0
  15. package/dist/lib/node-esm/chunk-OV5PMQPB.mjs.map +7 -0
  16. package/dist/lib/node-esm/extraction/index.mjs +273 -0
  17. package/dist/lib/node-esm/extraction/index.mjs.map +7 -0
  18. package/dist/lib/node-esm/index.mjs +686 -1649
  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 +97 -0
  24. package/dist/types/src/conversation/context.d.ts.map +1 -0
  25. package/dist/types/src/conversation/conversation.d.ts +25 -22
  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 +46 -9
  34. package/dist/types/src/errors.d.ts.map +1 -1
  35. package/dist/types/src/execution-graph.d.ts +82 -0
  36. package/dist/types/src/execution-graph.d.ts.map +1 -0
  37. package/dist/types/src/execution-graph.test.d.ts +2 -0
  38. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  39. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +1 -1
  40. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  41. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +103 -64
  42. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  43. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  44. package/dist/types/src/extraction/extraction.d.ts +252 -218
  45. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  46. package/dist/types/src/extraction/quotes.d.ts +1 -1
  47. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  48. package/dist/types/src/functions/services.d.ts +17 -4
  49. package/dist/types/src/functions/services.d.ts.map +1 -1
  50. package/dist/types/src/index.d.ts +3 -3
  51. package/dist/types/src/index.d.ts.map +1 -1
  52. package/dist/types/src/session/artifact-diff.d.ts +27 -0
  53. package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
  54. package/dist/types/src/session/error-handling.d.ts +4 -0
  55. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  56. package/dist/types/src/session/format.d.ts +184 -0
  57. package/dist/types/src/session/format.d.ts.map +1 -0
  58. package/dist/types/src/session/format.test.d.ts +2 -0
  59. package/dist/types/src/session/format.test.d.ts.map +1 -0
  60. package/dist/types/src/session/index.d.ts +3 -0
  61. package/dist/types/src/session/index.d.ts.map +1 -1
  62. package/dist/types/src/session/observer.d.ts +22 -0
  63. package/dist/types/src/session/observer.d.ts.map +1 -0
  64. package/dist/types/src/session/session.d.ts +27 -236
  65. package/dist/types/src/session/session.d.ts.map +1 -1
  66. package/dist/types/src/session/toolkit.d.ts +15 -0
  67. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  68. package/dist/types/src/session/version-pin.d.ts +3 -3
  69. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  70. package/dist/types/src/templates/index.d.ts +1 -1
  71. package/dist/types/src/templates/system.d.ts +18 -0
  72. package/dist/types/src/templates/system.d.ts.map +1 -0
  73. package/dist/types/src/types.d.ts +5 -2
  74. package/dist/types/src/types.d.ts.map +1 -1
  75. package/dist/types/tsconfig.tsbuildinfo +1 -1
  76. package/package.json +44 -32
  77. package/src/conversation/context.ts +156 -0
  78. package/src/conversation/conversation.ts +78 -53
  79. package/src/conversation/index.ts +1 -0
  80. package/src/diff.test.ts +43 -0
  81. package/src/diff.ts +79 -0
  82. package/src/errors.ts +6 -1
  83. package/src/execution-graph.test.ts +738 -0
  84. package/src/execution-graph.ts +500 -0
  85. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +8 -7
  86. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +13 -11
  87. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +9 -9
  88. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +15 -8
  89. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +2 -1
  90. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +2 -0
  91. package/src/extraction/extraction.ts +2 -2
  92. package/src/extraction/quotes.test.ts +3 -3
  93. package/src/extraction/quotes.ts +4 -4
  94. package/src/functions/services.ts +114 -95
  95. package/src/index.ts +3 -3
  96. package/src/session/artifact-diff.ts +41 -0
  97. package/src/session/error-handling.ts +41 -0
  98. package/src/session/format.test.ts +60 -0
  99. package/src/session/format.ts +142 -0
  100. package/src/session/index.ts +3 -0
  101. package/src/session/observer.ts +59 -0
  102. package/src/session/session.conversations.json +1 -0
  103. package/src/session/session.test.ts +37 -198
  104. package/src/session/session.ts +125 -249
  105. package/src/session/toolkit.ts +48 -0
  106. package/src/session/version-pin.ts +5 -5
  107. package/src/summarization/summarization.test.ts +16 -22
  108. package/src/templates/format.tpl +60 -0
  109. package/src/templates/index.ts +1 -1
  110. package/src/templates/system.tpl +48 -0
  111. package/src/templates/system.ts +41 -0
  112. package/src/types.ts +12 -7
  113. package/src/typings.d.ts +5 -0
  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/context/binder.d.ts +0 -34
  117. package/dist/types/src/context/binder.d.ts.map +0 -1
  118. package/dist/types/src/context/binding.d.ts +0 -56
  119. package/dist/types/src/context/binding.d.ts.map +0 -1
  120. package/dist/types/src/context/index.d.ts +0 -3
  121. package/dist/types/src/context/index.d.ts.map +0 -1
  122. package/dist/types/src/research/exa.d.ts +0 -12
  123. package/dist/types/src/research/exa.d.ts.map +0 -1
  124. package/dist/types/src/research/graph.d.ts +0 -51
  125. package/dist/types/src/research/graph.d.ts.map +0 -1
  126. package/dist/types/src/research/graph.test.d.ts +0 -2
  127. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  128. package/dist/types/src/research/index.d.ts +0 -4
  129. package/dist/types/src/research/index.d.ts.map +0 -1
  130. package/dist/types/src/research/research.d.ts +0 -10
  131. package/dist/types/src/research/research.d.ts.map +0 -1
  132. package/dist/types/src/research/research.test.d.ts +0 -2
  133. package/dist/types/src/research/research.test.d.ts.map +0 -1
  134. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  135. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  136. package/dist/types/src/templates/prompt.d.ts +0 -30
  137. package/dist/types/src/templates/prompt.d.ts.map +0 -1
  138. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  139. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  140. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  141. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  142. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  143. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  144. package/dist/types/src/testing/index.d.ts +0 -3
  145. package/dist/types/src/testing/index.d.ts.map +0 -1
  146. package/src/context/binder.ts +0 -103
  147. package/src/context/binding.ts +0 -32
  148. package/src/context/index.ts +0 -6
  149. package/src/research/exa.ts +0 -97
  150. package/src/research/graph.test.ts +0 -64
  151. package/src/research/graph.ts +0 -369
  152. package/src/research/index.ts +0 -7
  153. package/src/research/instructions-research.tpl +0 -98
  154. package/src/research/research.test.ts +0 -190
  155. package/src/research/research.ts +0 -87
  156. package/src/session/__snapshots__/session.test.ts.snap +0 -32
  157. package/src/session/version-pin.test.ts +0 -7
  158. package/src/templates/assistant.tpl +0 -111
  159. package/src/templates/prompt.ts +0 -45
  160. package/src/testing/exa-search-1748337321991.ts +0 -131
  161. package/src/testing/exa-search-1748337331526.ts +0 -144
  162. package/src/testing/exa-search-1748337344119.ts +0 -133
  163. package/src/testing/index.ts +0 -11
  164. package/src/typedefs.d.ts +0 -8
@@ -2,22 +2,26 @@
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';
9
- import { create } from '@dxos/echo-schema';
9
+ import { create } from '@dxos/echo/internal';
10
10
  import { DatabaseService, defineFunction } from '@dxos/functions';
11
11
  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({
23
+ key: 'dxos.org/function/extraction/extract-entities',
24
+ name: 'Extract Entities',
21
25
  description: 'Extracts named entities from a text',
22
26
  inputSchema: ExtractionInput,
23
27
  outputSchema: ExtractionOutput,
@@ -25,30 +29,33 @@ export const extractionNerFn = defineFunction({
25
29
  log.info('input', { message, options });
26
30
  const startTime = performance.now();
27
31
  const { db } = context.getService(DatabaseService);
32
+ const { extractFullEntities } = await import('./named-entity-recognition');
28
33
 
29
34
  const entitiesPromise = Promise.all(
30
35
  message.blocks.map(async (block) => {
31
- invariant(block._tag === 'transcript' || block._tag === 'text', 'Block must have text');
36
+ invariant(block._tag === 'transcript' || block._tag === 'text');
32
37
  return extractFullEntities(block.text);
33
38
  }),
34
39
  ).then((entities) => entities.flat());
35
40
  const entities = options?.timeout ? await asyncTimeout(entitiesPromise, options.timeout) : await entitiesPromise;
41
+
36
42
  log.info('entities', { entities });
37
43
  const quoteReferences = await findQuotes(
38
44
  entities.map((entity) => entity.word),
39
45
  db,
40
46
  );
41
- const blocksWithReferences = message.blocks.map((block, i) => {
42
- invariant(block._tag === 'transcript' || block._tag === 'text', 'Block must have text');
47
+
48
+ const blocksWithReferences = message.blocks.map((block) => {
49
+ invariant(block._tag === 'transcript' || block._tag === 'text');
43
50
  return { ...block, text: insertReferences(block._tag, quoteReferences) };
44
51
  });
52
+
45
53
  const messageWithReferences = create(DataType.Message, {
46
54
  ...message,
47
55
  blocks: blocksWithReferences,
48
56
  });
49
57
 
50
58
  log.info('output', { messageWithReferences });
51
-
52
59
  return {
53
60
  message: messageWithReferences,
54
61
  timeElapsed: performance.now() - startTime,
@@ -10,7 +10,8 @@ import { createTestData } from '@dxos/schema/testing';
10
10
 
11
11
  import { combineNerTokens, createTokenGroups, extractFullEntities, getNer } from './named-entity-recognition';
12
12
 
13
- describe('NamedEntityRecognition', () => {
13
+ // TODO(mykola): This should not run on CI.
14
+ describe.skip('NamedEntityRecognition', () => {
14
15
  let ner: TokenClassificationPipelineType;
15
16
 
16
17
  beforeAll(async () => {
@@ -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,10 +2,10 @@
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
7
  import { asyncTimeout } from '@dxos/async';
8
- import { Expando } from '@dxos/echo-schema';
8
+ import { Expando } from '@dxos/echo/internal';
9
9
  import { type FunctionDefinition, type FunctionExecutor } from '@dxos/functions';
10
10
  import { log } from '@dxos/log';
11
11
  import { DataType } from '@dxos/schema';
@@ -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
  });
@@ -2,11 +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 { Query, Filter } from '@dxos/echo';
7
+ import { Filter, Query } from '@dxos/echo';
8
+ import { ObjectId } from '@dxos/echo/internal';
8
9
  import { type EchoDatabase } from '@dxos/echo-db';
9
- import { ObjectId } from '@dxos/echo-schema';
10
10
  import { DXN } from '@dxos/keys';
11
11
  import { log } from '@dxos/log';
12
12
 
@@ -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;
@@ -2,72 +2,132 @@
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 * as Tool from '@effect/ai/Tool';
6
+ import type * as Toolkit from '@effect/ai/Toolkit';
7
+ import * as Context from 'effect/Context';
8
+ import * as Effect from 'effect/Effect';
9
+ import * as Layer from 'effect/Layer';
10
+ import * as Record from 'effect/Record';
11
+ import * as Schema from 'effect/Schema';
7
12
 
8
13
  import { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from '@dxos/ai';
9
14
  import { todo } from '@dxos/debug';
10
- import { FunctionError, type FunctionContext, type FunctionDefinition, type Services } from '@dxos/functions';
15
+ import { Query } from '@dxos/echo';
16
+ import { DatabaseService, FunctionDefinition, FunctionInvocationService, FunctionType } from '@dxos/functions';
11
17
  import { invariant } from '@dxos/invariant';
12
18
 
19
+ /**
20
+ * Constructs a `ToolResolverService` whose `resolve(id)` looks up tools in the following order:
21
+ * 1. Toolkit: return an existing tool from the provided `toolkit` if one is present under `id`.
22
+ * 2. Functions in DB: query `FunctionType` by `key=id`; if found, deserialize and project to a tool
23
+ * (propagating any `deployedFunctionId` discovered in the object's metadata).
24
+ * 3. Functions passed in: fall back to a matching `FunctionDefinition` from the `functions` array.
25
+ *
26
+ * If none of the above yield a match, the effect fails with `AiToolNotFoundError`.
27
+ *
28
+ * Requires `DatabaseService` in the environment.
29
+ */
13
30
  export const makeToolResolverFromFunctions = (
14
31
  functions: FunctionDefinition<any, any>[],
15
- ): Layer.Layer<ToolResolverService> => {
16
- return Layer.succeed(ToolResolverService, {
17
- resolve: Effect.fn('resolveTool')(function* (id) {
18
- const fn = functions.find((f) => f.name === id);
19
- if (!fn) {
20
- return yield* Effect.fail(new AiToolNotFoundError(id));
21
- }
22
-
23
- return projectFunctionToTool(fn);
32
+ toolkit: Toolkit.Toolkit<any>,
33
+ ): Layer.Layer<ToolResolverService, never, DatabaseService> => {
34
+ return Layer.effect(
35
+ ToolResolverService,
36
+ Effect.gen(function* () {
37
+ const dbService = yield* DatabaseService;
38
+ return {
39
+ resolve: (id): Effect.Effect<Tool.Any, AiToolNotFoundError> =>
40
+ Effect.gen(function* () {
41
+ const tool = toolkit.tools[id];
42
+ if (tool) {
43
+ return tool;
44
+ }
45
+
46
+ const {
47
+ objects: [dbFunction],
48
+ } = yield* DatabaseService.runQuery(Query.type(FunctionType, { key: id }));
49
+
50
+ const functionDef = dbFunction
51
+ ? FunctionDefinition.deserialize(dbFunction)
52
+ : functions.find((fn) => fn.key === id);
53
+
54
+ if (!functionDef) {
55
+ return yield* Effect.fail(new AiToolNotFoundError(id));
56
+ }
57
+
58
+ return projectFunctionToTool(functionDef);
59
+ }).pipe(Effect.provideService(DatabaseService, dbService)),
60
+ } satisfies Context.Tag.Service<ToolResolverService>;
24
61
  }),
25
- });
62
+ );
26
63
  };
27
64
 
28
65
  export const makeToolExecutionServiceFromFunctions = (
29
- 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
- });
66
+ toolkit: Toolkit.Toolkit<any>,
67
+ handlersLayer: Layer.Layer<Tool.Handler<any>, never, never>,
68
+ ): Layer.Layer<ToolExecutionService, never, FunctionInvocationService> => {
69
+ return Layer.effect(
70
+ ToolExecutionService,
71
+ Effect.gen(function* () {
72
+ const toolkitHandler = yield* toolkit.pipe(Effect.provide(handlersLayer));
73
+ invariant(isHandlerLike(toolkitHandler));
74
+ const functionInvocationService = yield* FunctionInvocationService;
75
+
76
+ return {
77
+ handlersFor: (toolkit) => {
78
+ const makeHandler = (tool: Tool.Any): ((params: unknown) => Effect.Effect<unknown, any, any>) => {
79
+ return Effect.fn(`toolFunctionHandler ${tool.name}`)(function* (input: any) {
80
+ if (toolkitHandler.tools[tool.name]) {
81
+ if (Tool.isProviderDefined(tool)) {
82
+ throw new Error('Attempted to call a provider-defined tool');
83
+ }
84
+ // TODO(wittjosiah): Everything is `never` here.
85
+ return yield* (toolkitHandler.handle as any)(tool.name, input);
86
+ }
87
+
88
+ const { definition: functionDef } = Context.get(FunctionToolAnnotation)(tool.annotations as any);
89
+
90
+ return yield* functionInvocationService
91
+ .invokeFunction(functionDef, input as any)
92
+ .pipe(Effect.catchAllDefect((defect) => Effect.fail(defect)));
93
+ });
94
+ };
95
+
96
+ return toolkit.of(
97
+ Record.map(toolkit.tools, (tool, _name) => (Tool.isUserDefined(tool) ? makeHandler(tool) : null)) as any,
98
+ ) as any;
99
+ },
43
100
  };
44
-
45
- return toolkit.of(Record.map(toolkit.tools, (tool, name) => makeHandler(tool)) as any) as any;
46
- },
47
- });
101
+ }),
102
+ );
48
103
  };
49
104
 
50
- /**
51
- * Tools that are projected from functions have this annotation.
52
- */
53
- class FunctionToolAnnotation extends Context.Tag('@dxos/assisatnt/FunctionToolAnnotation')<
105
+ class FunctionToolAnnotation extends Context.Tag('@dxos/assistant/FunctionToolAnnotation')<
54
106
  FunctionToolAnnotation,
55
- {
56
- functionName: string;
57
- }
107
+ { definition: FunctionDefinition<any, any> }
58
108
  >() {}
59
109
 
60
- const toolCache = new WeakMap<FunctionDefinition<any, any>, AiTool.Any>();
61
- const projectFunctionToTool = (fn: FunctionDefinition<any, any>): AiTool.Any => {
110
+ const toolCache = new WeakMap<FunctionDefinition<any, any>, Tool.Any>();
111
+
112
+ /**
113
+ * Projects a `FunctionDefinition` into an `AiTool`.
114
+ *
115
+ * @param fn The function definition to project into a tool.
116
+ * @param meta Optional projection metadata.
117
+ * @param meta.deployedFunctionId Backend deployment ID used for remote invocation when present. This is the
118
+ * EDGE service's function deployment identifier (not the ECHO object ID/DXN and not `FunctionDefinition.key`).
119
+ */
120
+ const projectFunctionToTool = (fn: FunctionDefinition<any, any>): Tool.Any => {
62
121
  if (toolCache.has(fn)) {
63
122
  return toolCache.get(fn)!;
64
123
  }
65
- const tool = AiTool.make(makeToolName(fn.name), {
124
+
125
+ const tool = Tool.make(makeToolName(fn.name), {
66
126
  description: fn.description,
67
127
  parameters: createStructFieldsFromSchema(fn.inputSchema),
68
128
  // TODO(dmaretskyi): Include output schema.
69
129
  failure: Schema.Any, // TODO(dmaretskyi): Better type for the failure?
70
- }).annotate(FunctionToolAnnotation, { functionName: fn.name });
130
+ }).annotate(FunctionToolAnnotation, { definition: fn });
71
131
  toolCache.set(fn, tool);
72
132
  return tool;
73
133
  };
@@ -76,64 +136,23 @@ const projectFunctionToTool = (fn: FunctionDefinition<any, any>): AiTool.Any =>
76
136
  * @returns Tool name produced from function name by escaping invalid characters.
77
137
  */
78
138
  const makeToolName = (name: string) => {
79
- const toolName = name.replace(/[^a-zA-Z0-9]/g, '');
139
+ const toolName = name.replace(/[^a-zA-Z0-9]/g, '_');
80
140
  invariant(toolName.match(/^[a-zA-Z_][a-zA-Z0-9-_]*$/));
81
141
  return toolName;
82
142
  };
83
143
 
84
144
  // TODO(dmaretskyi): Factor out.
85
145
  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
- );
146
+ switch (schema.ast._tag) {
147
+ case 'TypeLiteral':
148
+ return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [prop.name, Schema.make(prop.type)]));
149
+ case 'VoidKeyword':
150
+ return {};
151
+ default:
152
+ return todo(`Unsupported schema AST: ${schema.ast._tag}`);
153
+ }
92
154
  };
93
155
 
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 } }));
156
+ const isHandlerLike = (value: unknown): value is Toolkit.WithHandler<Record<string, Tool.Any>> => {
157
+ return typeof (value as any).tools === 'object' && typeof (value as any).handle === 'function';
158
+ };
package/src/index.ts CHANGED
@@ -2,11 +2,11 @@
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';
7
+ export * from './errors';
8
+ export * from './execution-graph';
8
9
  export * from './functions';
9
- export * from './research';
10
10
  export * from './session';
11
11
  export * from './templates';
12
12
  export * from './types';
@@ -0,0 +1,41 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Context from 'effect/Context';
6
+
7
+ import { type ObjectId } from '@dxos/echo/internal';
8
+ import { type ObjectVersion } from '@dxos/echo-db';
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,41 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as AiError from '@effect/ai/AiError';
6
+ import * as HttpClientError from '@effect/platform/HttpClientError';
7
+ import * as Effect from 'effect/Effect';
8
+ import * as Schema from 'effect/Schema';
9
+
10
+ import { AiModelError } from '../errors';
11
+
12
+ const AnthropicErrorResponse = Schema.Struct({
13
+ type: Schema.Literal('error'),
14
+ error: Schema.Struct({
15
+ type: Schema.String,
16
+ message: Schema.String,
17
+ }),
18
+ });
19
+
20
+ // TODO(dmaretskyi): Needs rework
21
+ export const mapAiError = (err: AiError.AiError): Effect.Effect<AiError.AiError> =>
22
+ Effect.gen(function* () {
23
+ const cause = err.cause;
24
+ if (HttpClientError.isHttpClientError(cause) && cause.reason === 'StatusCode') {
25
+ const body = yield* cause.response.json.pipe(
26
+ Effect.flatMap(Schema.decodeUnknown(AnthropicErrorResponse, { exact: false })),
27
+ );
28
+
29
+ const parsedCause = new AiModelError({
30
+ message: body.error.message,
31
+ context: { model: 'anthropic', type: body.error.type },
32
+ });
33
+ return AiError.UnknownError.make({
34
+ description: body.error.message,
35
+ module: err.module,
36
+ method: err.method,
37
+ cause: parsedCause,
38
+ });
39
+ }
40
+ return err;
41
+ }).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 * as Effect from 'effect/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
+ });