@dxos/assistant 0.8.4-main.e098934 → 0.8.4-main.ead640a
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.
- package/dist/lib/browser/{chunk-3K5SRE5A.mjs → chunk-CWGVG235.mjs} +59 -83
- package/dist/lib/browser/chunk-CWGVG235.mjs.map +7 -0
- package/dist/lib/browser/extraction/index.mjs +17 -13
- package/dist/lib/browser/extraction/index.mjs.map +4 -4
- package/dist/lib/browser/index.mjs +550 -86
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node-esm/{chunk-W7AIB6DP.mjs → chunk-OV5PMQPB.mjs} +59 -83
- package/dist/lib/node-esm/chunk-OV5PMQPB.mjs.map +7 -0
- package/dist/lib/node-esm/extraction/index.mjs +17 -13
- package/dist/lib/node-esm/extraction/index.mjs.map +4 -4
- package/dist/lib/node-esm/index.mjs +550 -86
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/types/src/conversation/context.d.ts +14 -7
- package/dist/types/src/conversation/context.d.ts.map +1 -1
- package/dist/types/src/conversation/conversation.d.ts +9 -10
- package/dist/types/src/conversation/conversation.d.ts.map +1 -1
- package/dist/types/src/errors.d.ts +8 -8
- package/dist/types/src/execution-graph.d.ts +82 -0
- package/dist/types/src/execution-graph.d.ts.map +1 -0
- package/dist/types/src/execution-graph.test.d.ts +2 -0
- package/dist/types/src/execution-graph.test.d.ts.map +1 -0
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +61 -57
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction.d.ts +10 -6
- package/dist/types/src/extraction/extraction.d.ts.map +1 -1
- package/dist/types/src/extraction/quotes.d.ts +1 -1
- package/dist/types/src/extraction/quotes.d.ts.map +1 -1
- package/dist/types/src/functions/services.d.ts +17 -5
- package/dist/types/src/functions/services.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +2 -1
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/session/artifact-diff.d.ts +2 -2
- package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
- package/dist/types/src/session/error-handling.d.ts +2 -2
- package/dist/types/src/session/error-handling.d.ts.map +1 -1
- package/dist/types/src/session/format.d.ts +33 -31
- package/dist/types/src/session/format.d.ts.map +1 -1
- package/dist/types/src/session/observer.d.ts +1 -1
- package/dist/types/src/session/observer.d.ts.map +1 -1
- package/dist/types/src/session/session.d.ts +13 -9
- package/dist/types/src/session/session.d.ts.map +1 -1
- package/dist/types/src/session/toolkit.d.ts +7 -6
- package/dist/types/src/session/toolkit.d.ts.map +1 -1
- package/dist/types/src/session/version-pin.d.ts +2 -2
- package/dist/types/src/session/version-pin.d.ts.map +1 -1
- package/dist/types/src/{types.d.ts → types/artifact.d.ts} +3 -3
- package/dist/types/src/types/artifact.d.ts.map +1 -0
- package/dist/types/src/types/index.d.ts +2 -0
- package/dist/types/src/types/index.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +26 -31
- package/src/conversation/context.ts +49 -17
- package/src/conversation/conversation.ts +23 -18
- package/src/execution-graph.test.ts +738 -0
- package/src/execution-graph.ts +500 -0
- package/src/extraction/extraction-llm-function/extraction-llm-function.ts +3 -1
- package/src/extraction/extraction-ner-function/extraction-ner-function.ts +3 -1
- package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +2 -1
- package/src/extraction/extraction.ts +2 -2
- package/src/extraction/quotes.ts +2 -2
- package/src/functions/services.ts +85 -46
- package/src/index.ts +2 -1
- package/src/session/artifact-diff.ts +2 -2
- package/src/session/error-handling.ts +6 -4
- package/src/session/format.test.ts +1 -1
- package/src/session/format.ts +8 -5
- package/src/session/observer.ts +2 -1
- package/src/session/session.conversations.json +1 -0
- package/src/session/session.test.ts +50 -209
- package/src/session/session.ts +31 -20
- package/src/session/toolkit.ts +19 -13
- package/src/session/version-pin.ts +2 -2
- package/src/summarization/summarization.test.ts +8 -3
- package/src/templates/system.tpl +10 -12
- package/src/{types.ts → types/artifact.ts} +2 -2
- package/src/types/index.ts +5 -0
- package/dist/lib/browser/chunk-3K5SRE5A.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-W7AIB6DP.mjs.map +0 -7
- package/dist/types/src/session/version-pin.test.d.ts +0 -2
- package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
- package/dist/types/src/types.d.ts.map +0 -1
- package/src/session/__snapshots__/session.test.ts.snap +0 -32
- package/src/session/version-pin.test.ts +0 -7
package/src/session/session.ts
CHANGED
|
@@ -2,14 +2,20 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import
|
|
6
|
-
import
|
|
5
|
+
import type * as AiError from '@effect/ai/AiError';
|
|
6
|
+
import * as LanguageModel from '@effect/ai/LanguageModel';
|
|
7
|
+
import type * as Tool from '@effect/ai/Tool';
|
|
8
|
+
import type * as Toolkit from '@effect/ai/Toolkit';
|
|
9
|
+
import * as Chunk from 'effect/Chunk';
|
|
10
|
+
import * as Effect from 'effect/Effect';
|
|
11
|
+
import type * as Schema from 'effect/Schema';
|
|
12
|
+
import * as Stream from 'effect/Stream';
|
|
7
13
|
|
|
8
14
|
import {
|
|
9
|
-
type AiInputPreprocessingError,
|
|
10
15
|
AiParser,
|
|
11
16
|
AiPreprocessor,
|
|
12
17
|
type AiToolNotFoundError,
|
|
18
|
+
type PromptPreprocessingError,
|
|
13
19
|
type ToolExecutionService,
|
|
14
20
|
type ToolResolverService,
|
|
15
21
|
callTool,
|
|
@@ -24,25 +30,24 @@ import { DataType } from '@dxos/schema';
|
|
|
24
30
|
|
|
25
31
|
import { type AiAssistantError } from '../errors';
|
|
26
32
|
|
|
27
|
-
import { mapAiError } from './error-handling';
|
|
28
33
|
import { formatSystemPrompt, formatUserPrompt } from './format';
|
|
29
34
|
import { GenerationObserver } from './observer';
|
|
30
35
|
|
|
31
|
-
export type AiSessionRunError = AiError.AiError |
|
|
36
|
+
export type AiSessionRunError = AiError.AiError | PromptPreprocessingError | AiToolNotFoundError | AiAssistantError;
|
|
32
37
|
|
|
33
38
|
export type AiSessionRunRequirements =
|
|
34
|
-
|
|
|
39
|
+
| LanguageModel.LanguageModel
|
|
35
40
|
| ToolExecutionService
|
|
36
41
|
| ToolResolverService
|
|
37
42
|
| TracingService;
|
|
38
43
|
|
|
39
|
-
export type AiSessionRunParams<Tools extends
|
|
44
|
+
export type AiSessionRunParams<Tools extends Record<string, Tool.Any>> = {
|
|
40
45
|
prompt: string;
|
|
41
46
|
system?: string;
|
|
42
47
|
history?: DataType.Message[];
|
|
43
48
|
objects?: Obj.Any[];
|
|
44
49
|
blueprints?: Blueprint.Blueprint[];
|
|
45
|
-
toolkit?:
|
|
50
|
+
toolkit?: Toolkit.WithHandler<Tools>;
|
|
46
51
|
observer?: GenerationObserver;
|
|
47
52
|
};
|
|
48
53
|
|
|
@@ -71,7 +76,7 @@ export class AiSession {
|
|
|
71
76
|
|
|
72
77
|
constructor(private readonly _options: AiSessionOptions = {}) {}
|
|
73
78
|
|
|
74
|
-
run = <Tools extends
|
|
79
|
+
run = <Tools extends Record<string, Tool.Any>>({
|
|
75
80
|
prompt,
|
|
76
81
|
system: systemTemplate,
|
|
77
82
|
history = [],
|
|
@@ -109,21 +114,16 @@ export class AiSession {
|
|
|
109
114
|
objects: objects?.length ?? 0,
|
|
110
115
|
});
|
|
111
116
|
|
|
112
|
-
const prompt = yield* AiPreprocessor.
|
|
117
|
+
const prompt = yield* AiPreprocessor.preprocessPrompt([...this._history, ...this._pending], { system });
|
|
113
118
|
|
|
114
119
|
// Execute the stream request.
|
|
115
|
-
|
|
120
|
+
// logDump('prompt', Prompt.Prompt.pipe(Schema.encodeSync)(prompt));
|
|
121
|
+
const blocks = yield* LanguageModel.streamText({
|
|
116
122
|
prompt,
|
|
117
|
-
system,
|
|
118
123
|
toolkit,
|
|
119
124
|
disableToolCallResolution: true,
|
|
120
125
|
}).pipe(
|
|
121
|
-
|
|
122
|
-
'AiError',
|
|
123
|
-
Effect.fnUntraced(function* (err) {
|
|
124
|
-
return yield* Effect.fail(yield* mapAiError(err));
|
|
125
|
-
}),
|
|
126
|
-
),
|
|
126
|
+
// TOOD(dmaretskyi): Error mapping.
|
|
127
127
|
AiParser.parseResponse({
|
|
128
128
|
onBegin: () => observer.onBegin(),
|
|
129
129
|
onBlock: (block) => observer.onBlock(block),
|
|
@@ -166,10 +166,12 @@ export class AiSession {
|
|
|
166
166
|
});
|
|
167
167
|
|
|
168
168
|
// Add to queue and continue loop.
|
|
169
|
+
// TODO(wittjosiah): Sometimes tool error results are added to the queue before the tool agent statuses.
|
|
170
|
+
// This results in a broken execution graph.
|
|
169
171
|
yield* submitMessage(
|
|
170
172
|
Obj.make(DataType.Message, {
|
|
171
173
|
created: new Date().toISOString(),
|
|
172
|
-
sender: { role: '
|
|
174
|
+
sender: { role: 'tool' },
|
|
173
175
|
blocks: toolResults,
|
|
174
176
|
}),
|
|
175
177
|
);
|
|
@@ -185,7 +187,7 @@ export class AiSession {
|
|
|
185
187
|
// TODO(burdon): Implement or remove.
|
|
186
188
|
async runStructured<S extends Schema.Schema.AnyNoContext>(
|
|
187
189
|
_schema: S,
|
|
188
|
-
_options: AiSessionRunParams<
|
|
190
|
+
_options: AiSessionRunParams<any>,
|
|
189
191
|
): Promise<Schema.Schema.Type<S>> {
|
|
190
192
|
return todo();
|
|
191
193
|
// const parser = structuredOutputParser(schema);
|
|
@@ -199,3 +201,12 @@ export class AiSession {
|
|
|
199
201
|
|
|
200
202
|
const createSnippet = (text: string, len = 32) =>
|
|
201
203
|
text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');
|
|
204
|
+
|
|
205
|
+
// TODO(dmaretskyi): Extract as a general util.
|
|
206
|
+
const logDump = (message: string, data: unknown) => {
|
|
207
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
208
|
+
const { writeFileSync } = require('node:fs');
|
|
209
|
+
const path = `/tmp/log-data-${Date.now()}.json`;
|
|
210
|
+
writeFileSync(path, JSON.stringify(data, null, 2));
|
|
211
|
+
log.info(message, { path });
|
|
212
|
+
};
|
package/src/session/toolkit.ts
CHANGED
|
@@ -2,15 +2,17 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import
|
|
6
|
-
import
|
|
5
|
+
import type * as Tool from '@effect/ai/Tool';
|
|
6
|
+
import * as Toolkit from '@effect/ai/Toolkit';
|
|
7
|
+
import type * as Context from 'effect/Context';
|
|
8
|
+
import * as Effect from 'effect/Effect';
|
|
7
9
|
|
|
8
|
-
import { ToolExecutionService, type ToolId, ToolResolverService } from '@dxos/ai';
|
|
10
|
+
import { type AiToolNotFoundError, ToolExecutionService, type ToolId, ToolResolverService } from '@dxos/ai';
|
|
9
11
|
import { type Blueprint } from '@dxos/blueprints';
|
|
10
|
-
import {
|
|
12
|
+
import { isTruthy } from '@dxos/util';
|
|
11
13
|
|
|
12
|
-
export type ToolkitParams<Tools extends
|
|
13
|
-
toolkit?:
|
|
14
|
+
export type ToolkitParams<Tools extends Record<string, Tool.Any>> = {
|
|
15
|
+
toolkit?: Toolkit.Toolkit<Tools>;
|
|
14
16
|
toolIds?: ToolId[];
|
|
15
17
|
blueprints?: Blueprint.Blueprint[];
|
|
16
18
|
};
|
|
@@ -18,25 +20,29 @@ export type ToolkitParams<Tools extends AiTool.Any> = {
|
|
|
18
20
|
/**
|
|
19
21
|
* Build a combined toolkit from the blueprint tools and the provided toolkit.
|
|
20
22
|
*/
|
|
21
|
-
export const createToolkit = <Tools extends
|
|
23
|
+
export const createToolkit = <Tools extends Record<string, Tool.Any> = {}>({
|
|
22
24
|
toolkit: toolkitParam,
|
|
23
25
|
toolIds = [],
|
|
24
26
|
blueprints = [],
|
|
25
|
-
}: ToolkitParams<Tools>)
|
|
27
|
+
}: ToolkitParams<Tools>): Effect.Effect<
|
|
28
|
+
Toolkit.WithHandler<any>,
|
|
29
|
+
AiToolNotFoundError,
|
|
30
|
+
ToolResolverService | ToolExecutionService | Tool.HandlersFor<Tools>
|
|
31
|
+
> =>
|
|
26
32
|
Effect.gen(function* () {
|
|
27
33
|
const blueprintToolkit = yield* ToolResolverService.resolveToolkit([
|
|
28
34
|
...blueprints.flatMap(({ tools }) => tools),
|
|
29
35
|
...toolIds,
|
|
30
36
|
]);
|
|
31
37
|
|
|
32
|
-
const blueprintToolkitHandler: Context.Context<
|
|
38
|
+
const blueprintToolkitHandler: Context.Context<Tool.HandlersFor<any>> = yield* blueprintToolkit.toContext(
|
|
33
39
|
ToolExecutionService.handlersFor(blueprintToolkit),
|
|
34
40
|
);
|
|
35
41
|
|
|
36
|
-
const toolkit =
|
|
37
|
-
return yield* toolkit.pipe(Effect.provide(blueprintToolkitHandler)) as Effect.Effect<
|
|
38
|
-
|
|
42
|
+
const toolkit = Toolkit.merge(...[toolkitParam, blueprintToolkit].filter(isTruthy));
|
|
43
|
+
return yield* toolkit.pipe(Effect.provide(blueprintToolkitHandler)) as any as Effect.Effect<
|
|
44
|
+
Toolkit.WithHandler<any>,
|
|
39
45
|
never,
|
|
40
|
-
|
|
46
|
+
Tool.HandlersFor<Tools>
|
|
41
47
|
>;
|
|
42
48
|
});
|
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import
|
|
5
|
+
import * as Schema from 'effect/Schema';
|
|
6
6
|
|
|
7
|
+
import { type AnyEchoObject, ObjectId } from '@dxos/echo/internal';
|
|
7
8
|
import { type ObjectVersion } from '@dxos/echo-db';
|
|
8
9
|
import { getVersion } from '@dxos/echo-db';
|
|
9
|
-
import { type AnyEchoObject, ObjectId } from '@dxos/echo-schema';
|
|
10
10
|
import { type ContentBlock } from '@dxos/schema';
|
|
11
11
|
|
|
12
12
|
// TODO(dmaretskyi): Extract.
|
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
// ISSUE(burdon): defineFunction
|
|
6
6
|
// @ts-nocheck
|
|
7
7
|
|
|
8
|
-
import
|
|
8
|
+
import * as Function from 'effect/Function';
|
|
9
|
+
import * as Schema from 'effect/Schema';
|
|
9
10
|
import { beforeAll, describe, test } from 'vitest';
|
|
10
11
|
|
|
11
12
|
import { AiService, MixedStreamParser } from '@dxos/ai';
|
|
@@ -18,6 +19,8 @@ import { createTestData } from '@dxos/schema/testing';
|
|
|
18
19
|
import { trim } from '@dxos/util';
|
|
19
20
|
|
|
20
21
|
const summarizationFn = defineFunction({
|
|
22
|
+
key: 'dxos.org/function/summarization/summarize',
|
|
23
|
+
name: 'Summarize transcript',
|
|
21
24
|
description: 'Summarize a document',
|
|
22
25
|
inputSchema: Schema.Struct({
|
|
23
26
|
document: Schema.optional(DataType.Text),
|
|
@@ -77,11 +80,13 @@ const summarizationFn = defineFunction({
|
|
|
77
80
|
}),
|
|
78
81
|
);
|
|
79
82
|
|
|
80
|
-
return DataType.makeText(pipe(result[0]?.blocks[0], (c) => (c?._tag === 'text' ? c.text : '')));
|
|
83
|
+
return DataType.makeText(Function.pipe(result[0]?.blocks[0], (c) => (c?._tag === 'text' ? c.text : '')));
|
|
81
84
|
},
|
|
82
85
|
});
|
|
83
86
|
|
|
84
87
|
const refinementFn = defineFunction({
|
|
88
|
+
key: 'dxos.org/function/summarization/refine',
|
|
89
|
+
name: 'Refine transcript summary',
|
|
85
90
|
description: 'Refine a summary',
|
|
86
91
|
inputSchema: Schema.Struct({
|
|
87
92
|
summaries: Schema.Array(DataType.Text),
|
|
@@ -132,7 +137,7 @@ const refinementFn = defineFunction({
|
|
|
132
137
|
}),
|
|
133
138
|
);
|
|
134
139
|
return {
|
|
135
|
-
summary: DataType.makeText(pipe(result[0]?.blocks[0], (c) => (c?._tag === 'text' ? c.text : ''))),
|
|
140
|
+
summary: DataType.makeText(Function.pipe(result[0]?.blocks[0], (c) => (c?._tag === 'text' ? c.text : ''))),
|
|
136
141
|
};
|
|
137
142
|
},
|
|
138
143
|
});
|
package/src/templates/system.tpl
CHANGED
|
@@ -1,17 +1,15 @@
|
|
|
1
1
|
{{! System Prompt }}
|
|
2
2
|
|
|
3
|
-
You are a helpful assistant called Kai.
|
|
4
|
-
Your name is Kai and you are powered by different language models.
|
|
5
|
-
You were created by DXOS and operate
|
|
6
|
-
In your initial greeting state your name and make some suggestions based on the current context objects.
|
|
3
|
+
- You are a helpful assistant called Kai.
|
|
4
|
+
- Your name is Kai and you are powered by different language models.
|
|
5
|
+
- You were created by DXOS and operate inside of Composer and on the DXOS EDGE network.
|
|
6
|
+
- In your initial greeting state your name and make some suggestions based on the current context objects.
|
|
7
|
+
- You are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.
|
|
8
|
+
- Your task is to process user commands and questions and decide how best to respond.
|
|
9
|
+
- In general be concise and direct.
|
|
10
|
+
- Follow all instructions carefully.
|
|
7
11
|
|
|
8
|
-
|
|
9
|
-
Your task is to process user commands and questions and decide how best to respond.
|
|
10
|
-
In general be concise and direct.
|
|
11
|
-
|
|
12
|
-
Follow these instructions carefully.
|
|
13
|
-
|
|
14
|
-
## Include the following steps
|
|
12
|
+
## Planning
|
|
15
13
|
|
|
16
14
|
- Analyze the structure and type of the content in the user's message.
|
|
17
15
|
- Determine if you complete the task using the available blueprint definitions?
|
|
@@ -27,7 +25,7 @@ Follow these instructions carefully.
|
|
|
27
25
|
- Call the show tool to show the artifact to the user.
|
|
28
26
|
- Your reasoning must include: whether to use artifacts or not, to create one or query, whether to show the artifact to the user, and how to structure the response.
|
|
29
27
|
|
|
30
|
-
## Blueprints
|
|
28
|
+
## Blueprints and Artifacts
|
|
31
29
|
|
|
32
30
|
- Determine if the interaction involves an artifact. Prefer artifacts for tables, lists, spreadsheets, kanbans, games, images, and other structured data.
|
|
33
31
|
- Determine if the user is explicitly talking about creating a new artifact, or wants to use an existing artifact.
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import
|
|
5
|
+
import * as Schema from 'effect/Schema';
|
|
6
6
|
|
|
7
|
-
import { type ObjectId } from '@dxos/echo
|
|
7
|
+
import { type ObjectId } from '@dxos/echo/internal';
|
|
8
8
|
import { DXN, LOCAL_SPACE_TAG, type SpaceId } from '@dxos/keys';
|
|
9
9
|
import { trim } from '@dxos/util';
|
|
10
10
|
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/session/artifact-diff.ts", "../../../src/session/observer.ts", "../../../src/errors.ts", "../../../src/session/session.ts", "../../../src/session/error-handling.ts", "../../../src/session/format.ts", "../../../src/session/toolkit.ts", "../../../src/session/version-pin.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context } from 'effect';\n\nimport { type ObjectVersion } from '@dxos/echo-db';\nimport { type ObjectId } from '@dxos/echo-schema';\n\n/**\n * Resolves artifact ids to their versions.\n * Used to give the model a sense of the changes to the artifacts made by users during the conversation.\n * The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,\n * a diff is inserted into the conversation.\n *\n * Can be optionally provided to the session run call.\n */\n// TODO(dmaretskyi): Convert to Context.Reference\nexport class ArtifactDiffResolver extends Context.Tag('@dxos/assistant/ArtifactDiffResolver')<\n ArtifactDiffResolver,\n ArtifactDiffResolver.Service\n>() {}\n\nexport namespace ArtifactDiffResolver {\n export type Service = {\n resolve: (\n artifacts: {\n id: ObjectId;\n lastVersion: ObjectVersion;\n }[],\n ) => Promise<\n Map<\n ObjectId,\n {\n version: ObjectVersion;\n diff?: string;\n }\n >\n >;\n };\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Effect, Function } from 'effect';\n\nimport { type AiParser, type ConsolePrinter } from '@dxos/ai';\nimport { type DataType } from '@dxos/schema';\n\n/**\n * Live observer of the generation process.\n */\nexport interface GenerationObserver extends AiParser.ParseResponseCallbacks {\n /**\n * Complete messages fired during the session, both from the model and from the user.\n * This message will contain all message blocks emitted through the `onBlock` callback.\n */\n onMessage: (message: DataType.Message) => Effect.Effect<void>;\n}\n\nexport const GenerationObserver = Object.freeze({\n make: ({\n onBegin = Function.constant(Effect.void),\n onPart = Function.constant(Effect.void),\n onBlock = Function.constant(Effect.void),\n onEnd = Function.constant(Effect.void),\n onMessage = Function.constant(Effect.void),\n }: Partial<GenerationObserver> = {}): GenerationObserver => ({\n onBegin,\n onPart,\n onBlock,\n onEnd,\n onMessage,\n }),\n\n noop: () => GenerationObserver.make(),\n\n /**\n * Debug printer to be used in unit-tests and browser devtools.\n */\n fromPrinter: (printer: ConsolePrinter) =>\n GenerationObserver.make({\n onBlock: (block) =>\n Effect.sync(() => {\n if (block.pending) {\n return; // Only prints full blocks (better for unit-tests and browser devtools).\n }\n printer.printContentBlock(block);\n }),\n onMessage: (message) =>\n Effect.sync(() => {\n if (message.sender.role === 'assistant') {\n return; // Skip assistant messages since they are printed in the `onBlock` callback.\n }\n printer.printMessage(message);\n }),\n }),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { BaseError } from '@dxos/errors';\n\n/**\n * Generic error from AI model.\n */\nexport class AiModelError extends BaseError.extend('AI_MODEL_ERROR', 'AI model error') {}\n\n/**\n * Generic error for AI agent execution.\n */\nexport class AiAssistantError extends BaseError.extend('AI_ASSISTANT_ERROR', 'AI assistant error') {}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type AiError, AiLanguageModel, type AiTool, type AiToolkit } from '@effect/ai';\nimport { Chunk, Effect, type Schema, Stream } from 'effect';\n\nimport {\n type AiInputPreprocessingError,\n AiParser,\n AiPreprocessor,\n type AiToolNotFoundError,\n type ToolExecutionService,\n type ToolResolverService,\n callTool,\n getToolCalls,\n} from '@dxos/ai';\nimport { type Blueprint } from '@dxos/blueprints';\nimport { todo } from '@dxos/debug';\nimport { Obj } from '@dxos/echo';\nimport { TracingService } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nimport { type AiAssistantError } from '../errors';\n\nimport { mapAiError } from './error-handling';\nimport { formatSystemPrompt, formatUserPrompt } from './format';\nimport { GenerationObserver } from './observer';\n\nexport type AiSessionRunError = AiError.AiError | AiInputPreprocessingError | AiToolNotFoundError | AiAssistantError;\n\nexport type AiSessionRunRequirements =\n | AiLanguageModel.AiLanguageModel\n | ToolExecutionService\n | ToolResolverService\n | TracingService;\n\nexport type AiSessionRunParams<Tools extends AiTool.Any> = {\n prompt: string;\n system?: string;\n history?: DataType.Message[];\n objects?: Obj.Any[];\n blueprints?: Blueprint.Blueprint[];\n toolkit?: AiToolkit.ToHandler<Tools>;\n observer?: GenerationObserver;\n};\n\nexport type AiSessionOptions = {};\n\n/**\n * Contains message history, tools, current context.\n * Current context means the state of the app, time of day, and other contextual information.\n * It makes requests to the model, its a state machine.\n * It keeps track of the current goal.\n * It manages the context window.\n * Tracks the success criteria of reaching the goal, exposing metrics (stretch).\n * Could be run locally in the app or remotely.\n * Could be personal or shared.\n */\nexport class AiSession {\n /** Prevents concurrent execution of session. */\n private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));\n\n /** Message history from queue. */\n // TODO(burdon): Evolve into supporting a git-like graph of messages.\n private _history: DataType.Message[] = [];\n\n /** Pending messages for this session (incl. the current prompt). */\n private _pending: DataType.Message[] = [];\n\n constructor(private readonly _options: AiSessionOptions = {}) {}\n\n run = <Tools extends AiTool.Any>({\n prompt,\n system: systemTemplate,\n history = [],\n objects = [],\n blueprints = [],\n toolkit,\n observer = GenerationObserver.noop(),\n }: AiSessionRunParams<Tools>): Effect.Effect<DataType.Message[], AiSessionRunError, AiSessionRunRequirements> =>\n Effect.gen(this, function* () {\n this._history = [...history];\n this._pending = [];\n const pending = this._pending;\n\n const submitMessage = Effect.fnUntraced(function* (message: DataType.Message) {\n pending.push(message);\n yield* observer.onMessage(message);\n yield* TracingService.emitConverationMessage(message);\n return message;\n });\n\n // Submit the prompt.\n // TODO(burdon): Remove if cancelled?\n const promptMessage = yield* submitMessage(yield* formatUserPrompt({ prompt, history }));\n\n // Generate system and prompt messages.\n const system = yield* formatSystemPrompt({ system: systemTemplate, blueprints, objects });\n\n // Tool call loop.\n do {\n log('request', {\n prompt: promptMessage,\n system: { snippet: createSnippet(system), length: system.length },\n pending: this._pending.length,\n history: this._history.length,\n objects: objects?.length ?? 0,\n });\n\n const prompt = yield* AiPreprocessor.preprocessAiInput([...this._history, ...this._pending]);\n\n // Execute the stream request.\n const blocks = yield* AiLanguageModel.streamText({\n prompt,\n system,\n toolkit,\n disableToolCallResolution: true,\n }).pipe(\n Stream.catchTag(\n 'AiError',\n Effect.fnUntraced(function* (err) {\n return yield* Effect.fail(yield* mapAiError(err));\n }),\n ),\n AiParser.parseResponse({\n onBegin: () => observer.onBegin(),\n onBlock: (block) => observer.onBlock(block),\n onPart: (part) => observer.onPart(part),\n onEnd: (summary) => observer.onEnd(summary),\n }),\n Stream.runCollect,\n Effect.map(Chunk.toArray),\n );\n\n // Create the response message.\n const response = yield* submitMessage(\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'assistant' },\n blocks,\n }),\n );\n\n // Parse the response for tool calls.\n const toolCalls = getToolCalls(response);\n if (toolCalls.length === 0) {\n break;\n } else if (!toolkit) {\n throw new Error('No toolkit provided'); // TODO(burdon): Throw user error?\n }\n\n // Execute the tool calls.\n // TODO(burdon): Retry errors? Write result when each completes individually?\n const toolResults = yield* Effect.forEach(toolCalls, (toolCall) => {\n return callTool(toolkit, toolCall).pipe(\n Effect.provide(\n TracingService.layerSubframe((context) => ({\n ...context,\n parentMessage: response.id,\n toolCallId: toolCall.toolCallId,\n })),\n ),\n );\n });\n\n // Add to queue and continue loop.\n yield* submitMessage(\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: toolResults,\n }),\n );\n } while (true);\n\n log('done', { pending: this._pending.length });\n return this._pending;\n }).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiSession.run'));\n\n /**\n * @deprecated\n */\n // TODO(burdon): Implement or remove.\n async runStructured<S extends Schema.Schema.AnyNoContext>(\n _schema: S,\n _options: AiSessionRunParams<AiTool.Any>,\n ): Promise<Schema.Schema.Type<S>> {\n return todo();\n // const parser = structuredOutputParser(schema);\n // const result = await this.run({\n // ...options,\n // executableTools: [...(options.executableTools ?? []), parser.tool],\n // });\n // return parser.getResult(result);\n }\n}\n\nconst createSnippet = (text: string, len = 32) =>\n text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { AiError } from '@effect/ai';\nimport { HttpClientError } from '@effect/platform';\nimport { Effect, Schema } from 'effect';\n\nimport { AiModelError } from '../errors';\n\nconst AnthropicErrorResponse = Schema.Struct({\n type: Schema.Literal('error'),\n error: Schema.Struct({\n type: Schema.String,\n message: Schema.String,\n }),\n});\n\nexport const mapAiError = (err: AiError.AiError): Effect.Effect<AiError.AiError> =>\n Effect.gen(function* () {\n const cause = err.cause;\n if (HttpClientError.isHttpClientError(cause) && cause.reason === 'StatusCode') {\n const body = yield* cause.response.json.pipe(\n Effect.flatMap(Schema.decodeUnknown(AnthropicErrorResponse, { exact: false })),\n );\n\n const parsedCause = new AiModelError({\n message: body.error.message,\n context: { model: 'anthropic', type: body.error.type },\n });\n return new AiError.AiError({\n description: body.error.message,\n module: err.module,\n method: err.method,\n cause: parsedCause,\n });\n }\n return err;\n }).pipe(Effect.catchAll(() => Effect.succeed(err)));\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Array, Effect, Option, pipe } from 'effect';\n\nimport { Template } from '@dxos/blueprints';\nimport { Obj } from '@dxos/echo';\nimport { ObjectVersion } from '@dxos/echo-db';\nimport { type ObjectId } from '@dxos/echo-schema';\nimport { DatabaseService } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { type ContentBlock, DataType } from '@dxos/schema';\nimport { trim } from '@dxos/util';\n\nimport { AiAssistantError } from '../errors';\n\nimport { ArtifactDiffResolver } from './artifact-diff';\nimport { type AiSessionRunParams } from './session';\n\n/**\n * Formats the system prompt.\n */\n// TODO(burdon): Move to AiPreprocessor.\nexport const formatSystemPrompt = ({\n system,\n blueprints = [],\n objects = [],\n}: Pick<AiSessionRunParams<any>, 'system' | 'blueprints' | 'objects'>) =>\n Effect.gen(function* () {\n const blueprintDefs = yield* pipe(\n blueprints,\n Effect.forEach((blueprint) => Effect.succeed(blueprint.instructions)),\n Effect.flatMap(Effect.forEach((template) => DatabaseService.loadOption(template.source))),\n Effect.map(Array.filter(Option.isSome)),\n Effect.map(\n Array.map(\n (template) => trim`\n <blueprint>\n ${Template.process(template.value.content)}\n </blueprint>\n `,\n ),\n ),\n Effect.map((blueprints) =>\n blueprints.length > 0 ? ['## Blueprints Definitions', ...blueprints].join('\\n\\n') : undefined,\n ),\n );\n\n const objectDefs = yield* pipe(\n objects,\n Effect.forEach((object) =>\n Effect.succeed(trim`\n <object>\n <dxn>${Obj.getDXN(object)}</dxn>\n <typename>${Obj.getTypename(object)}</typename>\n </object>\n `),\n ),\n Effect.map((objects) => (objects.length > 0 ? ['## Context Objects', ...objects].join('\\n\\n') : undefined)),\n );\n\n return yield* pipe(\n Effect.succeed([system, blueprintDefs, objectDefs].filter((def): def is string => def !== undefined)),\n Effect.map((parts) => parts.join('\\n\\n')),\n );\n });\n\n/**\n * Formats the user prompt.\n */\n// TODO(burdon): Move to AiPreprocessor.\n// TODO(burdon): Convert util below to `Effect.fn` (to preserve stack info)\nexport const formatUserPrompt = ({ prompt, history = [] }: Pick<AiSessionRunParams<any>, 'prompt' | 'history'>) =>\n Effect.gen(function* () {\n const blocks: ContentBlock.Any[] = [];\n\n // TODO(dmaretskyi): Evaluate other approaches as `serviceOption` isn't represented in the type system.\n const artifactDiffResolver = yield* Effect.serviceOption(ArtifactDiffResolver);\n if (Option.isSome(artifactDiffResolver)) {\n const versions = gatherObjectVersions(history);\n const artifactDiff = yield* Effect.tryPromise({\n try: () =>\n artifactDiffResolver.value.resolve(\n [...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),\n ),\n catch: AiAssistantError.wrap({ message: 'Artifact diff resolution error' }),\n });\n\n log('version', { artifactDiff, versions });\n for (const [id, { version }] of [...artifactDiff.entries()]) {\n if (ObjectVersion.equals(version, versions.get(id)!)) {\n artifactDiff.delete(id);\n continue;\n }\n\n blocks.push({ _tag: 'anchor', objectId: id, version });\n }\n\n if (artifactDiff.size > 0) {\n blocks.push(createArtifactUpdateBlock(artifactDiff));\n }\n }\n\n return Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: [...blocks, { _tag: 'text', text: prompt }],\n });\n });\n\nconst gatherObjectVersions = (messages: DataType.Message[]): Map<ObjectId, ObjectVersion> => {\n const artifactIds = new Map<ObjectId, ObjectVersion>();\n for (const message of messages) {\n for (const block of message.blocks) {\n if (block._tag === 'anchor') {\n artifactIds.set(block.objectId, block.version as ObjectVersion);\n }\n }\n }\n\n return artifactIds;\n};\n\nconst createArtifactUpdateBlock = (\n artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,\n): ContentBlock.Any => {\n return {\n _tag: 'text',\n // TODO(dmaretskyi): Does this need to be a special content-block?\n disposition: 'artifact-update',\n text: trim`\n The following artifacts have been updated since the last message:\n ${[...artifactDiff.entries()]\n .map(([id, { diff }]) => `<changed-artifact id=\"${id}\">${diff ? `\\n${diff}` : ''}</changed-artifact>`)\n .join('\\n')}\n `,\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type AiTool, AiToolkit } from '@effect/ai';\nimport { type Context, Effect } from 'effect';\n\nimport { ToolExecutionService, type ToolId, ToolResolverService } from '@dxos/ai';\nimport { type Blueprint } from '@dxos/blueprints';\nimport { isNotFalsy } from '@dxos/util';\n\nexport type ToolkitParams<Tools extends AiTool.Any> = {\n toolkit?: AiToolkit.AiToolkit<Tools>;\n toolIds?: ToolId[];\n blueprints?: Blueprint.Blueprint[];\n};\n\n/**\n * Build a combined toolkit from the blueprint tools and the provided toolkit.\n */\nexport const createToolkit = <Tools extends AiTool.Any>({\n toolkit: toolkitParam,\n toolIds = [],\n blueprints = [],\n}: ToolkitParams<Tools>) =>\n Effect.gen(function* () {\n const blueprintToolkit = yield* ToolResolverService.resolveToolkit([\n ...blueprints.flatMap(({ tools }) => tools),\n ...toolIds,\n ]);\n\n const blueprintToolkitHandler: Context.Context<AiTool.ToHandler<AiTool.Any>> = yield* blueprintToolkit.toContext(\n ToolExecutionService.handlersFor(blueprintToolkit),\n );\n\n const toolkit = AiToolkit.merge(...[toolkitParam, blueprintToolkit].filter(isNotFalsy));\n return yield* toolkit.pipe(Effect.provide(blueprintToolkitHandler)) as Effect.Effect<\n AiToolkit.ToHandler<any>,\n never,\n AiTool.ToHandler<Tools>\n >;\n });\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { type ObjectVersion } from '@dxos/echo-db';\nimport { getVersion } from '@dxos/echo-db';\nimport { type AnyEchoObject, ObjectId } from '@dxos/echo-schema';\nimport { type ContentBlock } from '@dxos/schema';\n\n// TODO(dmaretskyi): Extract.\nconst ObjectVersionSchema = Schema.Unknown as Schema.Schema<ObjectVersion>;\n\nconst VersionPinSchema = Schema.Struct({\n // TODO(dmaretskyi): Use Ref when those support encoding.\n objectId: ObjectId,\n // TODO(dmaretskyi): Could be opaque.\n version: ObjectVersionSchema,\n});\n\n/**\n * Used to pin a specific version of an object during the course of a conversation.\n * This allows us to detect when the object changes during the course of the conversation.\n */\nexport interface VersionPin extends Schema.Schema.Type<typeof VersionPinSchema> {}\n\nexport const VersionPin: typeof VersionPinSchema & {\n DISPOSITION: 'version-pin';\n fromObject: (object: AnyEchoObject) => VersionPin;\n createBlock: (pin: VersionPin) => ContentBlock.Any;\n} = class extends VersionPinSchema {\n static readonly DISPOSITION = 'version-pin';\n static fromObject(object: AnyEchoObject): VersionPin {\n return VersionPin.make({\n objectId: object.id,\n version: getVersion(object),\n });\n }\n\n static createBlock(pin: VersionPin): ContentBlock.Any {\n return {\n _tag: 'json',\n disposition: VersionPin.DISPOSITION,\n data: JSON.stringify(pin),\n };\n }\n};\n"],
|
|
5
|
-
"mappings": ";AAIA,SAASA,eAAe;AAcjB,IAAMC,uBAAN,cAAmCC,QAAQC,IAAI,sCAAA,EAAA,EAAA;AAGjD;;;ACjBL,SAASC,QAAQC,gBAAgB;AAgB1B,IAAMC,qBAAqBC,OAAOC,OAAO;EAC9CC,MAAM,CAAC,EACLC,UAAUC,SAASC,SAASC,OAAOC,IAAI,GACvCC,SAASJ,SAASC,SAASC,OAAOC,IAAI,GACtCE,UAAUL,SAASC,SAASC,OAAOC,IAAI,GACvCG,QAAQN,SAASC,SAASC,OAAOC,IAAI,GACrCI,YAAYP,SAASC,SAASC,OAAOC,IAAI,EAAC,IACX,CAAC,OAA2B;IAC3DJ;IACAK;IACAC;IACAC;IACAC;EACF;EAEAC,MAAM,MAAMb,mBAAmBG,KAAI;;;;EAKnCW,aAAa,CAACC,YACZf,mBAAmBG,KAAK;IACtBO,SAAS,CAACM,UACRT,OAAOU,KAAK,MAAA;AACV,UAAID,MAAME,SAAS;AACjB;MACF;AACAH,cAAQI,kBAAkBH,KAAAA;IAC5B,CAAA;IACFJ,WAAW,CAACQ,YACVb,OAAOU,KAAK,MAAA;AACV,UAAIG,QAAQC,OAAOC,SAAS,aAAa;AACvC;MACF;AACAP,cAAQQ,aAAaH,OAAAA;IACvB,CAAA;EACJ,CAAA;AACJ,CAAA;;;ACrDA,SAASI,iBAAiB;AAKnB,IAAMC,eAAN,cAA2BC,UAAUC,OAAO,kBAAkB,gBAAA,EAAA;AAAmB;AAKjF,IAAMC,mBAAN,cAA+BF,UAAUC,OAAO,sBAAsB,oBAAA,EA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,UACrGC,qBAAqBC,YAAYR,gBAAAA,CAAAA;AAGnC,QAAMN,UAAUe,UAAUC,MAAK,GAAI;IAACf;IAAcK;IAAkBW,OAAOC,UAAAA,CAAAA;AAC3E,SAAO,OAAOlB,QAAQmB,KAAKf,QAAOgB,QAAQT,uBAAAA,CAAAA;AAK5C,CAAA;;;ACrCF,SAASU,UAAAA,eAAc;AAGvB,SAASC,kBAAkB;AAC3B,SAA6BC,gBAAgB;;;;;;;;;;;;;;;AAI7C,IAAMC,sBAAsBC,QAAOC;AAEnC,IAAMC,mBAAmBF,QAAOG,OAAO;;EAErCC,UAAUC;;EAEVC,SAASP;AACX,CAAA;AAQO,IAAMQ,cAAAA,SAIT,cAAcL,iBAAAA;EAEhB,OAAOM,WAAWC,QAAmC;AACnD,WAAOF,WAAWG,KAAK;MACrBN,UAAUK,OAAOE;MACjBL,SAASM,WAAWH,MAAAA;IACtB,CAAA;EACF;EAEA,OAAOI,YAAYC,KAAmC;AACpD,WAAO;MACLC,MAAM;MACNC,aAAaT,WAAWU;MACxBC,MAAMC,KAAKC,UAAUN,GAAAA;IACvB;EACF;AACF,GAfEO,kBAAA,QAAgBJ,eAAc,aAAA,GAAA;",
|
|
6
|
-
"names": ["Context", "ArtifactDiffResolver", "Context", "Tag", "Effect", "Function", "GenerationObserver", "Object", "freeze", "make", "onBegin", "Function", "constant", "Effect", "void", "onPart", "onBlock", "onEnd", "onMessage", "noop", "fromPrinter", "printer", "block", "sync", "pending", "printContentBlock", "message", "sender", "role", "printMessage", "BaseError", "AiModelError", "BaseError", "extend", "AiAssistantError", "AiLanguageModel", "Chunk", "Effect", "Stream", "AiParser", "AiPreprocessor", "callTool", "getToolCalls", "todo", "Obj", "TracingService", "log", "DataType", "AiError", "HttpClientError", "Effect", "Schema", "AnthropicErrorResponse", "Schema", "Struct", "type", "Literal", "error", "String", "message", "mapAiError", "err", "Effect", "gen", "cause", "HttpClientError", "isHttpClientError", "reason", "body", "response", "json", "pipe", "flatMap", "decodeUnknown", "exact", "parsedCause", "AiModelError", "context", "model", "AiError", "description", "module", "method", "catchAll", "succeed", "Array", "Effect", "Option", "pipe", "Template", "Obj", "ObjectVersion", "DatabaseService", "log", "DataType", "trim", "formatSystemPrompt", "system", "blueprints", "objects", "Effect", "gen", "blueprintDefs", "pipe", "forEach", "blueprint", "succeed", "instructions", "flatMap", "template", "DatabaseService", "loadOption", "source", "map", "Array", "filter", "Option", "isSome", "trim", "Template", "process", "value", "content", "length", "join", "undefined", "objectDefs", "object", "Obj", "getDXN", "getTypename", "def", "parts", "formatUserPrompt", "prompt", "history", "blocks", "artifactDiffResolver", "serviceOption", "ArtifactDiffResolver", "versions", "gatherObjectVersions", "artifactDiff", "tryPromise", "try", "resolve", "entries", "id", "version", "lastVersion", "catch", "AiAssistantError", "wrap", "message", "log", "ObjectVersion", "equals", "get", "delete", "push", "_tag", "objectId", "size", "createArtifactUpdateBlock", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "text", "messages", "artifactIds", "Map", "block", "set", "disposition", "diff", "AiSession", "runStructured", "_schema", "_options", "todo", "_semaphore", "_history", "_pending", "run", "Effect", "runSync", "makeSemaphore", "prompt", "system", "systemTemplate", "history", "objects", "blueprints", "toolkit", "observer", "GenerationObserver", "noop", "gen", "pending", "submitMessage", "fnUntraced", "message", "push", "onMessage", "TracingService", "emitConverationMessage", "promptMessage", "formatUserPrompt", "formatSystemPrompt", "log", "snippet", "createSnippet", "length", "AiPreprocessor", "preprocessAiInput", "blocks", "AiLanguageModel", "streamText", "disableToolCallResolution", "pipe", "Stream", "catchTag", "err", "fail", "mapAiError", "AiParser", "parseResponse", "onBegin", "onBlock", "block", "onPart", "part", "onEnd", "summary", "runCollect", "map", "Chunk", "toArray", "response", "Obj", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "toolCalls", "getToolCalls", "Error", "toolResults", "forEach", "toolCall", "callTool", "provide", "layerSubframe", "context", "parentMessage", "id", "toolCallId", "withPermits", "withSpan", "text", "len", "slice", "join", "AiToolkit", "Effect", "ToolExecutionService", "ToolResolverService", "isNotFalsy", "createToolkit", "toolkit", "toolkitParam", "toolIds", "blueprints", "Effect", "gen", "blueprintToolkit", "ToolResolverService", "resolveToolkit", "flatMap", "tools", "blueprintToolkitHandler", "toContext", "ToolExecutionService", "handlersFor", "AiToolkit", "merge", "filter", "isNotFalsy", "pipe", "provide", "Schema", "getVersion", "ObjectId", "ObjectVersionSchema", "Schema", "Unknown", "VersionPinSchema", "Struct", "objectId", "ObjectId", "version", "VersionPin", "fromObject", "object", "make", "id", "getVersion", "createBlock", "pin", "_tag", "disposition", "DISPOSITION", "data", "JSON", "stringify", "_define_property"]
|
|
7
|
-
}
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/session/artifact-diff.ts", "../../../src/session/observer.ts", "../../../src/errors.ts", "../../../src/session/session.ts", "../../../src/session/error-handling.ts", "../../../src/session/format.ts", "../../../src/session/toolkit.ts", "../../../src/session/version-pin.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context } from 'effect';\n\nimport { type ObjectVersion } from '@dxos/echo-db';\nimport { type ObjectId } from '@dxos/echo-schema';\n\n/**\n * Resolves artifact ids to their versions.\n * Used to give the model a sense of the changes to the artifacts made by users during the conversation.\n * The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,\n * a diff is inserted into the conversation.\n *\n * Can be optionally provided to the session run call.\n */\n// TODO(dmaretskyi): Convert to Context.Reference\nexport class ArtifactDiffResolver extends Context.Tag('@dxos/assistant/ArtifactDiffResolver')<\n ArtifactDiffResolver,\n ArtifactDiffResolver.Service\n>() {}\n\nexport namespace ArtifactDiffResolver {\n export type Service = {\n resolve: (\n artifacts: {\n id: ObjectId;\n lastVersion: ObjectVersion;\n }[],\n ) => Promise<\n Map<\n ObjectId,\n {\n version: ObjectVersion;\n diff?: string;\n }\n >\n >;\n };\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Effect, Function } from 'effect';\n\nimport { type AiParser, type ConsolePrinter } from '@dxos/ai';\nimport { type DataType } from '@dxos/schema';\n\n/**\n * Live observer of the generation process.\n */\nexport interface GenerationObserver extends AiParser.ParseResponseCallbacks {\n /**\n * Complete messages fired during the session, both from the model and from the user.\n * This message will contain all message blocks emitted through the `onBlock` callback.\n */\n onMessage: (message: DataType.Message) => Effect.Effect<void>;\n}\n\nexport const GenerationObserver = Object.freeze({\n make: ({\n onBegin = Function.constant(Effect.void),\n onPart = Function.constant(Effect.void),\n onBlock = Function.constant(Effect.void),\n onEnd = Function.constant(Effect.void),\n onMessage = Function.constant(Effect.void),\n }: Partial<GenerationObserver> = {}): GenerationObserver => ({\n onBegin,\n onPart,\n onBlock,\n onEnd,\n onMessage,\n }),\n\n noop: () => GenerationObserver.make(),\n\n /**\n * Debug printer to be used in unit-tests and browser devtools.\n */\n fromPrinter: (printer: ConsolePrinter) =>\n GenerationObserver.make({\n onBlock: (block) =>\n Effect.sync(() => {\n if (block.pending) {\n return; // Only prints full blocks (better for unit-tests and browser devtools).\n }\n printer.printContentBlock(block);\n }),\n onMessage: (message) =>\n Effect.sync(() => {\n if (message.sender.role === 'assistant') {\n return; // Skip assistant messages since they are printed in the `onBlock` callback.\n }\n printer.printMessage(message);\n }),\n }),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { BaseError } from '@dxos/errors';\n\n/**\n * Generic error from AI model.\n */\nexport class AiModelError extends BaseError.extend('AI_MODEL_ERROR', 'AI model error') {}\n\n/**\n * Generic error for AI agent execution.\n */\nexport class AiAssistantError extends BaseError.extend('AI_ASSISTANT_ERROR', 'AI assistant error') {}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type AiError, AiLanguageModel, type AiTool, type AiToolkit } from '@effect/ai';\nimport { Chunk, Effect, type Schema, Stream } from 'effect';\n\nimport {\n type AiInputPreprocessingError,\n AiParser,\n AiPreprocessor,\n type AiToolNotFoundError,\n type ToolExecutionService,\n type ToolResolverService,\n callTool,\n getToolCalls,\n} from '@dxos/ai';\nimport { type Blueprint } from '@dxos/blueprints';\nimport { todo } from '@dxos/debug';\nimport { Obj } from '@dxos/echo';\nimport { TracingService } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nimport { type AiAssistantError } from '../errors';\n\nimport { mapAiError } from './error-handling';\nimport { formatSystemPrompt, formatUserPrompt } from './format';\nimport { GenerationObserver } from './observer';\n\nexport type AiSessionRunError = AiError.AiError | AiInputPreprocessingError | AiToolNotFoundError | AiAssistantError;\n\nexport type AiSessionRunRequirements =\n | AiLanguageModel.AiLanguageModel\n | ToolExecutionService\n | ToolResolverService\n | TracingService;\n\nexport type AiSessionRunParams<Tools extends AiTool.Any> = {\n prompt: string;\n system?: string;\n history?: DataType.Message[];\n objects?: Obj.Any[];\n blueprints?: Blueprint.Blueprint[];\n toolkit?: AiToolkit.ToHandler<Tools>;\n observer?: GenerationObserver;\n};\n\nexport type AiSessionOptions = {};\n\n/**\n * Contains message history, tools, current context.\n * Current context means the state of the app, time of day, and other contextual information.\n * It makes requests to the model, its a state machine.\n * It keeps track of the current goal.\n * It manages the context window.\n * Tracks the success criteria of reaching the goal, exposing metrics (stretch).\n * Could be run locally in the app or remotely.\n * Could be personal or shared.\n */\nexport class AiSession {\n /** Prevents concurrent execution of session. */\n private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));\n\n /** Message history from queue. */\n // TODO(burdon): Evolve into supporting a git-like graph of messages.\n private _history: DataType.Message[] = [];\n\n /** Pending messages for this session (incl. the current prompt). */\n private _pending: DataType.Message[] = [];\n\n constructor(private readonly _options: AiSessionOptions = {}) {}\n\n run = <Tools extends AiTool.Any>({\n prompt,\n system: systemTemplate,\n history = [],\n objects = [],\n blueprints = [],\n toolkit,\n observer = GenerationObserver.noop(),\n }: AiSessionRunParams<Tools>): Effect.Effect<DataType.Message[], AiSessionRunError, AiSessionRunRequirements> =>\n Effect.gen(this, function* () {\n this._history = [...history];\n this._pending = [];\n const pending = this._pending;\n\n const submitMessage = Effect.fnUntraced(function* (message: DataType.Message) {\n pending.push(message);\n yield* observer.onMessage(message);\n yield* TracingService.emitConverationMessage(message);\n return message;\n });\n\n // Submit the prompt.\n // TODO(burdon): Remove if cancelled?\n const promptMessage = yield* submitMessage(yield* formatUserPrompt({ prompt, history }));\n\n // Generate system and prompt messages.\n const system = yield* formatSystemPrompt({ system: systemTemplate, blueprints, objects });\n\n // Tool call loop.\n do {\n log('request', {\n prompt: promptMessage,\n system: { snippet: createSnippet(system), length: system.length },\n pending: this._pending.length,\n history: this._history.length,\n objects: objects?.length ?? 0,\n });\n\n const prompt = yield* AiPreprocessor.preprocessAiInput([...this._history, ...this._pending]);\n\n // Execute the stream request.\n const blocks = yield* AiLanguageModel.streamText({\n prompt,\n system,\n toolkit,\n disableToolCallResolution: true,\n }).pipe(\n Stream.catchTag(\n 'AiError',\n Effect.fnUntraced(function* (err) {\n return yield* Effect.fail(yield* mapAiError(err));\n }),\n ),\n AiParser.parseResponse({\n onBegin: () => observer.onBegin(),\n onBlock: (block) => observer.onBlock(block),\n onPart: (part) => observer.onPart(part),\n onEnd: (summary) => observer.onEnd(summary),\n }),\n Stream.runCollect,\n Effect.map(Chunk.toArray),\n );\n\n // Create the response message.\n const response = yield* submitMessage(\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'assistant' },\n blocks,\n }),\n );\n\n // Parse the response for tool calls.\n const toolCalls = getToolCalls(response);\n if (toolCalls.length === 0) {\n break;\n } else if (!toolkit) {\n throw new Error('No toolkit provided'); // TODO(burdon): Throw user error?\n }\n\n // Execute the tool calls.\n // TODO(burdon): Retry errors? Write result when each completes individually?\n const toolResults = yield* Effect.forEach(toolCalls, (toolCall) => {\n return callTool(toolkit, toolCall).pipe(\n Effect.provide(\n TracingService.layerSubframe((context) => ({\n ...context,\n parentMessage: response.id,\n toolCallId: toolCall.toolCallId,\n })),\n ),\n );\n });\n\n // Add to queue and continue loop.\n yield* submitMessage(\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: toolResults,\n }),\n );\n } while (true);\n\n log('done', { pending: this._pending.length });\n return this._pending;\n }).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiSession.run'));\n\n /**\n * @deprecated\n */\n // TODO(burdon): Implement or remove.\n async runStructured<S extends Schema.Schema.AnyNoContext>(\n _schema: S,\n _options: AiSessionRunParams<AiTool.Any>,\n ): Promise<Schema.Schema.Type<S>> {\n return todo();\n // const parser = structuredOutputParser(schema);\n // const result = await this.run({\n // ...options,\n // executableTools: [...(options.executableTools ?? []), parser.tool],\n // });\n // return parser.getResult(result);\n }\n}\n\nconst createSnippet = (text: string, len = 32) =>\n text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { AiError } from '@effect/ai';\nimport { HttpClientError } from '@effect/platform';\nimport { Effect, Schema } from 'effect';\n\nimport { AiModelError } from '../errors';\n\nconst AnthropicErrorResponse = Schema.Struct({\n type: Schema.Literal('error'),\n error: Schema.Struct({\n type: Schema.String,\n message: Schema.String,\n }),\n});\n\nexport const mapAiError = (err: AiError.AiError): Effect.Effect<AiError.AiError> =>\n Effect.gen(function* () {\n const cause = err.cause;\n if (HttpClientError.isHttpClientError(cause) && cause.reason === 'StatusCode') {\n const body = yield* cause.response.json.pipe(\n Effect.flatMap(Schema.decodeUnknown(AnthropicErrorResponse, { exact: false })),\n );\n\n const parsedCause = new AiModelError({\n message: body.error.message,\n context: { model: 'anthropic', type: body.error.type },\n });\n return new AiError.AiError({\n description: body.error.message,\n module: err.module,\n method: err.method,\n cause: parsedCause,\n });\n }\n return err;\n }).pipe(Effect.catchAll(() => Effect.succeed(err)));\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Array, Effect, Option, pipe } from 'effect';\n\nimport { Template } from '@dxos/blueprints';\nimport { Obj } from '@dxos/echo';\nimport { ObjectVersion } from '@dxos/echo-db';\nimport { type ObjectId } from '@dxos/echo-schema';\nimport { DatabaseService } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { type ContentBlock, DataType } from '@dxos/schema';\nimport { trim } from '@dxos/util';\n\nimport { AiAssistantError } from '../errors';\n\nimport { ArtifactDiffResolver } from './artifact-diff';\nimport { type AiSessionRunParams } from './session';\n\n/**\n * Formats the system prompt.\n */\n// TODO(burdon): Move to AiPreprocessor.\nexport const formatSystemPrompt = ({\n system,\n blueprints = [],\n objects = [],\n}: Pick<AiSessionRunParams<any>, 'system' | 'blueprints' | 'objects'>) =>\n Effect.gen(function* () {\n const blueprintDefs = yield* pipe(\n blueprints,\n Effect.forEach((blueprint) => Effect.succeed(blueprint.instructions)),\n Effect.flatMap(Effect.forEach((template) => DatabaseService.loadOption(template.source))),\n Effect.map(Array.filter(Option.isSome)),\n Effect.map(\n Array.map(\n (template) => trim`\n <blueprint>\n ${Template.process(template.value.content)}\n </blueprint>\n `,\n ),\n ),\n Effect.map((blueprints) =>\n blueprints.length > 0 ? ['## Blueprints Definitions', ...blueprints].join('\\n\\n') : undefined,\n ),\n );\n\n const objectDefs = yield* pipe(\n objects,\n Effect.forEach((object) =>\n Effect.succeed(trim`\n <object>\n <dxn>${Obj.getDXN(object)}</dxn>\n <typename>${Obj.getTypename(object)}</typename>\n </object>\n `),\n ),\n Effect.map((objects) => (objects.length > 0 ? ['## Context Objects', ...objects].join('\\n\\n') : undefined)),\n );\n\n return yield* pipe(\n Effect.succeed([system, blueprintDefs, objectDefs].filter((def): def is string => def !== undefined)),\n Effect.map((parts) => parts.join('\\n\\n')),\n );\n });\n\n/**\n * Formats the user prompt.\n */\n// TODO(burdon): Move to AiPreprocessor.\n// TODO(burdon): Convert util below to `Effect.fn` (to preserve stack info)\nexport const formatUserPrompt = ({ prompt, history = [] }: Pick<AiSessionRunParams<any>, 'prompt' | 'history'>) =>\n Effect.gen(function* () {\n const blocks: ContentBlock.Any[] = [];\n\n // TODO(dmaretskyi): Evaluate other approaches as `serviceOption` isn't represented in the type system.\n const artifactDiffResolver = yield* Effect.serviceOption(ArtifactDiffResolver);\n if (Option.isSome(artifactDiffResolver)) {\n const versions = gatherObjectVersions(history);\n const artifactDiff = yield* Effect.tryPromise({\n try: () =>\n artifactDiffResolver.value.resolve(\n [...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),\n ),\n catch: AiAssistantError.wrap({ message: 'Artifact diff resolution error' }),\n });\n\n log('version', { artifactDiff, versions });\n for (const [id, { version }] of [...artifactDiff.entries()]) {\n if (ObjectVersion.equals(version, versions.get(id)!)) {\n artifactDiff.delete(id);\n continue;\n }\n\n blocks.push({ _tag: 'anchor', objectId: id, version });\n }\n\n if (artifactDiff.size > 0) {\n blocks.push(createArtifactUpdateBlock(artifactDiff));\n }\n }\n\n return Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: [...blocks, { _tag: 'text', text: prompt }],\n });\n });\n\nconst gatherObjectVersions = (messages: DataType.Message[]): Map<ObjectId, ObjectVersion> => {\n const artifactIds = new Map<ObjectId, ObjectVersion>();\n for (const message of messages) {\n for (const block of message.blocks) {\n if (block._tag === 'anchor') {\n artifactIds.set(block.objectId, block.version as ObjectVersion);\n }\n }\n }\n\n return artifactIds;\n};\n\nconst createArtifactUpdateBlock = (\n artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,\n): ContentBlock.Any => {\n return {\n _tag: 'text',\n // TODO(dmaretskyi): Does this need to be a special content-block?\n disposition: 'artifact-update',\n text: trim`\n The following artifacts have been updated since the last message:\n ${[...artifactDiff.entries()]\n .map(([id, { diff }]) => `<changed-artifact id=\"${id}\">${diff ? `\\n${diff}` : ''}</changed-artifact>`)\n .join('\\n')}\n `,\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type AiTool, AiToolkit } from '@effect/ai';\nimport { type Context, Effect } from 'effect';\n\nimport { ToolExecutionService, type ToolId, ToolResolverService } from '@dxos/ai';\nimport { type Blueprint } from '@dxos/blueprints';\nimport { isNotFalsy } from '@dxos/util';\n\nexport type ToolkitParams<Tools extends AiTool.Any> = {\n toolkit?: AiToolkit.AiToolkit<Tools>;\n toolIds?: ToolId[];\n blueprints?: Blueprint.Blueprint[];\n};\n\n/**\n * Build a combined toolkit from the blueprint tools and the provided toolkit.\n */\nexport const createToolkit = <Tools extends AiTool.Any>({\n toolkit: toolkitParam,\n toolIds = [],\n blueprints = [],\n}: ToolkitParams<Tools>) =>\n Effect.gen(function* () {\n const blueprintToolkit = yield* ToolResolverService.resolveToolkit([\n ...blueprints.flatMap(({ tools }) => tools),\n ...toolIds,\n ]);\n\n const blueprintToolkitHandler: Context.Context<AiTool.ToHandler<AiTool.Any>> = yield* blueprintToolkit.toContext(\n ToolExecutionService.handlersFor(blueprintToolkit),\n );\n\n const toolkit = AiToolkit.merge(...[toolkitParam, blueprintToolkit].filter(isNotFalsy));\n return yield* toolkit.pipe(Effect.provide(blueprintToolkitHandler)) as Effect.Effect<\n AiToolkit.ToHandler<any>,\n never,\n AiTool.ToHandler<Tools>\n >;\n });\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { type ObjectVersion } from '@dxos/echo-db';\nimport { getVersion } from '@dxos/echo-db';\nimport { type AnyEchoObject, ObjectId } from '@dxos/echo-schema';\nimport { type ContentBlock } from '@dxos/schema';\n\n// TODO(dmaretskyi): Extract.\nconst ObjectVersionSchema = Schema.Unknown as Schema.Schema<ObjectVersion>;\n\nconst VersionPinSchema = Schema.Struct({\n // TODO(dmaretskyi): Use Ref when those support encoding.\n objectId: ObjectId,\n // TODO(dmaretskyi): Could be opaque.\n version: ObjectVersionSchema,\n});\n\n/**\n * Used to pin a specific version of an object during the course of a conversation.\n * This allows us to detect when the object changes during the course of the conversation.\n */\nexport interface VersionPin extends Schema.Schema.Type<typeof VersionPinSchema> {}\n\nexport const VersionPin: typeof VersionPinSchema & {\n DISPOSITION: 'version-pin';\n fromObject: (object: AnyEchoObject) => VersionPin;\n createBlock: (pin: VersionPin) => ContentBlock.Any;\n} = class extends VersionPinSchema {\n static readonly DISPOSITION = 'version-pin';\n static fromObject(object: AnyEchoObject): VersionPin {\n return VersionPin.make({\n objectId: object.id,\n version: getVersion(object),\n });\n }\n\n static createBlock(pin: VersionPin): ContentBlock.Any {\n return {\n _tag: 'json',\n disposition: VersionPin.DISPOSITION,\n data: JSON.stringify(pin),\n };\n }\n};\n"],
|
|
5
|
-
"mappings": ";;;AAIA,SAASA,eAAe;AAcjB,IAAMC,uBAAN,cAAmCC,QAAQC,IAAI,sCAAA,EAAA,EAAA;AAGjD;;;ACjBL,SAASC,QAAQC,gBAAgB;AAgB1B,IAAMC,qBAAqBC,OAAOC,OAAO;EAC9CC,MAAM,CAAC,EACLC,UAAUC,SAASC,SAASC,OAAOC,IAAI,GACvCC,SAASJ,SAASC,SAASC,OAAOC,IAAI,GACtCE,UAAUL,SAASC,SAASC,OAAOC,IAAI,GACvCG,QAAQN,SAASC,SAASC,OAAOC,IAAI,GACrCI,YAAYP,SAASC,SAASC,OAAOC,IAAI,EAAC,IACX,CAAC,OAA2B;IAC3DJ;IACAK;IACAC;IACAC;IACAC;EACF;EAEAC,MAAM,MAAMb,mBAAmBG,KAAI;;;;EAKnCW,aAAa,CAACC,YACZf,mBAAmBG,KAAK;IACtBO,SAAS,CAACM,UACRT,OAAOU,KAAK,MAAA;AACV,UAAID,MAAME,SAAS;AACjB;MACF;AACAH,cAAQI,kBAAkBH,KAAAA;IAC5B,CAAA;IACFJ,WAAW,CAACQ,YACVb,OAAOU,KAAK,MAAA;AACV,UAAIG,QAAQC,OAAOC,SAAS,aAAa;AACvC;MACF;AACAP,cAAQQ,aAAaH,OAAAA;IACvB,CAAA;EACJ,CAAA;AACJ,CAAA;;;ACrDA,SAASI,iBAAiB;AAKnB,IAAMC,eAAN,cAA2BC,UAAUC,OAAO,kBAAkB,gBAAA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AAEC,MAAK,MAAOA,KAAAA;OAClCR;GACJ;AAED,QAAMS,0BAAyE,OAAOL,iBAAiBM,UACrGC,qBAAqBC,YAAYR,gBAAAA,CAAAA;AAGnC,QAAMN,UAAUe,UAAUC,MAAK,GAAI;IAACf;IAAcK;IAAkBW,OAAOC,UAAAA,CAAAA;AAC3E,SAAO,OAAOlB,QAAQmB,KAAKf,QAAOgB,QAAQT,uBAAAA,CAAAA;AAK5C,CAAA;;;ACrCF,SAASU,UAAAA,eAAc;AAGvB,SAASC,kBAAkB;AAC3B,SAA6BC,gBAAgB;;;;;;;;;;;;;;;AAI7C,IAAMC,sBAAsBC,QAAOC;AAEnC,IAAMC,mBAAmBF,QAAOG,OAAO;;EAErCC,UAAUC;;EAEVC,SAASP;AACX,CAAA;AAQO,IAAMQ,cAAAA,SAIT,cAAcL,iBAAAA;EAEhB,OAAOM,WAAWC,QAAmC;AACnD,WAAOF,WAAWG,KAAK;MACrBN,UAAUK,OAAOE;MACjBL,SAASM,WAAWH,MAAAA;IACtB,CAAA;EACF;EAEA,OAAOI,YAAYC,KAAmC;AACpD,WAAO;MACLC,MAAM;MACNC,aAAaT,WAAWU;MACxBC,MAAMC,KAAKC,UAAUN,GAAAA;IACvB;EACF;AACF,GAfEO,kBAAA,QAAgBJ,eAAc,aAAA,GAAA;",
|
|
6
|
-
"names": ["Context", "ArtifactDiffResolver", "Context", "Tag", "Effect", "Function", "GenerationObserver", "Object", "freeze", "make", "onBegin", "Function", "constant", "Effect", "void", "onPart", "onBlock", "onEnd", "onMessage", "noop", "fromPrinter", "printer", "block", "sync", "pending", "printContentBlock", "message", "sender", "role", "printMessage", "BaseError", "AiModelError", "BaseError", "extend", "AiAssistantError", "AiLanguageModel", "Chunk", "Effect", "Stream", "AiParser", "AiPreprocessor", "callTool", "getToolCalls", "todo", "Obj", "TracingService", "log", "DataType", "AiError", "HttpClientError", "Effect", "Schema", "AnthropicErrorResponse", "Schema", "Struct", "type", "Literal", "error", "String", "message", "mapAiError", "err", "Effect", "gen", "cause", "HttpClientError", "isHttpClientError", "reason", "body", "response", "json", "pipe", "flatMap", "decodeUnknown", "exact", "parsedCause", "AiModelError", "context", "model", "AiError", "description", "module", "method", "catchAll", "succeed", "Array", "Effect", "Option", "pipe", "Template", "Obj", "ObjectVersion", "DatabaseService", "log", "DataType", "trim", "formatSystemPrompt", "system", "blueprints", "objects", "Effect", "gen", "blueprintDefs", "pipe", "forEach", "blueprint", "succeed", "instructions", "flatMap", "template", "DatabaseService", "loadOption", "source", "map", "Array", "filter", "Option", "isSome", "trim", "Template", "process", "value", "content", "length", "join", "undefined", "objectDefs", "object", "Obj", "getDXN", "getTypename", "def", "parts", "formatUserPrompt", "prompt", "history", "blocks", "artifactDiffResolver", "serviceOption", "ArtifactDiffResolver", "versions", "gatherObjectVersions", "artifactDiff", "tryPromise", "try", "resolve", "entries", "id", "version", "lastVersion", "catch", "AiAssistantError", "wrap", "message", "log", "ObjectVersion", "equals", "get", "delete", "push", "_tag", "objectId", "size", "createArtifactUpdateBlock", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "text", "messages", "artifactIds", "Map", "block", "set", "disposition", "diff", "AiSession", "runStructured", "_schema", "_options", "todo", "_semaphore", "_history", "_pending", "run", "Effect", "runSync", "makeSemaphore", "prompt", "system", "systemTemplate", "history", "objects", "blueprints", "toolkit", "observer", "GenerationObserver", "noop", "gen", "pending", "submitMessage", "fnUntraced", "message", "push", "onMessage", "TracingService", "emitConverationMessage", "promptMessage", "formatUserPrompt", "formatSystemPrompt", "log", "snippet", "createSnippet", "length", "AiPreprocessor", "preprocessAiInput", "blocks", "AiLanguageModel", "streamText", "disableToolCallResolution", "pipe", "Stream", "catchTag", "err", "fail", "mapAiError", "AiParser", "parseResponse", "onBegin", "onBlock", "block", "onPart", "part", "onEnd", "summary", "runCollect", "map", "Chunk", "toArray", "response", "Obj", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "toolCalls", "getToolCalls", "Error", "toolResults", "forEach", "toolCall", "callTool", "provide", "layerSubframe", "context", "parentMessage", "id", "toolCallId", "withPermits", "withSpan", "text", "len", "slice", "join", "AiToolkit", "Effect", "ToolExecutionService", "ToolResolverService", "isNotFalsy", "createToolkit", "toolkit", "toolkitParam", "toolIds", "blueprints", "Effect", "gen", "blueprintToolkit", "ToolResolverService", "resolveToolkit", "flatMap", "tools", "blueprintToolkitHandler", "toContext", "ToolExecutionService", "handlersFor", "AiToolkit", "merge", "filter", "isNotFalsy", "pipe", "provide", "Schema", "getVersion", "ObjectId", "ObjectVersionSchema", "Schema", "Unknown", "VersionPinSchema", "Struct", "objectId", "ObjectId", "version", "VersionPin", "fromObject", "object", "make", "id", "getVersion", "createBlock", "pin", "_tag", "disposition", "DISPOSITION", "data", "JSON", "stringify", "_define_property"]
|
|
7
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"version-pin.test.d.ts","sourceRoot":"","sources":["../../../../src/session/version-pin.test.ts"],"names":[],"mappings":""}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/types.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,GAAG,EAAmB,KAAK,OAAO,EAAE,MAAM,YAAY,CAAC;AAGhE;;GAEG;AACH,eAAO,MAAM,qBAAqB,GAAI,IAAI,QAAQ,WAA4B,CAAC;AAE/E;;;GAGG;AAEH,eAAO,MAAM,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG;IAC/C,KAAK,EAAE,CAAC,SAAS,EAAE,UAAU,EAAE,aAAa,CAAC,EAAE,OAAO,KAAK,GAAG,CAAC;CA4BhE,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,UAAU,CAAC,CAAC"}
|
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
|
2
|
-
|
|
3
|
-
exports[`AiSession > no tools 1`] = `
|
|
4
|
-
[
|
|
5
|
-
{
|
|
6
|
-
"blocks": ReactiveArray [
|
|
7
|
-
{
|
|
8
|
-
"_tag": "text",
|
|
9
|
-
"text": "Hello world!",
|
|
10
|
-
},
|
|
11
|
-
],
|
|
12
|
-
"created": "Sun, 20 Jul 2025 10:54:08 GMT",
|
|
13
|
-
"id": "01K0KQGFTFV3GBKGEWZW67K8HK",
|
|
14
|
-
"sender": {
|
|
15
|
-
"role": "user",
|
|
16
|
-
},
|
|
17
|
-
},
|
|
18
|
-
{
|
|
19
|
-
"blocks": ReactiveArray [
|
|
20
|
-
{
|
|
21
|
-
"_tag": "text",
|
|
22
|
-
"text": "Hi there! How can I help you today?",
|
|
23
|
-
},
|
|
24
|
-
],
|
|
25
|
-
"created": "2025-07-20T10:54:10.801Z",
|
|
26
|
-
"id": "01K0KQGHVHJ37D4YG45WG090WV",
|
|
27
|
-
"sender": {
|
|
28
|
-
"role": "assistant",
|
|
29
|
-
},
|
|
30
|
-
},
|
|
31
|
-
]
|
|
32
|
-
`;
|