@dxos/assistant 0.8.4-main.bc674ce → 0.8.4-main.bcb3aa67d6

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 (121) hide show
  1. package/README.md +1 -0
  2. package/dist/lib/neutral/chunk-KVYJFFLF.mjs +1805 -0
  3. package/dist/lib/neutral/chunk-KVYJFFLF.mjs.map +7 -0
  4. package/dist/lib/{browser → neutral}/extraction/index.mjs +26 -32
  5. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  6. package/dist/lib/{browser → neutral}/index.mjs +72 -371
  7. package/dist/lib/neutral/index.mjs.map +7 -0
  8. package/dist/lib/neutral/meta.json +1 -0
  9. package/dist/lib/neutral/testing/index.mjs +112 -0
  10. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  11. package/dist/types/src/conversation/context.d.ts +24 -5
  12. package/dist/types/src/conversation/context.d.ts.map +1 -1
  13. package/dist/types/src/conversation/conversation.d.ts +29 -4
  14. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  15. package/dist/types/src/diff.d.ts +3 -1
  16. package/dist/types/src/diff.d.ts.map +1 -1
  17. package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
  18. package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
  19. package/dist/types/src/extraction/extraction.d.ts +729 -17
  20. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  21. package/dist/types/src/extraction/index.d.ts +0 -1
  22. package/dist/types/src/extraction/index.d.ts.map +1 -1
  23. package/dist/types/src/functions/services.d.ts +27 -8
  24. package/dist/types/src/functions/services.d.ts.map +1 -1
  25. package/dist/types/src/index.d.ts +2 -0
  26. package/dist/types/src/index.d.ts.map +1 -1
  27. package/dist/types/src/service/AgentService.d.ts +62 -0
  28. package/dist/types/src/service/AgentService.d.ts.map +1 -0
  29. package/dist/types/src/service/AgentService.test.d.ts +2 -0
  30. package/dist/types/src/service/AgentService.test.d.ts.map +1 -0
  31. package/dist/types/src/service/agent-process.d.ts +17 -0
  32. package/dist/types/src/service/agent-process.d.ts.map +1 -0
  33. package/dist/types/src/service/index.d.ts +3 -0
  34. package/dist/types/src/service/index.d.ts.map +1 -0
  35. package/dist/types/src/session/index.d.ts +1 -1
  36. package/dist/types/src/session/index.d.ts.map +1 -1
  37. package/dist/types/src/session/observer.d.ts.map +1 -1
  38. package/dist/types/src/session/session.d.ts +64 -8
  39. package/dist/types/src/session/session.d.ts.map +1 -1
  40. package/dist/types/src/session/toolkit.d.ts +6 -2
  41. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  42. package/dist/types/src/templates/system.d.ts +0 -1
  43. package/dist/types/src/templates/system.d.ts.map +1 -1
  44. package/dist/types/src/testing/layer.d.ts +23 -9
  45. package/dist/types/src/testing/layer.d.ts.map +1 -1
  46. package/dist/types/src/tracing.d.ts +264 -0
  47. package/dist/types/src/tracing.d.ts.map +1 -0
  48. package/dist/types/src/types/artifact.d.ts +5 -5
  49. package/dist/types/src/types/artifact.d.ts.map +1 -1
  50. package/dist/types/tsconfig.tsbuildinfo +1 -1
  51. package/package.json +33 -33
  52. package/src/conversation/context.test.ts +1 -1
  53. package/src/conversation/context.ts +84 -18
  54. package/src/conversation/conversation.ts +173 -32
  55. package/src/diff.test.ts +36 -5
  56. package/src/diff.ts +13 -4
  57. package/src/execution-graph.test.ts +2 -2
  58. package/src/execution-graph.ts +2 -2
  59. package/src/extraction/extraction-ner-function/index.ts +0 -1
  60. package/src/extraction/extraction.ts +38 -10
  61. package/src/extraction/index.ts +0 -1
  62. package/src/functions/services.ts +199 -50
  63. package/src/functions.conversations.json +1 -1
  64. package/src/functions.test.ts +28 -20
  65. package/src/index.ts +2 -0
  66. package/src/service/AgentService.conversations.json +1 -0
  67. package/src/service/AgentService.test.ts +169 -0
  68. package/src/service/AgentService.ts +171 -0
  69. package/src/service/agent-process.ts +360 -0
  70. package/src/service/index.ts +6 -0
  71. package/src/session/format.test.ts +23 -14
  72. package/src/session/index.ts +1 -2
  73. package/src/session/observer.ts +3 -2
  74. package/src/session/session.conversations.json +1 -1
  75. package/src/session/session.test.ts +52 -4
  76. package/src/session/session.ts +231 -117
  77. package/src/session/toolkit.ts +12 -7
  78. package/src/templates/instructions/format.tpl +0 -4
  79. package/src/templates/instructions/system.tpl +11 -2
  80. package/src/templates/system.ts +6 -5
  81. package/src/testing/layer.ts +209 -24
  82. package/src/tracing.ts +112 -0
  83. package/src/types/artifact.ts +17 -10
  84. package/dist/lib/browser/chunk-7CDDG6LL.mjs +0 -578
  85. package/dist/lib/browser/chunk-7CDDG6LL.mjs.map +0 -7
  86. package/dist/lib/browser/extraction/index.mjs.map +0 -7
  87. package/dist/lib/browser/index.mjs.map +0 -7
  88. package/dist/lib/browser/meta.json +0 -1
  89. package/dist/lib/browser/testing/index.mjs +0 -32
  90. package/dist/lib/browser/testing/index.mjs.map +0 -7
  91. package/dist/lib/node-esm/chunk-CC7ER6Q3.mjs +0 -579
  92. package/dist/lib/node-esm/chunk-CC7ER6Q3.mjs.map +0 -7
  93. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  94. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  95. package/dist/lib/node-esm/extraction/index.mjs +0 -226
  96. package/dist/lib/node-esm/extraction/index.mjs.map +0 -7
  97. package/dist/lib/node-esm/index.mjs +0 -851
  98. package/dist/lib/node-esm/index.mjs.map +0 -7
  99. package/dist/lib/node-esm/meta.json +0 -1
  100. package/dist/lib/node-esm/testing/index.mjs +0 -33
  101. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  102. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
  103. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
  104. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
  105. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
  106. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
  107. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
  108. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -347
  109. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
  110. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
  111. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
  112. package/dist/types/src/session/GenericToolkit.d.ts +0 -85
  113. package/dist/types/src/session/GenericToolkit.d.ts.map +0 -1
  114. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -84
  115. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -62
  116. package/src/extraction/extraction-llm-function/index.ts +0 -5
  117. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -116
  118. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -56
  119. package/src/session/GenericToolkit.ts +0 -131
  120. /package/dist/lib/{browser → neutral}/chunk-J5LGTIGS.mjs +0 -0
  121. /package/dist/lib/{browser → neutral}/chunk-J5LGTIGS.mjs.map +0 -0
