@dxos/assistant 0.8.4-main.fd6878d → 0.8.4-main.fffef41

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 (122) hide show
  1. package/dist/lib/browser/chunk-J5LGTIGS.mjs +10 -0
  2. package/dist/lib/browser/extraction/index.mjs +121 -165
  3. package/dist/lib/browser/extraction/index.mjs.map +4 -4
  4. package/dist/lib/browser/index.mjs +1097 -161
  5. package/dist/lib/browser/index.mjs.map +4 -4
  6. package/dist/lib/browser/meta.json +1 -1
  7. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  8. package/dist/lib/node-esm/extraction/index.mjs +121 -165
  9. package/dist/lib/node-esm/extraction/index.mjs.map +4 -4
  10. package/dist/lib/node-esm/index.mjs +1097 -161
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/types/src/conversation/context.d.ts +23 -10
  14. package/dist/types/src/conversation/context.d.ts.map +1 -1
  15. package/dist/types/src/conversation/conversation.d.ts +22 -31
  16. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  17. package/dist/types/src/diff.d.ts +15 -0
  18. package/dist/types/src/diff.d.ts.map +1 -0
  19. package/dist/types/src/diff.test.d.ts +2 -0
  20. package/dist/types/src/diff.test.d.ts.map +1 -0
  21. package/dist/types/src/errors.d.ts +45 -13
  22. package/dist/types/src/errors.d.ts.map +1 -1
  23. package/dist/types/src/execution-graph.d.ts +85 -0
  24. package/dist/types/src/execution-graph.d.ts.map +1 -0
  25. package/dist/types/src/execution-graph.test.d.ts +2 -0
  26. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  27. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +1 -1
  28. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  29. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +82 -43
  30. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  31. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  32. package/dist/types/src/extraction/extraction.d.ts +262 -225
  33. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  34. package/dist/types/src/extraction/quotes.d.ts +1 -1
  35. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  36. package/dist/types/src/functions/services.d.ts +18 -5
  37. package/dist/types/src/functions/services.d.ts.map +1 -1
  38. package/dist/types/src/index.d.ts +3 -1
  39. package/dist/types/src/index.d.ts.map +1 -1
  40. package/dist/types/src/session/GenericToolkit.d.ts +84 -0
  41. package/dist/types/src/session/GenericToolkit.d.ts.map +1 -0
  42. package/dist/types/src/session/artifact-diff.d.ts +2 -2
  43. package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
  44. package/dist/types/src/session/error-handling.d.ts +4 -0
  45. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  46. package/dist/types/src/session/format.d.ts +5 -161
  47. package/dist/types/src/session/format.d.ts.map +1 -1
  48. package/dist/types/src/session/index.d.ts +3 -0
  49. package/dist/types/src/session/index.d.ts.map +1 -1
  50. package/dist/types/src/session/observer.d.ts +22 -0
  51. package/dist/types/src/session/observer.d.ts.map +1 -0
  52. package/dist/types/src/session/session.d.ts +22 -138
  53. package/dist/types/src/session/session.d.ts.map +1 -1
  54. package/dist/types/src/session/toolkit.d.ts +15 -0
  55. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  56. package/dist/types/src/session/version-pin.d.ts +3 -3
  57. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  58. package/dist/types/src/templates/system.d.ts +8 -12
  59. package/dist/types/src/templates/system.d.ts.map +1 -1
  60. package/dist/types/src/types/artifact.d.ts +20 -0
  61. package/dist/types/src/types/artifact.d.ts.map +1 -0
  62. package/dist/types/src/types/index.d.ts +2 -0
  63. package/dist/types/src/types/index.d.ts.map +1 -0
  64. package/dist/types/tsconfig.tsbuildinfo +1 -1
  65. package/package.json +29 -31
  66. package/src/conversation/context.ts +75 -22
  67. package/src/conversation/conversation.ts +80 -77
  68. package/src/diff.test.ts +43 -0
  69. package/src/diff.ts +84 -0
  70. package/src/errors.ts +6 -1
  71. package/src/execution-graph.test.ts +740 -0
  72. package/src/execution-graph.ts +509 -0
  73. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +9 -9
  74. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +47 -56
  75. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +16 -16
  76. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +42 -43
  77. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  78. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +2 -0
  79. package/src/extraction/extraction.ts +7 -6
  80. package/src/extraction/quotes.test.ts +2 -2
  81. package/src/extraction/quotes.ts +3 -3
  82. package/src/functions/services.ts +104 -56
  83. package/src/index.ts +3 -1
  84. package/src/session/GenericToolkit.ts +130 -0
  85. package/src/session/artifact-diff.ts +8 -4
  86. package/src/session/error-handling.ts +41 -0
  87. package/src/session/format.test.ts +5 -4
  88. package/src/session/format.ts +27 -22
  89. package/src/session/index.ts +4 -0
  90. package/src/session/observer.ts +59 -0
  91. package/src/session/session.conversations.json +1 -0
  92. package/src/session/session.test.ts +35 -191
  93. package/src/session/session.ts +119 -185
  94. package/src/session/toolkit.ts +48 -0
  95. package/src/session/version-pin.ts +4 -5
  96. package/src/templates/{format.tpl → instructions/format.tpl} +8 -2
  97. package/src/templates/{system.tpl → instructions/system.tpl} +15 -14
  98. package/src/templates/system.ts +25 -16
  99. package/src/{types.ts → types/artifact.ts} +22 -3
  100. package/src/types/index.ts +5 -0
  101. package/dist/lib/browser/chunk-6WRGDEMH.mjs +0 -89
  102. package/dist/lib/browser/chunk-6WRGDEMH.mjs.map +0 -7
  103. package/dist/lib/browser/chunk-NZGGCEF3.mjs +0 -341
  104. package/dist/lib/browser/chunk-NZGGCEF3.mjs.map +0 -7
  105. package/dist/lib/browser/named-entity-recognition-O46UTCLR.mjs +0 -13
  106. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs +0 -91
  107. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs.map +0 -7
  108. package/dist/lib/node-esm/chunk-XOOPGSGW.mjs +0 -343
  109. package/dist/lib/node-esm/chunk-XOOPGSGW.mjs.map +0 -7
  110. package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs +0 -14
  111. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  112. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  113. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  114. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  115. package/dist/types/src/types.d.ts +0 -16
  116. package/dist/types/src/types.d.ts.map +0 -1
  117. package/src/session/__snapshots__/session.test.ts.snap +0 -32
  118. package/src/session/version-pin.test.ts +0 -7
  119. package/src/summarization/summarization.test.ts +0 -197
  120. /package/dist/lib/browser/{named-entity-recognition-O46UTCLR.mjs.map → chunk-J5LGTIGS.mjs.map} +0 -0
  121. /package/dist/lib/node-esm/{named-entity-recognition-W4VMRCH6.mjs.map → chunk-HSLMI22Q.mjs.map} +0 -0
  122. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -0,0 +1,130 @@
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
+ },
117
+ R
118
+ >
119
+ >;
120
+
121
+ export interface AnyStructSchemaNoContext extends Pipeable.Pipeable {
122
+ readonly [Schema.TypeId]: any;
123
+ readonly make: any;
124
+ readonly Type: any;
125
+ readonly Encoded: any;
126
+ readonly Context: never;
127
+ readonly ast: SchemaAST.AST;
128
+ readonly fields: Schema.Struct.Fields;
129
+ readonly annotations: any;
130
+ }
@@ -2,10 +2,10 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Context } from 'effect';
5
+ import * as Context from 'effect/Context';
6
6
 
