@dxos/assistant 0.8.4-main.ae835ea → 0.8.4-main.bc674ce

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 (116) hide show
  1. package/dist/lib/browser/{chunk-4VIJTKPM.mjs → chunk-7CDDG6LL.mjs} +252 -28
  2. package/dist/lib/browser/chunk-7CDDG6LL.mjs.map +7 -0
  3. package/dist/lib/browser/chunk-J5LGTIGS.mjs +10 -0
  4. package/dist/lib/browser/extraction/index.mjs +119 -166
  5. package/dist/lib/browser/extraction/index.mjs.map +4 -4
  6. package/dist/lib/browser/index.mjs +239 -289
  7. package/dist/lib/browser/index.mjs.map +4 -4
  8. package/dist/lib/browser/meta.json +1 -1
  9. package/dist/lib/browser/testing/index.mjs +32 -0
  10. package/dist/lib/browser/testing/index.mjs.map +7 -0
  11. package/dist/lib/node-esm/{chunk-AUUC7II4.mjs → chunk-CC7ER6Q3.mjs} +251 -28
  12. package/dist/lib/node-esm/chunk-CC7ER6Q3.mjs.map +7 -0
  13. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  14. package/dist/lib/node-esm/extraction/index.mjs +119 -166
  15. package/dist/lib/node-esm/extraction/index.mjs.map +4 -4
  16. package/dist/lib/node-esm/index.mjs +239 -289
  17. package/dist/lib/node-esm/index.mjs.map +4 -4
  18. package/dist/lib/node-esm/meta.json +1 -1
  19. package/dist/lib/node-esm/testing/index.mjs +33 -0
  20. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  21. package/dist/types/src/conversation/context.d.ts +88 -62
  22. package/dist/types/src/conversation/context.d.ts.map +1 -1
  23. package/dist/types/src/conversation/context.test.d.ts +2 -0
  24. package/dist/types/src/conversation/context.test.d.ts.map +1 -0
  25. package/dist/types/src/conversation/conversation.d.ts +16 -16
  26. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  27. package/dist/types/src/conversation/conversation.test.d.ts +2 -0
  28. package/dist/types/src/conversation/conversation.test.d.ts.map +1 -0
  29. package/dist/types/src/errors.d.ts +22 -30
  30. package/dist/types/src/errors.d.ts.map +1 -1
  31. package/dist/types/src/execution-graph.d.ts +5 -2
  32. package/dist/types/src/execution-graph.d.ts.map +1 -1
  33. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  34. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +254 -252
  35. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  36. package/dist/types/src/extraction/extraction.d.ts +344 -309
  37. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  38. package/dist/types/src/extraction/quotes.d.ts +2 -2
  39. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  40. package/dist/types/src/functions/services.d.ts +4 -3
  41. package/dist/types/src/functions/services.d.ts.map +1 -1
  42. package/dist/types/src/functions.test.d.ts +2 -0
  43. package/dist/types/src/functions.test.d.ts.map +1 -0
  44. package/dist/types/src/session/GenericToolkit.d.ts +85 -0
  45. package/dist/types/src/session/GenericToolkit.d.ts.map +1 -0
  46. package/dist/types/src/session/artifact-diff.d.ts +1 -1
  47. package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
  48. package/dist/types/src/session/format.d.ts +4 -178
  49. package/dist/types/src/session/format.d.ts.map +1 -1
  50. package/dist/types/src/session/index.d.ts +1 -0
  51. package/dist/types/src/session/index.d.ts.map +1 -1
  52. package/dist/types/src/session/observer.d.ts +6 -5
  53. package/dist/types/src/session/observer.d.ts.map +1 -1
  54. package/dist/types/src/session/session.d.ts +16 -11
  55. package/dist/types/src/session/session.d.ts.map +1 -1
  56. package/dist/types/src/session/toolkit.d.ts +5 -6
  57. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  58. package/dist/types/src/session/version-pin.d.ts +3 -3
  59. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  60. package/dist/types/src/testing/index.d.ts +2 -0
  61. package/dist/types/src/testing/index.d.ts.map +1 -0
  62. package/dist/types/src/testing/layer.d.ts +21 -0
  63. package/dist/types/src/testing/layer.d.ts.map +1 -0
  64. package/dist/types/src/types/artifact.d.ts +14 -2
  65. package/dist/types/src/types/artifact.d.ts.map +1 -1
  66. package/dist/types/tsconfig.tsbuildinfo +1 -1
  67. package/package.json +38 -27
  68. package/src/conversation/context.test.ts +46 -0
  69. package/src/conversation/context.ts +183 -66
  70. package/src/conversation/conversation.test.ts +65 -0
  71. package/src/conversation/conversation.ts +51 -54
  72. package/src/diff.test.ts +3 -3
  73. package/src/errors.ts +2 -2
  74. package/src/execution-graph.test.ts +45 -43
  75. package/src/execution-graph.ts +23 -14
  76. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +2 -2
  77. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +44 -54
  78. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +14 -13
  79. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +36 -44
  80. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +10 -5
  81. package/src/extraction/extraction.ts +9 -8
  82. package/src/extraction/quotes.ts +4 -5
  83. package/src/functions/services.ts +41 -19
  84. package/src/functions.conversations.json +1 -0
  85. package/src/functions.test.ts +74 -0
  86. package/src/session/GenericToolkit.ts +131 -0
  87. package/src/session/artifact-diff.ts +1 -1
  88. package/src/session/format.test.ts +103 -39
  89. package/src/session/format.ts +17 -16
  90. package/src/session/index.ts +2 -0
  91. package/src/session/observer.ts +5 -3
  92. package/src/session/session.conversations.json +1 -1
  93. package/src/session/session.test.ts +7 -13
  94. package/src/session/session.ts +40 -19
  95. package/src/session/toolkit.ts +13 -22
  96. package/src/session/version-pin.ts +6 -6
  97. package/src/templates/{format.tpl → instructions/format.tpl} +1 -0
  98. package/src/templates/system.ts +2 -2
  99. package/src/testing/index.ts +5 -0
  100. package/src/testing/layer.ts +78 -0
  101. package/src/types/artifact.ts +33 -3
  102. package/dist/lib/browser/chunk-4VIJTKPM.mjs.map +0 -7
  103. package/dist/lib/browser/chunk-UB26N5UF.mjs +0 -89
  104. package/dist/lib/browser/chunk-UB26N5UF.mjs.map +0 -7
  105. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs +0 -13
  106. package/dist/lib/node-esm/chunk-AUUC7II4.mjs.map +0 -7
  107. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs +0 -91
  108. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs.map +0 -7
  109. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs +0 -14
  110. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  111. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  112. package/src/summarization/summarization.test.ts +0 -202
  113. /package/dist/lib/browser/{named-entity-recognition-QPYHML66.mjs.map → chunk-J5LGTIGS.mjs.map} +0 -0
  114. /package/dist/lib/node-esm/{named-entity-recognition-2HDF46YX.mjs.map → chunk-HSLMI22Q.mjs.map} +0 -0
  115. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
  116. /package/src/templates/{system.tpl → instructions/system.tpl} +0 -0
