@dxos/assistant 0.8.3 → 0.8.4-main.f9ba587

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/lib/browser/index.mjs +456 -595
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +456 -595
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/blueprint/blueprint.d.ts +33 -47
  8. package/dist/types/src/blueprint/blueprint.d.ts.map +1 -1
  9. package/dist/types/src/blueprint/index.d.ts +1 -2
  10. package/dist/types/src/blueprint/index.d.ts.map +1 -1
  11. package/dist/types/src/blueprint/registry.d.ts +7 -0
  12. package/dist/types/src/blueprint/registry.d.ts.map +1 -0
  13. package/dist/types/src/context/binder.d.ts +34 -0
  14. package/dist/types/src/context/binder.d.ts.map +1 -0
  15. package/dist/types/src/context/binding.d.ts +38 -0
  16. package/dist/types/src/context/binding.d.ts.map +1 -0
  17. package/dist/types/src/context/index.d.ts +3 -0
  18. package/dist/types/src/context/index.d.ts.map +1 -0
  19. package/dist/types/src/conversation/conversation.d.ts +44 -0
  20. package/dist/types/src/conversation/conversation.d.ts.map +1 -0
  21. package/dist/types/src/conversation/index.d.ts +2 -0
  22. package/dist/types/src/conversation/index.d.ts.map +1 -0
  23. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  24. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +10 -10
  25. package/dist/types/src/index.d.ts +4 -1
  26. package/dist/types/src/index.d.ts.map +1 -1
  27. package/dist/types/src/research/research.d.ts.map +1 -1
  28. package/dist/types/src/session/session.d.ts +25 -3
  29. package/dist/types/src/session/session.d.ts.map +1 -1
  30. package/dist/types/tsconfig.tsbuildinfo +1 -1
  31. package/package.json +21 -30
  32. package/src/blueprint/blueprint.ts +57 -57
  33. package/src/blueprint/index.ts +1 -2
  34. package/src/blueprint/registry.ts +15 -0
  35. package/src/context/binder.ts +101 -0
  36. package/src/context/binding.ts +31 -0
  37. package/src/context/index.ts +6 -0
  38. package/src/conversation/conversation.ts +103 -0
  39. package/src/conversation/index.ts +5 -0
  40. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +2 -1
  41. package/src/index.ts +4 -1
  42. package/src/research/research.ts +3 -2
  43. package/src/session/session.test.ts +48 -2
  44. package/src/session/session.ts +51 -18
  45. package/dist/lib/node/index.cjs +0 -2178
  46. package/dist/lib/node/index.cjs.map +0 -7
  47. package/dist/lib/node/meta.json +0 -1
  48. package/dist/types/src/blueprint/ai.test.d.ts +0 -2
  49. package/dist/types/src/blueprint/ai.test.d.ts.map +0 -1
  50. package/dist/types/src/blueprint/blueprint.test.d.ts +0 -2
  51. package/dist/types/src/blueprint/blueprint.test.d.ts.map +0 -1
  52. package/dist/types/src/blueprint/logger.d.ts +0 -25
  53. package/dist/types/src/blueprint/logger.d.ts.map +0 -1
  54. package/dist/types/src/blueprint/machine.d.ts +0 -143
  55. package/dist/types/src/blueprint/machine.d.ts.map +0 -1
  56. package/dist/types/src/blueprint/test-data.d.ts +0 -3
  57. package/dist/types/src/blueprint/test-data.d.ts.map +0 -1
  58. package/src/blueprint/ai.test.ts +0 -156
  59. package/src/blueprint/blueprint.test.ts +0 -151
  60. package/src/blueprint/logger.ts +0 -155
  61. package/src/blueprint/machine.ts +0 -251
  62. package/src/blueprint/test-data.ts +0 -55
