@dxos/assistant 0.8.4-main.5acf9ea → 0.8.4-main.5ea62a8

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 (145) hide show
  1. package/dist/lib/browser/chunk-6WRGDEMH.mjs +89 -0
  2. package/dist/lib/browser/chunk-6WRGDEMH.mjs.map +7 -0
  3. package/dist/lib/browser/chunk-N4O3C3T5.mjs +396 -0
  4. package/dist/lib/browser/chunk-N4O3C3T5.mjs.map +7 -0
  5. package/dist/lib/browser/extraction/index.mjs +268 -0
  6. package/dist/lib/browser/extraction/index.mjs.map +7 -0
  7. package/dist/lib/browser/index.mjs +284 -1609
  8. package/dist/lib/browser/index.mjs.map +4 -4
  9. package/dist/lib/browser/meta.json +1 -1
  10. package/dist/lib/browser/named-entity-recognition-O46UTCLR.mjs +13 -0
  11. package/dist/lib/browser/named-entity-recognition-O46UTCLR.mjs.map +7 -0
  12. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs +91 -0
  13. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs.map +7 -0
  14. package/dist/lib/node-esm/chunk-QVJ7EAM2.mjs +398 -0
  15. package/dist/lib/node-esm/chunk-QVJ7EAM2.mjs.map +7 -0
  16. package/dist/lib/node-esm/extraction/index.mjs +269 -0
  17. package/dist/lib/node-esm/extraction/index.mjs.map +7 -0
  18. package/dist/lib/node-esm/index.mjs +283 -1609
  19. package/dist/lib/node-esm/index.mjs.map +4 -4
  20. package/dist/lib/node-esm/meta.json +1 -1
  21. package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs +14 -0
  22. package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs.map +7 -0
  23. package/dist/types/src/{context/binding.d.ts → conversation/context.d.ts} +45 -3
  24. package/dist/types/src/conversation/context.d.ts.map +1 -0
  25. package/dist/types/src/conversation/conversation.d.ts +25 -21
  26. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  27. package/dist/types/src/conversation/index.d.ts +1 -0
  28. package/dist/types/src/conversation/index.d.ts.map +1 -1
  29. package/dist/types/src/diff.d.ts +15 -0
  30. package/dist/types/src/diff.d.ts.map +1 -0
  31. package/dist/types/src/diff.test.d.ts +2 -0
  32. package/dist/types/src/diff.test.d.ts.map +1 -0
  33. package/dist/types/src/errors.d.ts +41 -4
  34. package/dist/types/src/errors.d.ts.map +1 -1
  35. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  36. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +59 -27
  37. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  38. package/dist/types/src/extraction/extraction.d.ts +244 -214
  39. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  40. package/dist/types/src/functions/services.d.ts +4 -3
  41. package/dist/types/src/functions/services.d.ts.map +1 -1
  42. package/dist/types/src/index.d.ts +2 -3
  43. package/dist/types/src/index.d.ts.map +1 -1
  44. package/dist/types/src/session/artifact-diff.d.ts +27 -0
  45. package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
  46. package/dist/types/src/session/error-handling.d.ts +4 -0
  47. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  48. package/dist/types/src/session/format.d.ts +182 -0
  49. package/dist/types/src/session/format.d.ts.map +1 -0
  50. package/dist/types/src/session/format.test.d.ts +2 -0
  51. package/dist/types/src/session/format.test.d.ts.map +1 -0
  52. package/dist/types/src/session/index.d.ts +3 -0
  53. package/dist/types/src/session/index.d.ts.map +1 -1
  54. package/dist/types/src/session/observer.d.ts +22 -0
  55. package/dist/types/src/session/observer.d.ts.map +1 -0
  56. package/dist/types/src/session/session.d.ts +23 -236
  57. package/dist/types/src/session/session.d.ts.map +1 -1
  58. package/dist/types/src/session/toolkit.d.ts +14 -0
  59. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  60. package/dist/types/src/session/version-pin.d.ts +2 -2
  61. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  62. package/dist/types/src/templates/index.d.ts +1 -1
  63. package/dist/types/src/templates/system.d.ts +18 -0
  64. package/dist/types/src/templates/system.d.ts.map +1 -0
  65. package/dist/types/src/types.d.ts +3 -0
  66. package/dist/types/src/types.d.ts.map +1 -1
  67. package/dist/types/tsconfig.tsbuildinfo +1 -1
  68. package/package.json +45 -29
  69. package/src/conversation/context.ts +154 -0
  70. package/src/conversation/conversation.ts +80 -53
  71. package/src/conversation/index.ts +1 -0
  72. package/src/diff.test.ts +43 -0
  73. package/src/diff.ts +77 -0
  74. package/src/errors.ts +5 -0
  75. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +1 -0
  76. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +7 -7
  77. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +4 -3
  78. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +2 -2
  79. package/src/extraction/quotes.test.ts +1 -1
  80. package/src/extraction/quotes.ts +1 -1
  81. package/src/functions/services.ts +37 -17
  82. package/src/index.ts +2 -3
  83. package/src/session/artifact-diff.ts +41 -0
  84. package/src/session/error-handling.ts +36 -0
  85. package/src/session/format.test.ts +60 -0
  86. package/src/session/format.ts +139 -0
  87. package/src/session/index.ts +3 -0
  88. package/src/session/observer.ts +58 -0
  89. package/src/session/session.test.ts +36 -38
  90. package/src/session/session.ts +114 -249
  91. package/src/session/toolkit.ts +42 -0
  92. package/src/session/version-pin.ts +4 -4
  93. package/src/summarization/summarization.test.ts +5 -7
  94. package/src/templates/format.tpl +59 -0
  95. package/src/templates/index.ts +1 -1
  96. package/src/templates/system.tpl +50 -0
  97. package/src/templates/system.ts +41 -0
  98. package/src/types.ts +10 -5
  99. package/src/typings.d.ts +5 -0
  100. package/dist/types/bin/chat.d.ts +0 -2
  101. package/dist/types/bin/chat.d.ts.map +0 -1
  102. package/dist/types/src/context/binder.d.ts +0 -34
  103. package/dist/types/src/context/binder.d.ts.map +0 -1
  104. package/dist/types/src/context/binding.d.ts.map +0 -1
  105. package/dist/types/src/context/index.d.ts +0 -3
  106. package/dist/types/src/context/index.d.ts.map +0 -1
  107. package/dist/types/src/research/exa.d.ts +0 -12
  108. package/dist/types/src/research/exa.d.ts.map +0 -1
  109. package/dist/types/src/research/graph.d.ts +0 -51
  110. package/dist/types/src/research/graph.d.ts.map +0 -1
  111. package/dist/types/src/research/graph.test.d.ts +0 -2
  112. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  113. package/dist/types/src/research/index.d.ts +0 -4
  114. package/dist/types/src/research/index.d.ts.map +0 -1
  115. package/dist/types/src/research/research.d.ts +0 -10
  116. package/dist/types/src/research/research.d.ts.map +0 -1
  117. package/dist/types/src/research/research.test.d.ts +0 -2
  118. package/dist/types/src/research/research.test.d.ts.map +0 -1
  119. package/dist/types/src/templates/prompt.d.ts +0 -30
  120. package/dist/types/src/templates/prompt.d.ts.map +0 -1
  121. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  122. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  123. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  124. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  125. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  126. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  127. package/dist/types/src/testing/index.d.ts +0 -3
  128. package/dist/types/src/testing/index.d.ts.map +0 -1
  129. package/src/context/binder.ts +0 -103
  130. package/src/context/binding.ts +0 -32
  131. package/src/context/index.ts +0 -6
  132. package/src/research/exa.ts +0 -97
  133. package/src/research/graph.test.ts +0 -64
  134. package/src/research/graph.ts +0 -369
  135. package/src/research/index.ts +0 -7
  136. package/src/research/instructions-research.tpl +0 -98
  137. package/src/research/research.test.ts +0 -190
  138. package/src/research/research.ts +0 -87
  139. package/src/templates/assistant.tpl +0 -111
  140. package/src/templates/prompt.ts +0 -45
  141. package/src/testing/exa-search-1748337321991.ts +0 -131
  142. package/src/testing/exa-search-1748337331526.ts +0 -144
  143. package/src/testing/exa-search-1748337344119.ts +0 -133
  144. package/src/testing/index.ts +0 -11
  145. package/src/typedefs.d.ts +0 -8
