@dxos/assistant 0.8.4-main.84f28bd → 0.8.4-main.9735255

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 (198) hide show
  1. package/dist/lib/browser/chunk-7CDDG6LL.mjs +578 -0
  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/chunk-J5LGTIGS.mjs.map +7 -0
  5. package/dist/lib/browser/extraction/index.mjs +225 -0
  6. package/dist/lib/browser/extraction/index.mjs.map +7 -0
  7. package/dist/lib/browser/index.mjs +723 -1892
  8. package/dist/lib/browser/index.mjs.map +4 -4
  9. package/dist/lib/browser/meta.json +1 -1
  10. package/dist/lib/browser/testing/index.mjs +32 -0
  11. package/dist/lib/browser/testing/index.mjs.map +7 -0
  12. package/dist/lib/node-esm/chunk-CC7ER6Q3.mjs +579 -0
  13. package/dist/lib/node-esm/chunk-CC7ER6Q3.mjs.map +7 -0
  14. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  15. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +7 -0
  16. package/dist/lib/node-esm/extraction/index.mjs +226 -0
  17. package/dist/lib/node-esm/extraction/index.mjs.map +7 -0
  18. package/dist/lib/node-esm/index.mjs +723 -1893
  19. package/dist/lib/node-esm/index.mjs.map +4 -4
  20. package/dist/lib/node-esm/meta.json +1 -1
  21. package/dist/lib/node-esm/testing/index.mjs +33 -0
  22. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  23. package/dist/types/src/conversation/context.d.ts +129 -0
  24. package/dist/types/src/conversation/context.d.ts.map +1 -0
  25. package/dist/types/src/conversation/context.test.d.ts +2 -0
  26. package/dist/types/src/conversation/context.test.d.ts.map +1 -0
  27. package/dist/types/src/conversation/conversation.d.ts +29 -32
  28. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  29. package/dist/types/src/conversation/conversation.test.d.ts +2 -0
  30. package/dist/types/src/conversation/conversation.test.d.ts.map +1 -0
  31. package/dist/types/src/conversation/index.d.ts +1 -0
  32. package/dist/types/src/conversation/index.d.ts.map +1 -1
  33. package/dist/types/src/diff.d.ts +15 -0
  34. package/dist/types/src/diff.d.ts.map +1 -0
  35. package/dist/types/src/diff.test.d.ts +2 -0
  36. package/dist/types/src/diff.test.d.ts.map +1 -0
  37. package/dist/types/src/errors.d.ts +67 -0
  38. package/dist/types/src/errors.d.ts.map +1 -0
  39. package/dist/types/src/execution-graph.d.ts +85 -0
  40. package/dist/types/src/execution-graph.d.ts.map +1 -0
  41. package/dist/types/src/execution-graph.test.d.ts +2 -0
  42. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  43. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +1 -1
  44. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  45. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +279 -140
  46. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  47. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts +1 -1
  48. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  49. package/dist/types/src/extraction/extraction.d.ts +345 -212
  50. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  51. package/dist/types/src/extraction/quotes.d.ts +3 -3
  52. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  53. package/dist/types/src/functions/index.d.ts +2 -0
  54. package/dist/types/src/functions/index.d.ts.map +1 -0
  55. package/dist/types/src/functions/services.d.ts +20 -0
  56. package/dist/types/src/functions/services.d.ts.map +1 -0
  57. package/dist/types/src/functions.test.d.ts +2 -0
  58. package/dist/types/src/functions.test.d.ts.map +1 -0
  59. package/dist/types/src/index.d.ts +5 -5
  60. package/dist/types/src/index.d.ts.map +1 -1
  61. package/dist/types/src/session/GenericToolkit.d.ts +85 -0
  62. package/dist/types/src/session/GenericToolkit.d.ts.map +1 -0
  63. package/dist/types/src/session/artifact-diff.d.ts +27 -0
  64. package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
  65. package/dist/types/src/session/error-handling.d.ts +4 -0
  66. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  67. package/dist/types/src/session/format.d.ts +12 -0
  68. package/dist/types/src/session/format.d.ts.map +1 -0
  69. package/dist/types/src/session/format.test.d.ts +2 -0
  70. package/dist/types/src/session/format.test.d.ts.map +1 -0
  71. package/dist/types/src/session/index.d.ts +4 -0
  72. package/dist/types/src/session/index.d.ts.map +1 -1
  73. package/dist/types/src/session/observer.d.ts +23 -0
  74. package/dist/types/src/session/observer.d.ts.map +1 -0
  75. package/dist/types/src/session/session.d.ts +41 -268
  76. package/dist/types/src/session/session.d.ts.map +1 -1
  77. package/dist/types/src/session/toolkit.d.ts +14 -0
  78. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  79. package/dist/types/src/session/version-pin.d.ts +5 -5
  80. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  81. package/dist/types/src/templates/index.d.ts +2 -0
  82. package/dist/types/src/templates/index.d.ts.map +1 -0
  83. package/dist/types/src/templates/system.d.ts +18 -0
  84. package/dist/types/src/templates/system.d.ts.map +1 -0
  85. package/dist/types/src/testing/index.d.ts +1 -2
  86. package/dist/types/src/testing/index.d.ts.map +1 -1
  87. package/dist/types/src/testing/layer.d.ts +21 -0
  88. package/dist/types/src/testing/layer.d.ts.map +1 -0
  89. package/dist/types/src/types/artifact.d.ts +28 -0
  90. package/dist/types/src/types/artifact.d.ts.map +1 -0
  91. package/dist/types/src/types/index.d.ts +2 -0
  92. package/dist/types/src/types/index.d.ts.map +1 -0
  93. package/dist/types/tsconfig.tsbuildinfo +1 -1
  94. package/package.json +58 -27
  95. package/src/conversation/context.test.ts +46 -0
  96. package/src/conversation/context.ts +303 -0
  97. package/src/conversation/conversation.test.ts +65 -0
  98. package/src/conversation/conversation.ts +98 -76
  99. package/src/conversation/index.ts +1 -0
  100. package/src/diff.test.ts +43 -0
  101. package/src/diff.ts +84 -0
  102. package/src/errors.ts +15 -0
  103. package/src/execution-graph.test.ts +740 -0
  104. package/src/execution-graph.ts +509 -0
  105. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +14 -25
  106. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +48 -52
  107. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +22 -21
  108. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +43 -41
  109. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  110. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +3 -1
  111. package/src/extraction/extraction.ts +10 -9
  112. package/src/extraction/quotes.test.ts +3 -3
  113. package/src/extraction/quotes.ts +6 -7
  114. package/src/functions/index.ts +5 -0
  115. package/src/functions/services.ts +180 -0
  116. package/src/functions.conversations.json +1 -0
  117. package/src/functions.test.ts +74 -0
  118. package/src/index.ts +5 -5
  119. package/src/session/GenericToolkit.ts +131 -0
  120. package/src/session/artifact-diff.ts +41 -0
  121. package/src/session/error-handling.ts +41 -0
  122. package/src/session/format.test.ts +124 -0
  123. package/src/session/format.ts +143 -0
  124. package/src/session/index.ts +5 -0
  125. package/src/session/observer.ts +61 -0
  126. package/src/session/session.conversations.json +1 -0
  127. package/src/session/session.test.ts +83 -215
  128. package/src/session/session.ts +181 -529
  129. package/src/session/toolkit.ts +39 -0
  130. package/src/session/version-pin.ts +12 -12
  131. package/src/templates/index.ts +5 -0
  132. package/src/templates/instructions/format.tpl +61 -0
  133. package/src/templates/instructions/system.tpl +48 -0
  134. package/src/templates/system.ts +41 -0
  135. package/src/testing/index.ts +2 -8
  136. package/src/testing/layer.ts +78 -0
  137. package/src/types/artifact.ts +82 -0
  138. package/src/types/index.ts +5 -0
  139. package/src/typings.d.ts +5 -0
  140. package/dist/types/bin/chat.d.ts +0 -2
  141. package/dist/types/bin/chat.d.ts.map +0 -1
  142. package/dist/types/src/blueprint/blueprint.d.ts +0 -41
  143. package/dist/types/src/blueprint/blueprint.d.ts.map +0 -1
  144. package/dist/types/src/blueprint/index.d.ts +0 -3
  145. package/dist/types/src/blueprint/index.d.ts.map +0 -1
  146. package/dist/types/src/blueprint/registry.d.ts +0 -7
  147. package/dist/types/src/blueprint/registry.d.ts.map +0 -1
  148. package/dist/types/src/context/binder.d.ts +0 -34
  149. package/dist/types/src/context/binder.d.ts.map +0 -1
  150. package/dist/types/src/context/binding.d.ts +0 -38
  151. package/dist/types/src/context/binding.d.ts.map +0 -1
  152. package/dist/types/src/context/index.d.ts +0 -3
  153. package/dist/types/src/context/index.d.ts.map +0 -1
  154. package/dist/types/src/research/exa.d.ts +0 -7
  155. package/dist/types/src/research/exa.d.ts.map +0 -1
  156. package/dist/types/src/research/graph.d.ts +0 -41
  157. package/dist/types/src/research/graph.d.ts.map +0 -1
  158. package/dist/types/src/research/graph.test.d.ts +0 -2
  159. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  160. package/dist/types/src/research/index.d.ts +0 -4
  161. package/dist/types/src/research/index.d.ts.map +0 -1
  162. package/dist/types/src/research/research.d.ts +0 -10
  163. package/dist/types/src/research/research.d.ts.map +0 -1
  164. package/dist/types/src/research/research.test.d.ts +0 -2
  165. package/dist/types/src/research/research.test.d.ts.map +0 -1
  166. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  167. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  168. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  169. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  170. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  171. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  172. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  173. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  174. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  175. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  176. package/dist/types/src/types.d.ts +0 -3
  177. package/dist/types/src/types.d.ts.map +0 -1
  178. package/src/blueprint/blueprint.ts +0 -75
  179. package/src/blueprint/index.ts +0 -6
  180. package/src/blueprint/registry.ts +0 -15
  181. package/src/context/binder.ts +0 -101
  182. package/src/context/binding.ts +0 -31
  183. package/src/context/index.ts +0 -6
  184. package/src/research/exa.ts +0 -100
  185. package/src/research/graph.test.ts +0 -15
  186. package/src/research/graph.ts +0 -337
  187. package/src/research/index.ts +0 -7
  188. package/src/research/instructions-research.tpl +0 -97
  189. package/src/research/research.test.ts +0 -190
  190. package/src/research/research.ts +0 -90
  191. package/src/session/version-pin.test.ts +0 -26
  192. package/src/summarization/summarization.test.ts +0 -221
  193. package/src/testing/exa-search-1748337321991.ts +0 -131
  194. package/src/testing/exa-search-1748337331526.ts +0 -144
  195. package/src/testing/exa-search-1748337344119.ts +0 -133
  196. package/src/typedefs.d.ts +0 -8
  197. package/src/types.ts +0 -8
  198. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -0,0 +1,131 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import type * as Tool from '@effect/ai/Tool';