@@ -5,9 +5,9 @@
5
5
  import { beforeAll, describe, test } from 'vitest';
6
6
 
7
7
  import { todo } from '@dxos/debug';
8
- import { FunctionExecutor } from '@dxos/functions';
8
+ import { FunctionExecutor } from '@dxos/functions-runtime';
9
9
  import { log } from '@dxos/log';
10
- import { createTestData } from '@dxos/schema/testing';
10
+ import { createTestData } from '@dxos/types/testing';
11
11
  import { range } from '@dxos/util';
12
12
 
13
13
  import { processTranscriptMessage } from '../extraction';
@@ -2,20 +2,9 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- // ISSUE(burdon): defineFunction
6
- // @ts-nocheck
7
-
8
- import { AiService } from '@dxos/ai';
9
- import { Obj } from '@dxos/echo';
10
- import { create } from '@dxos/echo/internal';
11
5
  import { type FunctionDefinition, defineFunction } from '@dxos/functions';
12
- import { type ContentBlock, DataType } from '@dxos/schema';
13
6
 
14
- import { AiSession } from '../../session';
15
7
  import { ExtractionInput, ExtractionOutput } from '../extraction';
16
- import { ReferencedQuotes, insertReferences } from '../quotes';
17
-
18
- import PROMPT from './instructions.tpl?raw';
19
8
 