@@ -1,155 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { type ReadonlySignal, signal } from '@preact/signals-core';
6
- import chalk from 'chalk';
7
-
8
- import { ConsolePrinter } from '@dxos/ai';
9
- import { type CleanupFn, combine } from '@dxos/async';
10
- import { log } from '@dxos/log';
11
-
12
- import { type Blueprint } from './blueprint';
13
- import {
14
- type BlueprintEvent,
15
- type BlueprintLogger,
16
- type BlueprintMachine,
17
- type BlueprintMachineState,
18
- } from './machine';
19
-
20
- /* eslint-disable no-console */
21
-
22
- // Force chalk colors on for tests.
23
- chalk.level = 2;
24
-
25
- // TODO(burdon): Factor out.
26
- type ConsoleLogSignature = (message: string, arg?: any) => void;
27
-
28
- interface Logger {
29
- log: ConsoleLogSignature;
30
- }
31
-
32
- const DEFAULT_LOGGER: Logger = { log: log.info };
33
-
34
- /**
35
- * Reactive bufferedlogger.
36
- */
37
- export class BufferedLogger implements Logger {
38
- private _messages = signal<string[]>([]);
39
-
40
- get messages(): ReadonlySignal<string[]> {
41
- return this._messages;
42
- }
43
-
44
- clear() {
45
- this._messages.value = [];
46
- }
47
-
48
- log(message: string) {
49
- this._messages.value = [...this._messages.value, message];
50
- }
51
- }
52
-
53
- // TODO(burdon): Reconcile with ConsolePrinter.
54
- export class BlueprintLoggerAdapter implements BlueprintLogger {
55
- constructor(private readonly logger: Logger = DEFAULT_LOGGER) {}
56
-
57
- log(event: BlueprintEvent) {
58
- switch (event.type) {
59
- case 'begin':
60
- this.logger.log('begin', { invocationId: event.invocationId });
61
- break;
62
- case 'end':
63
- this.logger.log('end', { invocationId: event.invocationId });
64
- break;
65
- case 'step-start':
66
- this.logger.log('step-start', { invocationId: event.invocationId, step: event.step });
67
- break;
68
- case 'step-complete':
69
- this.logger.log('step-complete', { invocationId: event.invocationId, step: event.step });
70
- break;
71
- case 'message':
72
- this.logger.log('message', { invocationId: event.invocationId, message: event.message });
73
- break;
74
- case 'block':
75
- this.logger.log('block', { invocationId: event.invocationId, block: event.block });
76
- break;
77
- }
78
- }
79
- }
80
-
81
- export const setLogger = (machine: BlueprintMachine, logger: BufferedLogger): CleanupFn => {
82
- return combine(
83
- machine.begin.on(() => {
84
- logger.log('Starting...');
85
- }),
86
- machine.stepStart.on((step) => {
87
- const index = machine.blueprint.steps.indexOf(step);
88
- logger.log(`Step ${index + 1} of ${machine.blueprint.steps.length}`);
89
- logger.log(`Instructions: ${step.instructions}`);
90
- }),
91
- machine.stepComplete.on((step) => {
92
- const trace = machine.state.trace.find((t) => t.stepId === step.id);
93
- logger.log(`Complete: ${trace?.comment}`);
94
- }),
95
- machine.end.on(() => {
96
- logger.log('OK');
97
- }),
98
- );
99
- };
100
-
101
- export const setConsolePrinter = (machine: BlueprintMachine, verbose = false): CleanupFn => {
102
- const printer = new ConsolePrinter();
103
- return combine(
104
- machine.begin.on(() => printTrace(machine.blueprint, machine.state)),
105
- machine.stepStart.on((step) =>
106
- console.log(
107
- `\n${chalk.magenta(`${chalk.bold(`STEP ${machine.blueprint.steps.indexOf(step) + 1} of ${machine.blueprint.steps.length}:`)} ${step.instructions}`)}\n`,
108
- ),
109
- ),
110
- machine.stepComplete.on(() => printTrace(machine.blueprint, machine.state)),
111
- machine.end.on(() => console.log('DONE')),
112
- verbose
113
- ? [
114
- machine.message.on((msg) => printer.printMessage(msg)),
115
- machine.block.on((block) => printer.printContentBlock(block)),
116
- ]
117
- : [],
118
- );
119
- };
120
-
121
- const BREAK_LINE = `\n${'_'.repeat(80)}\n`;
122
-
123
- const printTrace = (blueprint: Blueprint, state: BlueprintMachineState) => {
124
- console.group(chalk.bold('\nBlueprint'));
125
- blueprint.steps.forEach((step) => {
126
- const traceStep = state.trace.find((t) => t.stepId === step.id);
127
-
128
- let color = chalk.gray; // Not executed.
129
- let bullet = '○';
130
- if (traceStep) {
131
- switch (traceStep.status) {
132
- case 'done':
133
- color = chalk.green;
134
- bullet = '✓';
135
- break;
136
- case 'skipped':
137
- color = chalk.blue;
138
- bullet = '↓';
139
- break;
140
- case 'bailed':
141
- color = chalk.red;
142
- bullet = '✗';
143
- break;
144
- }
145
- }
146
-
147
- console.log(color(`\n${bullet} ${step.instructions}`));
148
- if (traceStep?.comment) {
149
- console.log(chalk.white(` ↳ ${traceStep.comment}`));
150
- }
151
- });
152
-
153
- console.groupEnd();
154
- console.log(BREAK_LINE);
155
- };
@@ -1,251 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { Match, Schema } from 'effect';
6
-
7
- import {
8
- createTool,
9
- type AiServiceClient,
10
- Message,
11
- type MessageContentBlock,
12
- ToolResult,
13
- type ToolUseContentBlock,
14
- type ToolRegistry,
15
- } from '@dxos/ai';
16
- import { Event } from '@dxos/async';
17
- import { Key, Obj } from '@dxos/echo';
18
- import { type ObjectId } from '@dxos/keys';
19
- import { log } from '@dxos/log';
20
- import { isNonNullable } from '@dxos/util';
21
-
22
- import type { Blueprint, BlueprintStep } from './blueprint';
23
- import { AISession } from '../session';
24
-
25
- const SYSTEM_PROMPT = `
26
- You are a smart Rule-Following Agent.
27
- Rule-Following Agent executes the command that the user sent in the last message.
28
- After doing the work, the Rule-Following Agent calls report tool.
29
- If the Rule-Following agent believes that no action is needed, it calls the report tool with "skipped" status.
30
- If the Rule-Following Agent is unable to perform the task, it calls the report tool with "bail" status.
31
- Rule-Following Agent explains the reason it is unable to perform the task before bailing.
32
- The Rule-Following Agent can express creativity and imagination in the way it performs the task.
33
- The Rule-Following Agent precisely follows the instructions.
34
- `;
35
-
36
- export type BlueprintTraceStep = {
37
- status: 'done' | 'bailed' | 'skipped';
38
- stepId: ObjectId;
39
- comment: string;
40
- };
41
-
42
- export type BlueprintMachineState = {
43
- history: Message[];
44
- trace: BlueprintTraceStep[];
45
- state: 'working' | 'bail' | 'done';
46
- };
47
-
48
- const INITIAL_STATE: BlueprintMachineState = {
49
- state: 'working',
50
- history: [],
51
- trace: [],
52
- };
53
-
54
- type ExecutionOptions = {
55
- aiClient: AiServiceClient;
56
-
57
- /**
58
- * Input to the blueprint.
59
- */
60
- input?: unknown;
61
- };
62
-
63
- export type BlueprintEvent =
64
- | { type: 'begin'; invocationId: string }
65
- | { type: 'end'; invocationId: string }
66
- | { type: 'step-start'; invocationId: string; step: BlueprintStep }
67
- | { type: 'step-complete'; invocationId: string; step: BlueprintStep }
68
- | { type: 'message'; invocationId: string; message: Message }
69
- | { type: 'block'; invocationId: string; block: MessageContentBlock };
70
-
71
- export interface BlueprintLogger {
72
- log(event: BlueprintEvent): void;
73
- }
74
-
75
- /**
76
- * Blueprint state machine.
77
- */
78
- export class BlueprintMachine {
79
- public readonly begin = new Event<void>();
80
- public readonly end = new Event<void>();
81
- public readonly stepStart = new Event<BlueprintStep>();
82
- public readonly stepComplete = new Event<BlueprintStep>();
83
- public readonly message = new Event<Message>();
84
- public readonly block = new Event<MessageContentBlock>();
85
-
86
- // TODO(burdon): Replace events with logger?
87
- private logger?: BlueprintLogger;
88
-
89
- private _state: BlueprintMachineState = structuredClone(INITIAL_STATE);
90
-
91
- constructor(
92
- readonly registry: ToolRegistry,
93
- readonly blueprint: Blueprint,
94
- ) {}
95
-
96
- get state(): BlueprintMachineState {
97
- return this._state;
98
- }
99
-
100
- setLogger(logger: BlueprintLogger): this {
101
- this.logger = logger;
102
- return this;
103
- }
104
-
105
- async runToCompletion(options: ExecutionOptions): Promise<void> {
106
- const invocationId = Key.ObjectId.random();
107
- log.info('runToCompletion', { invocationId, options });
108
-
109
- this.begin.emit();
110
- this.logger?.log({ type: 'begin', invocationId });
111
-
112
- let firstStep = true;
113
- while (this._state.state !== 'done') {
114
- const input = firstStep ? options.input : undefined;
115
- firstStep = false;
116
-
117
- this._state = await this._execStep(invocationId, this._state, { input, aiClient: options.aiClient });
118
-
119
- const step = this.blueprint.steps.find((step) => step.id === this._state.trace.at(-1)?.stepId)!;
120
- this.stepComplete.emit(step);
121
- this.logger?.log({ type: 'step-complete', invocationId, step });
122
-
123
- if (this._state.state === 'bail') {
124
- throw new Error('Agent unable to follow the blueprint');
125
- }
126
- }
127
-
128
- this.end.emit();
129
- this.logger?.log({ type: 'end', invocationId });
130
- }
131
-
132
- private async _execStep(
133
- invocationId: string,
134
- state: BlueprintMachineState,
135
- options: ExecutionOptions,
136
- ): Promise<BlueprintMachineState> {
137
- const prevStep = this.blueprint.steps.findIndex((step) => step.id === this._state.trace.at(-1)?.stepId);
138
- if (prevStep === this.blueprint.steps.length - 1) {
139
- throw new Error('Done execution blueprint');
140
- }
141
-
142
- const nextStep = this.blueprint.steps[prevStep + 1];
143
- const onLastStep = prevStep === this.blueprint.steps.length - 2;
144
-
145
- this.stepStart.emit(nextStep);
146
- this.logger?.log({ type: 'step-start', invocationId, step: nextStep });
147
-
148
- const ReportSchema = Schema.Struct({
149
- status: Schema.Literal('done', 'bailed', 'skipped').annotations({
150
- description: 'The status of the task completion',
151
- }),
152
- comment: Schema.String.annotations({
153
- description:
154
- 'A comment about the task completion. If you bailed, you must explain why in detail (min couple of sentences).',
155
- }),
156
- });
157
-
158
- const report = createTool('system', {
159
- name: 'report',
160
- description: 'This tool reports that the agent has completed the task or is unable to do so.',
161
- schema: ReportSchema,
162
- execute: async (input) => ToolResult.Break(input),
163
- });
164
-
165
- const session = new AISession({
166
- operationModel: 'configured',
167
- });
168
-
169
- session.userMessage.pipeInto(this.message);
170
- session.message.pipeInto(this.message);
171
- session.block.pipeInto(this.block);
172
-
173
- const inputMessages = options.input
174
- ? [
175
- Obj.make(Message, {
176
- role: 'user',
177
- content: [taggedDataBlock('input', options.input)],
178
- }),
179
- ]
180
- : [];
181
- inputMessages.forEach((message) => {
182
- this.message.emit(message);
183
- this.logger?.log({ type: 'message', invocationId, message });
184
- });
185
-
186
- // TODO(wittjosiah): Warn if tool is not found.
187
- const tools = nextStep.tools?.map((tool) => this.registry.get(tool)).filter(isNonNullable) ?? [];
188
- const messages = await session.run({
189
- systemPrompt: SYSTEM_PROMPT,
190
- history: [...state.history, ...inputMessages],
191
- tools: [...tools, report],
192
- artifacts: [],
193
- client: options.aiClient,
194
- prompt: nextStep.instructions,
195
- });
196
-
197
- const { messages: trimmedHistory, call: lastBlock } = popLastToolCall(messages);
198
- if (!lastBlock) {
199
- // TODO(dmaretskyi): Handle this with grace.
200
- throw new Error('Agent did not call the report tool');
201
- }
202
-
203
- const { status, comment } = ReportSchema.pipe(Schema.decodeUnknownSync)(lastBlock.input);
204
-
205
- return {
206
- history: [...state.history, ...inputMessages, ...trimmedHistory],
207
- trace: [
208
- ...state.trace,
209
- {
210
- stepId: nextStep.id,
211
- status,
212
- comment,
213
- },
214
- ],
215
- state: Match.value(status).pipe(
216
- Match.withReturnType<BlueprintMachineState['state']>(),
217
- Match.when('done', () => (onLastStep ? 'done' : 'working')),
218
- Match.when('skipped', () => (onLastStep ? 'done' : 'working')),
219
- Match.when('bailed', () => 'bail'),
220
- Match.exhaustive,
221
- ),
222
- };
223
- }
224
- }
225
-
226
- const taggedDataBlock = (tag: string, data: unknown): MessageContentBlock => {
227
- return {
228
- type: 'text',
229
- text: `<${tag}>\n${JSON.stringify(data, null, 2)}\n</${tag}>`,
230
- } satisfies MessageContentBlock;
231
- };
232
-
233
- const popLastToolCall = (messages: Message[]): { messages: Message[]; call?: ToolUseContentBlock } => {
234
- const lastBlock = messages.at(-1)?.content.at(-1);
235
- if (lastBlock?.type !== 'tool_use') {
236
- return { messages };
237
- }
238
-
239
- const trimmedHistory = [
240
- ...messages.slice(0, -1),
241
- {
242
- ...messages.at(-1)!,
243
- content: [...messages.at(-1)!.content.slice(0, -1)],
244
- } satisfies Message,
245
- ];
246
-
247
- return {
248
- messages: trimmedHistory,
249
- call: lastBlock,
250
- };
251
- };
@@ -1,55 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { Obj } from '@dxos/echo';
6
- import { DataType } from '@dxos/schema';
7
-
8
- // TODO(burdon): Convert to queue.
9
- export const TEST_EMAILS: DataType.Message[] = [
10
- Obj.make(DataType.Message, {
11
- properties: {
12
- subject: 'Introduction email',
13
- },
14
- sender: {
15
- email: 'alice@example.com',
16
- },
17
- blocks: [
18
- {
19
- type: 'text',
20
- text: "Hi there! I came across your work and would love to connect. I'm working on some interesting projects in the decentralized space and think there could be good collaboration opportunities.",
21
- },
22
- ],
23
- created: new Date().toISOString(),
24
- }),
25
- Obj.make(DataType.Message, {
26
- properties: {
27
- subject: 'Question about integration',
28
- },
29
- sender: {
30
- email: 'bob@example.com',
31
- },
32
- blocks: [
33
- {
34
- type: 'text',
35
- text: "Hello, I was wondering if your system supports integration with external APIs? We have some custom services we'd like to connect. Could you explain the process?",
36
- },
37
- ],
38
- created: new Date().toISOString(),
39
- }),
40
- Obj.make(DataType.Message, {
41
- properties: {
42
- subject: 'MAKE MONEY FAST!!!',
43
- },
44
- sender: {
45
- email: 'spammer123@sketchy.com',
46
- },
47
- blocks: [
48
- {
49
- type: 'text',
50
- text: 'CONGRATULATIONS!!! You have been selected to receive $10 MILLION dollars! Just send us your bank details and social security number to claim your prize NOW!!!',
51
- },
52
- ],
53
- created: new Date().toISOString(),
54
- }),
55
- ];