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

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 (196) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +2 -1
  3. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
  4. package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +7 -0
  5. package/dist/lib/neutral/extraction/index.mjs +204 -0
  6. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  7. package/dist/lib/neutral/index.mjs +1755 -0
  8. package/dist/lib/neutral/index.mjs.map +7 -0
  9. package/dist/lib/neutral/meta.json +1 -0
  10. package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
  11. package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
  12. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  13. package/dist/types/src/extraction/extraction.d.ts +1066 -273
  14. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  15. package/dist/types/src/extraction/index.d.ts +0 -1
  16. package/dist/types/src/extraction/index.d.ts.map +1 -1
  17. package/dist/types/src/extraction/quotes.d.ts +3 -3
  18. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  19. package/dist/types/src/functions/services.d.ts +15 -4
  20. package/dist/types/src/functions/services.d.ts.map +1 -1
  21. package/dist/types/src/index.d.ts +2 -5
  22. package/dist/types/src/index.d.ts.map +1 -1
  23. package/dist/types/src/request/AiRequest.d.ts +104 -0
  24. package/dist/types/src/request/AiRequest.d.ts.map +1 -0
  25. package/dist/types/src/request/artifact-diff.d.ts +27 -0
  26. package/dist/types/src/request/artifact-diff.d.ts.map +1 -0
  27. package/dist/types/src/request/format.d.ts +15 -0
  28. package/dist/types/src/request/format.d.ts.map +1 -0
  29. package/dist/types/src/request/index.d.ts +4 -0
  30. package/dist/types/src/request/index.d.ts.map +1 -0
  31. package/dist/types/src/request/observer.d.ts +23 -0
  32. package/dist/types/src/request/observer.d.ts.map +1 -0
  33. package/dist/types/src/{session → request}/version-pin.d.ts +4 -4
  34. package/dist/types/src/request/version-pin.d.ts.map +1 -0
  35. package/dist/types/src/session/AiContext.d.ts +154 -0
  36. package/dist/types/src/session/AiContext.d.ts.map +1 -0
  37. package/dist/types/src/session/AiContext.test.d.ts +2 -0
  38. package/dist/types/src/session/AiContext.test.d.ts.map +1 -0
  39. package/dist/types/src/session/AiSession.d.ts +73 -0
  40. package/dist/types/src/session/AiSession.d.ts.map +1 -0
  41. package/dist/types/src/session/index.d.ts +3 -2
  42. package/dist/types/src/session/index.d.ts.map +1 -1
  43. package/dist/types/src/session/toolkit.d.ts +16 -0
  44. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  45. package/dist/types/src/templates/index.d.ts +1 -1
  46. package/dist/types/src/templates/system.d.ts +17 -0
  47. package/dist/types/src/templates/system.d.ts.map +1 -0
  48. package/dist/types/src/util/artifact.d.ts +27 -0
  49. package/dist/types/src/util/artifact.d.ts.map +1 -0
  50. package/dist/types/src/util/diff.d.ts +17 -0
  51. package/dist/types/src/util/diff.d.ts.map +1 -0
  52. package/dist/types/src/util/diff.test.d.ts +2 -0
  53. package/dist/types/src/util/diff.test.d.ts.map +1 -0
  54. package/dist/types/src/util/error-handling.d.ts +4 -0
  55. package/dist/types/src/util/error-handling.d.ts.map +1 -0
  56. package/dist/types/src/util/errors.d.ts +67 -0
  57. package/dist/types/src/util/errors.d.ts.map +1 -0
  58. package/dist/types/src/util/execution-graph.d.ts +85 -0
  59. package/dist/types/src/util/execution-graph.d.ts.map +1 -0
  60. package/dist/types/src/util/execution-graph.test.d.ts +2 -0
  61. package/dist/types/src/util/execution-graph.test.d.ts.map +1 -0
  62. package/dist/types/src/util/index.d.ts +7 -0
  63. package/dist/types/src/util/index.d.ts.map +1 -0
  64. package/dist/types/src/util/tracing.d.ts +233 -0
  65. package/dist/types/src/util/tracing.d.ts.map +1 -0
  66. package/dist/types/tsconfig.tsbuildinfo +1 -1
  67. package/package.json +42 -36
  68. package/src/extraction/extraction-ner-function/index.ts +0 -1
  69. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  70. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +2 -0
  71. package/src/extraction/extraction.ts +44 -15
  72. package/src/extraction/index.ts +0 -1
  73. package/src/extraction/quotes.test.ts +3 -3
  74. package/src/extraction/quotes.ts +6 -7
  75. package/src/functions/services.ts +173 -98
  76. package/src/index.ts +2 -5
  77. package/src/request/AiRequest.ts +348 -0
  78. package/src/request/artifact-diff.ts +41 -0
  79. package/src/request/format.ts +147 -0
  80. package/src/request/index.ts +8 -0
  81. package/src/request/observer.ts +62 -0
  82. package/src/{session → request}/version-pin.ts +8 -8
  83. package/src/session/AiContext.test.ts +53 -0
  84. package/src/session/AiContext.ts +403 -0
  85. package/src/session/AiSession.ts +324 -0
  86. package/src/session/index.ts +4 -2
  87. package/src/session/toolkit.ts +47 -0
  88. package/src/templates/index.ts +1 -1
  89. package/src/templates/instructions/format.tpl +57 -0
  90. package/src/templates/instructions/system.tpl +96 -0
  91. package/src/templates/system.ts +42 -0
  92. package/src/typings.d.ts +5 -0
  93. package/src/util/artifact.ts +88 -0
  94. package/src/util/diff.test.ts +74 -0
  95. package/src/util/diff.ts +93 -0
  96. package/src/util/error-handling.ts +42 -0
  97. package/src/util/errors.ts +15 -0
  98. package/src/util/execution-graph.test.ts +740 -0
  99. package/src/util/execution-graph.ts +519 -0
  100. package/src/util/index.ts +10 -0
  101. package/src/util/tracing.ts +57 -0
  102. package/dist/lib/browser/index.mjs +0 -1831
  103. package/dist/lib/browser/index.mjs.map +0 -7
  104. package/dist/lib/browser/meta.json +0 -1
  105. package/dist/lib/node-esm/index.mjs +0 -1833
  106. package/dist/lib/node-esm/index.mjs.map +0 -7
  107. package/dist/lib/node-esm/meta.json +0 -1
  108. package/dist/types/bin/chat.d.ts +0 -2
  109. package/dist/types/bin/chat.d.ts.map +0 -1
  110. package/dist/types/src/context/binder.d.ts +0 -34
  111. package/dist/types/src/context/binder.d.ts.map +0 -1
  112. package/dist/types/src/context/binding.d.ts +0 -56
  113. package/dist/types/src/context/binding.d.ts.map +0 -1
  114. package/dist/types/src/context/index.d.ts +0 -3
  115. package/dist/types/src/context/index.d.ts.map +0 -1
  116. package/dist/types/src/conversation/conversation.d.ts +0 -38
  117. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  118. package/dist/types/src/conversation/index.d.ts +0 -2
  119. package/dist/types/src/conversation/index.d.ts.map +0 -1
  120. package/dist/types/src/errors.d.ts +0 -38
  121. package/dist/types/src/errors.d.ts.map +0 -1
  122. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
  123. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
  124. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
  125. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
  126. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
  127. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
  128. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -302
  129. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
  130. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
  131. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
  132. package/dist/types/src/research/exa.d.ts +0 -12
  133. package/dist/types/src/research/exa.d.ts.map +0 -1
  134. package/dist/types/src/research/graph.d.ts +0 -51
  135. package/dist/types/src/research/graph.d.ts.map +0 -1
  136. package/dist/types/src/research/graph.test.d.ts +0 -2
  137. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  138. package/dist/types/src/research/index.d.ts +0 -4
  139. package/dist/types/src/research/index.d.ts.map +0 -1
  140. package/dist/types/src/research/research.d.ts +0 -10
  141. package/dist/types/src/research/research.d.ts.map +0 -1
  142. package/dist/types/src/research/research.test.d.ts +0 -2
  143. package/dist/types/src/research/research.test.d.ts.map +0 -1
  144. package/dist/types/src/session/session.d.ts +0 -260
  145. package/dist/types/src/session/session.d.ts.map +0 -1
  146. package/dist/types/src/session/session.test.d.ts +0 -2
  147. package/dist/types/src/session/session.test.d.ts.map +0 -1
  148. package/dist/types/src/session/version-pin.d.ts.map +0 -1
  149. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  150. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  151. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  152. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  153. package/dist/types/src/templates/prompt.d.ts +0 -30
  154. package/dist/types/src/templates/prompt.d.ts.map +0 -1
  155. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  156. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  157. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  158. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  159. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  160. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  161. package/dist/types/src/testing/index.d.ts +0 -3
  162. package/dist/types/src/testing/index.d.ts.map +0 -1
  163. package/dist/types/src/types.d.ts +0 -13
  164. package/dist/types/src/types.d.ts.map +0 -1
  165. package/src/context/binder.ts +0 -103
  166. package/src/context/binding.ts +0 -32
  167. package/src/context/index.ts +0 -6
  168. package/src/conversation/conversation.ts +0 -96
  169. package/src/conversation/index.ts +0 -5
  170. package/src/errors.ts +0 -10
  171. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -83
  172. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -70
  173. package/src/extraction/extraction-llm-function/index.ts +0 -5
  174. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -115
  175. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -57
  176. package/src/research/exa.ts +0 -97
  177. package/src/research/graph.test.ts +0 -64
  178. package/src/research/graph.ts +0 -369
  179. package/src/research/index.ts +0 -7
  180. package/src/research/instructions-research.tpl +0 -98
  181. package/src/research/research.test.ts +0 -190
  182. package/src/research/research.ts +0 -87
  183. package/src/session/__snapshots__/session.test.ts.snap +0 -32
  184. package/src/session/session.test.ts +0 -310
  185. package/src/session/session.ts +0 -336
  186. package/src/session/version-pin.test.ts +0 -7
  187. package/src/summarization/summarization.test.ts +0 -208
  188. package/src/templates/assistant.tpl +0 -111
  189. package/src/templates/prompt.ts +0 -45
  190. package/src/testing/exa-search-1748337321991.ts +0 -131
  191. package/src/testing/exa-search-1748337331526.ts +0 -144
  192. package/src/testing/exa-search-1748337344119.ts +0 -133
  193. package/src/testing/index.ts +0 -11
  194. package/src/typedefs.d.ts +0 -8
  195. package/src/types.ts +0 -47
  196. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -2,72 +2,149 @@
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 Option from 'effect/Option';
11
+ import * as Record from 'effect/Record';
12
+ import * as Schema from 'effect/Schema';
13
+ import * as SchemaAST from 'effect/SchemaAST';
7
14
 