@@ -4,7 +4,7 @@
4
4
 
5
5
  import * as Tool from '@effect/ai/Tool';
6
6
  import * as Toolkit from '@effect/ai/Toolkit';
7
- import { describe, it } from '@effect/vitest';
7
+ import { describe, expect, it } from '@effect/vitest';
8
8
  import * as Effect from 'effect/Effect';
9
9
  import * as Layer from 'effect/Layer';
10
10
  import * as Schema from 'effect/Schema';
@@ -12,6 +12,7 @@ import * as Schema from 'effect/Schema';
12
12
  import { Obj, Type } from '@dxos/echo';
13
13
  import { TestHelpers } from '@dxos/effect/testing';
14
14
  import { log } from '@dxos/log';
15
+ import { Message } from '@dxos/types';
15
16
 
16
17
  import { AssistantTestLayer } from '../testing';
17
18
 
@@ -25,7 +26,7 @@ const CalendarEventSchema = Schema.Struct({
25
26
  description: Schema.String,
26
27
  }).pipe(
27
28
  Type.object({
28
- typename: 'example.com/type/CalendarEvent',
29
+ typename: 'com.example.type.calendar-event',
29
30
  version: '0.1.0',
30
31
  }),
31
32
  );
@@ -67,6 +68,7 @@ const toolkitLayer = TestToolkit.toLayer({
67
68
  const TestLayer = Layer.mergeAll(
68
69
  AssistantTestLayer({
69
70
  types: [CalendarEventSchema],
71
+ tracing: 'pretty',
70
72
  }),
71
73
  toolkitLayer,
72
74
  );
@@ -76,7 +78,7 @@ describe('AiSession', () => {
76
78
  'no tools',
77
79
  Effect.fnUntraced(
78
80
  function* (_) {
79
- const session = new AiSession({ operationModel: 'configured' });
81
+ const session = new AiSession();
80
82
  const response = yield* session.run({
81
83
  prompt: 'Hello world!',
82
84
  history: [],
@@ -92,7 +94,7 @@ describe('AiSession', () => {
92
94
  'calculator',
93
95
  Effect.fnUntraced(
94
96
  function* (_) {
95
- const session = new AiSession({ operationModel: 'configured' });
97
+ const session = new AiSession();
96
98
  const toolkit = yield* TestToolkit;
97
99
  const response = yield* session.run({
98
100
  toolkit,
@@ -105,6 +107,52 @@ describe('AiSession', () => {
105
107
  TestHelpers.provideTestContext,
106
108
  ),
107
109
  );
110
+
111
+ it.effect(
112
+ 'tool schema error',
113
+ Effect.fnUntraced(
114
+ function* (_) {
115
+ const session = new AiSession();
116
+ const toolkit = yield* TestToolkit;
117
+ const response = yield* session.run({
118
+ toolkit,
119
+ prompt:
120
+ 'I am testing error handling in tool paramter parsing. I want you to call the calculator tool but omit the input parameter to intentionally differ from the tool schema.',
121
+ history: [],
122
+ });
123
+ log.info('response', { response });
124
+ },
125
+ Effect.provide(TestLayer),
126
+ TestHelpers.provideTestContext,
127
+ ),
128
+ );
129
+
130
+ it.effect(
131
+ 'summarization',
132
+ Effect.fnUntraced(
133
+ function* (_) {
134
+ const session = new AiSession({ summarizationThreshold: 0 }); // Force summarization.
135
+ const response = yield* session.run({
136
+ prompt: 'What did we talk about?',
137
+ history: [
138
+ Obj.make(Message.Message, {
139
+ created: '2024-01-01T10:00:00Z',
140
+ sender: { role: 'user' },
141
+ blocks: [{ _tag: 'text', text: 'How many apples are in the basket?' }],
142
+ }),
143
+ Obj.make(Message.Message, {
144
+ created: '2024-01-01T11:00:00Z',
145
+ sender: { role: 'assistant' },
146
+ blocks: [{ _tag: 'text', text: 'There are 10 apples in the basket.' }],
147
+ }),
148
+ ],
149
+ });
150
+ expect(response).toBeDefined();
151
+ },
152
+ Effect.provide(TestLayer),
153
+ TestHelpers.provideTestContext,
154
+ ),
155
+ );
108
156
  });
109
157
 
110
158
  // Travel to rome, florence, livorno, siena, madrid for conferences
@@ -8,30 +8,32 @@ import type * as Tool from '@effect/ai/Tool';
8
8
  import type * as Toolkit from '@effect/ai/Toolkit';
9
9
  import * as Chunk from 'effect/Chunk';
10
10
  import * as Effect from 'effect/Effect';
11
- import type * as Schema from 'effect/Schema';
12
11
  import * as Stream from 'effect/Stream';
13
-
12
+ import * as Array from 'effect/Array';
13
+ import * as Option from 'effect/Option';
14
14
  import {
15
15
  AiParser,
16
16
  AiPreprocessor,
17
+ AiSummarizer,
17
18
  type AiToolNotFoundError,
19
+ callTool,
18
20
  type PromptPreprocessingError,
19
21
  type ToolExecutionService,
20
22
  type ToolResolverService,
21
- callTool,
22
- getToolCalls,
23
+ withoutToolCallParising,
23
24
  } from '@dxos/ai';
24
25
  import { type Blueprint } from '@dxos/blueprints';
25
- import { todo } from '@dxos/debug';
26
26
  import { Obj } from '@dxos/echo';
27
- import { type FunctionInvocationService, TracingService } from '@dxos/functions';
27
+ import { type FunctionInvocationService, Trace, TracingService } from '@dxos/functions';
28
28
  import { log } from '@dxos/log';
29
- import { Message } from '@dxos/types';
29
+ import { ContentBlock, Message } from '@dxos/types';
30
30
 
31
31
  import { type AiAssistantError } from '../errors';
32
32
 
33
33
  import { formatSystemPrompt, formatUserPrompt } from './format';
34
34
  import { GenerationObserver } from './observer';
35
+ import { pipe } from 'effect/Function';
36
+ import { CompleteBlock, PartialBlock } from '../tracing';
35
37
 
36
38
  export type AiSessionRunError = AiError.AiError | PromptPreprocessingError | AiToolNotFoundError | AiAssistantError;
37
39
 
@@ -39,10 +41,28 @@ export type AiSessionRunRequirements =
39
41
  | LanguageModel.LanguageModel
40
42
  | ToolExecutionService
41
43
  | ToolResolverService
42
- | TracingService
43
- | FunctionInvocationService;
44
+ | FunctionInvocationService
45
+ | Trace.TraceService
46
+ /**
47
+ * @deprecated Retained for backward compatibility with tool handlers that use TracingService.emitStatus().
48
+ * New code should use Trace.TraceService instead.
49
+ */
50
+ | TracingService;
44
51
 
45
- export type AiSessionOptions = {};
52
+ export type AiSessionOptions = {
53
+ /**
54
+ * Summarize before executing the prompt if the existing history exceeds this threshold.
55
+ */
56
+ summarizationThreshold?: number;
57
+
58
+ // TODO(dmaretskyi): Plan to phase out in favor of TracingService and the return type being a stream.
59
+ observer?: GenerationObserver;
60
+ /**
61
+ * Callback for when a message is received from the user, model, or tool.
62
+ * This is useful for streaming the output to a queue.
63
+ */
64
+ onOutput?: (message: Message.Message) => Effect.Effect<void, never, never>;
65
+ };
46
66
 
47
67
  export type AiSessionRunProps<Tools extends Record<string, Tool.Any>> = {
48
68
  prompt: string;
@@ -52,7 +72,24 @@ export type AiSessionRunProps<Tools extends Record<string, Tool.Any>> = {
52
72
  objects?: Obj.Unknown[];
53
73
  blueprints?: readonly Blueprint.Blueprint[];
54
74
  toolkit?: Toolkit.WithHandler<Tools>;
55
- observer?: GenerationObserver<Tools>;
75
+ };
76
+
77
+ export type AiSessionBeginProps = {
78
+ prompt: string;
79
+ system?: string;
80
+ history?: Message.Message[];
81
+ objects?: Obj.Unknown[];
82
+ blueprints?: readonly Blueprint.Blueprint[];
83
+ };
84
+
85
+ export type AiSessionTurnProps<Tools extends Record<string, Tool.Any>> = {
86
+ system: string;
87
+ toolkit?: Toolkit.WithHandler<Tools>;
88
+ };
89
+
90
+ export type AiSessionTurnResult = {
91
+ messages: Message.Message[];
92
+ done: boolean;
56
93
  };
57
94
 
58
95
  /**
@@ -65,10 +102,14 @@ export type AiSessionRunProps<Tools extends Record<string, Tool.Any>> = {
65
102
  * Could be run locally in the app or remotely.
66
103
  * Could be personal or shared.
67
104
  */
105
+ // TODO(dmaretskyi): Rename AiSessionRequest
68
106
  export class AiSession {
69
107
  /** Prevents concurrent execution of session. */
70
108
  private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));
71
109
 
110
+ private readonly _observer: GenerationObserver;
111
+ private readonly _onOutput: (message: Message.Message) => Effect.Effect<void, never, never>;
112
+
72
113
  /** Message history from queue. */
73
114
  // TODO(burdon): Evolve into supporting a git-like graph of messages.
74
115
  private _history: Message.Message[] = [];
@@ -80,7 +121,10 @@ export class AiSession {
80
121
  private _ended = 0;
81
122
  private _toolCalls = 0;
82
123
 
83
- constructor(private readonly _options: AiSessionOptions = {}) {}
124
+ constructor(private readonly _options: AiSessionOptions = {}) {
125
+ this._observer = _options.observer ?? GenerationObserver.noop();
126
+ this._onOutput = _options.onOutput ?? (() => Effect.void);
127
+ }
84
128
 
85
129
  get duration(): number {
86
130
  return this._ended - this._started;
@@ -90,135 +134,205 @@ export class AiSession {
90
134
  return this._toolCalls;
91
135
  }
92
136
 
93
- run = <Tools extends Record<string, Tool.Any>>({
137
+ get pending(): readonly Message.Message[] {
138
+ return this._pending;
139
+ }
140
+
141
+ private _submitMessage = (message: Message.Message): Effect.Effect<Message.Message, never, Trace.TraceService> =>
142
+ Effect.gen(this, function* () {
143
+ this._pending.push(message);
144
+ yield* this._observer.onMessage(message);
145
+ for (const block of message.blocks) {
146
+ yield* Trace.write(CompleteBlock, {
147
+ messageId: message.id,
148
+ role: message.sender.role!,
149
+ block,
150
+ });
151
+ }
152
+ yield* this._onOutput(message);
153
+ return message;
154
+ });
155
+
156
+ getToolCalls = () =>
157
+ pipe(
158
+ [...this._history, ...this._pending],
159
+ Array.reverse,
160
+ Array.takeWhile((_) => _.sender.role === 'assistant'),
161
+ Array.flatMap((_) => _.blocks.filter(ContentBlock.is('toolCall')).map((block) => ({ block, message: _ }))),
162
+ Array.filter((_) => !_.block.providerExecuted),
163
+ );
164
+
165
+ /**
166
+ * Initialize a session: set up history, perform summarization if needed, and submit the user prompt.
167
+ * Must be called before `runTurn()`.
168
+ */
169
+ begin = ({
94
170
  prompt,
95
- system: systemTemplate,
171
+ system,
96
172
  history = [],
97
- objects = [],
98
173
  blueprints = [],
99
- toolkit,
100
- observer = GenerationObserver.noop(),
101
- }: AiSessionRunProps<Tools>): Effect.Effect<Message.Message[], AiSessionRunError, AiSessionRunRequirements> =>
174
+ objects = [],
175
+ }: AiSessionBeginProps): Effect.Effect<void, AiSessionRunError, AiSessionRunRequirements> =>
102
176
  Effect.gen(this, function* () {
103
177
  this._started = Date.now();
104
178
  this._history = [...history];
105
179
  this._pending = [];
106
- const pending = this._pending;
107
180
 
108
- const submitMessage = Effect.fnUntraced(function* (message: Message.Message) {
109
- pending.push(message);
110
- yield* observer.onMessage(message);
111
- yield* TracingService.emitConverationMessage(message);
112
- return message;
113
- });
181
+ const systemPrompt = yield* formatSystemPrompt({ system, blueprints, objects }).pipe(Effect.orDie);
114
182
 
115
- // Submit the prompt.
116
- // TODO(burdon): Remove if cancelled?
117
- const promptMessage = yield* submitMessage(yield* formatUserPrompt({ prompt, history }));
183
+ if (this._options.summarizationThreshold !== undefined) {
184
+ const tokenCount = yield* AiPreprocessor.estimateTokens(
185
+ yield* AiPreprocessor.preprocessPrompt([...this._history], {
186
+ system: systemPrompt,
187
+ }),
188
+ );
189
+ if (tokenCount > this._options.summarizationThreshold) {
190
+ const summary = yield* AiSummarizer.summarize([...this._history]);
191
+ yield* this._submitMessage(summary);
192
+ }
193
+ }
118
194
 
119
- // Generate system and prompt messages.
120
- const system = yield* formatSystemPrompt({ system: systemTemplate, blueprints, objects }).pipe(Effect.orDie);
195
+ yield* this._submitMessage(yield* formatUserPrompt({ prompt, history }));
196
+ });
121
197
 
122
- // log('system', { prompt: system });
198
+ /**
199
+ * Execute a single turn: one LLM generation followed by tool execution.
200
+ * The toolkit and system prompt can be updated between turns to reflect context changes (e.g. dynamically enabled blueprints).
201
+ */
202
+ runAgentTurn = <Tools extends Record<string, Tool.Any>>({
203
+ system,
204
+ toolkit,
205
+ }: AiSessionTurnProps<Tools>): Effect.Effect<AiSessionTurnResult, AiSessionRunError, AiSessionRunRequirements> =>
206
+ Effect.gen(this, function* () {
207
+ log('request', {
208
+ system: { snippet: createSnippet(system), length: system.length },
209
+ pending: this._pending.length,
210
+ history: this._history.length,
211
+ });
123
212
 
124
- // Tool call loop.
125
- do {
126
- log('request', {
127
- prompt: promptMessage,
128
- system: { snippet: createSnippet(system), length: system.length },
129
- pending: this._pending.length,
130
- history: this._history.length,
131
- objects: objects?.length ?? 0,
132
- });
213
+ const prompt = yield* AiPreprocessor.preprocessPrompt([...this._history, ...this._pending], {
214
+ system,
215
+ cacheControl: 'ephemeral',
216
+ });
133
217
 
134
- const prompt = yield* AiPreprocessor.preprocessPrompt([...this._history, ...this._pending], { system });
135
-
136
- // Execute the stream request.
137
- // logDump('prompt', Prompt.Prompt.pipe(Schema.encodeSync)(prompt));
138
- const blocks = yield* LanguageModel.streamText({
139
- prompt,
140
- toolkit,
141
- disableToolCallResolution: true,
142
- }).pipe(
143
- // TOOD(dmaretskyi): Error mapping.
144
- AiParser.parseResponse({
145
- onBegin: () => observer.onBegin(),
146
- onBlock: (block) => observer.onBlock(block),
147
- onPart: (part) => observer.onPart(part),
148
- onEnd: (summary) => observer.onEnd(summary),
149
- }),
150
- Stream.runCollect,
151
- Effect.map(Chunk.toArray),
218
+ const observer = this._observer;
219
+ let currentMessageId: Obj.ID | null = null; // Consistent IDs for pending blocks preceding the complete one.
220
+ const messages = yield* LanguageModel.streamText({
221
+ prompt,
222
+ toolkit,
223
+ disableToolCallResolution: true,
224
+ }).pipe(
225
+ withoutToolCallParising,
226
+ AiParser.parseResponse({
227
+ emitPartial: true,
228
+ onBegin: () => observer.onBegin(),
229
+ onBlock: (block) => observer.onBlock(block),
230
+ onPart: (part) => observer.onPart(part as any),
231
+ onEnd: (summary) => observer.onEnd(summary),
232
+ }),
233
+ Stream.mapEffect(
234
+ (block) =>
235
+ Effect.gen(this, function* () {
236
+ if (block.pending) {
237
+ currentMessageId ??= Obj.ID.random();
238
+ log('emit ephemeral message', { id: currentMessageId, type: block._tag });
239
+ yield* Trace.write(PartialBlock, {
240
+ messageId: currentMessageId,
241
+ role: 'assistant',
242
+ block,
243
+ });
244
+ return Option.none();
245
+ } else {
246
+ currentMessageId ??= Obj.ID.random();
247
+ const id = currentMessageId;
248
+ currentMessageId = null;
249
+ log('emit complete message', { id, type: block._tag });
250
+ const message = Obj.make(Message.Message, {
251
+ id,
252
+ created: new Date().toISOString(),
253
+ sender: { role: 'assistant' },
254
+ blocks: [block],
255
+ });
256
+ return Option.some(yield* this._submitMessage(message));
257
+ }
258
+ }),
259
+ { concurrency: 1, unordered: false },
260
+ ),
261
+ Stream.filterMap((_) => _),
262
+ Stream.runCollect,
263
+ Effect.map(Chunk.toArray),
264
+ );
265
+
266
+ const toolCalls = this.getToolCalls();
267
+
268
+ if (toolCalls.length === 0) {
269
+ this._ended = Date.now();
270
+ return { messages, done: true };
271
+ } else if (!toolkit) {
272
+ throw new Error('No toolkit provided');
273
+ }
274
+
275
+ return { messages, done: false };
276
+ });
277
+
278
+ runTools = <Tools extends Record<string, Tool.Any>>({ toolkit }: { toolkit?: Toolkit.WithHandler<Tools> }) =>
279
+ Effect.gen(this, function* () {
280
+ const toolCalls = this.getToolCalls();
281
+ // TODO(burdon): Retry errors? Write result when each completes individually?
282
+ const toolResults = yield* Effect.forEach(toolCalls, ({ block, message }) => {
283
+ if (!toolkit) {
284
+ throw new Error('No toolkit provided');
285
+ }
286
+ return callTool(toolkit, block).pipe(
287
+ Effect.provide(
288
+ TracingService.layerSubframe((context) => ({
289
+ ...context,
290
+ parentMessage: message.id,
291
+ toolCallId: block.toolCallId,
292
+ })),
293
+ ),
152
294
  );
295
+ });
153
296
 
154
- // log('blocks', { blocks });
297
+ // TODO(wittjosiah): Sometimes tool error results are added to the queue before the tool agent statuses.
298
+ // TODO(dmaretskyi): Stream tool results one by one.
299
+ yield* this._submitMessage(
300
+ Obj.make(Message.Message, {
301
+ created: new Date().toISOString(),
302
+ sender: { role: 'tool' },
303
+ blocks: toolResults,
304
+ }),
305
+ );
306
+
307
+ this._toolCalls += toolResults.length;
308
+ });
309
+ /**
310
+ * Run a full conversation turn loop. Equivalent to calling `begin()` then `runTurn()` in a loop.
311
+ */
312
+ run = <Tools extends Record<string, Tool.Any>>({
313
+ prompt,
314
+ system: systemTemplate,
315
+ history = [],
316
+ objects = [],
317
+ blueprints = [],
318
+ toolkit,
319
+ }: AiSessionRunProps<Tools>): Effect.Effect<Message.Message[], AiSessionRunError, AiSessionRunRequirements> =>
320
+ Effect.gen(this, function* () {
321
+ yield* this.begin({ prompt, system: systemTemplate, history, objects, blueprints });
155
322
 
156
- // Create the response message.
157
- const response = yield* submitMessage(
158
- Obj.make(Message.Message, {
159
- created: new Date().toISOString(),
160
- sender: { role: 'assistant' },
161
- blocks,
162
- }),
163
- );
323
+ const system = yield* formatSystemPrompt({ system: systemTemplate, blueprints, objects }).pipe(Effect.orDie);
164
324
 
165
- // Parse the response for tool calls.
166
- const toolCalls = getToolCalls(response);
167
- if (toolCalls.length === 0) {
325
+ do {
326
+ const { done } = yield* this.runAgentTurn({ system, toolkit });
327
+ if (done) {
168
328
  break;
169
- } else if (!toolkit) {
170
- throw new Error('No toolkit provided'); // TODO(burdon): Throw user error?
171
329
  }
172
-
173
- // Execute the tool calls.
174
- // TODO(burdon): Retry errors? Write result when each completes individually?
175
- const toolResults = yield* Effect.forEach(toolCalls, (toolCall) => {
176
- return callTool(toolkit, toolCall).pipe(
177
- Effect.provide(
178
- TracingService.layerSubframe((context) => ({
179
- ...context,
180
- parentMessage: response.id,
181
- toolCallId: toolCall.toolCallId,
182
- })),
183
- ),
184
- );
185
- });
186
-
187
- // Add to queue and continue loop.
188
- // TODO(wittjosiah): Sometimes tool error results are added to the queue before the tool agent statuses.
189
- // This results in a broken execution graph.
190
- yield* submitMessage(
191
- Obj.make(Message.Message, {
192
- created: new Date().toISOString(),
193
- sender: { role: 'tool' },
194
- blocks: toolResults,
195
- }),
196
- );
197
-
198
- this._toolCalls++;
330
+ yield* this.runTools({ toolkit });
199
331
  } while (true);
200
332
 
201
- this._ended = Date.now();
202
333
  log('done', { pending: this._pending.length, duration: this.duration, tools: this._toolCalls });
203
334
  return this._pending;
204
335
  }).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiSession.run'));
205
-
206
- /**
207
- * @deprecated
208
- */
209
- // TODO(burdon): Implement or remove.
210
- async runStructured<S extends Schema.Schema.AnyNoContext>(
211
- _schema: S,
212
- _options: AiSessionRunProps<any>,
213
- ): Promise<Schema.Schema.Type<S>> {
214
- return todo();
215
- // const parser = structuredOutputParser(schema);
216
- // const result = await this.run({
217
- // ...options,
218
- // executableTools: [...(options.executableTools ?? []), parser.tool],
219
- // });
220
- // return parser.getResult(result);
221
- }
222
336
  }
223
337
 
224
338
  const createSnippet = (text: string, len = 32) =>
@@ -6,13 +6,17 @@ import type * as Tool from '@effect/ai/Tool';
6
6
  import * as Toolkit from '@effect/ai/Toolkit';
7
7
  import * as Effect from 'effect/Effect';
8
8
 
9
- import { type AiToolNotFoundError, ToolExecutionService, ToolResolverService } from '@dxos/ai';
9
+ import { type AiToolNotFoundError, GenericToolkit, ToolExecutionService, ToolResolverService } from '@dxos/ai';
10
10
  import { type Blueprint } from '@dxos/blueprints';
11
11
  import { isTruthy } from '@dxos/util';
12
12
 
13
13
  export type CreateToolkitProps = {
14
14
  toolkit?: Toolkit.Any;
15
15
  blueprints?: readonly Blueprint.Blueprint[];
16
+ /**
17
+ * Self-contained with handlers toolkits.
18
+ */
19
+ genericToolkits?: readonly GenericToolkit.GenericToolkit[];
16
20
  };
17
21
 
18
22
  /**
@@ -21,6 +25,7 @@ export type CreateToolkitProps = {
21
25
  export const createToolkit = ({
22
26
  toolkit: toolkitProp,
23
27
  blueprints = [],
28
+ genericToolkits = [],
24
29
  }: CreateToolkitProps): Effect.Effect<
25
30
  Toolkit.WithHandler<any>,
26
31
  AiToolNotFoundError,
@@ -29,11 +34,11 @@ export const createToolkit = ({
29
34
  Effect.gen(function* () {
30
35
  const blueprintToolkit = yield* ToolResolverService.resolveToolkit(blueprints.flatMap(({ tools }) => tools));
31
36
  const blueprintToolHandler = yield* blueprintToolkit.toContext(ToolExecutionService.handlersFor(blueprintToolkit));
37
+ const genericToolkit = GenericToolkit.merge(...genericToolkits);
32
38
 
33
- const toolkit = Toolkit.merge(...[toolkitProp, blueprintToolkit].filter(isTruthy));
34
- return yield* toolkit.pipe(Effect.provide(blueprintToolHandler)) as any as Effect.Effect<
35
- Toolkit.WithHandler<any>,
36
- never,
37
- Tool.HandlersFor<any>
38
- >;
39
+ const toolkit = Toolkit.merge(...[toolkitProp, blueprintToolkit, genericToolkit.toolkit].filter(isTruthy));
40
+ return yield* toolkit.pipe(
41
+ Effect.provide(blueprintToolHandler),
42
+ Effect.provide(genericToolkit.layer),
43
+ ) as any as Effect.Effect<Toolkit.WithHandler<any>, never, Tool.HandlersFor<any>>;
39
44
  });
@@ -52,10 +52,6 @@ Do not use bullets when listing suggestions.
52
52
  You may ask multiple choice questions by wrapping consise options inside <option> tags inside a well formed <select> tag.
53
53
  Example: <select><option>Yes</option><option>No</option></select>
54
54
 
55
- ## Toolkit
56
-
57
- If the user asks for a list of tools, then just emit a single self-closing <toolkit/> tag instead of listing the tools.
58
-
59
55
  ## Context
60
56
 
61
57
  The current date and time is {{DATETIME}}.
@@ -43,6 +43,15 @@
43
43
  - Suggested actions could include actions that create artifacts.
44
44
  - After creating an artifact use a tool to add it to the chat context.
45
45
 
46
- ## Context
46
+ ## Navigation
47
+
48
+ - When the user asks to open, go to, navigate to, or show a specific document, page, or object, use the navigation tools instead of loading content inline.
49
+ - First, call the Resolve navigation targets tool to find the navigation path for the requested item.
50
+ - Without arguments, it returns available pages that can be navigated to.
51
+ - With a DXN in the query, it resolves that specific object to a navigation path.
52
+ - If you know the object's DXN (e.g. from a database query or context objects), pass it in the query to get the exact navigation path.
53
+ - Then, call the Open tool with the resolved navigation path(s) in the subject array to navigate the user to that item.
54
+ - Do not respond with the document's content when the user asks to open it — open it in the main content area instead.
55
+ - If multiple targets match, present the options to the user and let them choose which to open.
47
56
 
48
- Today is {{DATETIME}}.
57
+ ## Context
@@ -29,13 +29,14 @@ export const createSystemPrompt = (options: Partial<SystemPromptOptions> = {}) =
29
29
  }),
30
30
  );
31
31
 
32
+ /**
33
+ * NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.
34
+ */
35
+ const SYSTEM_ID = '01K2J2FZWH39F55CS7B26GP1Q3';
36
+
32
37
  export const templates = {
33
- /** Editable system prompt.*/
34
38
  system: Template.make({
35
- /**
36
- * NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.
37
- */
38
- id: '01K2J2FZWH39F55CS7B26GP1Q3',
39
+ id: SYSTEM_ID,
39
40
  source: SYSTEM,
40
41
  }),
41
42
  };