@@ -2,7 +2,7 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { describe, test, expect } from 'vitest';
5
+ import { describe, expect, test } from 'vitest';
6
6
 
7
7
  import { insertReferences } from './quotes';
8
8
 
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { Schema } from 'effect';
6
6
 
7
- import { Query, Filter } from '@dxos/echo';
7
+ import { Filter, Query } from '@dxos/echo';
8
8
  import { type EchoDatabase } from '@dxos/echo-db';
9
9
  import { ObjectId } from '@dxos/echo-schema';
10
10
  import { DXN } from '@dxos/keys';
@@ -2,52 +2,68 @@
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 { AiTool, type AiToolkit } from '@effect/ai';
6
+ import { Context, Effect, Layer, Record, Schema } from 'effect';
7
7
 
8
8
  import { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from '@dxos/ai';
9
- import { LocalFunctionExecutionService, type FunctionDefinition } from '@dxos/functions';
9
+ import { todo } from '@dxos/debug';
10
+ import { type FunctionDefinition, LocalFunctionExecutionService } from '@dxos/functions';
10
11
  import { invariant } from '@dxos/invariant';
11
12
 
12
13
  export const makeToolResolverFromFunctions = (
13
14
  functions: FunctionDefinition<any, any>[],
15
+ toolkit: AiToolkit.Any,
14
16
  ): Layer.Layer<ToolResolverService> => {
15
17
  return Layer.succeed(ToolResolverService, {
16
18
  resolve: Effect.fn('resolveTool')(function* (id) {
17
- const fn = functions.find((f) => f.name === id);
18
- if (!fn) {
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) {
19
26
  return yield* Effect.fail(new AiToolNotFoundError(id));
20
27
  }
21
28
 
22
- return projectFunctionToTool(fn);
29
+ return projectFunctionToTool(functionDef);
23
30
  }),
24
31
  });
25
32
  };
26
33
 
27
34
  export const makeToolExecutionServiceFromFunctions = (
28
35
  functions: FunctionDefinition<any, any>[],
36
+ toolkit: AiToolkit.AiToolkit<AiTool.Any>,
37
+ handlersLayer: Layer.Layer<AiTool.ToHandler<AiTool.AiTool<any>>, never, never>,
29
38
  ): Layer.Layer<ToolExecutionService, never, LocalFunctionExecutionService> => {
30
39
  return Layer.effect(
31
40
  ToolExecutionService,
32
41
  Effect.gen(function* () {
42
+ const toolkitHandler = yield* toolkit.pipe(Effect.provide(handlersLayer));
33
43
  const localFunctionExecutionService = yield* LocalFunctionExecutionService;
44
+
34
45
  return {
35
46
  handlersFor: (toolkit) => {
36
47
  const makeHandler = (tool: AiTool.Any): ((params: unknown) => Effect.Effect<unknown, any, any>) => {
37
48
  return Effect.fn('toolFunctionHandler')(function* (input: any) {
49
+ if (toolkitHandler.tools.find((t: AiTool.Any) => t.name === tool.name)) {
50
+ // TODO(wittjosiah): Everything is `never` here.
51
+ return yield* (toolkitHandler.handle as any)(tool.name, input);
52
+ }
53
+
38
54
  const { functionName } = Context.get(FunctionToolAnnotation)(tool.annotations as any);
39
- const fnDef = functions.find((f) => f.name === functionName);
40
- if (!fnDef) {
55
+ const functionDef = functions.find((fn) => fn.name === functionName);
56
+ if (!functionDef) {
41
57
  return yield* Effect.fail(new AiToolNotFoundError(tool.name));
42
58
  }
43
59
 
44
60
  return yield* localFunctionExecutionService
45
- .invokeFunction(fnDef, input)
61
+ .invokeFunction(functionDef, input)
46
62
  .pipe(Effect.catchAllDefect((defect) => Effect.fail(defect)));
47
63
  });
48
64
  };
49
65
 
50
- return toolkit.of(Record.map(toolkit.tools, (tool, name) => makeHandler(tool)) as any) as any;
66
+ return toolkit.of(Record.map(toolkit.tools, (tool, _name) => makeHandler(tool)) as any) as any;
51
67
  },
52
68
  };
53
69
  }),
@@ -65,10 +81,12 @@ class FunctionToolAnnotation extends Context.Tag('@dxos/assisatnt/FunctionToolAn
65
81
  >() {}
66
82
 
67
83
  const toolCache = new WeakMap<FunctionDefinition<any, any>, AiTool.Any>();
84
+
68
85
  const projectFunctionToTool = (fn: FunctionDefinition<any, any>): AiTool.Any => {
69
86
  if (toolCache.has(fn)) {
70
87
  return toolCache.get(fn)!;
71
88
  }
89
+
72
90
  const tool = AiTool.make(makeToolName(fn.name), {
73
91
  description: fn.description,
74
92
  parameters: createStructFieldsFromSchema(fn.inputSchema),
@@ -83,17 +101,19 @@ const projectFunctionToTool = (fn: FunctionDefinition<any, any>): AiTool.Any =>
83
101
  * @returns Tool name produced from function name by escaping invalid characters.
84
102
  */
85
103
  const makeToolName = (name: string) => {
86
- const toolName = name.replace(/[^a-zA-Z0-9]/g, '');
104
+ const toolName = name.replace(/[^a-zA-Z0-9]/g, '_');
87
105
  invariant(toolName.match(/^[a-zA-Z_][a-zA-Z0-9-_]*$/));
88
106
  return toolName;
89
107
  };
90
108
 
91
109
  // TODO(dmaretskyi): Factor out.
92
110
  const createStructFieldsFromSchema = (schema: Schema.Schema<any, any>): Record<string, Schema.Schema<any, any>> => {
93
- return Match.value(schema.ast).pipe(
94
- Match.when(Predicate.isTagged('TypeLiteral'), (ast) => {
95
- return Object.fromEntries(ast.propertySignatures.map((prop) => [prop.name, Schema.make(prop.type)]));
96
- }),
97
- Match.orElseAbsurd,
98
- );
111
+ switch (schema.ast._tag) {
112
+ case 'TypeLiteral':
113
+ return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [prop.name, Schema.make(prop.type)]));
114
+ case 'VoidKeyword':
115
+ return {};
116
+ default:
117
+ return todo(`Unsupported schema AST: ${schema.ast._tag}`);
118
+ }
99
119
  };
package/src/index.ts CHANGED
@@ -2,11 +2,10 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- export * from './context';
6
5
  export * from './conversation';
7
- export * from './extraction';
6
+ export * from './diff';
8
7
  export * from './functions';
9
- export * from './research';
10
8
  export * from './session';
11
9
  export * from './templates';
12
10
  export * from './types';
11
+ export * from './errors';
@@ -0,0 +1,41 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Context } from 'effect';
6
+
7
+ import { type ObjectVersion } from '@dxos/echo-db';
8
+ import { type ObjectId } from '@dxos/echo-schema';
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,36 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { AiError } from '@effect/ai';
6
+ import { HttpClientError } from '@effect/platform';
7
+ import { Effect, Schema } from 'effect';
8
+
9
+ import { AnthropicError } from '../errors';
10
+
11
+ const AnthropicErrorResponse = Schema.Struct({
12
+ type: Schema.Literal('error'),
13
+ error: Schema.Struct({
14
+ type: Schema.String,
15
+ message: Schema.String,
16
+ }),
17
+ });
18
+
19
+ export const mapAiError = (err: AiError.AiError): Effect.Effect<AiError.AiError> =>
20
+ Effect.gen(function* () {
21
+ const cause = err.cause;
22
+ if (HttpClientError.isHttpClientError(cause) && cause.reason === 'StatusCode') {
23
+ const body = yield* cause.response.json.pipe(
24
+ Effect.flatMap(Schema.decodeUnknown(AnthropicErrorResponse, { exact: false })),
25
+ );
26
+
27
+ const parsedCause = new AnthropicError(`${body.error.type}: ${body.error.message}`);
28
+ return new AiError.AiError({
29
+ description: body.error.message,
30
+ module: err.module,
31
+ method: err.method,
32
+ cause: parsedCause,
33
+ });
34
+ }
35
+ return err;
36
+ }).pipe(Effect.catchAll(() => Effect.succeed(err)));
@@ -0,0 +1,60 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { beforeAll, describe, it } from '@effect/vitest';
6
+ import { Effect } from 'effect';
7
+
8
+ import { Blueprint, Template } from '@dxos/blueprints';
9
+ import { Obj } from '@dxos/echo';
10
+ import { type EchoDatabase } from '@dxos/echo-db';
11
+ import { EchoTestBuilder } from '@dxos/echo-db/testing';
12
+ import { DataType } from '@dxos/schema';
13
+ import { trim } from '@dxos/util';
14
+
15
+ import { createSystemPrompt } from '../templates/system';
16
+
17
+ import { formatSystemPrompt } from './format';
18
+
19
+ describe('format', () => {
20
+ let db: EchoDatabase;
21
+ beforeAll(async () => {
22
+ const builder = await new EchoTestBuilder().open();
23
+ ({ db } = await builder.createDatabase({
24
+ types: [DataType.Text, DataType.Organization, Blueprint.Blueprint],
25
+ }));
26
+ });
27
+
28
+ it.effect(
29
+ 'should format',
30
+ Effect.fn(function* () {
31
+ const object = db.add(
32
+ Obj.make(DataType.Organization, {
33
+ name: 'Test',
34
+ website: 'https://www.test.com',
35
+ }),
36
+ );
37
+
38
+ const blueprint = db.add(
39
+ Blueprint.make({
40
+ key: 'example.com/blueprint/test',
41
+ name: 'Test',
42
+ instructions: Template.make({
43
+ source: trim`
44
+ Test
45
+ This is the test blueprint.
46
+ `,
47
+ }),
48
+ }),
49
+ );
50
+
51
+ const output = yield* formatSystemPrompt({
52
+ system: createSystemPrompt({}),
53
+ blueprints: [blueprint, blueprint],
54
+ objects: [object, object],
55
+ });
56
+
57
+ console.log(output);
58
+ }),
59
+ );
60
+ });
@@ -0,0 +1,139 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Array, Effect, Option, pipe } from 'effect';
6
+
7
+ import { Template } from '@dxos/blueprints';
8
+ import { Obj } from '@dxos/echo';
9
+ import { ObjectVersion } from '@dxos/echo-db';
10
+ import { type ObjectId } from '@dxos/echo-schema';
11
+ import { DatabaseService } from '@dxos/functions';
12
+ import { log } from '@dxos/log';
13
+ import { type ContentBlock, DataType } from '@dxos/schema';
14
+ import { trim } from '@dxos/util';
15
+
16
+ import { AiAssistantError } from '../errors';
17
+
18
+ import { ArtifactDiffResolver } from './artifact-diff';
19
+ import { type AiSessionRunParams } from './session';
20
+
21
+ /**
22
+ * Formats the system prompt.
23
+ */
24
+ // TODO(burdon): Move to AiPreprocessor.
25
+ export const formatSystemPrompt = ({
26
+ system,
27
+ blueprints = [],
28
+ objects = [],
29
+ }: Pick<AiSessionRunParams<any>, 'system' | 'blueprints' | 'objects'>) =>
30
+ Effect.gen(function* () {
31
+ const blueprintDefs = yield* pipe(
32
+ blueprints,
33
+ Effect.forEach((blueprint) => Effect.succeed(blueprint.instructions)),
34
+ Effect.flatMap(Effect.forEach((template) => DatabaseService.loadOption(template.source))),
35
+ Effect.map(Array.filter(Option.isSome)),
36
+ Effect.map(
37
+ Array.map(
38
+ (template) => trim`
39
+ <blueprint>
40
+ ${Template.process(template.value.content)}
41
+ </blueprint>
42
+ `,
43
+ ),
44
+ ),
45
+ Effect.map((blueprints) =>
46
+ blueprints.length > 0 ? ['## Blueprints Definitions', ...blueprints].join('\n\n') : undefined,
47
+ ),
48
+ );
49
+
50
+ const objectDefs = yield* pipe(
51
+ objects,
52
+ Effect.forEach((object) =>
53
+ Effect.succeed(trim`
54
+ <object>
55
+ <dxn>${Obj.getDXN(object)}</dxn>
56
+ <typename>${Obj.getTypename(object)}</typename>
57
+ </object>
58
+ `),
59
+ ),
60
+ Effect.map((objects) => (objects.length > 0 ? ['## Context Objects', ...objects].join('\n\n') : undefined)),
61
+ );
62
+
63
+ return yield* pipe(
64
+ Effect.succeed([system, blueprintDefs, objectDefs].filter((def): def is string => def !== undefined)),
65
+ Effect.map((parts) => parts.join('\n\n')),
66
+ );
67
+ });
68
+
69
+ /**
70
+ * Formats the user prompt.
71
+ */
72
+ // TODO(burdon): Move to AiPreprocessor.
73
+ // TODO(burdon): Convert util below to `Effect.fn` (to preserve stack info)
74
+ export const formatUserPrompt = ({ prompt, history = [] }: Pick<AiSessionRunParams<any>, 'prompt' | 'history'>) =>
75
+ Effect.gen(function* () {
76
+ const blocks: ContentBlock.Any[] = [];
77
+
78
+ // TODO(dmaretskyi): Evaluate other approaches as `serviceOption` isn't represented in the type system.
79
+ const artifactDiffResolver = yield* Effect.serviceOption(ArtifactDiffResolver);
80
+ if (Option.isSome(artifactDiffResolver)) {
81
+ const versions = gatherObjectVersions(history);
82
+ const artifactDiff = yield* Effect.tryPromise({
83
+ try: () =>
84
+ artifactDiffResolver.value.resolve(
85
+ [...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),
86
+ ),
87
+ catch: AiAssistantError.wrap('Artifact diff resolution error'),
88
+ });
89
+
90
+ log.info('version', { artifactDiff, versions });
91
+ for (const [id, { version }] of [...artifactDiff.entries()]) {
92
+ if (ObjectVersion.equals(version, versions.get(id)!)) {
93
+ artifactDiff.delete(id);
94
+ continue;
95
+ }
96
+
97
+ blocks.push({ _tag: 'anchor', objectId: id, version });
98
+ }
99
+
100
+ if (artifactDiff.size > 0) {
101
+ blocks.push(createArtifactUpdateBlock(artifactDiff));
102
+ }
103
+ }
104
+
105
+ return Obj.make(DataType.Message, {
106
+ created: new Date().toISOString(),
107
+ sender: { role: 'user' },
108
+ blocks: [...blocks, { _tag: 'text', text: prompt }],
109
+ });
110
+ });
111
+
112
+ const gatherObjectVersions = (messages: DataType.Message[]): Map<ObjectId, ObjectVersion> => {
113
+ const artifactIds = new Map<ObjectId, ObjectVersion>();
114
+ for (const message of messages) {
115
+ for (const block of message.blocks) {
116
+ if (block._tag === 'anchor') {
117
+ artifactIds.set(block.objectId, block.version as ObjectVersion);
118
+ }
119
+ }
120
+ }
121
+
122
+ return artifactIds;
123
+ };
124
+
125
+ const createArtifactUpdateBlock = (
126
+ artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,
127
+ ): ContentBlock.Any => {
128
+ return {
129
+ _tag: 'text',
130
+ // TODO(dmaretskyi): Does this need to be a special content-block?
131
+ disposition: 'artifact-update',
132
+ text: trim`
133
+ The following artifacts have been updated since the last message:
134
+ ${[...artifactDiff.entries()]
135
+ .map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `\n${diff}` : ''}</changed-artifact>`)
136
+ .join('\n')}
137
+ `,
138
+ };
139
+ };
@@ -2,5 +2,8 @@
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';
@@ -0,0 +1,58 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Effect, Function } from 'effect';
6
+
7
+ import { type AiParser, type ConsolePrinter } from '@dxos/ai';
8
+ import { type DataType } from '@dxos/schema';
9
+
10
+ /**
11
+ * Live observer of the generation process.
12
+ */
13
+ export interface GenerationObserver extends AiParser.ParseResponseCallbacks {
14
+ /**
15
+ * Complete messages fired during the session, both from the model and from the user.
16
+ * This message will contain all message blocks emitted through the `onBlock` callback.
17
+ */
18
+ onMessage: (message: DataType.Message) => Effect.Effect<void>;
19
+ }
20
+
21
+ export const GenerationObserver = Object.freeze({
22
+ make: ({
23
+ onBegin = Function.constant(Effect.void),
24
+ onPart = Function.constant(Effect.void),
25
+ onBlock = Function.constant(Effect.void),
26
+ onEnd = Function.constant(Effect.void),
27
+ onMessage = Function.constant(Effect.void),
28
+ }: Partial<GenerationObserver> = {}): GenerationObserver => ({
29
+ onBegin,
30
+ onPart,
31
+ onBlock,
32
+ onEnd,
33
+ onMessage,
34
+ }),
35
+
36
+ noop: () => GenerationObserver.make(),
37
+
38
+ /**
39
+ * Debug printer to be used in unit-tests and browser devtools.
40
+ */
41
+ fromPrinter: (printer: ConsolePrinter) =>
42
+ GenerationObserver.make({
43
+ onBlock: (block) =>
44
+ Effect.sync(() => {
45
+ if (block.pending) {
46
+ return; // Only prints full blocks (better for unit-tests and browser devtools).
47
+ }
48
+ printer.printContentBlock(block);
49
+ }),
50
+ onMessage: (message) =>
51
+ Effect.sync(() => {
52
+ if (message.sender.role === 'assistant') {
53
+ return; // Skip assistant messages since they are printed in the `onBlock` callback.
54
+ }
55
+ printer.printMessage(message);
56
+ }),
57
+ }),
58
+ });
@@ -9,6 +9,7 @@ import { Effect, Layer, Schema } from 'effect';
9
9
  import { AiService, ToolExecutionService, ToolResolverService } from '@dxos/ai';
10
10
  import { AiServiceTestingPreset } from '@dxos/ai/testing';
11
11
  import { Obj, Type } from '@dxos/echo';
12
+ import { TracingService } from '@dxos/functions';
12
13
  import { log } from '@dxos/log';
13
14
 
14
15
  import { AiSession } from './session';
@@ -52,7 +53,7 @@ const toolkitLayer = TestToolkit.toLayer({
52
53
  const sanitizedInput = input.replace(/[^0-9+\-*/().\s]/g, '');
53
54
  log.info('calculate', { sanitizedInput });
54
55
 
55
- // eslint-disable-next-line no-new-func, @typescript-eslint/no-implied-eval
56
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
56
57
  return Function(`"use strict"; return (${sanitizedInput})`)();
57
58
  })();
58
59
 
@@ -61,49 +62,49 @@ const toolkitLayer = TestToolkit.toLayer({
61
62
  });
62
63
 
63
64
  describe.runIf(process.env.DX_RUN_SLOW_TESTS)('AiSession', () => {
64
- it.effect(
65
- 'no tools',
66
- Effect.fn(
67
- function* ({ expect }) {
68
- const session = new AiSession({ operationModel: 'configured' });
69
-
70
- const response = yield* session.run({
71
- prompt: 'Hello world!',
72
- history: [],
73
- });
74
- log.info('response', { response });
75
- },
65
+ it.effect('no tools', () =>
66
+ Effect.gen(function* () {
67
+ const session = new AiSession({ operationModel: 'configured' });
68
+ const response = yield* session.run({
69
+ prompt: 'Hello world!',
70
+ history: [],
71
+ });
72
+ log.info('response', { response });
73
+ }).pipe(
76
74
  Effect.provide(
77
- AiService.model('@anthropic/claude-3-5-sonnet-20241022').pipe(
78
- Layer.provideMerge(ToolResolverService.layerEmpty),
79
- Layer.provideMerge(ToolExecutionService.layerEmpty),
80
- Layer.provideMerge(AiServiceTestingPreset('direct')),
75
+ Layer.mergeAll(
76
+ toolkitLayer,
77
+ AiService.model('@anthropic/claude-3-5-sonnet-20241022').pipe(
78
+ Layer.provideMerge(ToolResolverService.layerEmpty),
79
+ Layer.provideMerge(ToolExecutionService.layerEmpty),
80
+ Layer.provideMerge(AiServiceTestingPreset('direct')),
81
+ Layer.provideMerge(TracingService.layerNoop),
82
+ ),
81
83
  ),
82
84
  ),
83
85
  ),
84
86
  );
85
87
 
86
- it.effect.only(
87
- 'calculator',
88
- Effect.fn(
89
- function* ({ expect }) {
90
- const session = new AiSession({ operationModel: 'configured' });
91
-
92
- const response = yield* session.run({
93
- prompt: 'What is 10 + 20?',
94
- history: [],
95
- toolkit: TestToolkit,
96
- });
97
- log.info('response', { response });
98
- },
88
+ it.effect('calculator', () =>
89
+ Effect.gen(function* () {
90
+ const session = new AiSession({ operationModel: 'configured' });
91
+ const toolkit = yield* TestToolkit;
92
+ const response = yield* session.run({
93
+ toolkit,
94
+ prompt: 'What is 10 + 20?',
95
+ history: [],
96
+ });
97
+ log.info('response', { response });
98
+ }).pipe(
99
99
  Effect.provide(
100
100
  Layer.mergeAll(
101
- toolkitLayer,
102
- ToolResolverService.layerEmpty,
103
- ToolExecutionService.layerEmpty,
101
+ TracingService.layerNoop,
104
102
  AiService.model('@anthropic/claude-3-5-sonnet-20241022').pipe(
105
103
  Layer.provideMerge(AiServiceTestingPreset('direct')),
106
104
  ),
105
+ ToolResolverService.layerEmpty,
106
+ ToolExecutionService.layerEmpty,
107
+ toolkitLayer,
107
108
  ),
108
109
  ),
109
110
  ),
@@ -112,11 +113,8 @@ describe.runIf(process.env.DX_RUN_SLOW_TESTS)('AiSession', () => {
112
113
  // TODO(dmaretskyi): Revive test.
113
114
  /*
114
115
  it.skip('create calendar itinerary', { timeout: 60_000 }, async () => {
115
-
116
- // overrides: { model: 'llama3.1:8b' },
117
-
116
+ // overrides: { model: 'llama3.1:8b' },
118
117
  const session = new AiSession({ operationModel: 'configured' });
119
-
120
118
  const objects = new Set<string>();
121
119
 
122
120
  // Define calendar artifact.
@@ -235,7 +233,7 @@ describe.runIf(process.env.DX_RUN_SLOW_TESTS)('AiSession', () => {
235
233
  });
236
234
 
237
235
  // Travel to rome, florence, livorno, siena, madrid for conferences
238
- // eslint-disable-next-line no-unused-vars
236
+
239
237
  const _CALENDAR_EVENTS: CalendarEvent[] = [
240
238
  Obj.make(CalendarEventSchema, {
241
239
  title: 'Exploring Ancient Ruins in Rome',