7
+ import { type ObjectId } from '@dxos/echo/internal';
7
8
  import { type ObjectVersion } from '@dxos/echo-db';
8
- import { type ObjectId } from '@dxos/echo-schema';
9
9
 
10
10
  /**
11
11
  * Resolves artifact ids to their versions.
@@ -15,7 +15,6 @@ import { type ObjectId } from '@dxos/echo-schema';
15
15
  *
16
16
  * Can be optionally provided to the session run call.
17
17
  */
18
- // TODO(burdon): Move.
19
18
  // TODO(dmaretskyi): Convert to Context.Reference
20
19
  export class ArtifactDiffResolver extends Context.Tag('@dxos/assistant/ArtifactDiffResolver')<
21
20
  ArtifactDiffResolver,
@@ -24,7 +23,12 @@ export class ArtifactDiffResolver extends Context.Tag('@dxos/assistant/ArtifactD
24
23
 
25
24
  export namespace ArtifactDiffResolver {
26
25
  export type Service = {
27
- resolve: (artifacts: { id: ObjectId; lastVersion: ObjectVersion }[]) => Promise<
26
+ resolve: (
27
+ artifacts: {
28
+ id: ObjectId;
29
+ lastVersion: ObjectVersion;
30
+ }[],
31
+ ) => Promise<
28
32
  Map<
29
33
  ObjectId,
30
34
  {
@@ -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)));
@@ -3,13 +3,14 @@
3
3
  //
4
4
 
5
5
  import { beforeAll, describe, it } from '@effect/vitest';
6
- import { Effect } from 'effect';
6
+ import * as Effect from 'effect/Effect';
7
7
 
8
8
  import { Blueprint, Template } from '@dxos/blueprints';
9
9
  import { Obj } from '@dxos/echo';
10
10
  import { type EchoDatabase } from '@dxos/echo-db';
11
11
  import { EchoTestBuilder } from '@dxos/echo-db/testing';
12
- import { DataType } from '@dxos/schema';
12
+ import { Text } from '@dxos/schema';
13
+ import { Organization } from '@dxos/types';
13
14
  import { trim } from '@dxos/util';
14
15
 
15
16
  import { createSystemPrompt } from '../templates/system';
@@ -21,7 +22,7 @@ describe('format', () => {
21
22
  beforeAll(async () => {
22
23
  const builder = await new EchoTestBuilder().open();
23
24
  ({ db } = await builder.createDatabase({
24
- types: [DataType.Text, DataType.Organization, Blueprint.Blueprint],
25
+ types: [Text.Text, Organization.Organization, Blueprint.Blueprint],
25
26
  }));
26
27
  });
27
28
 
@@ -29,7 +30,7 @@ describe('format', () => {
29
30
  'should format',
30
31
  Effect.fn(function* () {
31
32
  const object = db.add(
32
- Obj.make(DataType.Organization, {
33
+ Obj.make(Organization.Organization, {
33
34
  name: 'Test',
34
35
  website: 'https://www.test.com',
35
36
  }),
@@ -2,21 +2,23 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Array, Effect, Option, pipe } from 'effect';
5
+ import * as Array from 'effect/Array';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Function from 'effect/Function';
8
+ import * as Option from 'effect/Option';
6
9
 
7
10
  import { Template } from '@dxos/blueprints';
8
11
  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 { type ObjectId } from '@dxos/echo/internal';
13
+ import { DatabaseService, ObjectVersion } from '@dxos/echo-db';
12
14
  import { log } from '@dxos/log';
13
- import { type ContentBlock, DataType } from '@dxos/schema';
15
+ import { type ContentBlock, Message } from '@dxos/types';
14
16
  import { trim } from '@dxos/util';
15
17
 
16
18
  import { AiAssistantError } from '../errors';
17
19
 
18
20
  import { ArtifactDiffResolver } from './artifact-diff';
19
- import { type SessionRunParams } from './session';
21
+ import { type AiSessionRunError, type AiSessionRunParams } from './session';
20
22
 
21
23
  /**
22
24
  * Formats the system prompt.
@@ -26,18 +28,18 @@ export const formatSystemPrompt = ({
26
28
  system,
27
29
  blueprints = [],
28
30
  objects = [],
29
- }: Pick<SessionRunParams<any>, 'system' | 'blueprints' | 'objects'>) =>
31
+ }: Pick<AiSessionRunParams<any>, 'system' | 'blueprints' | 'objects'>) =>
30
32
  Effect.gen(function* () {
31
- // TOOD(burdon): Should process templates.
32
- const blueprintDefs = yield* pipe(
33
+ const blueprintDefs = yield* Function.pipe(
33
34
  blueprints,
34
35
  Effect.forEach((blueprint) => Effect.succeed(blueprint.instructions)),
35
- Effect.flatMap(Effect.forEach((template) => DatabaseService.load(template.source))),
36
+ Effect.flatMap(Effect.forEach((template) => DatabaseService.loadOption(template.source))),
37
+ Effect.map(Array.filter(Option.isSome)),
36
38
  Effect.map(
37
39
  Array.map(
38
40
  (template) => trim`
39
41
  <blueprint>
40
- ${Template.process(template.content)}
42
+ ${Template.process(template.value.content)}
41
43
  </blueprint>
42
44
  `,
43
45
  ),
@@ -47,7 +49,7 @@ export const formatSystemPrompt = ({
47
49
  ),
48
50
  );
49
51
 
50
- const objectDefs = yield* pipe(
52
+ const objectDefs = yield* Function.pipe(
51
53
  objects,
52
54
  Effect.forEach((object) =>
53
55
  Effect.succeed(trim`
@@ -60,7 +62,7 @@ export const formatSystemPrompt = ({
60
62
  Effect.map((objects) => (objects.length > 0 ? ['## Context Objects', ...objects].join('\n\n') : undefined)),
61
63
  );
62
64
 
63
- return yield* pipe(
65
+ return yield* Function.pipe(
64
66
  Effect.succeed([system, blueprintDefs, objectDefs].filter((def): def is string => def !== undefined)),
65
67
  Effect.map((parts) => parts.join('\n\n')),
66
68
  );
@@ -71,9 +73,12 @@ export const formatSystemPrompt = ({
71
73
  */
72
74
  // TODO(burdon): Move to AiPreprocessor.
73
75
  // TODO(burdon): Convert util below to `Effect.fn` (to preserve stack info)
74
- export const formatUserPrompt = ({ prompt, history = [] }: Pick<SessionRunParams<any>, 'prompt' | 'history'>) =>
76
+ export const formatUserPrompt = ({
77
+ prompt,
78
+ history = [],
79
+ }: Pick<AiSessionRunParams<any>, 'prompt' | 'history'>): Effect.Effect<Message.Message, AiSessionRunError> =>
75
80
  Effect.gen(function* () {
76
- const prelude: ContentBlock.Any[] = [];
81
+ const blocks: ContentBlock.Any[] = [];
77
82
 
78
83
  // TODO(dmaretskyi): Evaluate other approaches as `serviceOption` isn't represented in the type system.
79
84
  const artifactDiffResolver = yield* Effect.serviceOption(ArtifactDiffResolver);
@@ -84,32 +89,32 @@ export const formatUserPrompt = ({ prompt, history = [] }: Pick<SessionRunParams
84
89
  artifactDiffResolver.value.resolve(
85
90
  [...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),
86
91
  ),
87
- catch: AiAssistantError.wrap('Artifact diff resolution error'),
92
+ catch: AiAssistantError.wrap({ message: 'Artifact diff resolution error' }),
88
93
  });
89
94
 
90
- log.info('version', { artifactDiff, versions });
95
+ log('version', { artifactDiff, versions });
91
96
  for (const [id, { version }] of [...artifactDiff.entries()]) {
92
97
  if (ObjectVersion.equals(version, versions.get(id)!)) {
93
98
  artifactDiff.delete(id);
94
99
  continue;
95
100
  }
96
101
 
97
- prelude.push({ _tag: 'anchor', objectId: id, version });
102
+ blocks.push({ _tag: 'anchor', objectId: id, version });
98
103
  }
99
104
 
100
105
  if (artifactDiff.size > 0) {
101
- prelude.push(createArtifactUpdateBlock(artifactDiff));
106
+ blocks.push(createArtifactUpdateBlock(artifactDiff));
102
107
  }
103
108
  }
104
109
 
105
- return Obj.make(DataType.Message, {
110
+ return Obj.make(Message.Message, {
106
111
  created: new Date().toISOString(),
107
112
  sender: { role: 'user' },
108
- blocks: [...prelude, { _tag: 'text', text: prompt }],
113
+ blocks: [...blocks, { _tag: 'text', text: prompt }],
109
114
  });
110
115
  });
111
116
 
112
- const gatherObjectVersions = (messages: DataType.Message[]): Map<ObjectId, ObjectVersion> => {
117
+ const gatherObjectVersions = (messages: Message.Message[]): Map<ObjectId, ObjectVersion> => {
113
118
  const artifactIds = new Map<ObjectId, ObjectVersion>();
114
119
  for (const message of messages) {
115
120
  for (const block of message.blocks) {
@@ -3,5 +3,9 @@
3
3
  //
4
4
 
5
5
  export * from './artifact-diff';
6
+ export * from './observer';
6
7
  export * from './session';
8
+ export * from './toolkit';
7
9
  export * from './version-pin';
10
+
11
+ export * as GenericToolkit from './GenericToolkit';
@@ -0,0 +1,59 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Effect from 'effect/Effect';
6
+ import * as Function from 'effect/Function';
7
+
8
+ import { type AiParser, type ConsolePrinter } from '@dxos/ai';
9
+ import { type Message } from '@dxos/types';
10
+
11
+ /**
12
+ * Live observer of the generation process.
13
+ */
14
+ export interface GenerationObserver extends AiParser.ParseResponseCallbacks {
15
+ /**
16
+ * Complete messages fired during the session, both from the model and from the user.
17
+ * This message will contain all message blocks emitted through the `onBlock` callback.
18
+ */
19
+ onMessage: (message: Message.Message) => Effect.Effect<void>;
20
+ }
21
+
22
+ export const GenerationObserver = Object.freeze({
23
+ make: ({
24
+ onBegin = Function.constant(Effect.void),
25
+ onPart = Function.constant(Effect.void),
26
+ onBlock = Function.constant(Effect.void),
27
+ onEnd = Function.constant(Effect.void),
28
+ onMessage = Function.constant(Effect.void),
29
+ }: Partial<GenerationObserver> = {}): GenerationObserver => ({
30
+ onBegin,
31
+ onPart,
32
+ onBlock,
33
+ onEnd,
34
+ onMessage,
35
+ }),
36
+
37
+ noop: () => GenerationObserver.make(),
38
+
39
+ /**
40
+ * Debug printer to be used in unit-tests and browser devtools.
41
+ */
42
+ fromPrinter: (printer: ConsolePrinter) =>
43
+ GenerationObserver.make({
44
+ onBlock: (block) =>
45
+ Effect.sync(() => {
46
+ if (block.pending) {
47
+ return; // Only prints full blocks (better for unit-tests and browser devtools).
48
+ }
49
+ printer.printContentBlock(block);
50
+ }),
51
+ onMessage: (message) =>
52
+ Effect.sync(() => {
53
+ if (message.sender.role === 'assistant') {
54
+ return; // Skip assistant messages since they are printed in the `onBlock` callback.
55
+ }
56
+ printer.printMessage(message);
57
+ }),
58
+ }),
59
+ });
@@ -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","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"}}}}]}]}