@jupyterlite/ai 0.8.1 → 0.9.0-a0

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 (162) hide show
  1. package/lib/agent.d.ts +233 -0
  2. package/lib/agent.js +604 -0
  3. package/lib/chat-model.d.ts +195 -0
  4. package/lib/chat-model.js +590 -0
  5. package/lib/completion/completion-provider.d.ts +83 -0
  6. package/lib/completion/completion-provider.js +209 -0
  7. package/lib/completion/index.d.ts +1 -0
  8. package/lib/completion/index.js +1 -0
  9. package/lib/components/clear-button.d.ts +18 -0
  10. package/lib/components/clear-button.js +31 -0
  11. package/lib/components/index.d.ts +3 -0
  12. package/lib/components/index.js +3 -0
  13. package/lib/components/model-select.d.ts +19 -0
  14. package/lib/components/model-select.js +154 -0
  15. package/lib/components/stop-button.d.ts +3 -3
  16. package/lib/components/stop-button.js +8 -9
  17. package/lib/components/token-usage-display.d.ts +45 -0
  18. package/lib/components/token-usage-display.js +74 -0
  19. package/lib/components/tool-select.d.ts +27 -0
  20. package/lib/components/tool-select.js +130 -0
  21. package/lib/icons.d.ts +3 -1
  22. package/lib/icons.js +10 -13
  23. package/lib/index.d.ts +4 -5
  24. package/lib/index.js +322 -167
  25. package/lib/mcp/browser.d.ts +68 -0
  26. package/lib/mcp/browser.js +132 -0
  27. package/lib/models/settings-model.d.ts +69 -0
  28. package/lib/models/settings-model.js +295 -0
  29. package/lib/providers/built-in-providers.d.ts +9 -0
  30. package/lib/providers/built-in-providers.js +192 -0
  31. package/lib/providers/models.d.ts +37 -0
  32. package/lib/providers/models.js +28 -0
  33. package/lib/providers/provider-registry.d.ts +94 -0
  34. package/lib/providers/provider-registry.js +155 -0
  35. package/lib/tokens.d.ts +157 -86
  36. package/lib/tokens.js +16 -12
  37. package/lib/tools/commands.d.ts +11 -0
  38. package/lib/tools/commands.js +126 -0
  39. package/lib/tools/file.d.ts +27 -0
  40. package/lib/tools/file.js +262 -0
  41. package/lib/tools/notebook.d.ts +40 -0
  42. package/lib/tools/notebook.js +762 -0
  43. package/lib/tools/tool-registry.d.ts +35 -0
  44. package/lib/tools/tool-registry.js +55 -0
  45. package/lib/widgets/ai-settings.d.ts +39 -0
  46. package/lib/widgets/ai-settings.js +506 -0
  47. package/lib/widgets/chat-wrapper.d.ts +144 -0
  48. package/lib/widgets/chat-wrapper.js +390 -0
  49. package/lib/widgets/provider-config-dialog.d.ts +13 -0
  50. package/lib/widgets/provider-config-dialog.js +104 -0
  51. package/package.json +150 -41
  52. package/schema/settings-model.json +153 -0
  53. package/src/agent.ts +800 -0
  54. package/src/chat-model.ts +770 -0
  55. package/src/completion/completion-provider.ts +308 -0
  56. package/src/completion/index.ts +1 -0
  57. package/src/components/clear-button.tsx +56 -0
  58. package/src/components/index.ts +3 -0
  59. package/src/components/model-select.tsx +245 -0
  60. package/src/components/stop-button.tsx +11 -11
  61. package/src/components/token-usage-display.tsx +130 -0
  62. package/src/components/tool-select.tsx +218 -0
  63. package/src/icons.ts +12 -14
  64. package/src/index.ts +468 -238
  65. package/src/mcp/browser.ts +213 -0
  66. package/src/models/settings-model.ts +409 -0
  67. package/src/providers/built-in-providers.ts +216 -0
  68. package/src/providers/models.ts +79 -0
  69. package/src/providers/provider-registry.ts +189 -0
  70. package/src/tokens.ts +203 -90
  71. package/src/tools/commands.ts +151 -0
  72. package/src/tools/file.ts +307 -0
  73. package/src/tools/notebook.ts +964 -0
  74. package/src/tools/tool-registry.ts +63 -0
  75. package/src/types.d.ts +4 -0
  76. package/src/widgets/ai-settings.tsx +1100 -0
  77. package/src/widgets/chat-wrapper.tsx +543 -0
  78. package/src/widgets/provider-config-dialog.tsx +256 -0
  79. package/style/base.css +335 -14
  80. package/style/icons/jupyternaut-lite.svg +1 -1
  81. package/lib/base-completer.d.ts +0 -49
  82. package/lib/base-completer.js +0 -14
  83. package/lib/chat-handler.d.ts +0 -56
  84. package/lib/chat-handler.js +0 -201
  85. package/lib/completion-provider.d.ts +0 -34
  86. package/lib/completion-provider.js +0 -32
  87. package/lib/default-prompts.d.ts +0 -2
  88. package/lib/default-prompts.js +0 -31
  89. package/lib/default-providers/Anthropic/completer.d.ts +0 -12
  90. package/lib/default-providers/Anthropic/completer.js +0 -46
  91. package/lib/default-providers/Anthropic/settings-schema.json +0 -70
  92. package/lib/default-providers/ChromeAI/completer.d.ts +0 -12
  93. package/lib/default-providers/ChromeAI/completer.js +0 -56
  94. package/lib/default-providers/ChromeAI/instructions.d.ts +0 -6
  95. package/lib/default-providers/ChromeAI/instructions.js +0 -42
  96. package/lib/default-providers/ChromeAI/settings-schema.json +0 -18
  97. package/lib/default-providers/Gemini/completer.d.ts +0 -12
  98. package/lib/default-providers/Gemini/completer.js +0 -48
  99. package/lib/default-providers/Gemini/instructions.d.ts +0 -2
  100. package/lib/default-providers/Gemini/instructions.js +0 -9
  101. package/lib/default-providers/Gemini/settings-schema.json +0 -64
  102. package/lib/default-providers/MistralAI/completer.d.ts +0 -13
  103. package/lib/default-providers/MistralAI/completer.js +0 -52
  104. package/lib/default-providers/MistralAI/instructions.d.ts +0 -2
  105. package/lib/default-providers/MistralAI/instructions.js +0 -18
  106. package/lib/default-providers/MistralAI/settings-schema.json +0 -75
  107. package/lib/default-providers/Ollama/completer.d.ts +0 -12
  108. package/lib/default-providers/Ollama/completer.js +0 -43
  109. package/lib/default-providers/Ollama/instructions.d.ts +0 -2
  110. package/lib/default-providers/Ollama/instructions.js +0 -70
  111. package/lib/default-providers/Ollama/settings-schema.json +0 -143
  112. package/lib/default-providers/OpenAI/completer.d.ts +0 -12
  113. package/lib/default-providers/OpenAI/completer.js +0 -43
  114. package/lib/default-providers/OpenAI/settings-schema.json +0 -628
  115. package/lib/default-providers/WebLLM/completer.d.ts +0 -21
  116. package/lib/default-providers/WebLLM/completer.js +0 -127
  117. package/lib/default-providers/WebLLM/instructions.d.ts +0 -6
  118. package/lib/default-providers/WebLLM/instructions.js +0 -32
  119. package/lib/default-providers/WebLLM/settings-schema.json +0 -19
  120. package/lib/default-providers/index.d.ts +0 -2
  121. package/lib/default-providers/index.js +0 -179
  122. package/lib/provider.d.ts +0 -144
  123. package/lib/provider.js +0 -412
  124. package/lib/settings/base.json +0 -7
  125. package/lib/settings/index.d.ts +0 -3
  126. package/lib/settings/index.js +0 -3
  127. package/lib/settings/panel.d.ts +0 -226
  128. package/lib/settings/panel.js +0 -510
  129. package/lib/settings/textarea.d.ts +0 -2
  130. package/lib/settings/textarea.js +0 -18
  131. package/lib/settings/utils.d.ts +0 -2
  132. package/lib/settings/utils.js +0 -4
  133. package/lib/types/ai-model.d.ts +0 -24
  134. package/lib/types/ai-model.js +0 -5
  135. package/schema/chat.json +0 -28
  136. package/schema/provider-registry.json +0 -29
  137. package/schema/system-prompts.json +0 -22
  138. package/src/base-completer.ts +0 -75
  139. package/src/chat-handler.ts +0 -262
  140. package/src/completion-provider.ts +0 -64
  141. package/src/default-prompts.ts +0 -33
  142. package/src/default-providers/Anthropic/completer.ts +0 -59
  143. package/src/default-providers/ChromeAI/completer.ts +0 -73
  144. package/src/default-providers/ChromeAI/instructions.ts +0 -45
  145. package/src/default-providers/Gemini/completer.ts +0 -61
  146. package/src/default-providers/Gemini/instructions.ts +0 -9
  147. package/src/default-providers/MistralAI/completer.ts +0 -69
  148. package/src/default-providers/MistralAI/instructions.ts +0 -18
  149. package/src/default-providers/Ollama/completer.ts +0 -54
  150. package/src/default-providers/Ollama/instructions.ts +0 -70
  151. package/src/default-providers/OpenAI/completer.ts +0 -54
  152. package/src/default-providers/WebLLM/completer.ts +0 -151
  153. package/src/default-providers/WebLLM/instructions.ts +0 -33
  154. package/src/default-providers/index.ts +0 -211
  155. package/src/global.d.ts +0 -9
  156. package/src/provider.ts +0 -514
  157. package/src/settings/index.ts +0 -3
  158. package/src/settings/panel.tsx +0 -773
  159. package/src/settings/textarea.tsx +0 -33
  160. package/src/settings/utils.ts +0 -5
  161. package/src/types/ai-model.ts +0 -37
  162. package/src/types/service-worker.d.ts +0 -6