6
+ import * as Toolkit from '@effect/ai/Toolkit';
7
+ import * as Effect from 'effect/Effect';
8
+ import * as Layer from 'effect/Layer';
9
+ import * as Pipeable from 'effect/Pipeable';
10
+ import type * as Schema from 'effect/Schema';
11
+ import type * as SchemaAST from 'effect/SchemaAST';
12
+
13
+ /**
14
+ * Unique identifier for generic toolkit instances.
15
+ */
16
+ export const TypeId = '~@dxos/assistant/GenericToolkit';
17
+
18
+ /**
19
+ * Type-level representation of the generic toolkit identifier.
20
+ */
21
+ export type TypeId = typeof TypeId;
22
+
23
+ /**
24
+ * Type-safe way to define toolkits where we don't know specific types of tools,
25
+ * and we want to bundle definition and handlers together.
26
+ *
27
+ * Usefull for plugin-based systems, where tools are dynamically added.
28
+ *
29
+ * @param TR requirements type to the tool invocation.
30
+ * @param E failure type to the handlers layer.
31
+ * @param R requirements type to the handlers layer.
32
+ */
33
+ export interface GenericToolkit<TR = never, E = never, R = never> extends Pipeable.Pipeable {
34
+ readonly [TypeId]: TypeId;
35
+
36
+ /**
37
+ * Toolkit definition.
38
+ */
39
+ readonly toolkit: Toolkit.Toolkit<GenericTools<TR>>;
40
+
41
+ /**
42
+ * Handlers layer.
43
+ */
44
+ readonly layer: Layer.Layer<unknown, E, R>;
45
+
46
+ /**
47
+ * Handlers effect.
48
+ */
49
+ readonly handlers: Effect.Effect<Toolkit.WithHandler<GenericTools<TR>>, E, R>;
50
+ }
51
+
52
+ /**
53
+ * Generic constraint.
54
+ *
55
+ * NOTE: Only use in place of `T extends PortableToolkit.Any`. Not suitable for standalone use.
56
+ */
57
+ export interface Any {
58
+ readonly [TypeId]: TypeId;
59
+ readonly toolkit: Toolkit.Toolkit<any>;
60
+ readonly layer: Layer.Layer<unknown, any, any>;
61
+ }
62
+
63
+ export type InvocationRequirements<T extends Any> = T extends GenericToolkit<infer TR, infer _E, infer _R> ? TR : never;
64
+ export type Failure<T extends Any> = T extends GenericToolkit<infer _TR, infer E, infer _R> ? E : never;
65
+ export type Requirements<T extends Any> = T extends GenericToolkit<infer _TR, infer _E, infer R> ? R : never;
66
+
67
+ /**
68
+ * Creates a portable toolkit from toolkit definition and handlers layer.
69
+ */
70
+ export const make = <Tools extends Record<string, Tool.Any>, E, R>(
71
+ toolkit: Toolkit.Toolkit<Tools>,
72
+ layer: Layer.Layer<Tool.HandlersFor<Tools>, E, R>,
73
+ ): GenericToolkit<E, R> => {
74
+ return {
75
+ [TypeId]: TypeId,
76
+ toolkit: toolkit as any,
77
+ layer: layer as any,
78
+ handlers: toolkit.pipe(Effect.provide(layer)) as any,
79
+ pipe() {
80
+ // eslint-disable-next-line prefer-rest-params
81
+ return Pipeable.pipeArguments(this, arguments);
82
+ },
83
+ };
84
+ };
85
+
86
+ /**
87
+ * Merges multiple portable toolkits into a single portable toolkit.
88
+ */
89
+ export const merge = <const Toolkits extends ReadonlyArray<Any>>(
90
+ /**
91
+ * The toolkits to merge together.
92
+ */
93
+ ...toolkits: Toolkits
94
+ ): GenericToolkit<
95
+ InvocationRequirements<Toolkits[number]>,
96
+ Failure<Toolkits[number]>,
97
+ Requirements<Toolkits[number]>
98
+ > => {
99
+ return make(
100
+ Toolkit.merge(...toolkits.map((t) => t.toolkit)),
101
+ Layer.mergeAll(...(toolkits.map((t) => t.layer) as any)),
102
+ ) as any;
103
+ };
104
+
105
+ /**
106
+ * Generic tools type where we cannot statically enumerate individual tools.
107
+ */
108
+ export type GenericTools<R = never> = Record<
109
+ string,
110
+ Tool.Tool<
111
+ string,
112
+ {
113
+ readonly parameters: AnyStructSchemaNoContext;
114
+ readonly success: Schema.Schema.AnyNoContext;
115
+ readonly failure: typeof Schema.Never;
116
+ readonly failureMode: Tool.FailureMode;
117
+ },
118
+ R
119
+ >
120
+ >;
121
+
122
+ export interface AnyStructSchemaNoContext extends Pipeable.Pipeable {
123
+ readonly [Schema.TypeId]: any;
124
+ readonly make: any;
125
+ readonly Type: any;
126
+ readonly Encoded: any;
127
+ readonly Context: never;
128
+ readonly ast: SchemaAST.AST;
129
+ readonly fields: Schema.Struct.Fields;
130
+ readonly annotations: any;
131
+ }
@@ -0,0 +1,41 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Context from 'effect/Context';
6
+
7
+ import { type ObjectVersion } from '@dxos/echo-db';
8
+ import { type ObjectId } from '@dxos/keys';
9
+
10
+ /**
11
+ * Resolves artifact ids to their versions.
12
+ * Used to give the model a sense of the changes to the artifacts made by users during the conversation.
13
+ * The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,
14
+ * a diff is inserted into the conversation.
15
+ *
16
+ * Can be optionally provided to the session run call.
17
+ */
18
+ // TODO(dmaretskyi): Convert to Context.Reference
19
+ export class ArtifactDiffResolver extends Context.Tag('@dxos/assistant/ArtifactDiffResolver')<
20
+ ArtifactDiffResolver,
21
+ ArtifactDiffResolver.Service
22
+ >() {}
23
+
24
+ export namespace ArtifactDiffResolver {
25
+ export type Service = {
26
+ resolve: (
27
+ artifacts: {
28
+ id: ObjectId;
29
+ lastVersion: ObjectVersion;
30
+ }[],
31
+ ) => Promise<
32
+ Map<
33
+ ObjectId,
34
+ {
35
+ version: ObjectVersion;
36
+ diff?: string;
37
+ }
38
+ >
39
+ >;
40
+ };
41
+ }
@@ -0,0 +1,41 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as AiError from '@effect/ai/AiError';
6
+ import * as HttpClientError from '@effect/platform/HttpClientError';
7
+ import * as Effect from 'effect/Effect';
8
+ import * as Schema from 'effect/Schema';
9
+
10
+ import { AiModelError } from '../errors';
11
+
12
+ const AnthropicErrorResponse = Schema.Struct({
13
+ type: Schema.Literal('error'),
14
+ error: Schema.Struct({
15
+ type: Schema.String,
16
+ message: Schema.String,
17
+ }),
18
+ });
19
+
20
+ // TODO(dmaretskyi): Needs rework
21
+ export const mapAiError = (err: AiError.AiError): Effect.Effect<AiError.AiError> =>
22
+ Effect.gen(function* () {
23
+ const cause = err.cause;
24
+ if (HttpClientError.isHttpClientError(cause) && cause.reason === 'StatusCode') {
25
+ const body = yield* cause.response.json.pipe(
26
+ Effect.flatMap(Schema.decodeUnknown(AnthropicErrorResponse, { exact: false })),
27
+ );
28
+
29
+ const parsedCause = new AiModelError({
30
+ message: body.error.message,
31
+ context: { model: 'anthropic', type: body.error.type },
32
+ });
33
+ return AiError.UnknownError.make({
34
+ description: body.error.message,
35
+ module: err.module,
36
+ method: err.method,
37
+ cause: parsedCause,
38
+ });
39
+ }
40
+ return err;
41
+ }).pipe(Effect.catchAll(() => Effect.succeed(err)));
@@ -0,0 +1,124 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { describe, expect, it } from '@effect/vitest';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Schema from 'effect/Schema';
8
+
9
+ import { Blueprint, Template } from '@dxos/blueprints';
10
+ import { Database, Obj, Query } from '@dxos/echo';
11
+ import { TestHelpers } from '@dxos/effect/testing';
12
+ import { defineFunction } from '@dxos/functions';
13
+ import { Text } from '@dxos/schema';
14
+ import { Organization } from '@dxos/types';
15
+ import { trim } from '@dxos/util';
16
+
17
+ import { createSystemPrompt } from '../templates/system';
18
+ import { AssistantTestLayer } from '../testing';
19
+
20
+ import { formatSystemPrompt } from './format';
21
+
22
+ const organizationListFunction = defineFunction({
23
+ key: 'dxos.org/function/organization-list',
24
+ name: 'Organization List',
25
+ description: 'List organizations',
26
+ inputSchema: Schema.Struct({}),
27
+ outputSchema: Schema.Array(Schema.String),
28
+ handler: Effect.fnUntraced(function* () {
29
+ const organizations = yield* Database.Service.runQuery(Query.type(Organization.Organization));
30
+ return organizations.map((organization) => organization.name);
31
+ }),
32
+ });
33
+
34
+ const TestLayer = AssistantTestLayer({
35
+ types: [Text.Text, Organization.Organization, Blueprint.Blueprint],
36
+ functions: [organizationListFunction],
37
+ });
38
+
39
+ describe('format', () => {
40
+ it.effect(
41
+ 'should format',
42
+ Effect.fnUntraced(
43
+ function* (_) {
44
+ const { db } = yield* Database.Service;
45
+ const object = db.add(
46
+ Obj.make(Organization.Organization, {
47
+ name: 'Test',
48
+ website: 'https://www.test.com',
49
+ }),
50
+ );
51
+
52
+ const blueprint = db.add(
53
+ Blueprint.make({
54
+ key: 'example.com/blueprint/test',
55
+ name: 'Test',
56
+ instructions: Template.make({
57
+ source: trim`
58
+ Test
59
+ This is the test blueprint.
60
+ `,
61
+ }),
62
+ }),
63
+ );
64
+
65
+ const output = yield* formatSystemPrompt({
66
+ system: createSystemPrompt({}),
67
+ blueprints: [blueprint],
68
+ objects: [object],
69
+ });
70
+
71
+ console.log(output);
72
+ },
73
+ Effect.provide(TestLayer),
74
+ TestHelpers.provideTestContext,
75
+ ),
76
+ );
77
+
78
+ it.effect(
79
+ 'should format with function input',
80
+ Effect.fnUntraced(
81
+ function* (_) {
82
+ const { db } = yield* Database.Service;
83
+ const object = db.add(
84
+ Obj.make(Organization.Organization, {
85
+ name: 'Test Org',
86
+ website: 'https://www.test.com',
87
+ }),
88
+ );
89
+
90
+ const blueprint = db.add(
91
+ Blueprint.make({
92
+ key: 'example.com/blueprint/test',
93
+ name: 'Test',
94
+ instructions: Template.make({
95
+ source: trim`
96
+ Organization List:
97
+ {{#each organizations}}
98
+ - {{this}}
99
+ {{/each}}
100
+ `,
101
+ inputs: [
102
+ {
103
+ name: 'organizations',
104
+ kind: 'function',
105
+ function: organizationListFunction.key,
106
+ },
107
+ ],
108
+ }),
109
+ }),
110
+ );
111
+
112
+ const output = yield* formatSystemPrompt({
113
+ system: createSystemPrompt({}),
114
+ blueprints: [blueprint],
115
+ objects: [object],
116
+ });
117
+
118
+ expect(output).to.include('Test Org');
119
+ },
120
+ Effect.provide(TestLayer),
121
+ TestHelpers.provideTestContext,
122
+ ),
123
+ );
124
+ });
@@ -0,0 +1,143 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Effect from 'effect/Effect';
6
+ import * as Function from 'effect/Function';
7
+ import * as Option from 'effect/Option';
8
+
9
+ import { Template } from '@dxos/blueprints';
10
+ import { Obj } from '@dxos/echo';
11
+ import { ObjectVersion } from '@dxos/echo-db';
12
+ import { type ObjectId } from '@dxos/keys';
13
+ import { log } from '@dxos/log';
14
+ import { type ContentBlock, Message } from '@dxos/types';
15
+ import { trim } from '@dxos/util';
16
+
17
+ import { AiAssistantError } from '../errors';
18
+
19
+ import { ArtifactDiffResolver } from './artifact-diff';
20
+ import { type AiSessionRunError, type AiSessionRunProps } from './session';
21
+
22
+ /**
23
+ * Formats the system prompt.
24
+ */
25
+ // TODO(burdon): Move to AiPreprocessor.
26
+ export const formatSystemPrompt = ({
27
+ system,
28
+ blueprints = [],
29
+ objects = [],
30
+ }: Pick<AiSessionRunProps<any>, 'system' | 'blueprints' | 'objects'>) =>
31
+ Effect.gen(function* () {
32
+ const blueprintDefs = yield* Function.pipe(
33
+ blueprints,
34
+ Effect.forEach((blueprint) => Effect.succeed(blueprint.instructions)),
35
+ Effect.flatMap(
36
+ Effect.forEach((template) =>
37
+ Effect.gen(function* () {
38
+ return trim`
39
+ <blueprint>
40
+ ${yield* Template.processTemplate(template)}
41
+ </blueprint>
42
+ `;
43
+ }),
44
+ ),
45
+ ),
46
+ Effect.map((blueprints) =>
47
+ blueprints.length > 0 ? ['## Blueprints Definitions', ...blueprints].join('\n\n') : undefined,
48
+ ),
49
+ );
50
+
51
+ const objectDefs = yield* Function.pipe(
52
+ objects,
53
+ Effect.forEach((object) =>
54
+ Effect.succeed(trim`
55
+ <object>
56
+ <dxn>${Obj.getDXN(object)}</dxn>
57
+ <typename>${Obj.getTypename(object)}</typename>
58
+ </object>
59
+ `),
60
+ ),
61
+ Effect.map((objects) => (objects.length > 0 ? ['## Context Objects', ...objects].join('\n\n') : undefined)),
62
+ );
63
+
64
+ return yield* Function.pipe(
65
+ Effect.succeed([system, blueprintDefs, objectDefs].filter((def): def is string => def !== undefined)),
66
+ Effect.map((parts) => parts.join('\n\n')),
67
+ );
68
+ });
69
+
70
+ /**
71
+ * Formats the user prompt.
72
+ */
73
+ // TODO(burdon): Move to AiPreprocessor.
74
+ // TODO(burdon): Convert util below to `Effect.fn` (to preserve stack info)
75
+ export const formatUserPrompt = ({
76
+ prompt,
77
+ history = [],
78
+ }: Pick<AiSessionRunProps<any>, 'prompt' | 'history'>): Effect.Effect<Message.Message, AiSessionRunError> =>
79
+ Effect.gen(function* () {
80
+ const blocks: ContentBlock.Any[] = [];
81
+
82
+ // TODO(dmaretskyi): Evaluate other approaches as `serviceOption` isn't represented in the type system.
83
+ const artifactDiffResolver = yield* Effect.serviceOption(ArtifactDiffResolver);
84
+ if (Option.isSome(artifactDiffResolver)) {
85
+ const versions = gatherObjectVersions(history);
86
+ const artifactDiff = yield* Effect.tryPromise({
87
+ try: () =>
88
+ artifactDiffResolver.value.resolve(
89
+ [...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),
90
+ ),
91
+ catch: AiAssistantError.wrap({ message: 'Artifact diff resolution error' }),
92
+ });
93
+
94
+ log('version', { artifactDiff, versions });
95
+ for (const [id, { version }] of [...artifactDiff.entries()]) {
96
+ if (ObjectVersion.equals(version, versions.get(id)!)) {
97
+ artifactDiff.delete(id);
98
+ continue;
99
+ }
100
+
101
+ blocks.push({ _tag: 'anchor', objectId: id, version });
102
+ }
103
+
104
+ if (artifactDiff.size > 0) {
105
+ blocks.push(createArtifactUpdateBlock(artifactDiff));
106
+ }
107
+ }
108
+
109
+ return Obj.make(Message.Message, {
110
+ created: new Date().toISOString(),
111
+ sender: { role: 'user' },
112
+ blocks: [...blocks, { _tag: 'text', text: prompt }],
113
+ });
114
+ });
115
+
116
+ const gatherObjectVersions = (messages: Message.Message[]): Map<ObjectId, ObjectVersion> => {
117
+ const artifactIds = new Map<ObjectId, ObjectVersion>();
118
+ for (const message of messages) {
119
+ for (const block of message.blocks) {
120
+ if (block._tag === 'anchor') {
121
+ artifactIds.set(block.objectId, block.version as ObjectVersion);
122
+ }
123
+ }
124
+ }
125
+
126
+ return artifactIds;
127
+ };
128
+
129
+ const createArtifactUpdateBlock = (
130
+ artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,
131
+ ): ContentBlock.Any => {
132
+ return {
133
+ _tag: 'text',
134
+ // TODO(dmaretskyi): Does this need to be a special content-block?
135
+ disposition: 'artifact-update',
136
+ text: trim`
137
+ The following artifacts have been updated since the last message:
138
+ ${[...artifactDiff.entries()]
139
+ .map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `\n${diff}` : ''}</changed-artifact>`)
140
+ .join('\n')}
141
+ `,
142
+ };
143
+ };
@@ -2,5 +2,10 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ export * from './artifact-diff';
6
+ export * from './observer';
5
7
  export * from './session';
8
+ export * from './toolkit';
6
9
  export * from './version-pin';
10
+
11
+ export * as GenericToolkit from './GenericToolkit';
@@ -0,0 +1,61 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import type * as Tool from '@effect/ai/Tool';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Function from 'effect/Function';
8
+
9
+ import { type AiParser, type ConsolePrinter } from '@dxos/ai';
10
+ import { type Message } from '@dxos/types';
11
+
12
+ /**
13
+ * Live observer of the generation process.
14
+ */
15
+ export interface GenerationObserver<Tools extends Record<string, Tool.Any> = any>
16
+ extends AiParser.ParseResponseCallbacks<Tools> {
17
+ /**
18
+ * Complete messages fired during the session, both from the model and from the user.
19
+ * This message will contain all message blocks emitted through the `onBlock` callback.
20
+ */
21
+ onMessage: (message: Message.Message) => Effect.Effect<void>;
22
+ }
23
+
24
+ export const GenerationObserver = Object.freeze({
25
+ make: ({
26
+ onBegin = Function.constant(Effect.void),
27
+ onPart = Function.constant(Effect.void),
28
+ onBlock = Function.constant(Effect.void),
29
+ onEnd = Function.constant(Effect.void),
30
+ onMessage = Function.constant(Effect.void),
31
+ }: Partial<GenerationObserver> = {}): GenerationObserver => ({
32
+ onBegin,
33
+ onPart,
34
+ onBlock,
35
+ onEnd,
36
+ onMessage,
37
+ }),
38
+
39
+ noop: () => GenerationObserver.make(),
40
+
41
+ /**
42
+ * Debug printer to be used in unit-tests and browser devtools.
43
+ */
44
+ fromPrinter: (printer: ConsolePrinter) =>
45
+ GenerationObserver.make({
46
+ onBlock: (block) =>
47
+ Effect.sync(() => {
48
+ if (block.pending) {
49
+ return; // Only prints full blocks (better for unit-tests and browser devtools).
50
+ }
51
+ printer.printContentBlock(block);
52
+ }),
53
+ onMessage: (message) =>
54
+ Effect.sync(() => {
55
+ if (message.sender.role === 'assistant') {
56
+ return; // Skip assistant messages since they are printed in the `onBlock` callback.
57
+ }
58
+ printer.printMessage(message);
59
+ }),
60
+ }),
61
+ });
@@ -0,0 +1 @@
1
+ {"conversations":[{"parameters":{"model":"@anthropic/claude-3-5-sonnet-20241022","stream":true,"tools":[]},"prompt":{"content":[{"role":"user","content":"Hello world!","options":{}}]},"response":[{"type":"response-metadata","id":"msg_01Bm496JGgDMgC9YwdYTFFHo","modelId":"claude-3-5-sonnet-20241022","timestamp":"1970-01-01T00:00:00.000Z","metadata":{}},{"type":"text-start","id":"0","metadata":{}},{"type":"text-delta","id":"0","delta":"Hi","metadata":{}},{"type":"text-delta","id":"0","delta":"!","metadata":{}},{"type":"text-delta","id":"0","delta":" How can","metadata":{}},{"type":"text-delta","id":"0","delta":" I help you today?","metadata":{}},{"type":"text-end","id":"0","metadata":{}},{"type":"finish","reason":"stop","usage":{"inputTokens":10,"outputTokens":12,"totalTokens":22},"metadata":{"anthropic":{"usage":{"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":10,"output_tokens":1,"server_tool_use":null,"service_tier":"standard"}}}}]},{"parameters":{"model":"@anthropic/claude-3-5-sonnet-20241022","stream":true,"tools":[{"name":"Calculator","description":"Basic calculator tool","inputSchema":{"type":"object","required":["input"],"properties":{"input":{"type":"string","description":"The calculation to perform."}},"additionalProperties":false}}]},"prompt":{"content":[{"role":"user","content":"What is 10 + 30?","options":{}}]},"response":[{"type":"response-metadata","id":"msg_01UNTbjtTHEpdFgGunu2k8Br","modelId":"claude-3-5-sonnet-20241022","timestamp":"1970-01-01T00:00:00.000Z","metadata":{}},{"type":"text-start","id":"0","metadata":{}},{"type":"text-delta","id":"0","delta":"I","metadata":{}},{"type":"text-delta","id":"0","delta":"'ll help","metadata":{}},{"type":"text-delta","id":"0","delta":" you calculate","metadata":{}},{"type":"text-delta","id":"0","delta":" ","metadata":{}},{"type":"text-delta","id":"0","delta":"10 + 30","metadata":{}},{"type":"text-delta","id":"0","delta":" using the","metadata":{}},{"type":"text-delta","id":"0","delta":" Calculator tool.","metadata":{}},{"type":"text-end","id":"0","metadata":{}},{"type":"tool-params-start","id":"toolu_01LTGUgfihCQtVchm1b37xHQ","name":"Calculator","providerExecuted":false,"metadata":{}},{"type":"tool-params-delta","id":"toolu_01LTGUgfihCQtVchm1b37xHQ","delta":"","metadata":{}},{"type":"tool-params-delta","id":"toolu_01LTGUgfihCQtVchm1b37xHQ","delta":"{\"input\": \"","metadata":{}},{"type":"tool-params-delta","id":"toolu_01LTGUgfihCQtVchm1b37xHQ","delta":"10 + 30","metadata":{}},{"type":"tool-params-delta","id":"toolu_01LTGUgfihCQtVchm1b37xHQ","delta":"\"}","metadata":{}},{"type":"tool-params-end","id":"toolu_01LTGUgfihCQtVchm1b37xHQ","metadata":{}},{"type":"tool-call","id":"toolu_01LTGUgfihCQtVchm1b37xHQ","name":"Calculator","params":{"input":"10 + 30"},"providerExecuted":false,"metadata":{}},{"type":"finish","reason":"tool-calls","usage":{"inputTokens":394,"outputTokens":73,"totalTokens":467},"metadata":{"anthropic":{"usage":{"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":394,"output_tokens":1,"server_tool_use":null,"service_tier":"standard"}}}}]},{"parameters":{"model":"@anthropic/claude-3-5-sonnet-20241022","stream":true,"tools":[{"name":"Calculator","description":"Basic calculator tool","inputSchema":{"type":"object","required":["input"],"properties":{"input":{"type":"string","description":"The calculation to perform."}},"additionalProperties":false}}]},"prompt":{"content":[{"role":"user","content":"What is 10 + 30?","options":{}},{"role":"assistant","content":[{"type":"text","text":"I'll help you calculate 10 + 30 using the Calculator tool.","options":{}},{"type":"tool-call","id":"toolu_01LTGUgfihCQtVchm1b37xHQ","name":"Calculator","params":{"input":"10 + 30"},"providerExecuted":false,"options":{}}],"options":{}},{"role":"tool","content":[{"type":"tool-result","id":"toolu_01LTGUgfihCQtVchm1b37xHQ","name":"Calculator","isFailure":false,"result":{"result":40},"options":{}}],"options":{}}]},"response":[{"type":"response-metadata","id":"msg_01AKio3GheJGn38BhvAp33rs","modelId":"claude-3-5-sonnet-20241022","timestamp":"1970-01-01T00:00:00.000Z","metadata":{}},{"type":"text-start","id":"0","metadata":{}},{"type":"text-delta","id":"0","delta":"The result","metadata":{}},{"type":"text-delta","id":"0","delta":" of 10 +","metadata":{}},{"type":"text-delta","id":"0","delta":" 30 is ","metadata":{}},{"type":"text-delta","id":"0","delta":"40.","metadata":{}},{"type":"text-end","id":"0","metadata":{}},{"type":"finish","reason":"stop","usage":{"inputTokens":482,"outputTokens":18,"totalTokens":500},"metadata":{"anthropic":{"usage":{"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":482,"output_tokens":3,"server_tool_use":null,"service_tier":"standard"}}}}]},{"parameters":{"model":"@anthropic/claude-opus-4-0","stream":true,"tools":[]},"prompt":{"content":[{"role":"user","content":"Hello world!","options":{}}]},"response":[{"type":"response-metadata","id":"msg_01QPPeofAkjiYa83LPCeSYfS","modelId":"claude-opus-4-20250514","timestamp":"1970-01-01T00:00:00.000Z","metadata":{}},{"type":"text-start","id":"0","metadata":{}},{"type":"text-delta","id":"0","delta":"Hello!","metadata":{}},{"type":"text-delta","id":"0","delta":" Welcome","metadata":{}},{"type":"text-delta","id":"0","delta":" to the worl","metadata":{}},{"type":"text-delta","id":"0","delta":"d!","metadata":{}},{"type":"text-delta","id":"0","delta":" 🌍 ","metadata":{}},{"type":"text-delta","id":"0","delta":"How","metadata":{}},{"type":"text-delta","id":"0","delta":" are you doing today? Is there anything","metadata":{}},{"type":"text-delta","id":"0","delta":" specific you'd like to chat about or","metadata":{}},{"type":"text-delta","id":"0","delta":" any questions","metadata":{}},{"type":"text-delta","id":"0","delta":" I can help you with?","metadata":{}},{"type":"text-end","id":"0","metadata":{}},{"type":"finish","reason":"stop","usage":{"inputTokens":10,"outputTokens":40,"totalTokens":50},"metadata":{"anthropic":{"usage":{"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":10,"output_tokens":2,"server_tool_use":null,"service_tier":"standard"}}}}]},{"parameters":{"model":"@anthropic/claude-opus-4-0","stream":true,"tools":[{"name":"Calculator","description":"Basic calculator tool","inputSchema":{"type":"object","required":["input"],"properties":{"input":{"type":"string","description":"The calculation to perform."}},"additionalProperties":false}}]},"prompt":{"content":[{"role":"user","content":"What is 10 + 30?","options":{}}]},"response":[{"type":"response-metadata","id":"msg_01EaHNEDYN3Hvp5toY8hQGe6","modelId":"claude-opus-4-20250514","timestamp":"1970-01-01T00:00:00.000Z","metadata":{}},{"type":"text-start","id":"0","metadata":{}},{"type":"text-delta","id":"0","delta":"I'll help","metadata":{}},{"type":"text-delta","id":"0","delta":" you calculate ","metadata":{}},{"type":"text-delta","id":"0","delta":"10 + 30.","metadata":{}},{"type":"text-end","id":"0","metadata":{}},{"type":"tool-params-start","id":"toolu_01X4qkrMwCisiUN8Cm4E4Voe","name":"Calculator","providerExecuted":false,"metadata":{}},{"type":"tool-params-delta","id":"toolu_01X4qkrMwCisiUN8Cm4E4Voe","delta":"","metadata":{}},{"type":"tool-params-delta","id":"toolu_01X4qkrMwCisiUN8Cm4E4Voe","delta":"{\"input\": ","metadata":{}},{"type":"tool-params-delta","id":"toolu_01X4qkrMwCisiUN8Cm4E4Voe","delta":"\"10 + 3","metadata":{}},{"type":"tool-params-delta","id":"toolu_01X4qkrMwCisiUN8Cm4E4Voe","delta":"0\"}","metadata":{}},{"type":"tool-params-end","id":"toolu_01X4qkrMwCisiUN8Cm4E4Voe","metadata":{}},{"type":"tool-call","id":"toolu_01X4qkrMwCisiUN8Cm4E4Voe","name":"Calculator","params":{"input":"10 + 30"},"providerExecuted":false,"metadata":{}},{"type":"finish","reason":"tool-calls","usage":{"inputTokens":394,"outputTokens":68,"totalTokens":462},"metadata":{"anthropic":{"usage":{"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":394,"output_tokens":3,"server_tool_use":null,"service_tier":"standard"}}}}]},{"parameters":{"model":"@anthropic/claude-opus-4-0","stream":true,"tools":[{"name":"Calculator","description":"Basic calculator tool","inputSchema":{"type":"object","required":["input"],"properties":{"input":{"type":"string","description":"The calculation to perform."}},"additionalProperties":false}}]},"prompt":{"content":[{"role":"user","content":"What is 10 + 30?","options":{}},{"role":"assistant","content":[{"type":"text","text":"I'll help you calculate 10 + 30.","options":{}},{"type":"tool-call","id":"toolu_01X4qkrMwCisiUN8Cm4E4Voe","name":"Calculator","params":{"input":"10 + 30"},"providerExecuted":false,"options":{}}],"options":{}},{"role":"tool","content":[{"type":"tool-result","id":"toolu_01X4qkrMwCisiUN8Cm4E4Voe","name":"Calculator","isFailure":false,"result":{"result":40},"options":{}}],"options":{}}]},"response":[{"type":"response-metadata","id":"msg_01RjnEkFT3iEUFCpfC4B28aS","modelId":"claude-opus-4-20250514","timestamp":"1970-01-01T00:00:00.000Z","metadata":{}},{"type":"text-start","id":"0","metadata":{}},{"type":"text-delta","id":"0","delta":"10 + 30 = ","metadata":{}},{"type":"text-delta","id":"0","delta":"40","metadata":{}},{"type":"text-end","id":"0","metadata":{}},{"type":"finish","reason":"stop","usage":{"inputTokens":478,"outputTokens":12,"totalTokens":490},"metadata":{"anthropic":{"usage":{"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":478,"output_tokens":8,"server_tool_use":null,"service_tier":"standard"}}}}]}]}