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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/lib/browser/chunk-J5LGTIGS.mjs +10 -0
  2. package/dist/lib/browser/extraction/index.mjs +121 -164
  3. package/dist/lib/browser/extraction/index.mjs.map +4 -4
  4. package/dist/lib/browser/index.mjs +978 -157
  5. package/dist/lib/browser/index.mjs.map +4 -4
  6. package/dist/lib/browser/meta.json +1 -1
  7. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  8. package/dist/lib/node-esm/extraction/index.mjs +121 -164
  9. package/dist/lib/node-esm/extraction/index.mjs.map +4 -4
  10. package/dist/lib/node-esm/index.mjs +978 -157
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/types/src/conversation/context.d.ts +14 -7
  14. package/dist/types/src/conversation/context.d.ts.map +1 -1
  15. package/dist/types/src/conversation/conversation.d.ts +11 -12
  16. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  17. package/dist/types/src/diff.d.ts.map +1 -1
  18. package/dist/types/src/errors.d.ts +38 -42
  19. package/dist/types/src/errors.d.ts.map +1 -1
  20. package/dist/types/src/execution-graph.d.ts +85 -0
  21. package/dist/types/src/execution-graph.d.ts.map +1 -0
  22. package/dist/types/src/execution-graph.test.d.ts +2 -0
  23. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  24. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +1 -1
  25. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  26. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +64 -53
  27. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  28. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  29. package/dist/types/src/extraction/extraction.d.ts +24 -13
  30. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  31. package/dist/types/src/extraction/quotes.d.ts +1 -1
  32. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  33. package/dist/types/src/functions/services.d.ts +18 -5
  34. package/dist/types/src/functions/services.d.ts.map +1 -1
  35. package/dist/types/src/index.d.ts +2 -1
  36. package/dist/types/src/index.d.ts.map +1 -1
  37. package/dist/types/src/session/GenericToolkit.d.ts +84 -0
  38. package/dist/types/src/session/GenericToolkit.d.ts.map +1 -0
  39. package/dist/types/src/session/artifact-diff.d.ts +2 -2
  40. package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
  41. package/dist/types/src/session/error-handling.d.ts +2 -2
  42. package/dist/types/src/session/error-handling.d.ts.map +1 -1
  43. package/dist/types/src/session/format.d.ts +4 -174
  44. package/dist/types/src/session/format.d.ts.map +1 -1
  45. package/dist/types/src/session/index.d.ts +1 -0
  46. package/dist/types/src/session/index.d.ts.map +1 -1
  47. package/dist/types/src/session/observer.d.ts +3 -3
  48. package/dist/types/src/session/observer.d.ts.map +1 -1
  49. package/dist/types/src/session/session.d.ts +15 -11
  50. package/dist/types/src/session/session.d.ts.map +1 -1
  51. package/dist/types/src/session/toolkit.d.ts +7 -6
  52. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  53. package/dist/types/src/session/version-pin.d.ts +3 -3
  54. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  55. package/dist/types/src/types/artifact.d.ts +20 -0
  56. package/dist/types/src/types/artifact.d.ts.map +1 -0
  57. package/dist/types/src/types/index.d.ts +2 -0
  58. package/dist/types/src/types/index.d.ts.map +1 -0
  59. package/dist/types/tsconfig.tsbuildinfo +1 -1
  60. package/package.json +29 -32
  61. package/src/conversation/context.ts +49 -17
  62. package/src/conversation/conversation.ts +30 -25
  63. package/src/diff.test.ts +3 -3
  64. package/src/diff.ts +7 -0
  65. package/src/errors.ts +4 -4
  66. package/src/execution-graph.test.ts +740 -0
  67. package/src/execution-graph.ts +509 -0
  68. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +9 -9
  69. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +47 -55
  70. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +16 -16
  71. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +42 -43
  72. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  73. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +2 -0
  74. package/src/extraction/extraction.ts +7 -6
  75. package/src/extraction/quotes.test.ts +2 -2
  76. package/src/extraction/quotes.ts +3 -3
  77. package/src/functions/services.ts +93 -50
  78. package/src/index.ts +2 -1
  79. package/src/session/GenericToolkit.ts +130 -0
  80. package/src/session/artifact-diff.ts +2 -2
  81. package/src/session/error-handling.ts +11 -6
  82. package/src/session/format.test.ts +5 -4
  83. package/src/session/format.ts +19 -14
  84. package/src/session/index.ts +2 -0
  85. package/src/session/observer.ts +4 -3
  86. package/src/session/session.conversations.json +1 -0
  87. package/src/session/session.test.ts +51 -210
  88. package/src/session/session.ts +41 -29
  89. package/src/session/toolkit.ts +19 -13
  90. package/src/session/version-pin.ts +4 -5
  91. package/src/templates/{format.tpl → instructions/format.tpl} +4 -2
  92. package/src/templates/{system.tpl → instructions/system.tpl} +10 -12
  93. package/src/templates/system.ts +2 -2
  94. package/src/{types.ts → types/artifact.ts} +22 -3
  95. package/src/types/index.ts +5 -0
  96. package/dist/lib/browser/chunk-6WRGDEMH.mjs +0 -89
  97. package/dist/lib/browser/chunk-6WRGDEMH.mjs.map +0 -7
  98. package/dist/lib/browser/chunk-N4O3C3T5.mjs +0 -396
  99. package/dist/lib/browser/chunk-N4O3C3T5.mjs.map +0 -7
  100. package/dist/lib/browser/named-entity-recognition-O46UTCLR.mjs +0 -13
  101. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs +0 -91
  102. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs.map +0 -7
  103. package/dist/lib/node-esm/chunk-QVJ7EAM2.mjs +0 -398
  104. package/dist/lib/node-esm/chunk-QVJ7EAM2.mjs.map +0 -7
  105. package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs +0 -14
  106. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  107. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  108. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  109. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  110. package/dist/types/src/types.d.ts +0 -16
  111. package/dist/types/src/types.d.ts.map +0 -1
  112. package/src/session/__snapshots__/session.test.ts.snap +0 -32
  113. package/src/session/version-pin.test.ts +0 -7
  114. package/src/summarization/summarization.test.ts +0 -197
  115. /package/dist/lib/browser/{named-entity-recognition-O46UTCLR.mjs.map → chunk-J5LGTIGS.mjs.map} +0 -0
  116. /package/dist/lib/node-esm/{named-entity-recognition-W4VMRCH6.mjs.map → chunk-HSLMI22Q.mjs.map} +0 -0
  117. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -6,29 +6,31 @@ 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