8
15
  import { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from '@dxos/ai';
16
+ import { OpaqueToolkit } from '@dxos/ai';
17
+ import { Operation, OperationRegistry } from '@dxos/compute';
9
18
  import { todo } from '@dxos/debug';
10
- import { FunctionError, type FunctionContext, type FunctionDefinition, type Services } from '@dxos/functions';
19
+ import { Ref } from '@dxos/echo';
11
20
  import { invariant } from '@dxos/invariant';
12
21
 
13
- export const makeToolResolverFromFunctions = (
14
- 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);
22
+ import { RefFromLLM } from '../util';
23
+
24
+ export const makeToolResolverFromOperations = <R = never>({
25
+ toolkit: extraToolkit = OpaqueToolkit.empty,
26
+ }: { toolkit?: OpaqueToolkit.OpaqueToolkit<never, never, R> } = {}): Layer.Layer<
27
+ ToolResolverService,
28
+ never,
29
+ OpaqueToolkit.OpaqueToolkitProvider | OperationRegistry.Service | R
30
+ > => {
31
+ return Layer.effect(
32
+ ToolResolverService,
33
+ Effect.gen(function* () {
34
+ const toolkitProvider = yield* OpaqueToolkit.OpaqueToolkitProvider;
35
+ const operationRegistry = yield* OperationRegistry.Service;
36
+ return {
37
+ resolve: (id): Effect.Effect<Tool.Any, AiToolNotFoundError> =>
38
+ Effect.gen(function* () {
39
+ const toolkit = OpaqueToolkit.merge(extraToolkit, toolkitProvider.getToolkit());
40
+
41
+ const tool = toolkit.toolkit.tools[id];
42
+ if (tool) {
43
+ return tool;
44
+ }
45
+
46
+ return yield* operationRegistry.resolve(id).pipe(
47
+ Effect.flatMap(
48
+ Option.match({
49
+ onSome: (_) => Effect.succeed(projectFunctionToTool(_)),
50
+ onNone: () => Effect.fail(new AiToolNotFoundError(id)),
51
+ }),
52
+ ),
53
+ );
54
+ }),
55
+ } satisfies Context.Tag.Service<ToolResolverService>;
24
56
  }),
25
- });
57
+ );
26
58
  };