package/src/agent.ts ADDED
@@ -0,0 +1,800 @@
1
+ import { ISignal, Signal } from '@lumino/signaling';
2
+ import {
3
+ Agent,
4
+ AgentInputItem,
5
+ Runner,
6
+ RunToolApprovalItem,
7
+ RunToolCallOutputItem,
8
+ StreamedRunResult,
9
+ user
10
+ } from '@openai/agents';
11
+
12
+ import { BrowserMCPServerStreamableHttp } from './mcp/browser';
13
+ import { AISettingsModel } from './models/settings-model';
14
+ import { createModel } from './providers/models';
15
+ import type { IChatProviderRegistry } from './tokens';
16
+ import { ITool, IToolRegistry, ITokenUsage } from './tokens';
17
+
18
+ /**
19
+ * Event type mapping for type safety with inlined interface definitions
20
+ */
21
+ export interface IAgentEventTypeMap {
22
+ message_start: {
23
+ messageId: string;
24
+ };
25
+ message_chunk: {
26
+ messageId: string;
27
+ chunk: string;
28
+ fullContent: string;
29
+ };
30
+ message_complete: {
31
+ messageId: string;
32
+ content: string;
33
+ };
34
+ tool_call_start: {
35
+ callId: string;
36
+ toolName: string;
37
+ input: any;
38
+ };
39
+ tool_call_complete: {
40
+ callId: string;
41
+ toolName: string;
42
+ output: any;
43
+ isError: boolean;
44
+ };
45
+ tool_approval_required: {
46
+ interruptionId: string;
47
+ toolName: string;
48
+ toolInput: any;
49
+ callId?: string;
50
+ };
51
+ grouped_approval_required: {
52
+ groupId: string;
53
+ approvals: Array<{
54
+ interruptionId: string;
55
+ toolName: string;
56
+ toolInput: any;
57
+ }>;
58
+ };
59
+ error: {
60
+ error: Error;
61
+ };
62
+ }
63
+
64
+ /**
65
+ * Events emitted by the AgentManager
66
+ */
67
+ export type IAgentEvent<
68
+ T extends keyof IAgentEventTypeMap = keyof IAgentEventTypeMap
69
+ > = T extends keyof IAgentEventTypeMap
70
+ ? {
71
+ type: T;
72
+ data: IAgentEventTypeMap[T];
73
+ }
74
+ : never;
75
+
76
+ /**
77
+ * Configuration options for the AgentManager
78
+ */
79
+ export interface IAgentManagerOptions {
80
+ /**
81
+ * AI settings model for configuration
82
+ */
83
+ settingsModel: AISettingsModel;
84
+
85
+ /**
86
+ * Optional tool registry for managing available tools
87
+ */
88
+ toolRegistry?: IToolRegistry;
89
+
90
+ /**
91
+ * Optional chat provider registry for model creation
92
+ */
93
+ chatProviderRegistry?: IChatProviderRegistry;
94
+ }
95
+
96
+ /**
97
+ * Manages the AI agent lifecycle and execution loop.
98
+ * Provides agent initialization, tool management, MCP server integration,
99
+ * and handles the complete agent execution cycle including tool approvals.
100
+ * Emits events for UI updates instead of directly manipulating the chat interface.
101
+ */
102
+ export class AgentManager {
103
+ /**
104
+ * Creates a new AgentManager instance.
105
+ * @param options Configuration options for the agent manager
106
+ */
107
+ constructor(options: IAgentManagerOptions) {
108
+ this._settingsModel = options.settingsModel;
109
+ this._toolRegistry = options.toolRegistry;
110
+ this._chatProviderRegistry = options.chatProviderRegistry;
111
+ this._selectedToolNames = [];
112
+ this._agent = null;
113
+ this._runner = new Runner({ tracingDisabled: true });
114
+ this._history = [];
115
+ this._mcpServers = [];
116
+ this._isInitializing = false;
117
+ this._controller = null;
118
+ this._pendingApprovals = new Map();
119
+ this._interruptedState = null;
120
+ this._agentEvent = new Signal<this, IAgentEvent>(this);
121
+ this._mcpConnectionChanged = new Signal<this, boolean>(this);
122
+ this._tokenUsage = { inputTokens: 0, outputTokens: 0 };
123
+ this._tokenUsageChanged = new Signal<this, ITokenUsage>(this);
124
+
125
+ // Initialize selected tools to all available tools by default
126
+ if (this._toolRegistry) {
127
+ this._selectedToolNames = Object.keys(this._toolRegistry.tools);
128
+ }
129
+
130
+ // Initialize agent on construction
131
+ this._initializeAgent().catch(error =>
132
+ console.warn('Failed to initialize agent in constructor:', error)
133
+ );
134
+
135
+ // Listen for settings changes
136
+ this._settingsModel.stateChanged.connect(this._onSettingsChanged, this);
137
+ }
138
+
139
+ /**
140
+ * Signal emitted when agent events occur
141
+ */
142
+ get agentEvent(): ISignal<this, IAgentEvent> {
143
+ return this._agentEvent;
144
+ }
145
+
146
+ /**
147
+ * Signal emitted when MCP connection status changes
148
+ */
149
+ get mcpConnectionChanged(): ISignal<this, boolean> {
150
+ return this._mcpConnectionChanged;
151
+ }
152
+
153
+ /**
154
+ * Gets the current token usage statistics.
155
+ */
156
+ get tokenUsage(): ITokenUsage {
157
+ return this._tokenUsage;
158
+ }
159
+
160
+ /**
161
+ * Signal emitted when token usage statistics change.
162
+ */
163
+ get tokenUsageChanged(): ISignal<this, ITokenUsage> {
164
+ return this._tokenUsageChanged;
165
+ }
166
+
167
+ /**
168
+ * Sets the selected tools by name and reinitializes the agent.
169
+ * @param toolNames Array of tool names to select
170
+ */
171
+ setSelectedTools(toolNames: string[]): void {
172
+ this._selectedToolNames = [...toolNames];
173
+ this._initializeAgent().catch(error =>
174
+ console.warn('Failed to initialize agent on tools change:', error)
175
+ );
176
+ }
177
+
178
+ /**
179
+ * Gets the currently selected tools as OpenAI agents tools.
180
+ * @returns Array of selected tools formatted for OpenAI agents
181
+ */
182
+ get selectedAgentTools(): ITool[] {
183
+ if (!this._toolRegistry) {
184
+ return [];
185
+ }
186
+
187
+ const result: ITool[] = [];
188
+ for (const name of this._selectedToolNames) {
189
+ const tool: ITool | null = this._toolRegistry.get(name);
190
+ if (tool) {
191
+ result.push(tool);
192
+ }
193
+ }
194
+
195
+ return result;
196
+ }
197
+
198
+ /**
199
+ * Checks if a specific MCP server is connected by server name.
200
+ * @param serverName The name of the MCP server to check
201
+ * @returns True if the server is connected, false otherwise
202
+ */
203
+ isMCPServerConnected(serverName: string): boolean {
204
+ return this._mcpServers.some(server => server.name === serverName);
205
+ }
206
+
207
+ /**
208
+ * Checks if the current configuration is valid for agent operations.
209
+ * Uses the provider registry to determine if an API key is required.
210
+ * @returns True if the configuration is valid, false otherwise
211
+ */
212
+ hasValidConfig(): boolean {
213
+ const activeProvider = this._settingsModel.getActiveProvider();
214
+ if (!activeProvider) {
215
+ return false;
216
+ }
217
+
218
+ if (!activeProvider.model) {
219
+ return false;
220
+ }
221
+
222
+ if (this._chatProviderRegistry) {
223
+ const providerInfo = this._chatProviderRegistry.getProviderInfo(
224
+ activeProvider.provider
225
+ );
226
+ if (providerInfo?.requiresApiKey) {
227
+ return !!activeProvider.apiKey;
228
+ }
229
+ }
230
+
231
+ return true;
232
+ }
233
+
234
+ /**
235
+ * Clears conversation history and resets agent state.
236
+ * Removes all conversation history, pending approvals, and interrupted state.
237
+ */
238
+ clearHistory(): void {
239
+ this._history = [];
240
+ this._runner = new Runner();
241
+ this._pendingApprovals.clear();
242
+ this._interruptedState = null;
243
+ // Reset token usage
244
+ this._tokenUsage = { inputTokens: 0, outputTokens: 0 };
245
+ this._tokenUsageChanged.emit(this._tokenUsage);
246
+ }
247
+
248
+ /**
249
+ * Stops the current streaming response by aborting the request.
250
+ */
251
+ stopStreaming(): void {
252
+ this._controller?.abort();
253
+ }
254
+
255
+ /**
256
+ * Generates AI response to user message using the agent.
257
+ * Handles the complete execution cycle including tool calls and approvals.
258
+ * @param message The user message to respond to (may include processed attachment content)
259
+ */
260
+ async generateResponse(message: string): Promise<void> {
261
+ const config = this._settingsModel.config;
262
+ this._controller = new AbortController();
263
+
264
+ try {
265
+ // Ensure we have an agent
266
+ if (!this._agent) {
267
+ await this._initializeAgent();
268
+ }
269
+
270
+ if (!this._agent) {
271
+ throw new Error('Failed to initialize agent');
272
+ }
273
+
274
+ const shouldUseTools =
275
+ config.toolsEnabled &&
276
+ this._selectedToolNames.length > 0 &&
277
+ this._toolRegistry &&
278
+ Object.keys(this._toolRegistry.tools).length > 0 &&
279
+ this._supportsToolCalling();
280
+
281
+ // Add user message to history
282
+ this._history.push(user(message));
283
+
284
+ // Main agentic loop
285
+ let result = await this._runner.run(this._agent, this._history, {
286
+ stream: true,
287
+ signal: this._controller.signal,
288
+ ...(shouldUseTools && { maxTurns: config.maxTurns })
289
+ });
290
+
291
+ await this._processRunResult(result);
292
+
293
+ let hasInterruptions =
294
+ result.interruptions && result.interruptions.length > 0;
295
+
296
+ while (hasInterruptions) {
297
+ this._interruptedState = result;
298
+ const interruptions = result.interruptions!;
299
+
300
+ if (interruptions.length > 1) {
301
+ await this._handleGroupedToolApprovals(interruptions);
302
+ } else {
303
+ await this._handleSingleToolApproval(interruptions[0]);
304
+ }
305
+
306
+ // Wait for all approvals to be resolved
307
+ while (this._pendingApprovals.size > 0) {
308
+ await new Promise(resolve => setTimeout(resolve, 100));
309
+ }
310
+
311
+ // Continue execution
312
+ result = await this._runner.run(this._agent!, result.state, {
313
+ stream: true,
314
+ signal: this._controller.signal,
315
+ maxTurns: config.maxTurns
316
+ });
317
+
318
+ await this._processRunResult(result);
319
+ hasInterruptions =
320
+ result.interruptions && result.interruptions.length > 0;
321
+ }
322
+
323
+ // Clear interrupted state
324
+ this._interruptedState = null;
325
+ this._history = result.history;
326
+ } catch (error) {
327
+ this._agentEvent.emit({
328
+ type: 'error',
329
+ data: { error: error as Error }
330
+ });
331
+ } finally {
332
+ this._controller = null;
333
+ }
334
+ }
335
+
336
+ /**
337
+ * Approves a tool call by interruption ID.
338
+ * @param interruptionId The interruption ID to approve
339
+ */
340
+ async approveToolCall(interruptionId: string): Promise<void> {
341
+ const pending = this._pendingApprovals.get(interruptionId);
342
+ if (!pending) {
343
+ console.warn(
344
+ `No pending approval found for interruption ${interruptionId}`
345
+ );
346
+ return;
347
+ }
348
+
349
+ if (this._interruptedState) {
350
+ this._interruptedState.state.approve(pending.interruption);
351
+ }
352
+
353
+ pending.approved = true;
354
+ this._pendingApprovals.delete(interruptionId);
355
+ }
356
+
357
+ /**
358
+ * Rejects a tool call by interruption ID.
359
+ * @param interruptionId The interruption ID to reject
360
+ */
361
+ async rejectToolCall(interruptionId: string): Promise<void> {
362
+ const pending = this._pendingApprovals.get(interruptionId);
363
+ if (!pending) {
364
+ console.warn(
365
+ `No pending approval found for interruption ${interruptionId}`
366
+ );
367
+ return;
368
+ }
369
+
370
+ if (this._interruptedState) {
371
+ this._interruptedState.state.reject(pending.interruption);
372
+ }
373
+
374
+ pending.approved = false;
375
+ this._pendingApprovals.delete(interruptionId);
376
+ }
377
+
378
+ /**
379
+ * Approves all tools in a group by group ID.
380
+ * @param groupId The group ID containing the tool calls
381
+ * @param interruptionIds Array of interruption IDs to approve
382
+ */
383
+ async approveGroupedToolCalls(
384
+ groupId: string,
385
+ interruptionIds: string[]
386
+ ): Promise<void> {
387
+ for (const interruptionId of interruptionIds) {
388
+ const pending = this._pendingApprovals.get(interruptionId);
389
+ if (pending && pending.groupId === groupId) {
390
+ if (this._interruptedState) {
391
+ this._interruptedState.state.approve(pending.interruption);
392
+ }
393
+ pending.approved = true;
394
+ this._pendingApprovals.delete(interruptionId);
395
+ }
396
+ }
397
+ }
398
+
399
+ /**
400
+ * Rejects all tools in a group by group ID.
401
+ * @param groupId The group ID containing the tool calls
402
+ * @param interruptionIds Array of interruption IDs to reject
403
+ */
404
+ async rejectGroupedToolCalls(
405
+ groupId: string,
406
+ interruptionIds: string[]
407
+ ): Promise<void> {
408
+ for (const interruptionId of interruptionIds) {
409
+ const pending = this._pendingApprovals.get(interruptionId);
410
+ if (pending && pending.groupId === groupId) {
411
+ if (this._interruptedState) {
412
+ this._interruptedState.state.reject(pending.interruption);
413
+ }
414
+ pending.approved = false;
415
+ this._pendingApprovals.delete(interruptionId);
416
+ }
417
+ }
418
+ }
419
+
420
+ /**
421
+ * Handles settings changes and reinitializes the agent.
422
+ */
423
+ private _onSettingsChanged(): void {
424
+ this._initializeAgent().catch(error =>
425
+ console.warn('Failed to initialize agent on settings change:', error)
426
+ );
427
+ }
428
+
429
+ /**
430
+ * Initializes the AI agent with current settings and tools.
431
+ * Sets up the agent with model configuration, tools, and MCP servers.
432
+ */
433
+ private async _initializeAgent(): Promise<void> {
434
+ if (this._isInitializing) {
435
+ return;
436
+ }
437
+ this._isInitializing = true;
438
+
439
+ try {
440
+ const config = this._settingsModel.config;
441
+ const model = this._createModel();
442
+
443
+ const shouldUseTools =
444
+ config.toolsEnabled &&
445
+ this._selectedToolNames.length > 0 &&
446
+ this._toolRegistry &&
447
+ Object.keys(this._toolRegistry.tools).length > 0 &&
448
+ this._supportsToolCalling();
449
+
450
+ await this._initializeMCPServers();
451
+
452
+ const tools = shouldUseTools ? this.selectedAgentTools : [];
453
+
454
+ const mcpServers = this._mcpServers.filter(server => server !== null);
455
+
456
+ this._agent = new Agent({
457
+ name: 'Assistant',
458
+ instructions: shouldUseTools
459
+ ? this._getEnhancedSystemPrompt(config.systemPrompt || '')
460
+ : config.systemPrompt || 'You are a helpful assistant.',
461
+ model: model,
462
+ mcpServers,
463
+ tools,
464
+ ...(config.temperature && {
465
+ modelSettings: {
466
+ temperature: config.temperature,
467
+ ...(config.maxTokens && { maxTokens: config.maxTokens })
468
+ }
469
+ })
470
+ });
471
+ } catch (error) {
472
+ console.warn('Failed to initialize agent:', error);
473
+ this._agent = null;
474
+ } finally {
475
+ this._isInitializing = false;
476
+ }
477
+ }
478
+
479
+ /**
480
+ * Initializes MCP (Model Context Protocol) servers based on current settings.
481
+ * Closes existing servers and connects to enabled servers from configuration.
482
+ */
483
+ private async _initializeMCPServers(): Promise<void> {
484
+ const config = this._settingsModel.config;
485
+ const enabledServers = config.mcpServers.filter(server => server.enabled);
486
+ let connectionChanged = false;
487
+
488
+ // Close existing servers
489
+ for (const server of this._mcpServers) {
490
+ try {
491
+ await server.close();
492
+ connectionChanged = true;
493
+ } catch (error) {
494
+ console.warn('Error closing MCP server:', error);
495
+ }
496
+ }
497
+ this._mcpServers = [];
498
+
499
+ // Initialize new servers
500
+ for (const serverConfig of enabledServers) {
501
+ try {
502
+ const mcpServer = new BrowserMCPServerStreamableHttp({
503
+ url: serverConfig.url,
504
+ name: serverConfig.name
505
+ });
506
+ await mcpServer.connect();
507
+ this._mcpServers.push(mcpServer);
508
+ connectionChanged = true;
509
+ } catch (error) {
510
+ console.warn(
511
+ `Failed to connect to MCP server "${serverConfig.name}" at ${serverConfig.url}:`,
512
+ error
513
+ );
514
+ }
515
+ }
516
+
517
+ // Emit connection change signal if there were any changes
518
+ if (connectionChanged) {
519
+ this._mcpConnectionChanged.emit(this._mcpServers.length > 0);
520
+ }
521
+ }
522
+
523
+ /**
524
+ * Processes the result stream from agent execution.
525
+ * Handles message streaming, tool calls, and emits appropriate events.
526
+ * @param result The async iterable result from agent execution
527
+ */
528
+ private async _processRunResult(
529
+ result: StreamedRunResult<any, any>
530
+ ): Promise<void> {
531
+ let fullResponse = '';
532
+ let currentMessageId: string | null = null;
533
+
534
+ for await (const event of result) {
535
+ if (event.type === 'raw_model_stream_event') {
536
+ const data = event.data;
537
+
538
+ if (data.type === 'response_started') {
539
+ currentMessageId = `msg-${Date.now()}-${Math.random()}`;
540
+ fullResponse = '';
541
+ this._agentEvent.emit({
542
+ type: 'message_start',
543
+ data: { messageId: currentMessageId }
544
+ });
545
+ } else if (data.type === 'output_text_delta') {
546
+ if (currentMessageId) {
547
+ const chunk = data.delta || '';
548
+ fullResponse += chunk;
549
+ this._agentEvent.emit({
550
+ type: 'message_chunk',
551
+ data: {
552
+ messageId: currentMessageId,
553
+ chunk,
554
+ fullContent: fullResponse
555
+ }
556
+ });
557
+ }
558
+ } else if (data.type === 'response_done') {
559
+ if (currentMessageId) {
560
+ this._agentEvent.emit({
561
+ type: 'message_complete',
562
+ data: {
563
+ messageId: currentMessageId,
564
+ content: fullResponse
565
+ }
566
+ });
567
+ currentMessageId = null;
568
+ }
569
+ } else if (data.type === 'model') {
570
+ const modelEvent = data.event as any;
571
+ if (modelEvent.type === 'tool-call') {
572
+ this._handleToolCallStart(modelEvent);
573
+ }
574
+ }
575
+ } else if (event.type === 'run_item_stream_event') {
576
+ if (event.name === 'tool_output') {
577
+ this._handleToolOutput(event);
578
+ }
579
+ }
580
+ }
581
+ }
582
+
583
+ /**
584
+ * Handles the start of a tool call from the model event.
585
+ * @param modelEvent The model event containing tool call information
586
+ */
587
+ private _handleToolCallStart(modelEvent: any): void {
588
+ const toolCallId = modelEvent.toolCallId;
589
+ const toolName = modelEvent.toolName;
590
+ const toolInput = modelEvent.input;
591
+ let parsedToolInput;
592
+ try {
593
+ parsedToolInput = JSON.parse(toolInput);
594
+ } catch (error) {
595
+ parsedToolInput = {};
596
+ }
597
+
598
+ this._agentEvent.emit({
599
+ type: 'tool_call_start',
600
+ data: {
601
+ callId: toolCallId,
602
+ toolName,
603
+ input: parsedToolInput
604
+ }
605
+ });
606
+ }
607
+
608
+ /**
609
+ * Handles tool execution output and completion.
610
+ * @param event The tool output event containing result information
611
+ */
612
+ private _handleToolOutput(event: any): void {
613
+ const toolEvent = event;
614
+ const toolCallOutput = toolEvent.item as RunToolCallOutputItem;
615
+ const callId = toolCallOutput.rawItem.callId;
616
+ const resultText =
617
+ typeof toolCallOutput.output === 'string'
618
+ ? toolCallOutput.output
619
+ : JSON.stringify(toolCallOutput.output, null, 2);
620
+
621
+ const isError =
622
+ toolCallOutput.rawItem.type === 'function_call_result' &&
623
+ (toolCallOutput.rawItem as any).error;
624
+
625
+ const toolName =
626
+ toolCallOutput.rawItem.type === 'function_call_result'
627
+ ? toolCallOutput.rawItem.name
628
+ : 'Unknown Tool';
629
+
630
+ this._agentEvent.emit({
631
+ type: 'tool_call_complete',
632
+ data: {
633
+ callId,
634
+ toolName,
635
+ output: resultText,
636
+ isError
637
+ }
638
+ });
639
+ }
640
+
641
+ /**
642
+ * Handles approval request for a single tool call.
643
+ * @param interruption The tool approval interruption item
644
+ */
645
+ private async _handleSingleToolApproval(
646
+ interruption: RunToolApprovalItem
647
+ ): Promise<void> {
648
+ const toolName = (interruption.rawItem as any)?.name || 'Unknown Tool';
649
+ const toolInput = (interruption.rawItem as any)?.arguments || {};
650
+ const interruptionId = `int-${Date.now()}-${Math.random()}`;
651
+ const callId = (interruption.rawItem as any)?.callId;
652
+
653
+ this._pendingApprovals.set(interruptionId, { interruption });
654
+
655
+ this._agentEvent.emit({
656
+ type: 'tool_approval_required',
657
+ data: {
658
+ interruptionId,
659
+ toolName,
660
+ toolInput,
661
+ callId
662
+ }
663
+ });
664
+ }
665
+
666
+ /**
667
+ * Handles approval requests for multiple grouped tool calls.
668
+ * @param interruptions Array of tool approval interruption items
669
+ */
670
+ private async _handleGroupedToolApprovals(
671
+ interruptions: RunToolApprovalItem[]
672
+ ): Promise<void> {
673
+ const groupId = `group-${Date.now()}-${Math.random()}`;
674
+ const approvals = interruptions.map(interruption => {
675
+ const toolName = (interruption.rawItem as any)?.name || 'Unknown Tool';
676
+ const toolInput = (interruption.rawItem as any)?.arguments || {};
677
+ const interruptionId = `int-${Date.now()}-${Math.random()}`;
678
+
679
+ this._pendingApprovals.set(interruptionId, { interruption, groupId });
680
+
681
+ return {
682
+ interruptionId,
683
+ toolName,
684
+ toolInput
685
+ };
686
+ });
687
+
688
+ this._agentEvent.emit({
689
+ type: 'grouped_approval_required',
690
+ data: {
691
+ groupId,
692
+ approvals
693
+ }
694
+ });
695
+ }
696
+
697
+ /**
698
+ * Checks if the current provider supports tool calling.
699
+ * @returns True if the provider supports tool calling, false otherwise
700
+ */
701
+ private _supportsToolCalling(): boolean {
702
+ const activeProvider = this._settingsModel.getActiveProvider();
703
+ if (!activeProvider || !this._chatProviderRegistry) {
704
+ return false;
705
+ }
706
+
707
+ const providerInfo = this._chatProviderRegistry.getProviderInfo(
708
+ activeProvider.provider
709
+ );
710
+
711
+ // Default to true if supportsToolCalling is not specified
712
+ return providerInfo?.supportsToolCalling !== false;
713
+ }
714
+
715
+ /**
716
+ * Creates a model instance based on current settings.
717
+ * @returns The configured model instance for the agent
718
+ */
719
+ private _createModel() {
720
+ const activeProvider = this._settingsModel.getActiveProvider();
721
+ if (!activeProvider) {
722
+ throw new Error('No active provider configured');
723
+ }
724
+ const provider = activeProvider.provider;
725
+ const model = activeProvider.model;
726
+ const apiKey = this._settingsModel.getApiKey(activeProvider.id);
727
+
728
+ return createModel(
729
+ {
730
+ provider,
731
+ model,
732
+ apiKey
733
+ },
734
+ this._chatProviderRegistry
735
+ );
736
+ }
737
+
738
+ /**
739
+ * Enhances the base system prompt with tool usage guidelines.
740
+ * @param baseSystemPrompt The base system prompt from settings
741
+ * @returns The enhanced system prompt with tool usage instructions
742
+ */
743
+ private _getEnhancedSystemPrompt(baseSystemPrompt: string): string {
744
+ const progressReportingPrompt = `
745
+
746
+ IMPORTANT: Follow this message flow pattern for better user experience:
747
+
748
+ 1. FIRST: Explain what you're going to do and your approach
749
+ 2. THEN: Execute tools (these will show automatically with step numbers)
750
+ 3. FINALLY: Provide a concise summary of what was accomplished
751
+
752
+ Example flow:
753
+ - "I'll help you create a notebook with example cells. Let me first create the file structure, then add Python and Markdown cells."
754
+ - [Tool executions happen with automatic step display]
755
+ - "Successfully created your notebook with 3 cells: a title, code example, and visualization cell."
756
+
757
+ Guidelines:
758
+ - Start responses with your plan/approach before tool execution
759
+ - Let the system handle tool execution display (don't duplicate details)
760
+ - End with a brief summary of accomplishments
761
+ - Use natural, conversational tone throughout
762
+
763
+ COMMAND DISCOVERY: When you want to execute JupyterLab commands, ALWAYS use the 'discover_commands' tool first to find available commands and their metadata. This ensures you have complete information about command IDs, descriptions, and required arguments before attempting to execute them. Only after discovering the available commands should you use the 'execute_command' tool with the correct command ID and arguments.
764
+
765
+ TOOL SELECTION GUIDELINES:
766
+ - For file operations (create, read, write, modify files and directories): Use dedicated file manipulation tools
767
+ - For general JupyterLab UI interactions (opening panels, running commands, navigating interface): Use the general command tool (execute_command)
768
+ - Examples of file operations: Creating notebooks, editing code files, managing project structure
769
+ - Examples of UI interactions: Opening terminal, switching tabs, running notebook cells, accessing menus
770
+
771
+ NOTEBOOK CELL CONTENT MANAGEMENT:
772
+ - After setting the content of a cell using the 'set_cell_content' tool, ALWAYS follow up by showing the cell diff
773
+ - First, use the 'discover_commands' tool to check for available commands that can show cell diffs (look for commands containing 'diff', 'show-cell-diff', or similar)
774
+ - Then use the 'execute_command' tool with the appropriate command ID to display the changes made to the cell
775
+ - This helps users visualize exactly what changed in their notebook cells and provides transparency about modifications`;
776
+
777
+ return baseSystemPrompt + progressReportingPrompt;
778
+ }
779
+
780
+ // Private attributes
781
+ private _settingsModel: AISettingsModel;
782
+ private _toolRegistry?: IToolRegistry;
783
+ private _chatProviderRegistry?: IChatProviderRegistry;
784
+ private _selectedToolNames: string[];
785
+ private _agent: Agent | null;
786
+ private _runner: Runner;
787
+ private _history: AgentInputItem[];
788
+ private _mcpServers: BrowserMCPServerStreamableHttp[];
789
+ private _isInitializing: boolean;
790
+ private _controller: AbortController | null;
791
+ private _pendingApprovals: Map<
792
+ string,
793
+ { interruption: RunToolApprovalItem; approved?: boolean; groupId?: string }
794
+ >;
795
+ private _interruptedState: any;
796
+ private _agentEvent: Signal<this, IAgentEvent>;
797
+ private _mcpConnectionChanged: Signal<this, boolean>;
798
+ private _tokenUsage: ITokenUsage;
799
+ private _tokenUsageChanged: Signal<this, ITokenUsage>;
800
+ }