20
9
  export const extractionAnthropicFunction: FunctionDefinition<ExtractionInput, ExtractionOutput> = defineFunction({
21
10
  key: 'dxos.org/function/extraction/extract-entities',
@@ -24,49 +13,50 @@ export const extractionAnthropicFunction: FunctionDefinition<ExtractionInput, Ex
24
13
  inputSchema: ExtractionInput,
25
14
  outputSchema: ExtractionOutput,
26
15
  handler: async ({ data: { message, objects }, context }) => {
27
- const startTime = performance.now();
28
- const ai = context.getService(AiService.AiService);
29
- const session = new AiSession({ operationModel: 'configured' });
30
- const result = await session.runStructured(ReferencedQuotes, {
31
- generationOptions: {
32
- model: '@anthropic/claude-3-5-haiku-20241022',
33
- },
34
- client: ai.client,
35
- systemPrompt: PROMPT,
36
- history: [
37
- Obj.make(DataType.Message, {
38
- created: new Date().toISOString(),
39
- sender: { role: 'user' },
40
- blocks: [
41
- {
42
- _tag: 'text',
43
- text: `<context>${JSON.stringify(objects)}</context>`,
44
- } satisfies ContentBlock.Text,
45
- {
46
- _tag: 'text',
47
- text: `<transcript>${JSON.stringify(message.blocks)}</transcript>`,
48
- } satisfies ContentBlock.Text,
49
- ],
50
- }),
51
- ],
52
- artifacts: [],
53
- prompt: '',
54
- tools: [],
55
- } as any); // TODO(burdon): Rewrite test.
16
+ throw new Error('not implemented');
17
+ // const startTime = performance.now();
18
+ // const ai = context.getService(AiService.AiService);
19
+ // const session = new AiSession({ operationModel: 'configured' });
20
+ // const result = await session.runStructured(ReferencedQuotes, {
21
+ // generationOptions: {
22
+ // model: '@anthropic/claude-3-5-haiku-20241022',
23
+ // },
24
+ // client: ai.client,
25
+ // systemPrompt: PROMPT,
26
+ // history: [
27
+ // Obj.make(DataType.Message.Message, {
28
+ // created: new Date().toISOString(),
29
+ // sender: { role: 'user' },
30
+ // blocks: [
31
+ // {
32
+ // _tag: 'text',
33
+ // text: `<context>${JSON.stringify(objects)}</context>`,
34
+ // } satisfies DataType.ContentBlock.Text,
35
+ // {
36
+ // _tag: 'text',
37
+ // text: `<transcript>${JSON.stringify(message.blocks)}</transcript>`,
38
+ // } satisfies DataType.ContentBlock.Text,
39
+ // ],
40
+ // }),
41
+ // ],
42
+ // artifacts: [],
43
+ // prompt: '',
44
+ // tools: [],
45
+ // } as any); // TODO(burdon): Rewrite test.
56
46
 
57
- return {
58
- timeElapsed: performance.now() - startTime,
59
- message: create(DataType.Message, {
60
- ...message,
61
- blocks: message.blocks.map((block) =>
62
- block._tag !== 'transcript'
63
- ? block
64
- : {
65
- ...block,
66
- text: insertReferences(block.text, result),
67
- },
68
- ),
69
- }),
70
- };
47
+ // return {
48
+ // timeElapsed: performance.now() - startTime,
49
+ // message: create(DataType.Message.Message, {
50
+ // ...message,
51
+ // blocks: message.blocks.map((block) =>
52
+ // block._tag !== 'transcript'
53
+ // ? block
54
+ // : {
55
+ // ...block,
56
+ // text: insertReferences(block.text, result),
57
+ // },
58
+ // ),
59
+ // }),
60
+ // };
71
61
  },
72
62
  });
@@ -4,12 +4,13 @@
4
4
 
5
5
  import { beforeAll, describe, test } from 'vitest';
6
6
 