- 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 { Testing } 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';
16
17
 
17
- import { extractionNerFn } from './extraction-ner-function';
18
+ import { extractionNerFunction } from './extraction-ner-function';
18
19
 
19
20
  describe.skip('NER EntityExtraction', () => {
20
21
  let builder: EchoTestBuilder;
21
22
  let db: EchoDatabase;
22
23
  let executor: FunctionExecutor;
23
24
  let testData: {
24
- transcriptJosiah: DataType.Message[];
25
- transcriptWoflram: DataType.Message[];
26
- transcriptMessages: DataType.Message[];
25
+ transcriptJosiah: Message.Message[];
26
+ transcriptWoflram: Message.Message[];
27
+ transcriptMessages: Message.Message[];
27
28
  documents: Testing.DocumentType[];
28
- contacts: Record<string, DataType.Person>;
29
- organizations: Record<string, DataType.Organization>;
29
+ contacts: Record<string, Person.Person>;
30
+ organizations: Record<string, Organization.Organization>;
30
31
  };
31
- const TYPES = [DataType.Organization, DataType.Person, Testing.Contact, Testing.DocumentType];
32
+
33
+ const TYPES = [Organization.Organization, Person.Person, Testing.Person, Testing.DocumentType];
32
34
 
33
35
  beforeAll(async () => {
34
36
  // TODO(dmaretskyi): Helper to scaffold this from a config.
@@ -45,8 +47,8 @@ describe.skip('NER EntityExtraction', () => {
45
47
  contacts: Object.fromEntries(Object.entries(data.contacts).map(([key, value]) => [key, db.add(value)])),
46
48
  organizations: Object.fromEntries(Object.entries(data.organizations).map(([key, value]) => [key, db.add(value)])),
47
49
  };
48
- await db.flush();
49
50
 
51
+ await db.flush();
50
52
  executor = new FunctionExecutor(
51
53
  new ServiceContainer().setServices({
52
54
  database: { db },
@@ -65,7 +67,7 @@ describe.skip('NER EntityExtraction', () => {
65
67
  message,
66
68
  objects: [...documents, ...Object.values(contacts)],
67
69
  },
68
- function: extractionNerFn,
70
+ function: extractionNerFunction,
69
71
  executor,
70
72
  });
71
73
  log.info('output', enhancedMessage);
@@ -74,7 +76,6 @@ describe.skip('NER EntityExtraction', () => {
74
76
 
75
77
  test('computational irreducibility', async () => {
76
78
  const { transcriptWoflram, documents, contacts } = testData;
77
-
78
79
  log.info('context', { documents, contacts });
79
80
  const message = transcriptWoflram[0];
80
81
  log.info('input', message);
@@ -86,7 +87,7 @@ describe.skip('NER EntityExtraction', () => {
86
87
  message,
87
88
  objects: [...documents, ...Object.values(contacts)],
88
89
  },
89
- function: extractionNerFn,
90
+ function: extractionNerFunction,
90
91
  executor,
91
92
  });
92
93
  log.info('output', { message: enhancedMessage.blocks[0], timeElapsed });
@@ -96,7 +97,6 @@ describe.skip('NER EntityExtraction', () => {
96
97
 
97
98
  test('org and document linking', async () => {
98
99
  const { transcriptJosiah, documents, contacts, organizations } = testData;
99
-
100
100
  log.info('context', { contacts, organizations, documents });
101
101
 
102
102
  for (const message of transcriptJosiah) {
@@ -107,7 +107,7 @@ describe.skip('NER EntityExtraction', () => {
107
107
  message,
108
108
  objects: [...documents, ...Object.values(contacts), ...Object.values(organizations)],
109
109
  },
110
- function: extractionNerFn,
110
+ function: extractionNerFunction,
111
111
  executor,
112
112
  });
113
113
  log.info('output', enhancedMessage);
@@ -2,56 +2,55 @@
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-schema';
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
 
9
+ /**
10
+ * Named Entity Recognition model
11
+ */
18
12
  // TODO(mykola): Make it use vector index to query objects and not pass objects as input.
19
- export const extractionNerFn = defineFunction({
13
+ export const extractionNerFunction = defineFunction({
14
+ key: 'dxos.org/function/extraction/extract-entities',
15
+ name: 'Extract Entities',
20
16
  description: 'Extracts named entities from a text',
21
17
  inputSchema: ExtractionInput,
22
18
  outputSchema: ExtractionOutput,
23
19
  handler: async ({ data: { message, options }, context }) => {
24
- log.info('input', { message, options });
25
- const startTime = performance.now();
26
- const { db } = context.getService(DatabaseService);
27
- const { extractFullEntities } = await import('./named-entity-recognition');
28
-
29
- const entitiesPromise = Promise.all(
30
- message.blocks.map(async (block) => {
31
- invariant(block._tag === 'transcript' || block._tag === 'text', 'Block must have text');
32
- return extractFullEntities(block.text);
33
- }),
34
- ).then((entities) => entities.flat());
35
- const entities = options?.timeout ? await asyncTimeout(entitiesPromise, options.timeout) : await entitiesPromise;
36
- log.info('entities', { entities });
37
- const quoteReferences = await findQuotes(
38
- entities.map((entity) => entity.word),
39
- db,
40
- );
41
- const blocksWithReferences = message.blocks.map((block, i) => {
42
- invariant(block._tag === 'transcript' || block._tag === 'text', 'Block must have text');
43
- return { ...block, text: insertReferences(block._tag, quoteReferences) };
44
- });
45
- const messageWithReferences = create(DataType.Message, {
46
- ...message,
47
- blocks: blocksWithReferences,
48
- });
49
-
50
- log.info('output', { messageWithReferences });
51
-
52
- return {
53
- message: messageWithReferences,
54
- timeElapsed: performance.now() - startTime,
55
- };
20
+ throw new Error('not implemented');
21
+ // log.info('input', { message, options });
22
+ // const startTime = performance.now();
23
+ // const { db } = context.getService(DatabaseService);
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
+ // };
56
55
  },
57
56
  });
@@ -6,11 +6,13 @@ 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
 
13
- describe('NamedEntityRecognition', () => {
14
+ // TODO(mykola): This should not run on CI.
15
+ describe.skip('NamedEntityRecognition', () => {
14
16
  let ner: TokenClassificationPipelineType;
15
17
 
16
18
  beforeAll(async () => {
@@ -56,8 +58,10 @@ describe('NamedEntityRecognition', () => {
56
58
  test('own data', async () => {
57
59
  const { transcriptWoflram, transcriptJosiah } = await createTestData();
58
60
 
59
- const blocks = [...transcriptWoflram, ...transcriptJosiah].flatMap((message) =>
60
- 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
+ ),
61
65
  );
62
66
 
63
67
  for (const block of blocks) {
@@ -69,8 +73,10 @@ describe('NamedEntityRecognition', () => {
69
73
  test('more own data', async () => {
70
74
  const { transcriptMessages } = await createTestData();
71
75
 
72
- const blocks = transcriptMessages.flatMap((message) =>
73
- 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
+ ),
74
80
  );
75
81
 
76
82
  for (const block of blocks) {
@@ -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,16 +2,17 @@
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';
9
- import { type FunctionDefinition, type FunctionExecutor } from '@dxos/functions';
8
+ import { Expando } from '@dxos/echo/internal';
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
+ message: Message.Message,
15
16
  objects: Schema.optional(Schema.Array(Expando)),
16
17
  options: Schema.optional(
17
18
  Schema.Struct({
@@ -23,7 +24,7 @@ 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> {}
@@ -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
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,97 +2,136 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { AiTool, type AiToolkit } from '@effect/ai';
6
- import { Context, Effect, Layer, 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 { type FunctionDefinition, LocalFunctionExecutionService } from '@dxos/functions';
15
+ import { Query } from '@dxos/echo';
16
+ import { DatabaseService } from '@dxos/echo-db';
17
+ import { Function, FunctionDefinition, FunctionInvocationService } from '@dxos/functions';
11
18
  import { invariant } from '@dxos/invariant';
12
19
 
20
+ /**
21
+ * Constructs a `ToolResolverService` whose `resolve(id)` looks up tools in the following order:
22
+ * 1. Toolkit: return an existing tool from the provided `toolkit` if one is present under `id`.
23
+ * 2. Functions in DB: query `FunctionType` by `key=id`; if found, deserialize and project to a tool
24
+ * (propagating any `deployedFunctionId` discovered in the object's metadata).
25
+ * 3. Functions passed in: fall back to a matching `FunctionDefinition` from the `functions` array.
26
+ *
27
+ * If none of the above yield a match, the effect fails with `AiToolNotFoundError`.
28
+ *
29
+ * Requires `DatabaseService` in the environment.
30
+ */
13
31
  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);
32
+ functions: FunctionDefinition.Any[],
33
+ toolkit: Toolkit.Toolkit<any>,
34
+ ): Layer.Layer<ToolResolverService, never, DatabaseService> => {
35
+ return Layer.effect(
36
+ ToolResolverService,
37
+ Effect.gen(function* () {
38
+ const dbService = yield* DatabaseService;
39
+ return {
40
+ resolve: (id): Effect.Effect<Tool.Any, AiToolNotFoundError> =>
41
+ Effect.gen(function* () {
42
+ const tool = toolkit.tools[id];
43
+ if (tool) {
44
+ return tool;
45
+ }
46
+
47
+ const {
48
+ objects: [dbFunction],
49
+ } = yield* DatabaseService.runQuery(Query.type(Function.Function, { key: id }));
50
+
51
+ const functionDef = dbFunction
52
+ ? FunctionDefinition.deserialize(dbFunction)
53
+ : functions.find((fn) => fn.key === id);
54
+
55
+ if (!functionDef) {
56
+ return yield* Effect.fail(new AiToolNotFoundError(id));
57
+ }
58
+
59
+ return projectFunctionToTool(functionDef);
60
+ }).pipe(Effect.provideService(DatabaseService, dbService)),
61
+ } satisfies Context.Tag.Service<ToolResolverService>;
30
62
  }),
31
- });
63
+ );
32
64
  };
33
65
 
34
66
  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> => {
67
+ toolkit: Toolkit.Toolkit<any>,
68
+ handlersLayer: Layer.Layer<Tool.Handler<any>, never, never>,
69
+ ): Layer.Layer<ToolExecutionService, never, FunctionInvocationService> => {
39
70
  return Layer.effect(
40
71
  ToolExecutionService,
41
72
  Effect.gen(function* () {
42
73
  const toolkitHandler = yield* toolkit.pipe(Effect.provide(handlersLayer));
43
- const localFunctionExecutionService = yield* LocalFunctionExecutionService;
74
+ invariant(isHandlerLike(toolkitHandler));
75
+ const functionInvocationService = yield* FunctionInvocationService;
44
76
 
45
77
  return {
46
78
  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)) {
79
+ const makeHandler = (tool: Tool.Any): ((params: unknown) => Effect.Effect<unknown, any, any>) => {
80
+ return Effect.fn(`toolFunctionHandler ${tool.name}`)(function* (input: any) {
81
+ if (toolkitHandler.tools[tool.name]) {
82
+ if (Tool.isProviderDefined(tool)) {
83
+ throw new Error('Attempted to call a provider-defined tool');
84
+ }
50
85
  // TODO(wittjosiah): Everything is `never` here.
51
- return yield* (toolkitHandler.handle as any)(tool.name, input);
86
+ const { result } = yield* (toolkitHandler.handle as any)(tool.name, input);
87
+ return result;
52
88
  }
53
89
 
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
- }
90
+ const { definition: functionDef } = Context.get(FunctionToolAnnotation)(tool.annotations as any);
59
91
 
60
- return yield* localFunctionExecutionService
61
- .invokeFunction(functionDef, input)
92
+ return yield* functionInvocationService
93
+ .invokeFunction(functionDef, input as any)
62
94
  .pipe(Effect.catchAllDefect((defect) => Effect.fail(defect)));
63
95
  });
64
96
  };
65
97
 
66
- return toolkit.of(Record.map(toolkit.tools, (tool, _name) => makeHandler(tool)) as any) as any;
98
+ return toolkit.of(
99
+ Record.map(toolkit.tools, (tool, _name) => (Tool.isUserDefined(tool) ? makeHandler(tool) : null)) as any,
100
+ ) as any;
67
101
  },
68
102
  };
69
103
  }),
70
104
  );
71
105
  };
72
106
 
73
- /**
74
- * Tools that are projected from functions have this annotation.
75
- */
76
- class FunctionToolAnnotation extends Context.Tag('@dxos/assisatnt/FunctionToolAnnotation')<
107
+ class FunctionToolAnnotation extends Context.Tag('@dxos/assistant/FunctionToolAnnotation')<
77
108
  FunctionToolAnnotation,
78
- {
79
- functionName: string;
80
- }
109
+ { definition: FunctionDefinition.Any }
81
110
  >() {}
82
111
 
83
- const toolCache = new WeakMap<FunctionDefinition<any, any>, AiTool.Any>();
112
+ const toolCache = new WeakMap<FunctionDefinition.Any, Tool.Any>();
84
113
 
85
- const projectFunctionToTool = (fn: FunctionDefinition<any, any>): AiTool.Any => {
114
+ /**
115
+ * Projects a `FunctionDefinition` into an `AiTool`.
116
+ *
117
+ * @param fn The function definition to project into a tool.
118
+ * @param meta Optional projection metadata.
119
+ * @param meta.deployedFunctionId Backend deployment ID used for remote invocation when present.
120
+ * This is the EDGE service's function deployment identifier (not the ECHO object ID/DXN and not `FunctionDefinition.key`).
121
+ */
122
+ const projectFunctionToTool = (fn: FunctionDefinition.Any): Tool.Any => {
86
123
  if (toolCache.has(fn)) {
87
124
  return toolCache.get(fn)!;
88
125
  }
89
126
 
90
- const tool = AiTool.make(makeToolName(fn.name), {
127
+ // TODO(burdon): Use and map function.key?
128
+ // TODO(dmaretskyi): Use function key instead.
129
+ const tool = Tool.make(makeToolName(fn.name), {
91
130
  description: fn.description,
92
131
  parameters: createStructFieldsFromSchema(fn.inputSchema),
93
132
  // TODO(dmaretskyi): Include output schema.
94
133
  failure: Schema.Any, // TODO(dmaretskyi): Better type for the failure?
95
- }).annotate(FunctionToolAnnotation, { functionName: fn.name });
134
+ }).annotate(FunctionToolAnnotation, { definition: fn });
96
135
  toolCache.set(fn, tool);
97
136
  return tool;
98
137
  };
@@ -101,8 +140,8 @@ const projectFunctionToTool = (fn: FunctionDefinition<any, any>): AiTool.Any =>
101
140
  * @returns Tool name produced from function name by escaping invalid characters.
102
141
  */
103
142
  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-_]*$/));
143
+ const toolName = name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
144
+ invariant(toolName.match(/^[a-z_][a-z0-9-_]*$/));
106
145
  return toolName;
107
146
  };
108
147
 
@@ -117,3 +156,7 @@ const createStructFieldsFromSchema = (schema: Schema.Schema<any, any>): Record<s
117
156
  return todo(`Unsupported schema AST: ${schema.ast._tag}`);
118
157
  }
119
158
  };
159
+
160
+ const isHandlerLike = (value: unknown): value is Toolkit.WithHandler<Record<string, Tool.Any>> => {
161
+ return typeof (value as any).tools === 'object' && typeof (value as any).handle === 'function';
162
+ };
package/src/index.ts CHANGED
@@ -4,8 +4,9 @@
4
4
 
5
5
  export * from './conversation';
6
6
  export * from './diff';
7
+ export * from './errors';
8
+ export * from './execution-graph';
7
9
  export * from './functions';
8
10
  export * from './session';
9
11
  export * from './templates';
10
12
  export * from './types';
11
- export * from './errors';