@dxos/assistant 0.8.4-main.fd6878d → 0.8.4-staging.60fe92afc8
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/LICENSE +102 -5
- package/README.md +2 -1
- package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
- package/dist/lib/neutral/extraction/index.mjs +208 -0
- package/dist/lib/neutral/extraction/index.mjs.map +7 -0
- package/dist/lib/neutral/index.mjs +1886 -0
- package/dist/lib/neutral/index.mjs.map +7 -0
- package/dist/lib/neutral/meta.json +1 -0
- package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
- package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction.d.ts +1650 -281
- package/dist/types/src/extraction/extraction.d.ts.map +1 -1
- package/dist/types/src/extraction/index.d.ts +0 -1
- package/dist/types/src/extraction/index.d.ts.map +1 -1
- package/dist/types/src/extraction/quotes.d.ts +3 -3
- package/dist/types/src/extraction/quotes.d.ts.map +1 -1
- package/dist/types/src/functions/services.d.ts +16 -5
- package/dist/types/src/functions/services.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +2 -3
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/request/AiRequest.d.ts +308 -0
- package/dist/types/src/request/AiRequest.d.ts.map +1 -0
- package/dist/types/src/{session → request}/artifact-diff.d.ts +5 -5
- package/dist/types/src/request/artifact-diff.d.ts.map +1 -0
- package/dist/types/src/request/format.d.ts +15 -0
- package/dist/types/src/request/format.d.ts.map +1 -0
- package/dist/types/src/request/index.d.ts +4 -0
- package/dist/types/src/request/index.d.ts.map +1 -0
- package/dist/types/src/request/observer.d.ts +23 -0
- package/dist/types/src/request/observer.d.ts.map +1 -0
- package/dist/types/src/{session → request}/version-pin.d.ts +6 -6
- package/dist/types/src/request/version-pin.d.ts.map +1 -0
- package/dist/types/src/session/AiContext.d.ts +178 -0
- package/dist/types/src/session/AiContext.d.ts.map +1 -0
- package/dist/types/src/session/AiContext.test.d.ts +2 -0
- package/dist/types/src/session/AiContext.test.d.ts.map +1 -0
- package/dist/types/src/session/AiSession.d.ts +79 -0
- package/dist/types/src/session/AiSession.d.ts.map +1 -0
- package/dist/types/src/session/AiSession.test.d.ts +2 -0
- package/dist/types/src/session/AiSession.test.d.ts.map +1 -0
- package/dist/types/src/session/SessionLink.d.ts +17 -0
- package/dist/types/src/session/SessionLink.d.ts.map +1 -0
- package/dist/types/src/session/SessionLoader.d.ts +15 -0
- package/dist/types/src/session/SessionLoader.d.ts.map +1 -0
- package/dist/types/src/session/SessionLoader.test.d.ts +2 -0
- package/dist/types/src/session/SessionLoader.test.d.ts.map +1 -0
- package/dist/types/src/session/index.d.ts +5 -3
- package/dist/types/src/session/index.d.ts.map +1 -1
- package/dist/types/src/session/toolkit.d.ts +16 -0
- package/dist/types/src/session/toolkit.d.ts.map +1 -0
- package/dist/types/src/templates/system.d.ts +19 -14
- package/dist/types/src/templates/system.d.ts.map +1 -1
- package/dist/types/src/util/artifact.d.ts +18 -0
- package/dist/types/src/util/artifact.d.ts.map +1 -0
- package/dist/types/src/util/diff.d.ts +17 -0
- package/dist/types/src/util/diff.d.ts.map +1 -0
- package/dist/types/src/util/diff.test.d.ts +2 -0
- package/dist/types/src/util/diff.test.d.ts.map +1 -0
- package/dist/types/src/util/error-handling.d.ts +4 -0
- package/dist/types/src/util/error-handling.d.ts.map +1 -0
- package/dist/types/src/util/errors.d.ts +67 -0
- package/dist/types/src/util/errors.d.ts.map +1 -0
- package/dist/types/src/util/execution-graph.d.ts +85 -0
- package/dist/types/src/util/execution-graph.d.ts.map +1 -0
- package/dist/types/src/util/execution-graph.test.d.ts +2 -0
- package/dist/types/src/util/execution-graph.test.d.ts.map +1 -0
- package/dist/types/src/util/index.d.ts +7 -0
- package/dist/types/src/util/index.d.ts.map +1 -0
- package/dist/types/src/util/tracing.d.ts +296 -0
- package/dist/types/src/util/tracing.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +37 -47
- package/src/extraction/extraction-ner-function/index.ts +0 -1
- package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
- package/src/extraction/extraction-ner-function/named-entity-recognition.ts +2 -0
- package/src/extraction/extraction.ts +49 -19
- package/src/extraction/index.ts +0 -1
- package/src/extraction/quotes.test.ts +2 -2
- package/src/extraction/quotes.ts +7 -9
- package/src/functions/services.ts +180 -66
- package/src/index.ts +2 -3
- package/src/request/AiRequest.ts +387 -0
- package/src/{session → request}/artifact-diff.ts +10 -6
- package/src/{session → request}/format.ts +45 -37
- package/src/request/index.ts +8 -0
- package/src/request/observer.ts +62 -0
- package/src/{session → request}/version-pin.ts +8 -8
- package/src/session/AiContext.test.ts +49 -0
- package/src/session/AiContext.ts +420 -0
- package/src/session/AiSession.test.ts +111 -0
- package/src/session/AiSession.ts +328 -0
- package/src/session/SessionLink.ts +23 -0
- package/src/session/SessionLoader.test.ts +115 -0
- package/src/session/SessionLoader.ts +55 -0
- package/src/session/index.ts +6 -3
- package/src/session/toolkit.ts +47 -0
- package/src/templates/{format.tpl → instructions/format.tpl} +6 -4
- package/src/templates/instructions/system.tpl +96 -0
- package/src/templates/system.ts +26 -16
- package/src/util/artifact.ts +96 -0
- package/src/util/diff.test.ts +74 -0
- package/src/util/diff.ts +93 -0
- package/src/util/error-handling.ts +42 -0
- package/src/util/errors.ts +15 -0
- package/src/util/execution-graph.test.ts +740 -0
- package/src/util/execution-graph.ts +520 -0
- package/src/util/index.ts +10 -0
- package/src/util/tracing.ts +60 -0
- package/dist/lib/browser/chunk-6WRGDEMH.mjs +0 -89
- package/dist/lib/browser/chunk-6WRGDEMH.mjs.map +0 -7
- package/dist/lib/browser/chunk-NZGGCEF3.mjs +0 -341
- package/dist/lib/browser/chunk-NZGGCEF3.mjs.map +0 -7
- package/dist/lib/browser/extraction/index.mjs +0 -269
- package/dist/lib/browser/extraction/index.mjs.map +0 -7
- package/dist/lib/browser/index.mjs +0 -354
- package/dist/lib/browser/index.mjs.map +0 -7
- package/dist/lib/browser/meta.json +0 -1
- package/dist/lib/browser/named-entity-recognition-O46UTCLR.mjs +0 -13
- package/dist/lib/node-esm/chunk-3UU5V4FS.mjs +0 -91
- package/dist/lib/node-esm/chunk-3UU5V4FS.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-XOOPGSGW.mjs +0 -343
- package/dist/lib/node-esm/chunk-XOOPGSGW.mjs.map +0 -7
- package/dist/lib/node-esm/extraction/index.mjs +0 -270
- package/dist/lib/node-esm/extraction/index.mjs.map +0 -7
- package/dist/lib/node-esm/index.mjs +0 -355
- package/dist/lib/node-esm/index.mjs.map +0 -7
- package/dist/lib/node-esm/meta.json +0 -1
- package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs +0 -14
- package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs.map +0 -7
- package/dist/types/src/conversation/context.d.ts +0 -90
- package/dist/types/src/conversation/context.d.ts.map +0 -1
- package/dist/types/src/conversation/conversation.d.ts +0 -50
- package/dist/types/src/conversation/conversation.d.ts.map +0 -1
- package/dist/types/src/conversation/index.d.ts +0 -3
- package/dist/types/src/conversation/index.d.ts.map +0 -1
- package/dist/types/src/errors.d.ts +0 -39
- package/dist/types/src/errors.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
- package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -306
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
- package/dist/types/src/session/artifact-diff.d.ts.map +0 -1
- package/dist/types/src/session/format.d.ts +0 -168
- package/dist/types/src/session/format.d.ts.map +0 -1
- package/dist/types/src/session/format.test.d.ts +0 -2
- package/dist/types/src/session/format.test.d.ts.map +0 -1
- package/dist/types/src/session/session.d.ts +0 -167
- package/dist/types/src/session/session.d.ts.map +0 -1
- package/dist/types/src/session/session.test.d.ts +0 -2
- package/dist/types/src/session/session.test.d.ts.map +0 -1
- package/dist/types/src/session/version-pin.d.ts.map +0 -1
- 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/summarization/summarization.test.d.ts +0 -2
- package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
- package/dist/types/src/types.d.ts +0 -16
- package/dist/types/src/types.d.ts.map +0 -1
- package/src/conversation/context.ts +0 -133
- package/src/conversation/conversation.ts +0 -125
- package/src/conversation/index.ts +0 -6
- package/src/errors.ts +0 -10
- package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -84
- package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -71
- package/src/extraction/extraction-llm-function/index.ts +0 -5
- package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -116
- package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -57
- package/src/session/__snapshots__/session.test.ts.snap +0 -32
- package/src/session/format.test.ts +0 -60
- package/src/session/session.test.ts +0 -305
- package/src/session/session.ts +0 -279
- package/src/session/version-pin.test.ts +0 -7
- package/src/summarization/summarization.test.ts +0 -197
- package/src/templates/system.tpl +0 -47
- package/src/types.ts +0 -52
- /package/dist/lib/{browser/named-entity-recognition-O46UTCLR.mjs.map → neutral/chunk-J5LGTIGS.mjs.map} +0 -0
- /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2025 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
// @import-as-namespace
|
|
6
|
+
|
|
7
|
+
import type * as AiError from '@effect/ai/AiError';
|
|
8
|
+
import * as LanguageModel from '@effect/ai/LanguageModel';
|
|
9
|
+
import type * as Toolkit from '@effect/ai/Toolkit';
|
|
10
|
+
import * as Array from 'effect/Array';
|
|
11
|
+
import * as Chunk from 'effect/Chunk';
|
|
12
|
+
import * as Effect from 'effect/Effect';
|
|
13
|
+
import { pipe } from 'effect/Function';
|
|
14
|
+
import * as Option from 'effect/Option';
|
|
15
|
+
import * as Stream from 'effect/Stream';
|
|
16
|
+
|
|
17
|
+
import {
|
|
18
|
+
AiParser,
|
|
19
|
+
AiPreprocessor,
|
|
20
|
+
AiSummarizer,
|
|
21
|
+
type AiToolNotFoundError,
|
|
22
|
+
callTool,
|
|
23
|
+
type OpaqueToolkit,
|
|
24
|
+
type PromptPreprocessingError,
|
|
25
|
+
type ToolExecutionService,
|
|
26
|
+
type ToolResolverService,
|
|
27
|
+
withoutToolCallParising,
|
|
28
|
+
} from '@dxos/ai';
|
|
29
|
+
import { type Blueprint, Trace, Operation } from '@dxos/compute';
|
|
30
|
+
import { Database, Obj, Registry } from '@dxos/echo';
|
|
31
|
+
import { log } from '@dxos/log';
|
|
32
|
+
import { ContentBlock, Message } from '@dxos/types';
|
|
33
|
+
|
|
34
|
+
import { getOperationFromTool } from '../functions/services';
|
|
35
|
+
import { type AiAssistantError, CompleteBlock, PartialBlock } from '../util';
|
|
36
|
+
import { formatSystemPrompt, formatUserPrompt } from './format';
|
|
37
|
+
import { GenerationObserver } from './observer';
|
|
38
|
+
|
|
39
|
+
export type RunError = AiError.AiError | PromptPreprocessingError | AiToolNotFoundError | AiAssistantError;
|
|
40
|
+
|
|
41
|
+
export type RunRequirements =
|
|
42
|
+
| LanguageModel.LanguageModel
|
|
43
|
+
| ToolExecutionService
|
|
44
|
+
| ToolResolverService
|
|
45
|
+
| Database.Service
|
|
46
|
+
| Operation.Service
|
|
47
|
+
| Registry.Service
|
|
48
|
+
| Trace.TraceService;
|
|
49
|
+
|
|
50
|
+
export type Options = {
|
|
51
|
+
/**
|
|
52
|
+
* Summarize before executing the prompt if the existing history exceeds this threshold.
|
|
53
|
+
*/
|
|
54
|
+
summarizationThreshold?: number;
|
|
55
|
+
|
|
56
|
+
// TODO(dmaretskyi): Plan to phase out in favor of TracingService and the return type being a stream.
|
|
57
|
+
observer?: GenerationObserver;
|
|
58
|
+
/**
|
|
59
|
+
* Callback for when a message is received from the user, model, or tool.
|
|
60
|
+
* This is useful for streaming the output to a queue.
|
|
61
|
+
*/
|
|
62
|
+
onOutput?: (message: Message.Message) => Effect.Effect<void, never, never>;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
export type RunProps<R = never> = {
|
|
66
|
+
prompt: string | ContentBlock.Any[];
|
|
67
|
+
// TODO(wittjosiah): Rename to systemPrompt.
|
|
68
|
+
system?: string;
|
|
69
|
+
history?: Message.Message[];
|
|
70
|
+
objects?: Obj.Unknown[];
|
|
71
|
+
blueprints?: readonly Blueprint.Blueprint[];
|
|
72
|
+
toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export type BeginProps = {
|
|
76
|
+
prompt: string | ContentBlock.Any[];
|
|
77
|
+
system?: string;
|
|
78
|
+
history?: Message.Message[];
|
|
79
|
+
objects?: Obj.Unknown[];
|
|
80
|
+
blueprints?: readonly Blueprint.Blueprint[];
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
export type TurnProps<R = never> = {
|
|
84
|
+
system: string;
|
|
85
|
+
toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
export type TurnResult = {
|
|
89
|
+
messages: Message.Message[];
|
|
90
|
+
done: boolean;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Contains message history, tools, current context.
|
|
95
|
+
* Current context means the state of the app, time of day, and other contextual information.
|
|
96
|
+
* It makes requests to the model, its a state machine.
|
|
97
|
+
* It keeps track of the current goal.
|
|
98
|
+
* It manages the context window.
|
|
99
|
+
* Tracks the success criteria of reaching the goal, exposing metrics (stretch).
|
|
100
|
+
* Could be run locally in the app or remotely.
|
|
101
|
+
* Could be personal or shared.
|
|
102
|
+
*/
|
|
103
|
+
export class Request {
|
|
104
|
+
/** Prevents concurrent execution of session. */
|
|
105
|
+
private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));
|
|
106
|
+
|
|
107
|
+
private readonly _observer: GenerationObserver;
|
|
108
|
+
private readonly _onOutput: (message: Message.Message) => Effect.Effect<void, never, never>;
|
|
109
|
+
|
|
110
|
+
/** Message history from queue. */
|
|
111
|
+
// TODO(burdon): Evolve into supporting a git-like graph of messages.
|
|
112
|
+
private _history: Message.Message[] = [];
|
|
113
|
+
|
|
114
|
+
/** Pending messages for this session (incl. the current prompt). */
|
|
115
|
+
private _pending: Message.Message[] = [];
|
|
116
|
+
|
|
117
|
+
private _started = 0;
|
|
118
|
+
private _ended = 0;
|
|
119
|
+
private _toolCalls = 0;
|
|
120
|
+
|
|
121
|
+
constructor(private readonly _options: Options = {}) {
|
|
122
|
+
this._observer = _options.observer ?? GenerationObserver.noop();
|
|
123
|
+
this._onOutput = _options.onOutput ?? (() => Effect.void);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
get duration(): number {
|
|
127
|
+
return this._ended - this._started;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
get toolCalls(): number {
|
|
131
|
+
return this._toolCalls;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
get pending(): readonly Message.Message[] {
|
|
135
|
+
return this._pending;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private _submitMessage = (message: Message.Message): Effect.Effect<Message.Message, never, Trace.TraceService> =>
|
|
139
|
+
Effect.gen(this, function* () {
|
|
140
|
+
this._pending.push(message);
|
|
141
|
+
yield* this._observer.onMessage(message);
|
|
142
|
+
for (const block of message.blocks) {
|
|
143
|
+
log('write complete block', {
|
|
144
|
+
messageId: message.id,
|
|
145
|
+
role: message.sender.role!,
|
|
146
|
+
block: JSON.stringify(block),
|
|
147
|
+
});
|
|
148
|
+
yield* Trace.write(CompleteBlock, {
|
|
149
|
+
messageId: message.id,
|
|
150
|
+
role: message.sender.role!,
|
|
151
|
+
block,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
yield* this._onOutput(message);
|
|
155
|
+
return message;
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
getToolCalls = () =>
|
|
159
|
+
pipe(
|
|
160
|
+
[...this._history, ...this._pending],
|
|
161
|
+
Array.reverse,
|
|
162
|
+
Array.takeWhile((_) => _.sender.role === 'assistant'),
|
|
163
|
+
Array.flatMap((_) => _.blocks.filter(ContentBlock.is('toolCall')).map((block) => ({ block, message: _ }))),
|
|
164
|
+
Array.filter((_) => !_.block.providerExecuted),
|
|
165
|
+
Array.reverse,
|
|
166
|
+
);
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Initialize a session: set up history, perform summarization if needed, and submit the user prompt.
|
|
170
|
+
* Must be called before `runTurn()`.
|
|
171
|
+
*/
|
|
172
|
+
begin = ({
|
|
173
|
+
prompt,
|
|
174
|
+
system,
|
|
175
|
+
history = [],
|
|
176
|
+
blueprints = [],
|
|
177
|
+
objects = [],
|
|
178
|
+
}: BeginProps): Effect.Effect<void, RunError, RunRequirements> =>
|
|
179
|
+
Effect.gen(this, function* () {
|
|
180
|
+
this._started = Date.now();
|
|
181
|
+
this._history = [...history];
|
|
182
|
+
this._pending = [];
|
|
183
|
+
|
|
184
|
+
const systemPrompt = yield* formatSystemPrompt({ system, blueprints, objects }).pipe(Effect.orDie);
|
|
185
|
+
|
|
186
|
+
if (this._options.summarizationThreshold !== undefined) {
|
|
187
|
+
const tokenCount = yield* AiPreprocessor.estimateTokens(
|
|
188
|
+
yield* AiPreprocessor.preprocessPrompt([...this._history], {
|
|
189
|
+
system: systemPrompt,
|
|
190
|
+
}),
|
|
191
|
+
);
|
|
192
|
+
if (tokenCount > this._options.summarizationThreshold) {
|
|
193
|
+
const summary = yield* AiSummarizer.summarize([...this._history]);
|
|
194
|
+
yield* this._submitMessage(summary);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
yield* this._submitMessage(yield* formatUserPrompt({ prompt, history }));
|
|
199
|
+
}).pipe(Effect.withSpan('AiRequest.begin'));
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Execute a single turn: one LLM generation followed by tool execution.
|
|
203
|
+
* The toolkit and system prompt can be updated between turns to reflect context changes (e.g. dynamically enabled blueprints).
|
|
204
|
+
*/
|
|
205
|
+
runAgentTurn = <const R = never>({
|
|
206
|
+
system,
|
|
207
|
+
toolkit: opaqueToolkit,
|
|
208
|
+
}: TurnProps<R>): Effect.Effect<TurnResult, RunError, RunRequirements | R> =>
|
|
209
|
+
Effect.gen(this, function* () {
|
|
210
|
+
log('request', {
|
|
211
|
+
system: { snippet: createSnippet(system), length: system.length },
|
|
212
|
+
pending: this._pending.length,
|
|
213
|
+
history: this._history.length,
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
const prompt = yield* AiPreprocessor.preprocessPrompt([...this._history, ...this._pending], {
|
|
217
|
+
system,
|
|
218
|
+
cacheControl: 'ephemeral',
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : undefined;
|
|
222
|
+
|
|
223
|
+
const observer = this._observer;
|
|
224
|
+
let currentMessageId: Obj.ID | null = null;
|
|
225
|
+
|
|
226
|
+
const messages = yield* LanguageModel.streamText({
|
|
227
|
+
prompt,
|
|
228
|
+
toolkit,
|
|
229
|
+
disableToolCallResolution: true,
|
|
230
|
+
}).pipe(
|
|
231
|
+
withoutToolCallParising,
|
|
232
|
+
AiParser.parseResponse({
|
|
233
|
+
emitPartial: true,
|
|
234
|
+
onBegin: () => observer.onBegin(),
|
|
235
|
+
onBlock: (block) => observer.onBlock(block),
|
|
236
|
+
onPart: (part) => observer.onPart(part as any),
|
|
237
|
+
onEnd: (summary) => observer.onEnd(summary),
|
|
238
|
+
}),
|
|
239
|
+
Stream.map((block) => enrichToolCallBlock(block, toolkit)),
|
|
240
|
+
Stream.mapEffect(
|
|
241
|
+
(block) =>
|
|
242
|
+
Effect.gen(this, function* () {
|
|
243
|
+
if (block.pending) {
|
|
244
|
+
currentMessageId ??= Obj.ID.random();
|
|
245
|
+
log('emit ephemeral message', { id: currentMessageId, type: block._tag });
|
|
246
|
+
yield* Trace.write(PartialBlock, {
|
|
247
|
+
messageId: currentMessageId,
|
|
248
|
+
role: 'assistant',
|
|
249
|
+
block,
|
|
250
|
+
});
|
|
251
|
+
return Option.none();
|
|
252
|
+
} else {
|
|
253
|
+
currentMessageId ??= Obj.ID.random();
|
|
254
|
+
const id = currentMessageId;
|
|
255
|
+
currentMessageId = null;
|
|
256
|
+
log('emit complete message', { id, type: block._tag });
|
|
257
|
+
const message = Obj.make(Message.Message, {
|
|
258
|
+
id,
|
|
259
|
+
created: new Date().toISOString(),
|
|
260
|
+
sender: { role: 'assistant' },
|
|
261
|
+
blocks: [block],
|
|
262
|
+
});
|
|
263
|
+
return Option.some(yield* this._submitMessage(message));
|
|
264
|
+
}
|
|
265
|
+
}),
|
|
266
|
+
{ concurrency: 1, unordered: false },
|
|
267
|
+
),
|
|
268
|
+
Stream.filterMap((_) => _),
|
|
269
|
+
Stream.runCollect,
|
|
270
|
+
Effect.map(Chunk.toArray),
|
|
271
|
+
);
|
|
272
|
+
log('messages', { messages });
|
|
273
|
+
|
|
274
|
+
const toolCalls = this.getToolCalls();
|
|
275
|
+
|
|
276
|
+
if (toolCalls.length === 0) {
|
|
277
|
+
this._ended = Date.now();
|
|
278
|
+
return { messages, done: true };
|
|
279
|
+
} else if (!toolkit) {
|
|
280
|
+
throw new Error('No toolkit provided');
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
return { messages, done: false };
|
|
284
|
+
}).pipe(Effect.withSpan('AiRequest.runAgentTurn'));
|
|
285
|
+
|
|
286
|
+
runTools = <const R = never>({
|
|
287
|
+
toolkit: opaqueToolkit,
|
|
288
|
+
}: {
|
|
289
|
+
toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
|
|
290
|
+
}): Effect.Effect<void, RunError, RunRequirements | R> =>
|
|
291
|
+
Effect.gen(this, function* () {
|
|
292
|
+
const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : undefined;
|
|
293
|
+
const toolCalls = this.getToolCalls();
|
|
294
|
+
const toolResults = yield* Effect.forEach(toolCalls, ({ block, message }) => {
|
|
295
|
+
if (!toolkit) {
|
|
296
|
+
throw new Error('No toolkit provided');
|
|
297
|
+
}
|
|
298
|
+
return callTool(toolkit, block);
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
yield* this._submitMessage(
|
|
302
|
+
Obj.make(Message.Message, {
|
|
303
|
+
created: new Date().toISOString(),
|
|
304
|
+
sender: { role: 'tool' },
|
|
305
|
+
blocks: toolResults,
|
|
306
|
+
}),
|
|
307
|
+
);
|
|
308
|
+
|
|
309
|
+
this._toolCalls += toolResults.length;
|
|
310
|
+
}).pipe(Effect.withSpan('AiRequest.runTools'));
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Run a full conversation turn loop. Equivalent to calling `begin()` then `runTurn()` in a loop.
|
|
314
|
+
*/
|
|
315
|
+
run = <const R = never>({
|
|
316
|
+
prompt,
|
|
317
|
+
system: systemTemplate,
|
|
318
|
+
history = [],
|
|
319
|
+
objects = [],
|
|
320
|
+
blueprints = [],
|
|
321
|
+
toolkit,
|
|
322
|
+
}: RunProps<R>): Effect.Effect<Message.Message[], RunError, RunRequirements | R> =>
|
|
323
|
+
Effect.gen(this, function* () {
|
|
324
|
+
yield* this.begin({ prompt, system: systemTemplate, history, objects, blueprints });
|
|
325
|
+
|
|
326
|
+
const system = yield* formatSystemPrompt({ system: systemTemplate, blueprints, objects }).pipe(Effect.orDie);
|
|
327
|
+
|
|
328
|
+
do {
|
|
329
|
+
const { done } = yield* this.runAgentTurn({ system, toolkit });
|
|
330
|
+
if (done) {
|
|
331
|
+
break;
|
|
332
|
+
}
|
|
333
|
+
yield* this.runTools({ toolkit });
|
|
334
|
+
} while (true);
|
|
335
|
+
|
|
336
|
+
log('done', { pending: this._pending.length, duration: this.duration, tools: this._toolCalls });
|
|
337
|
+
return this._pending;
|
|
338
|
+
}).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiRequest.run'));
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Annotates `toolCall` blocks with metadata about the backing Operation, when one exists.
|
|
343
|
+
* Tool calls that resolve to a toolkit handler (no Operation) are left unchanged so callers can
|
|
344
|
+
* distinguish operation invocations from inline tool calls.
|
|
345
|
+
*/
|
|
346
|
+
const enrichToolCallBlock = (
|
|
347
|
+
block: ContentBlock.Any,
|
|
348
|
+
toolkit: Toolkit.WithHandler<any> | undefined,
|
|
349
|
+
): ContentBlock.Any => {
|
|
350
|
+
if (block._tag !== 'toolCall' || !toolkit) {
|
|
351
|
+
return block;
|
|
352
|
+
}
|
|
353
|
+
const tool = toolkit.tools[block.name];
|
|
354
|
+
if (!tool) {
|
|
355
|
+
return block;
|
|
356
|
+
}
|
|
357
|
+
// Some tools (provider-defined, raw MCP) don't carry an Effect `Context` for annotations and
|
|
358
|
+
// `getOperationFromTool` throws. Be defensive: treat any failure as "no operation".
|
|
359
|
+
let operationOpt: Option.Option<Operation.Definition.Any>;
|
|
360
|
+
try {
|
|
361
|
+
operationOpt = getOperationFromTool(tool);
|
|
362
|
+
} catch {
|
|
363
|
+
return block;
|
|
364
|
+
}
|
|
365
|
+
if (Option.isNone(operationOpt)) {
|
|
366
|
+
return block;
|
|
367
|
+
}
|
|
368
|
+
const { meta } = operationOpt.value;
|
|
369
|
+
return {
|
|
370
|
+
...block,
|
|
371
|
+
operationKey: meta.key,
|
|
372
|
+
operationName: meta.name,
|
|
373
|
+
operationIcon: meta.icon,
|
|
374
|
+
} satisfies ContentBlock.ToolCall;
|
|
375
|
+
};
|
|
376
|
+
|
|
377
|
+
const createSnippet = (text: string, len = 32) =>
|
|
378
|
+
text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');
|
|
379
|
+
|
|
380
|
+
// TODO(dmaretskyi): Extract as a general util.
|
|
381
|
+
const logDump = (message: string, data: unknown) => {
|
|
382
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
383
|
+
const { writeFileSync } = require('node:fs');
|
|
384
|
+
const path = `/tmp/log-data-${Date.now()}.json`;
|
|
385
|
+
writeFileSync(path, JSON.stringify(data, null, 2));
|
|
386
|
+
log.info(message, { path });
|
|
387
|
+
};
|
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import
|
|
5
|
+
import * as Context from 'effect/Context';
|
|
6
6
|
|
|
7
|
-
import { type ObjectVersion } from '@dxos/echo-
|
|
8
|
-
import { type
|
|
7
|
+
import { type ObjectVersion } from '@dxos/echo-client';
|
|
8
|
+
import { type EntityId } from '@dxos/keys';
|
|
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,9 +23,14 @@ export class ArtifactDiffResolver extends Context.Tag('@dxos/assistant/ArtifactD
|
|
|
24
23
|
|
|
25
24
|
export namespace ArtifactDiffResolver {
|
|
26
25
|
export type Service = {
|
|
27
|
-
resolve: (
|
|
26
|
+
resolve: (
|
|
27
|
+
artifacts: {
|
|
28
|
+
id: EntityId;
|
|
29
|
+
lastVersion: ObjectVersion;
|
|
30
|
+
}[],
|
|
31
|
+
) => Promise<
|
|
28
32
|
Map<
|
|
29
|
-
|
|
33
|
+
EntityId,
|
|
30
34
|
{
|
|
31
35
|
version: ObjectVersion;
|
|
32
36
|
diff?: string;
|
|
@@ -2,21 +2,22 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import
|
|
6
|
-
|
|
7
|
-
import
|
|
8
|
-
|
|
9
|
-
import {
|
|
10
|
-
import { type
|
|
11
|
-
import {
|
|
5
|
+
import * as Effect from 'effect/Effect';
|
|
6
|
+
import * as Function from 'effect/Function';
|
|
7
|
+
import * as Option from 'effect/Option';
|
|
8
|
+
|
|
9
|
+
import { type FunctionNotFoundError, type Operation, Template } from '@dxos/compute';
|
|
10
|
+
import { type Database, Obj, type Registry } from '@dxos/echo';
|
|
11
|
+
import { ObjectVersion } from '@dxos/echo-client';
|
|
12
|
+
import { type EntityNotFoundError } from '@dxos/echo/Err';
|
|
13
|
+
import { type EntityId } from '@dxos/keys';
|
|
12
14
|
import { log } from '@dxos/log';
|
|
13
|
-
import { type ContentBlock,
|
|
15
|
+
import { type ContentBlock, Message } from '@dxos/types';
|
|
14
16
|
import { trim } from '@dxos/util';
|
|
15
17
|
|
|
16
|
-
import { AiAssistantError } from '../
|
|
17
|
-
|
|
18
|
+
import { AiAssistantError } from '../util';
|
|
19
|
+
import type * as AiRequest from './AiRequest';
|
|
18
20
|
import { ArtifactDiffResolver } from './artifact-diff';
|
|
19
|
-
import { type SessionRunParams } from './session';
|
|
20
21
|
|
|
21
22
|
/**
|
|
22
23
|
* Formats the system prompt.
|
|
@@ -26,20 +27,24 @@ export const formatSystemPrompt = ({
|
|
|
26
27
|
system,
|
|
27
28
|
blueprints = [],
|
|
28
29
|
objects = [],
|
|
29
|
-
}: Pick<
|
|
30
|
+
}: Pick<AiRequest.RunProps, 'system' | 'blueprints' | 'objects'>): Effect.Effect<
|
|
31
|
+
string,
|
|
32
|
+
FunctionNotFoundError | EntityNotFoundError,
|
|
33
|
+
Database.Service | Registry.Service | Operation.Service
|
|
34
|
+
> =>
|
|
30
35
|
Effect.gen(function* () {
|
|
31
|
-
|
|
32
|
-
const blueprintDefs = yield* pipe(
|
|
36
|
+
const blueprintDefs = yield* Function.pipe(
|
|
33
37
|
blueprints,
|
|
34
38
|
Effect.forEach((blueprint) => Effect.succeed(blueprint.instructions)),
|
|
35
|
-
Effect.flatMap(
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
+
Effect.flatMap(
|
|
40
|
+
Effect.forEach((template) =>
|
|
41
|
+
Effect.gen(function* () {
|
|
42
|
+
return trim`
|
|
39
43
|
<blueprint>
|
|
40
|
-
${Template.
|
|
44
|
+
${yield* Template.processTemplate(template)}
|
|
41
45
|
</blueprint>
|
|
42
|
-
|
|
46
|
+
`;
|
|
47
|
+
}),
|
|
43
48
|
),
|
|
44
49
|
),
|
|
45
50
|
Effect.map((blueprints) =>
|
|
@@ -47,12 +52,12 @@ export const formatSystemPrompt = ({
|
|
|
47
52
|
),
|
|
48
53
|
);
|
|
49
54
|
|
|
50
|
-
const objectDefs = yield* pipe(
|
|
55
|
+
const objectDefs = yield* Function.pipe(
|
|
51
56
|
objects,
|
|
52
57
|
Effect.forEach((object) =>
|
|
53
58
|
Effect.succeed(trim`
|
|
54
59
|
<object>
|
|
55
|
-
<dxn>${Obj.
|
|
60
|
+
<dxn>${Obj.getURI(object)}</dxn>
|
|
56
61
|
<typename>${Obj.getTypename(object)}</typename>
|
|
57
62
|
</object>
|
|
58
63
|
`),
|
|
@@ -60,20 +65,23 @@ export const formatSystemPrompt = ({
|
|
|
60
65
|
Effect.map((objects) => (objects.length > 0 ? ['## Context Objects', ...objects].join('\n\n') : undefined)),
|
|
61
66
|
);
|
|
62
67
|
|
|
63
|
-
return yield* pipe(
|
|
68
|
+
return yield* Function.pipe(
|
|
64
69
|
Effect.succeed([system, blueprintDefs, objectDefs].filter((def): def is string => def !== undefined)),
|
|
65
70
|
Effect.map((parts) => parts.join('\n\n')),
|
|
66
71
|
);
|
|
67
|
-
});
|
|
72
|
+
}).pipe(Effect.withSpan('formatSystemPrompt'));
|
|
68
73
|
|
|
69
74
|
/**
|
|
70
75
|
* Formats the user prompt.
|
|
71
76
|
*/
|
|
72
77
|
// TODO(burdon): Move to AiPreprocessor.
|
|
73
78
|
// TODO(burdon): Convert util below to `Effect.fn` (to preserve stack info)
|
|
74
|
-
export const formatUserPrompt = ({
|
|
79
|
+
export const formatUserPrompt = ({
|
|
80
|
+
prompt,
|
|
81
|
+
history = [],
|
|
82
|
+
}: Pick<AiRequest.RunProps, 'prompt' | 'history'>): Effect.Effect<Message.Message, AiRequest.RunError> =>
|
|
75
83
|
Effect.gen(function* () {
|
|
76
|
-
const
|
|
84
|
+
const blocks: ContentBlock.Any[] = [];
|
|
77
85
|
|
|
78
86
|
// TODO(dmaretskyi): Evaluate other approaches as `serviceOption` isn't represented in the type system.
|
|
79
87
|
const artifactDiffResolver = yield* Effect.serviceOption(ArtifactDiffResolver);
|
|
@@ -84,33 +92,33 @@ export const formatUserPrompt = ({ prompt, history = [] }: Pick<SessionRunParams
|
|
|
84
92
|
artifactDiffResolver.value.resolve(
|
|
85
93
|
[...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),
|
|
86
94
|
),
|
|
87
|
-
catch: AiAssistantError.wrap('Artifact diff resolution error'),
|
|
95
|
+
catch: AiAssistantError.wrap({ message: 'Artifact diff resolution error' }),
|
|
88
96
|
});
|
|
89
97
|
|
|
90
|
-
log
|
|
98
|
+
log('version', { artifactDiff, versions });
|
|
91
99
|
for (const [id, { version }] of [...artifactDiff.entries()]) {
|
|
92
100
|
if (ObjectVersion.equals(version, versions.get(id)!)) {
|
|
93
101
|
artifactDiff.delete(id);
|
|
94
102
|
continue;
|
|
95
103
|
}
|
|
96
104
|
|
|
97
|
-
|
|
105
|
+
blocks.push({ _tag: 'anchor', objectId: id, version });
|
|
98
106
|
}
|
|
99
107
|
|
|
100
108
|
if (artifactDiff.size > 0) {
|
|
101
|
-
|
|
109
|
+
blocks.push(createArtifactUpdateBlock(artifactDiff));
|
|
102
110
|
}
|
|
103
111
|
}
|
|
104
112
|
|
|
105
|
-
return Obj.make(
|
|
113
|
+
return Obj.make(Message.Message, {
|
|
106
114
|
created: new Date().toISOString(),
|
|
107
115
|
sender: { role: 'user' },
|
|
108
|
-
blocks: [...
|
|
116
|
+
blocks: typeof prompt === 'string' ? [...blocks, { _tag: 'text', text: prompt }] : [...blocks, ...prompt],
|
|
109
117
|
});
|
|
110
|
-
});
|
|
118
|
+
}).pipe(Effect.withSpan('formatUserPrompt'));
|
|
111
119
|
|
|
112
|
-
const gatherObjectVersions = (messages:
|
|
113
|
-
const artifactIds = new Map<
|
|
120
|
+
const gatherObjectVersions = (messages: Message.Message[]): Map<EntityId, ObjectVersion> => {
|
|
121
|
+
const artifactIds = new Map<EntityId, ObjectVersion>();
|
|
114
122
|
for (const message of messages) {
|
|
115
123
|
for (const block of message.blocks) {
|
|
116
124
|
if (block._tag === 'anchor') {
|
|
@@ -123,12 +131,12 @@ const gatherObjectVersions = (messages: DataType.Message[]): Map<ObjectId, Objec
|
|
|
123
131
|
};
|
|
124
132
|
|
|
125
133
|
const createArtifactUpdateBlock = (
|
|
126
|
-
artifactDiff: Map<
|
|
134
|
+
artifactDiff: Map<EntityId, { version: ObjectVersion; diff?: string }>,
|
|
127
135
|
): ContentBlock.Any => {
|
|
128
136
|
return {
|
|
129
137
|
_tag: 'text',
|
|
130
138
|
// TODO(dmaretskyi): Does this need to be a special content-block?
|
|
131
|
-
disposition: '
|
|
139
|
+
disposition: 'synthetic',
|
|
132
140
|
text: trim`
|
|
133
141
|
The following artifacts have been updated since the last message:
|
|
134
142
|
${[...artifactDiff.entries()]
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2025 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import type * as Tool from '@effect/ai/Tool';
|
|
6
|
+
import * as Effect from 'effect/Effect';
|
|
7
|
+
import * as Function from 'effect/Function';
|
|
8
|
+
|
|
9
|
+
import { type AiParser, type ConsolePrinter } from '@dxos/ai';
|
|
10
|
+
import { type Message } from '@dxos/types';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Live observer of the generation process.
|
|
14
|
+
*/
|
|
15
|
+
export interface GenerationObserver<
|
|
16
|
+
Tools extends Record<string, Tool.Any> = any,
|
|
17
|
+
> extends AiParser.ParseResponseCallbacks<Tools> {
|
|
18
|
+
/**
|
|
19
|
+
* Complete messages fired during the session, both from the model and from the user.
|
|
20
|
+
* This message will contain all message blocks emitted through the `onBlock` callback.
|
|
21
|
+
*/
|
|
22
|
+
onMessage: (message: Message.Message) => Effect.Effect<void>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const GenerationObserver = Object.freeze({
|
|
26
|
+
make: ({
|
|
27
|
+
onBegin = Function.constant(Effect.void),
|
|
28
|
+
onPart = Function.constant(Effect.void),
|
|
29
|
+
onBlock = Function.constant(Effect.void),
|
|
30
|
+
onEnd = Function.constant(Effect.void),
|
|
31
|
+
onMessage = Function.constant(Effect.void),
|
|
32
|
+
}: Partial<GenerationObserver> = {}): GenerationObserver => ({
|
|
33
|
+
onBegin,
|
|
34
|
+
onPart,
|
|
35
|
+
onBlock,
|
|
36
|
+
onEnd,
|
|
37
|
+
onMessage,
|
|
38
|
+
}),
|
|
39
|
+
|
|
40
|
+
noop: () => GenerationObserver.make(),
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Debug printer to be used in unit-tests and browser devtools.
|
|
44
|
+
*/
|
|
45
|
+
fromPrinter: (printer: ConsolePrinter) =>
|
|
46
|
+
GenerationObserver.make({
|
|
47
|
+
onBlock: (block) =>
|
|
48
|
+
Effect.sync(() => {
|
|
49
|
+
if (block.pending) {
|
|
50
|
+
return; // Only prints full blocks (better for unit-tests and browser devtools).
|
|
51
|
+
}
|
|
52
|
+
printer.printContentBlock(block);
|
|
53
|
+
}),
|
|
54
|
+
onMessage: (message) =>
|
|
55
|
+
Effect.sync(() => {
|
|
56
|
+
if (message.sender.role === 'assistant') {
|
|
57
|
+
return; // Skip assistant messages since they are printed in the `onBlock` callback.
|
|
58
|
+
}
|
|
59
|
+
printer.printMessage(message);
|
|
60
|
+
}),
|
|
61
|
+
}),
|
|
62
|
+
});
|