7
- import { type EchoDatabase } from '@dxos/echo-db';
7
+ import { type Database } from '@dxos/echo';
8
8
  import { EchoTestBuilder } from '@dxos/echo-db/testing';
9
- import { FunctionExecutor, ServiceContainer } from '@dxos/functions';
9
+ import { FunctionExecutor, ServiceContainer } from '@dxos/functions-runtime';
10
10
  import { log } from '@dxos/log';
11
- import { DataType } from '@dxos/schema';
12
- import { Testing, createTestData } from '@dxos/schema/testing';
11
+ import { TestSchema } from '@dxos/schema/testing';
12
+ import { type Message, Organization, Person } from '@dxos/types';
13
+ import { createTestData } from '@dxos/types/testing';
13
14
  import { range } from '@dxos/util';
14
15
 
15
16
  import { processTranscriptMessage } from '../extraction';
@@ -18,25 +19,25 @@ import { extractionNerFunction } from './extraction-ner-function';
18
19
 
19
20
  describe.skip('NER EntityExtraction', () => {
20
21
  let builder: EchoTestBuilder;
21
- let db: EchoDatabase;
22
+ let db: Database.Database;
22
23
  let executor: FunctionExecutor;
23
24
  let testData: {
24
- transcriptJosiah: DataType.Message[];
25
- transcriptWoflram: DataType.Message[];
26
- transcriptMessages: DataType.Message[];
27
- documents: Testing.DocumentType[];
28
- contacts: Record<string, DataType.Person>;
29
- organizations: Record<string, DataType.Organization>;
25
+ transcriptJosiah: Message.Message[];
26
+ transcriptWoflram: Message.Message[];
27
+ transcriptMessages: Message.Message[];
28
+ documents: TestSchema.DocumentType[];
29
+ contacts: Record<string, Person.Person>;
30
+ organizations: Record<string, Organization.Organization>;
30
31
  };
31
32
 
32
- const TYPES = [DataType.Organization, DataType.Person, Testing.Contact, Testing.DocumentType];
33
+ const TYPES = [Organization.Organization, Person.Person, TestSchema.Person, TestSchema.DocumentType];
33
34
 
34
35
  beforeAll(async () => {
35
36
  // TODO(dmaretskyi): Helper to scaffold this from a config.
36
37
  builder = await new EchoTestBuilder().open();
37
38
  const { db: db1 } = await builder.createDatabase({ indexing: { vector: true } });
38
39
  db = db1;
39
- db.graph.schemaRegistry.addSchema(TYPES);
40
+ await db.graph.schemaRegistry.register(TYPES);
40
41
  const data = createTestData();
41
42
  testData = {
42
43
  transcriptJosiah: data.transcriptJosiah,
@@ -2,18 +2,9 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- // ISSUE(burdon): defineFunction
6
- // @ts-nocheck
7
-
8
- import { asyncTimeout } from '@dxos/async';
9
- import { create } from '@dxos/echo/internal';
10
- import { DatabaseService, defineFunction } from '@dxos/functions';
11
- import { invariant } from '@dxos/invariant';
12
- import { log } from '@dxos/log';
13
- import { DataType } from '@dxos/schema';
5
+ import { defineFunction } from '@dxos/functions';
14
6
 
15
7
  import { ExtractionInput, ExtractionOutput } from '../extraction';
16
- import { findQuotes, insertReferences } from '../quotes';
17
8
 
18
9
  /**
19
10
  * Named Entity Recognition model
@@ -26,39 +17,40 @@ export const extractionNerFunction = defineFunction({
26
17
  inputSchema: ExtractionInput,
27
18
  outputSchema: ExtractionOutput,
28
19
  handler: async ({ data: { message, options }, context }) => {
29
- log.info('input', { message, options });
30
- const startTime = performance.now();
31
- const { db } = context.getService(DatabaseService);
32
- const { extractFullEntities } = await import('./named-entity-recognition');
33
-
34
- const entitiesPromise = Promise.all(
35
- message.blocks.map(async (block) => {
36
- invariant(block._tag === 'transcript' || block._tag === 'text');
37
- return extractFullEntities(block.text);
38
- }),
39
- ).then((entities) => entities.flat());
40
- const entities = options?.timeout ? await asyncTimeout(entitiesPromise, options.timeout) : await entitiesPromise;
41
-
42
- log.info('entities', { entities });
43
- const quoteReferences = await findQuotes(
44
- entities.map((entity) => entity.word),
45
- db,
46
- );
47
-
48
- const blocksWithReferences = message.blocks.map((block) => {
49
- invariant(block._tag === 'transcript' || block._tag === 'text');
50
- return { ...block, text: insertReferences(block._tag, quoteReferences) };
51
- });
52
-
53
- const messageWithReferences = create(DataType.Message, {
54
- ...message,
55
- blocks: blocksWithReferences,
56
- });
57
-
58
- log.info('output', { messageWithReferences });
59
- return {
60
- message: messageWithReferences,
61
- timeElapsed: performance.now() - startTime,
62
- };
20
+ throw new Error('not implemented');
21
+ // log.info('input', { message, options });
22
+ // const startTime = performance.now();
23
+ // const { db } = context.getService(Database.Service);
24
+ // const { extractFullEntities } = await import('./named-entity-recognition');
25
+
26
+ // const entitiesPromise = Promise.all(
27
+ // message.blocks.map(async (block) => {
28
+ // invariant(block._tag === 'transcript' || block._tag === 'text');
29
+ // return extractFullEntities(block.text);
30
+ // }),
31
+ // ).then((entities) => entities.flat());
32
+ // const entities = options?.timeout ? await asyncTimeout(entitiesPromise, options.timeout) : await entitiesPromise;
33
+
34
+ // log.info('entities', { entities });
35
+ // const quoteReferences = await findQuotes(
36
+ // entities.map((entity) => entity.word),
37
+ // db,
38
+ // );
39
+
40
+ // const blocksWithReferences = message.blocks.map((block) => {
41
+ // invariant(block._tag === 'transcript' || block._tag === 'text');
42
+ // return { ...block, text: insertReferences(block._tag, quoteReferences) };
43
+ // });
44
+
45
+ // const messageWithReferences = create(Message.Message, {
46
+ // ...message,
47
+ // blocks: blocksWithReferences,
48
+ // });
49
+
50
+ // log.info('output', { messageWithReferences });
51
+ // return {
52
+ // message: messageWithReferences,
53
+ // timeElapsed: performance.now() - startTime,
54
+ // };
63
55
  },
64
56
  });
@@ -6,7 +6,8 @@ import { type TokenClassificationOutput, type TokenClassificationPipelineType }
6
6
  import { beforeAll, describe, expect, test } from 'vitest';
7
7
 
8
8
  import { log } from '@dxos/log';
9
- import { createTestData } from '@dxos/schema/testing';
9
+ import { type ContentBlock, type Message } from '@dxos/types';
10
+ import { createTestData } from '@dxos/types/testing';
10
11
 
11
12
  import { combineNerTokens, createTokenGroups, extractFullEntities, getNer } from './named-entity-recognition';
12
13
 
@@ -57,8 +58,10 @@ describe.skip('NamedEntityRecognition', () => {
57
58
  test('own data', async () => {
58
59
  const { transcriptWoflram, transcriptJosiah } = await createTestData();
59
60
 
60
- const blocks = [...transcriptWoflram, ...transcriptJosiah].flatMap((message) =>
61
- message.blocks.flatMap((block) => (block._tag === 'transcript' ? [block.text] : [])),
61
+ const blocks = [...transcriptWoflram, ...transcriptJosiah].flatMap((message: Message.Message) =>
62
+ message.blocks.flatMap((block: ContentBlock.Any) =>
63
+ block._tag === 'transcript' ? [(block as ContentBlock.Transcript).text] : [],
64
+ ),
62
65
  );
63
66
 
64
67
  for (const block of blocks) {
@@ -70,8 +73,10 @@ describe.skip('NamedEntityRecognition', () => {
70
73
  test('more own data', async () => {
71
74
  const { transcriptMessages } = await createTestData();
72
75
 
73
- const blocks = transcriptMessages.flatMap((message) =>
74
- message.blocks.flatMap((block) => (block._tag === 'transcript' ? [block.text] : [])),
76
+ const blocks = transcriptMessages.flatMap((message: Message.Message) =>
77
+ message.blocks.flatMap((block: ContentBlock.Any) =>
78
+ block._tag === 'transcript' ? [(block as ContentBlock.Transcript).text] : [],
79
+ ),
75
80
  );
76
81
 
77
82
  for (const block of blocks) {
@@ -5,14 +5,15 @@
5
5
  import * as Schema from 'effect/Schema';
6
6
 
7
7
  import { asyncTimeout } from '@dxos/async';
8
- import { Expando } from '@dxos/echo/internal';
9
- import { type FunctionDefinition, type FunctionExecutor } from '@dxos/functions';
8
+ import { Type } from '@dxos/echo';
9
+ import { type FunctionDefinition } from '@dxos/functions';
10
+ import { type FunctionExecutor } from '@dxos/functions-runtime';
10
11
  import { log } from '@dxos/log';
11
- import { DataType } from '@dxos/schema';
12
+ import { Message } from '@dxos/types';
12
13
 
13
14
  export const ExtractionInput = Schema.Struct({
14
- message: DataType.Message,
15
- objects: Schema.optional(Schema.Array(Expando)),
15
+ message: Message.Message,
16
+ objects: Schema.optional(Schema.Array(Type.Obj)),
16
17
  options: Schema.optional(
17
18
  Schema.Struct({
18
19
  timeout: Schema.optional(Schema.Number),
@@ -23,12 +24,12 @@ export const ExtractionInput = Schema.Struct({
23
24
  export interface ExtractionInput extends Schema.Schema.Type<typeof ExtractionInput> {}
24
25
 
25
26
  export const ExtractionOutput = Schema.Struct({
26
- message: DataType.Message,
27
+ message: Message.Message,
27
28
  timeElapsed: Schema.Number,
28
29
  });
29
30
  export interface ExtractionOutput extends Schema.Schema.Type<typeof ExtractionOutput> {}
30
31
 
31
- export type ProcessTranscriptMessageParams = {
32
+ export type ProcessTranscriptMessageProps = {
32
33
  input: ExtractionInput;
33
34
  function: FunctionDefinition<ExtractionInput, ExtractionOutput>;
34
35
  executor: FunctionExecutor;
@@ -54,7 +55,7 @@ export type ExtractionFunction = FunctionDefinition<ExtractionInput, ExtractionO
54
55
  * Extract entities from the transcript message and add them to the message.
55
56
  */
56
57
  // TODO(dmaretskyi): Move context to a vector search index.
57
- export const processTranscriptMessage = async (params: ProcessTranscriptMessageParams): Promise<ExtractionOutput> => {
58
+ export const processTranscriptMessage = async (params: ProcessTranscriptMessageProps): Promise<ExtractionOutput> => {
58
59
  try {
59
60
  if (params.options?.timeout && params.options.timeout > 0) {
60
61
  return await asyncTimeout(params.executor.invoke(params.function, params.input), params.options.timeout);
@@ -4,9 +4,8 @@
4
4
 
5
5
  import * as Schema from 'effect/Schema';
6
6
 
7
- import { Filter, Query } from '@dxos/echo';
8
- import { ObjectId } from '@dxos/echo/internal';
9
- import { type EchoDatabase } from '@dxos/echo-db';
7
+ import { type Database, Filter, Query } from '@dxos/echo';
8
+ import { ObjectId } from '@dxos/keys';
10
9
  import { DXN } from '@dxos/keys';
11
10
  import { log } from '@dxos/log';
12
11
 
@@ -28,10 +27,10 @@ export const ReferencedQuotes = Schema.Struct({
28
27
  });
29
28
  export type ReferencedQuotes = Schema.Schema.Type<typeof ReferencedQuotes>;
30
29
 
31
- export const findQuotes = async (quotes: string[], db: EchoDatabase): Promise<ReferencedQuotes> => {
30
+ export const findQuotes = async (quotes: string[], db: Database.Database): Promise<ReferencedQuotes> => {
32
31
  const references = await Promise.all(
33
32
  quotes.map(async (quote) => {
34
- const { objects } = await db.query(Query.select(Filter.text(quote, { type: 'vector' }))).run();
33
+ const objects = await db.query(Query.select(Filter.text(quote, { type: 'vector' }))).run();
35
34
  log.info('found quotes in vector index', { objects, quote });
36
35
  return objects.length > 0 ? [{ id: objects[0].id.toString(), quote }] : [];
37
36
  }),
@@ -9,13 +9,17 @@ import * as Effect from 'effect/Effect';
9
9
  import * as Layer from 'effect/Layer';
10
10
  import * as Record from 'effect/Record';
11
11
  import * as Schema from 'effect/Schema';
12
+ import type * as SchemaAST from 'effect/SchemaAST';
12
13
 
13
14
  import { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from '@dxos/ai';
14
15
  import { todo } from '@dxos/debug';
15
- import { Query } from '@dxos/echo';
16
- import { DatabaseService, Function, FunctionDefinition, FunctionInvocationService } from '@dxos/functions';
16
+ import { Query, Type } from '@dxos/echo';
17
+ import { Database } from '@dxos/echo';
18
+ import { Function, FunctionDefinition, FunctionInvocationService } from '@dxos/functions';
17
19
  import { invariant } from '@dxos/invariant';
18
20
 
21
+ import { RefFromLLM } from '../types';
22
+
19
23
  /**
20
24
  * Constructs a `ToolResolverService` whose `resolve(id)` looks up tools in the following order:
21
25
  * 1. Toolkit: return an existing tool from the provided `toolkit` if one is present under `id`.
@@ -25,27 +29,27 @@ import { invariant } from '@dxos/invariant';
25
29
  *
26
30
  * If none of the above yield a match, the effect fails with `AiToolNotFoundError`.
27
31
  *
28
- * Requires `DatabaseService` in the environment.
32
+ * Requires `Database.Service` in the environment.
29
33
  */
30
34
  export const makeToolResolverFromFunctions = (
31
- functions: FunctionDefinition<any, any>[],
35
+ functions: FunctionDefinition.Any[],
32
36
  toolkit: Toolkit.Toolkit<any>,
33
- ): Layer.Layer<ToolResolverService, never, DatabaseService> => {
37
+ ): Layer.Layer<ToolResolverService, never, Database.Service> => {
34
38
  return Layer.effect(
35
39
  ToolResolverService,
36
40
  Effect.gen(function* () {
37
- const dbService = yield* DatabaseService;
41
+ const dbService = yield* Database.Service;
38
42
  return {
39
43
  resolve: (id): Effect.Effect<Tool.Any, AiToolNotFoundError> =>
40
44
  Effect.gen(function* () {
45
+ // TODO(dmaretskyi): Use FunctionInvocationService.resolveFunction().
46
+
41
47
  const tool = toolkit.tools[id];
42
48
  if (tool) {
43
49
  return tool;
44
50
  }
45
51
 
46
- const {
47
- objects: [dbFunction],
48
- } = yield* DatabaseService.runQuery(Query.type(Function.Function, { key: id }));
52
+ const [dbFunction] = yield* Database.Service.runQuery(Query.type(Function.Function, { key: id }));
49
53
 
50
54
  const functionDef = dbFunction
51
55
  ? FunctionDefinition.deserialize(dbFunction)
@@ -56,7 +60,7 @@ export const makeToolResolverFromFunctions = (
56
60
  }
57
61
 
58
62
  return projectFunctionToTool(functionDef);
59
- }).pipe(Effect.provideService(DatabaseService, dbService)),
63
+ }).pipe(Effect.provideService(Database.Service, dbService)),
60
64
  } satisfies Context.Tag.Service<ToolResolverService>;
61
65
  }),
62
66
  );
@@ -81,8 +85,10 @@ export const makeToolExecutionServiceFromFunctions = (
81
85
  if (Tool.isProviderDefined(tool)) {
82
86
  throw new Error('Attempted to call a provider-defined tool');
83
87
  }
88
+
84
89
  // TODO(wittjosiah): Everything is `never` here.
85
- return yield* (toolkitHandler.handle as any)(tool.name, input);
90
+ const { result } = yield* (toolkitHandler.handle as any)(tool.name, input);
91
+ return result;
86
92
  }
87
93
 
88
94
  const { definition: functionDef } = Context.get(FunctionToolAnnotation)(tool.annotations as any);
@@ -104,24 +110,26 @@ export const makeToolExecutionServiceFromFunctions = (
104
110
 
105
111
  class FunctionToolAnnotation extends Context.Tag('@dxos/assistant/FunctionToolAnnotation')<
106
112
  FunctionToolAnnotation,
107
- { definition: FunctionDefinition<any, any> }
113
+ { definition: FunctionDefinition.Any }
108
114
  >() {}
109
115
 
110
- const toolCache = new WeakMap<FunctionDefinition<any, any>, Tool.Any>();
116
+ const toolCache = new WeakMap<FunctionDefinition.Any, Tool.Any>();
111
117
 
112
118
  /**
113
119
  * Projects a `FunctionDefinition` into an `AiTool`.
114
120
  *
115
121
  * @param fn The function definition to project into a tool.
116
122
  * @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`).
123
+ * @param meta.deployedFunctionId Backend deployment ID used for remote invocation when present.
124
+ * This is the EDGE service's function deployment identifier (not the ECHO object ID/DXN and not `FunctionDefinition.key`).
119
125
  */
120
- const projectFunctionToTool = (fn: FunctionDefinition<any, any>): Tool.Any => {
126
+ const projectFunctionToTool = (fn: FunctionDefinition.Any): Tool.Any => {
121
127
  if (toolCache.has(fn)) {
122
128
  return toolCache.get(fn)!;
123
129
  }
124
130
 
131
+ // TODO(burdon): Use and map function.key?
132
+ // TODO(dmaretskyi): Use function key instead.
125
133
  const tool = Tool.make(makeToolName(fn.name), {
126
134
  description: fn.description,
127
135
  parameters: createStructFieldsFromSchema(fn.inputSchema),
@@ -136,8 +144,8 @@ const projectFunctionToTool = (fn: FunctionDefinition<any, any>): Tool.Any => {
136
144
  * @returns Tool name produced from function name by escaping invalid characters.
137
145
  */
138
146
  const makeToolName = (name: string) => {
139
- const toolName = name.replace(/[^a-zA-Z0-9]/g, '_');
140
- invariant(toolName.match(/^[a-zA-Z_][a-zA-Z0-9-_]*$/));
147
+ const toolName = name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
148
+ invariant(toolName.match(/^[a-z_][a-z0-9-_]*$/));
141
149
  return toolName;
142
150
  };
143
151
 
@@ -145,7 +153,9 @@ const makeToolName = (name: string) => {
145
153
  const createStructFieldsFromSchema = (schema: Schema.Schema<any, any>): Record<string, Schema.Schema<any, any>> => {
146
154
  switch (schema.ast._tag) {
147
155
  case 'TypeLiteral':
148
- return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [prop.name, Schema.make(prop.type)]));
156
+ return Object.fromEntries(
157
+ schema.ast.propertySignatures.map((prop) => [prop.name, Schema.make(mapSchemaTypeForLLM(prop.type))]),
158
+ );
149
159
  case 'VoidKeyword':
150
160
  return {};
151
161
  default:
@@ -153,6 +163,18 @@ const createStructFieldsFromSchema = (schema: Schema.Schema<any, any>): Record<s
153
163
  }
154
164
  };
155
165
 
166
+ /**
167
+ * Picks an LLM-friendly schema type for the given schema AST.
168
+ * The picked schema type decodes to the original schema type.
169
+ */
170
+ const mapSchemaTypeForLLM = (ast: SchemaAST.AST): SchemaAST.AST => {
171
+ if (Type.Ref.isRefSchemaAST(ast)) {
172
+ return RefFromLLM.ast;
173
+ }
174
+
175
+ return ast;
176
+ };
177
+
156
178
  const isHandlerLike = (value: unknown): value is Toolkit.WithHandler<Record<string, Tool.Any>> => {
157
179
  return typeof (value as any).tools === 'object' && typeof (value as any).handle === 'function';
158
180
  };