27
59
 
28
- 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
- });
60
+ export const makeToolExecutionService = <E, R>(opts: {
61
+ invoke: (tool: Tool.Any, input: unknown) => Effect.Effect<unknown>;
62
+ }): Layer.Layer<ToolExecutionService, never, OpaqueToolkit.OpaqueToolkitProvider> =>
63
+ Layer.effect(
64
+ ToolExecutionService,
65
+ Effect.gen(function* () {
66
+ const toolkitProvider = yield* OpaqueToolkit.OpaqueToolkitProvider;
67
+ const toolkit = toolkitProvider.getToolkit();
68
+
69
+ const toolkitHandler = yield* toolkit.toolkit.pipe(Effect.provide(toolkit.layer));
70
+ invariant(isHandlerLike(toolkitHandler));
71
+
72
+ return {
73
+ handlersFor: (toolkit) => {
74
+ const makeHandler = (tool: Tool.Any): ((params: unknown) => Effect.Effect<unknown, any, any>) => {
75
+ return Effect.fn(`toolFunctionHandler ${tool.name}`)(function* (input: any) {
76
+ if (toolkitHandler.tools[tool.name]) {
77
+ if (Tool.isProviderDefined(tool)) {
78
+ throw new Error('Attempted to call a provider-defined tool');
79
+ }
80
+
81
+ // TODO(wittjosiah): Everything is `never` here.
82
+ const { result } = yield* (toolkitHandler.handle as any)(tool.name, input);
83
+ return result;
84
+ }
85
+
86
+ return yield* opts.invoke(tool, input).pipe(Effect.catchAllDefect((defect) => Effect.fail(defect)));
87
+ });
88
+ };
89
+
90
+ return toolkit.of(
91
+ Record.map(toolkit.tools, (tool, _name) => (Tool.isUserDefined(tool) ? makeHandler(tool) : null)) as any,
92
+ ) as any;
93
+ },
43
94
  };
95
+ }),
96
+ );
44
97
 
