@jupyterlite/ai 0.8.1 → 0.9.0-a1

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