45
- return toolkit.of(Record.map(toolkit.tools, (tool, name) => makeHandler(tool)) as any) as any;
46
- },
47
- });
98
+ export const makeToolExecutionServiceFromOperationInvoker = (): Layer.Layer<
99
+ ToolExecutionService,
100
+ never,
101
+ Operation.Service | OpaqueToolkit.OpaqueToolkitProvider
102
+ > => {
103
+ return Layer.unwrapEffect(
104
+ Effect.gen(function* () {
105
+ const operationInvoker = yield* Operation.Service;
106
+
107
+ return makeToolExecutionService({
108
+ invoke: (tool, input) =>
109
+ Effect.gen(function* () {
110
+ const operationDef = getOperationFromTool(tool).pipe(Option.getOrThrow);
111
+
112
+ return yield* operationInvoker.invoke(operationDef, input).pipe(Effect.orDie);
113
+ }),
114
+ });
115
+ }),
116
+ );
48
117
  };
49
118
 
50
- /**
51
- * Tools that are projected from functions have this annotation.
52
- */
53
- class FunctionToolAnnotation extends Context.Tag('@dxos/assisatnt/FunctionToolAnnotation')<
119
+ export const ToolExecutionServices = Layer.mergeAll(
120
+ makeToolResolverFromOperations(),
121
+ makeToolExecutionServiceFromOperationInvoker(),
122
+ );
123
+
124
+ class FunctionToolAnnotation extends Context.Tag('@dxos/assistant/FunctionToolAnnotation')<
54
125
  FunctionToolAnnotation,
55
- {
56
- functionName: string;
57
- }
126
+ { definition: Operation.Definition.Any }
58
127
  >() {}
59
128
 
60
- const toolCache = new WeakMap<FunctionDefinition<any, any>, AiTool.Any>();
61
- const projectFunctionToTool = (fn: FunctionDefinition<any, any>): AiTool.Any => {
129
+ export const getOperationFromTool = (tool: Tool.Any): Option.Option<Operation.Definition.Any> => {
130
+ return Context.getOption(FunctionToolAnnotation)(tool.annotations).pipe(Option.map(({ definition }) => definition));
131
+ };
132
+
133
+ const toolCache = new WeakMap<Operation.Definition.Any, Tool.Any>();
134
+
135
+ /**
136
+ * Projects an `Operation.Definition` into an `AiTool`.
137
+ */
138
+ const projectFunctionToTool = (fn: Operation.Definition.Any): Tool.Any => {
62
139
  if (toolCache.has(fn)) {
63
140
  return toolCache.get(fn)!;
64
141
  }
65
- const tool = AiTool.make(makeToolName(fn.name), {
66
- description: fn.description,
67
- parameters: createStructFieldsFromSchema(fn.inputSchema),
68
- // TODO(dmaretskyi): Include output schema.
69
- failure: Schema.Any, // TODO(dmaretskyi): Better type for the failure?
70
- }).annotate(FunctionToolAnnotation, { functionName: fn.name });
142
+
143
+ const tool = Tool.make(makeToolName(fn.meta.name ?? fn.meta.key), {
144
+ description: fn.meta.description,
145
+ parameters: createStructFieldsFromSchema(fn.input),
146
+ failure: Schema.Any,
147
+ }).annotate(FunctionToolAnnotation, { definition: fn });
71
148
  toolCache.set(fn, tool);
72
149
  return tool;
73
150
  };
@@ -76,64 +153,62 @@ const projectFunctionToTool = (fn: FunctionDefinition<any, any>): AiTool.Any =>
76
153
  * @returns Tool name produced from function name by escaping invalid characters.
77
154
  */
78
155
  const makeToolName = (name: string) => {
79
- const toolName = name.replace(/[^a-zA-Z0-9]/g, '');
80
- invariant(toolName.match(/^[a-zA-Z_][a-zA-Z0-9-_]*$/));
156
+ const toolName = name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
157
+ invariant(toolName.match(/^[a-z_][a-z0-9-_]*$/));
81
158
  return toolName;
82
159
  };
83
160
 
84
161
  // TODO(dmaretskyi): Factor out.
85
162
  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
- );
163
+ switch (schema.ast._tag) {
164
+ case 'TypeLiteral':
165
+ return Object.fromEntries(
166
+ schema.ast.propertySignatures.map((prop) => [prop.name, Schema.make(mapSchemaTypeForLLM(prop.type))]),
167
+ );
168
+ case 'VoidKeyword':
169
+ return {};
170
+ default:
171
+ return todo(`Unsupported schema AST: ${schema.ast._tag}`);
172
+ }
92
173
  };
93
174
 
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 })),
175
+ /**
176
+ * Picks an LLM-friendly schema type for the given schema AST.
177
+ * The picked schema type decodes to the original schema type.
178
+ */
179
+ const mapSchemaTypeForLLM = (ast: SchemaAST.AST): SchemaAST.AST => {
180
+ if (Ref.isRefType(ast)) {
181
+ const description = ast.annotations.description
182
+ ? ast.annotations.description + '\n' + RefFromLLM.ast.annotations.description
183
+ : (RefFromLLM.ast.annotations.description as string);
184
+ return RefFromLLM.annotations({ description }).ast;
185
+ } else if (SchemaAST.isTupleType(ast)) {
186
+ return new SchemaAST.TupleType(
187
+ ast.elements.map((t) => new SchemaAST.OptionalType(mapSchemaTypeForLLM(t.type), t.isOptional, t.annotations)),
188
+ ast.rest.map((t) => new SchemaAST.Type(mapSchemaTypeForLLM(t.type), t.annotations)),
189
+ ast.isReadonly,
190
+ ast.annotations,
191
+ );
192
+ } else if (SchemaAST.isTypeLiteral(ast)) {
193
+ return new SchemaAST.TypeLiteral(
194
+ ast.propertySignatures.map(
195
+ (p) =>
196
+ new SchemaAST.PropertySignature(
197
+ p.name,
198
+ mapSchemaTypeForLLM(p.type),
199
+ p.isOptional,
200
+ p.isReadonly,
201
+ p.annotations,
202
+ ),
131
203
  ),
204
+ ast.indexSignatures,
205
+ ast.annotations,
132
206
  );
207
+ }
133
208
 
134
- // Assert output matches schema
135
- const assertOutput = fnDef.outputSchema?.pipe(Schema.asserts);
136
- (assertOutput as any)(data);
209
+ return ast;
210
+ };
137
211
 
138
- return data;
139
- }).pipe(Effect.withSpan('invokeFunction', { attributes: { name: fnDef.name } }));
212
+ const isHandlerLike = (value: unknown): value is Toolkit.WithHandler<Record<string, Tool.Any>> => {
213
+ return typeof (value as any).tools === 'object' && typeof (value as any).handle === 'function';
214
+ };
package/src/index.ts CHANGED
@@ -2,11 +2,8 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- export * from './context';
6
- export * from './conversation';
7
- export * from './extraction';
8
5
  export * from './functions';
9
- export * from './research';
6
+ export * from './request';
10
7
  export * from './session';
11
8
  export * from './templates';
12
- export * from './types';
9
+ export * from './util';
@@ -0,0 +1,348 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import type * as AiError from '@effect/ai/AiError';
8
+ import * as LanguageModel from '@effect/ai/LanguageModel';
9
+ import * as Array from 'effect/Array';
10
+ import * as Chunk from 'effect/Chunk';
11
+ import * as Effect from 'effect/Effect';
12
+ import { pipe } from 'effect/Function';
13
+ import * as Option from 'effect/Option';
14
+ import * as Stream from 'effect/Stream';
15
+
16
+ import {
17
+ AiParser,
18
+ AiPreprocessor,
19
+ AiSummarizer,
20
+ type AiToolNotFoundError,
21
+ callTool,
22
+ type OpaqueToolkit,
23
+ type PromptPreprocessingError,
24
+ type ToolExecutionService,
25
+ type ToolResolverService,
26
+ withoutToolCallParising,
27
+ } from '@dxos/ai';
28
+ import { type Blueprint, Trace, Operation, OperationRegistry } from '@dxos/compute';
29
+ import { Database, Obj } from '@dxos/echo';
30
+ import { log } from '@dxos/log';
31
+ import { ContentBlock, Message } from '@dxos/types';
32
+
33
+ import { type AiAssistantError, CompleteBlock, PartialBlock } from '../util';
34
+ import { formatSystemPrompt, formatUserPrompt } from './format';
35
+ import { GenerationObserver } from './observer';
36
+
37
+ export type RunError = AiError.AiError | PromptPreprocessingError | AiToolNotFoundError | AiAssistantError;
38
+
39
+ export type RunRequirements =
40
+ | LanguageModel.LanguageModel
41
+ | ToolExecutionService
42
+ | ToolResolverService
43
+ | Database.Service
44
+ | Operation.Service
45
+ | OperationRegistry.Service
46
+ | Trace.TraceService;
47
+
48
+ export type Options = {
49
+ /**
50
+ * Summarize before executing the prompt if the existing history exceeds this threshold.
51
+ */
52
+ summarizationThreshold?: number;
53
+
54
+ // TODO(dmaretskyi): Plan to phase out in favor of TracingService and the return type being a stream.
55
+ observer?: GenerationObserver;
56
+ /**
57
+ * Callback for when a message is received from the user, model, or tool.
58
+ * This is useful for streaming the output to a queue.
59
+ */
60
+ onOutput?: (message: Message.Message) => Effect.Effect<void, never, never>;
61
+ };
62
+
63
+ export type RunProps<R = never> = {
64
+ prompt: string | ContentBlock.Any[];
65
+ // TODO(wittjosiah): Rename to systemPrompt.
66
+ system?: string;
67
+ history?: Message.Message[];
68
+ objects?: Obj.Unknown[];
69
+ blueprints?: readonly Blueprint.Blueprint[];
70
+ toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
71
+ };
72
+
73
+ export type BeginProps = {
74
+ prompt: string | ContentBlock.Any[];
75
+ system?: string;
76
+ history?: Message.Message[];
77
+ objects?: Obj.Unknown[];
78
+ blueprints?: readonly Blueprint.Blueprint[];
79
+ };
80
+
81
+ export type TurnProps<R = never> = {
82
+ system: string;
83
+ toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
84
+ };
85
+
86
+ export type TurnResult = {
87
+ messages: Message.Message[];
88
+ done: boolean;
89
+ };
90
+
91
+ /**
92
+ * Contains message history, tools, current context.
93
+ * Current context means the state of the app, time of day, and other contextual information.
94
+ * It makes requests to the model, its a state machine.
95
+ * It keeps track of the current goal.
96
+ * It manages the context window.
97
+ * Tracks the success criteria of reaching the goal, exposing metrics (stretch).
98
+ * Could be run locally in the app or remotely.
99
+ * Could be personal or shared.
100
+ */
101
+ export class Request {
102
+ /** Prevents concurrent execution of session. */
103
+ private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));
104
+
105
+ private readonly _observer: GenerationObserver;
106
+ private readonly _onOutput: (message: Message.Message) => Effect.Effect<void, never, never>;
107
+
108
+ /** Message history from queue. */
109
+ // TODO(burdon): Evolve into supporting a git-like graph of messages.
110
+ private _history: Message.Message[] = [];
111
+
112
+ /** Pending messages for this session (incl. the current prompt). */
113
+ private _pending: Message.Message[] = [];
114
+
115
+ private _started = 0;
116
+ private _ended = 0;
117
+ private _toolCalls = 0;
118
+
119
+ constructor(private readonly _options: Options = {}) {
120
+ this._observer = _options.observer ?? GenerationObserver.noop();
121
+ this._onOutput = _options.onOutput ?? (() => Effect.void);
122
+ }
123
+
124
+ get duration(): number {
125
+ return this._ended - this._started;
126
+ }
127
+
128
+ get toolCalls(): number {
129
+ return this._toolCalls;
130
+ }
131
+
132
+ get pending(): readonly Message.Message[] {
133
+ return this._pending;
134
+ }
135
+
136
+ private _submitMessage = (message: Message.Message): Effect.Effect<Message.Message, never, Trace.TraceService> =>
137
+ Effect.gen(this, function* () {
138
+ this._pending.push(message);
139
+ yield* this._observer.onMessage(message);
140
+ for (const block of message.blocks) {
141
+ log('write complete block', {
142
+ messageId: message.id,
143
+ role: message.sender.role!,
144
+ block: JSON.stringify(block),
145
+ });
146
+ yield* Trace.write(CompleteBlock, {
147
+ messageId: message.id,
148
+ role: message.sender.role!,
149
+ block,
150
+ });
151
+ }
152
+ yield* this._onOutput(message);
153
+ return message;
154
+ });
155
+
156
+ getToolCalls = () =>
157
+ pipe(
158
+ [...this._history, ...this._pending],
159
+ Array.reverse,
160
+ Array.takeWhile((_) => _.sender.role === 'assistant'),
161
+ Array.flatMap((_) => _.blocks.filter(ContentBlock.is('toolCall')).map((block) => ({ block, message: _ }))),
162
+ Array.filter((_) => !_.block.providerExecuted),
163
+ Array.reverse,
164
+ );
165
+
166
+ /**
167
+ * Initialize a session: set up history, perform summarization if needed, and submit the user prompt.
168
+ * Must be called before `runTurn()`.
169
+ */
170
+ begin = ({
171
+ prompt,
172
+ system,
173
+ history = [],
174
+ blueprints = [],
175
+ objects = [],
176
+ }: BeginProps): Effect.Effect<void, RunError, RunRequirements> =>
177
+ Effect.gen(this, function* () {
178
+ this._started = Date.now();
179
+ this._history = [...history];
180
+ this._pending = [];
181
+
182
+ const systemPrompt = yield* formatSystemPrompt({ system, blueprints, objects }).pipe(Effect.orDie);
183
+
184
+ if (this._options.summarizationThreshold !== undefined) {
185
+ const tokenCount = yield* AiPreprocessor.estimateTokens(
186
+ yield* AiPreprocessor.preprocessPrompt([...this._history], {
187
+ system: systemPrompt,
188
+ }),
189
+ );
190
+ if (tokenCount > this._options.summarizationThreshold) {
191
+ const summary = yield* AiSummarizer.summarize([...this._history]);
192
+ yield* this._submitMessage(summary);
193
+ }
194
+ }
195
+
196
+ yield* this._submitMessage(yield* formatUserPrompt({ prompt, history }));
197
+ }).pipe(Effect.withSpan('AiRequest.begin'));
198
+
199
+ /**
200
+ * Execute a single turn: one LLM generation followed by tool execution.
201
+ * The toolkit and system prompt can be updated between turns to reflect context changes (e.g. dynamically enabled blueprints).
202
+ */
203
+ runAgentTurn = <const R = never>({
204
+ system,
205
+ toolkit: opaqueToolkit,
206
+ }: TurnProps<R>): Effect.Effect<TurnResult, RunError, RunRequirements | R> =>
207
+ Effect.gen(this, function* () {
208
+ log.info('request', {
209
+ system: { snippet: createSnippet(system), length: system.length },
210
+ pending: this._pending.length,
211
+ history: this._history.length,
212
+ });
213
+
214
+ const prompt = yield* AiPreprocessor.preprocessPrompt([...this._history, ...this._pending], {
215
+ system,
216
+ cacheControl: 'ephemeral',
217
+ });
218
+
219
+ const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : undefined;
220
+
221
+ const observer = this._observer;
222
+ let currentMessageId: Obj.ID | null = null;
223
+
224
+ const messages = yield* LanguageModel.streamText({
225
+ prompt,
226
+ toolkit,
227
+ disableToolCallResolution: true,
228
+ }).pipe(
229
+ withoutToolCallParising,
230
+ AiParser.parseResponse({
231
+ emitPartial: true,
232
+ onBegin: () => observer.onBegin(),
233
+ onBlock: (block) => observer.onBlock(block),
234
+ onPart: (part) => observer.onPart(part as any),
235
+ onEnd: (summary) => observer.onEnd(summary),
236
+ }),
237
+ Stream.mapEffect(
238
+ (block) =>
239
+ Effect.gen(this, function* () {
240
+ if (block.pending) {
241
+ currentMessageId ??= Obj.ID.random();
242
+ log('emit ephemeral message', { id: currentMessageId, type: block._tag });
243
+ yield* Trace.write(PartialBlock, {
244
+ messageId: currentMessageId,
245
+ role: 'assistant',
246
+ block,
247
+ });
248
+ return Option.none();
249
+ } else {
250
+ currentMessageId ??= Obj.ID.random();
251
+ const id = currentMessageId;
252
+ currentMessageId = null;
253
+ log('emit complete message', { id, type: block._tag });
254
+ const message = Obj.make(Message.Message, {
255
+ id,
256
+ created: new Date().toISOString(),
257
+ sender: { role: 'assistant' },
258
+ blocks: [block],
259
+ });
260
+ return Option.some(yield* this._submitMessage(message));
261
+ }
262
+ }),
263
+ { concurrency: 1, unordered: false },
264
+ ),
265
+ Stream.filterMap((_) => _),
266
+ Stream.runCollect,
267
+ Effect.map(Chunk.toArray),
268
+ );
269
+ log.info('messages', { messages });
270
+
271
+ const toolCalls = this.getToolCalls();
272
+
273
+ if (toolCalls.length === 0) {
274
+ this._ended = Date.now();
275
+ return { messages, done: true };
276
+ } else if (!toolkit) {
277
+ throw new Error('No toolkit provided');
278
+ }
279
+
280
+ return { messages, done: false };
281
+ }).pipe(Effect.withSpan('AiRequest.runAgentTurn'));
282
+
283
+ runTools = <const R = never>({
284
+ toolkit: opaqueToolkit,
285
+ }: {
286
+ toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
287
+ }): Effect.Effect<void, RunError, RunRequirements | R> =>
288
+ Effect.gen(this, function* () {
289
+ const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : undefined;
290
+ const toolCalls = this.getToolCalls();
291
+ const toolResults = yield* Effect.forEach(toolCalls, ({ block, message }) => {
292
+ if (!toolkit) {
293
+ throw new Error('No toolkit provided');
294
+ }
295
+ return callTool(toolkit, block);
296
+ });
297
+
298
+ yield* this._submitMessage(
299
+ Obj.make(Message.Message, {
300
+ created: new Date().toISOString(),
301
+ sender: { role: 'tool' },
302
+ blocks: toolResults,
303
+ }),
304
+ );
305
+
306
+ this._toolCalls += toolResults.length;
307
+ }).pipe(Effect.withSpan('AiRequest.runTools'));
308
+
309
+ /**
310
+ * Run a full conversation turn loop. Equivalent to calling `begin()` then `runTurn()` in a loop.
311
+ */
312
+ run = <const R = never>({
313
+ prompt,
314
+ system: systemTemplate,
315
+ history = [],
316
+ objects = [],
317
+ blueprints = [],
318
+ toolkit,
319
+ }: RunProps<R>): Effect.Effect<Message.Message[], RunError, RunRequirements | R> =>
320
+ Effect.gen(this, function* () {
321
+ yield* this.begin({ prompt, system: systemTemplate, history, objects, blueprints });
322
+
323
+ const system = yield* formatSystemPrompt({ system: systemTemplate, blueprints, objects }).pipe(Effect.orDie);
324
+
325
+ do {
326
+ const { done } = yield* this.runAgentTurn({ system, toolkit });
327
+ if (done) {
328
+ break;
329
+ }
330
+ yield* this.runTools({ toolkit });
331
+ } while (true);
332
+
333
+ log('done', { pending: this._pending.length, duration: this.duration, tools: this._toolCalls });
334
+ return this._pending;
335
+ }).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiRequest.run'));
336
+ }
337
+
338
+ const createSnippet = (text: string, len = 32) =>
339
+ text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');
340
+
341
+ // TODO(dmaretskyi): Extract as a general util.
342
+ const logDump = (message: string, data: unknown) => {
343
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
344
+ const { writeFileSync } = require('node:fs');
345
+ const path = `/tmp/log-data-${Date.now()}.json`;
346
+ writeFileSync(path, JSON.stringify(data, null, 2));
347
+ log.info(message, { path });
348
+ };