@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
@@ -0,0 +1,591 @@
1
+ import { AbstractChatModel } from '@jupyter/chat';
2
+ import { UUID } from '@lumino/coreutils';
3
+ import { PathExt } from '@jupyterlab/coreutils';
4
+ import { AI_AVATAR } from './icons';
5
+ /**
6
+ * AI Chat Model implementation that provides chat functionality with OpenAI agents,
7
+ * tool integration, and MCP server support.
8
+ * Extends the base AbstractChatModel to provide AI-powered conversations.
9
+ */
10
+ export class AIChatModel extends AbstractChatModel {
11
+ /**
12
+ * Constructs a new AIChatModel instance.
13
+ * @param options Configuration options for the chat model
14
+ */
15
+ constructor(options) {
16
+ super({
17
+ activeCellManager: options.activeCellManager,
18
+ documentManager: options.documentManager,
19
+ config: {
20
+ enableCodeToolbar: true,
21
+ sendWithShiftEnter: options.settingsModel.config.sendWithShiftEnter
22
+ }
23
+ });
24
+ this._settingsModel = options.settingsModel;
25
+ this._user = options.user;
26
+ this._agentManager = options.agentManager;
27
+ // Listen for agent events
28
+ this._agentManager.agentEvent.connect(this._onAgentEvent, this);
29
+ // Listen for settings changes to update chat behavior
30
+ this._settingsModel.stateChanged.connect(this._onSettingsChanged, this);
31
+ this.setReady();
32
+ }
33
+ /**
34
+ * Gets the current user information.
35
+ */
36
+ get user() {
37
+ return this._user;
38
+ }
39
+ get tokenUsageChanged() {
40
+ return this._agentManager.tokenUsageChanged;
41
+ }
42
+ /**
43
+ * Creates a chat context for the current conversation.
44
+ */
45
+ createChatContext() {
46
+ return {
47
+ name: this.name,
48
+ user: { username: 'me' },
49
+ users: [],
50
+ messages: this.messages,
51
+ stopStreaming: () => this.stopStreaming(),
52
+ clearMessages: () => this.clearMessages(),
53
+ agentManager: this._agentManager
54
+ };
55
+ }
56
+ /**
57
+ * Stops the current streaming response by aborting the request.
58
+ */
59
+ stopStreaming = () => {
60
+ this._agentManager.stopStreaming();
61
+ };
62
+ /**
63
+ * Clears all messages from the chat and resets conversation state.
64
+ */
65
+ clearMessages = () => {
66
+ this.messagesDeleted(0, this.messages.length);
67
+ this._pendingToolCalls.clear();
68
+ this._agentManager.clearHistory();
69
+ };
70
+ /**
71
+ * Sends a message to the AI and generates a response.
72
+ * @param message The user message to send
73
+ */
74
+ async sendMessage(message) {
75
+ // Add user message to chat
76
+ const userMessage = {
77
+ body: message.body,
78
+ sender: this.user || { username: 'user', display_name: 'User' },
79
+ id: UUID.uuid4(),
80
+ time: Date.now() / 1000,
81
+ type: 'msg',
82
+ raw_time: false,
83
+ attachments: this.input.attachments
84
+ };
85
+ this.messageAdded(userMessage);
86
+ // Check if we have valid configuration
87
+ if (!this._agentManager.hasValidConfig()) {
88
+ const errorMessage = {
89
+ body: 'Please configure your AI settings first. Open the AI Settings to set your API key and model.',
90
+ sender: this._getAIUser(),
91
+ id: UUID.uuid4(),
92
+ time: Date.now() / 1000,
93
+ type: 'msg',
94
+ raw_time: false
95
+ };
96
+ this.messageAdded(errorMessage);
97
+ return;
98
+ }
99
+ try {
100
+ // Process attachments and add their content to the message
101
+ let enhancedMessage = message.body;
102
+ if (this.input.attachments.length > 0) {
103
+ const attachmentContents = await this._processAttachments(this.input.attachments);
104
+ if (attachmentContents.length > 0) {
105
+ enhancedMessage +=
106
+ '\n\n--- Attached Files ---\n' + attachmentContents.join('\n\n');
107
+ }
108
+ }
109
+ this.updateWriters([{ user: this._getAIUser() }]);
110
+ await this._agentManager.generateResponse(enhancedMessage);
111
+ // Clear attachments after processing
112
+ this.input.clearAttachments();
113
+ }
114
+ catch (error) {
115
+ const errorMessage = {
116
+ body: `Error generating AI response: ${error.message}`,
117
+ sender: this._getAIUser(),
118
+ id: UUID.uuid4(),
119
+ time: Date.now() / 1000,
120
+ type: 'msg',
121
+ raw_time: false
122
+ };
123
+ this.messageAdded(errorMessage);
124
+ }
125
+ finally {
126
+ this.updateWriters([]);
127
+ }
128
+ }
129
+ /**
130
+ * Approves a tool call and updates the UI accordingly.
131
+ * @param interruptionId The interruption ID to approve
132
+ * @param messageId Optional message ID for UI updates
133
+ */
134
+ async approveToolCall(interruptionId, messageId) {
135
+ await this._agentManager.approveToolCall(interruptionId);
136
+ // Update the tool call box to show "Approved" status
137
+ if (messageId) {
138
+ this._updateToolCallBoxStatus(messageId, 'Approved', true);
139
+ }
140
+ }
141
+ /**
142
+ * Rejects a tool call and updates the UI accordingly.
143
+ * @param interruptionId The interruption ID to reject
144
+ * @param messageId Optional message ID for UI updates
145
+ */
146
+ async rejectToolCall(interruptionId, messageId) {
147
+ await this._agentManager.rejectToolCall(interruptionId);
148
+ // Update the tool call box to show "Rejected" status
149
+ if (messageId) {
150
+ this._updateToolCallBoxStatus(messageId, 'Rejected', false);
151
+ }
152
+ }
153
+ /**
154
+ * Approves all tools in a group.
155
+ * @param groupId The group ID containing the tool calls
156
+ * @param interruptionIds Array of interruption IDs to approve
157
+ * @param messageId Optional message ID for UI updates
158
+ */
159
+ async approveGroupedToolCalls(groupId, interruptionIds, messageId) {
160
+ await this._agentManager.approveGroupedToolCalls(groupId, interruptionIds);
161
+ // Update the grouped approval message to show approved status
162
+ if (messageId) {
163
+ this._updateGroupedApprovalStatus(messageId, 'Tools approved', true);
164
+ }
165
+ }
166
+ /**
167
+ * Rejects all tools in a group.
168
+ * @param groupId The group ID containing the tool calls
169
+ * @param interruptionIds Array of interruption IDs to reject
170
+ * @param messageId Optional message ID for UI updates
171
+ */
172
+ async rejectGroupedToolCalls(groupId, interruptionIds, messageId) {
173
+ await this._agentManager.rejectGroupedToolCalls(groupId, interruptionIds);
174
+ // Update the grouped approval message to show rejected status
175
+ if (messageId) {
176
+ this._updateGroupedApprovalStatus(messageId, 'Tools rejected', false);
177
+ }
178
+ }
179
+ /**
180
+ * Gets the AI user information for system messages.
181
+ */
182
+ _getAIUser() {
183
+ return {
184
+ username: 'ai-assistant',
185
+ display_name: 'Jupyternaut',
186
+ initials: 'JN',
187
+ color: '#2196F3',
188
+ avatar_url: AI_AVATAR
189
+ };
190
+ }
191
+ /**
192
+ * Handles settings changes and updates chat configuration accordingly.
193
+ */
194
+ _onSettingsChanged() {
195
+ const config = this._settingsModel.config;
196
+ this.config = {
197
+ ...config,
198
+ enableCodeToolbar: true
199
+ };
200
+ // Agent manager handles agent recreation automatically via its own settings listener
201
+ }
202
+ /**
203
+ * Handles events emitted by the agent manager.
204
+ * @param event The event data containing type and payload
205
+ */
206
+ _onAgentEvent(_sender, event) {
207
+ switch (event.type) {
208
+ case 'message_start':
209
+ this._handleMessageStart(event);
210
+ break;
211
+ case 'message_chunk':
212
+ this._handleMessageChunk(event);
213
+ break;
214
+ case 'message_complete':
215
+ this._handleMessageComplete(event);
216
+ break;
217
+ case 'tool_call_start':
218
+ this._handleToolCallStartEvent(event);
219
+ break;
220
+ case 'tool_call_complete':
221
+ this._handleToolCallCompleteEvent(event);
222
+ break;
223
+ case 'tool_approval_required':
224
+ this._handleToolApprovalRequired(event);
225
+ break;
226
+ case 'grouped_approval_required':
227
+ this._handleGroupedApprovalRequired(event);
228
+ break;
229
+ case 'error':
230
+ this._handleErrorEvent(event);
231
+ break;
232
+ }
233
+ }
234
+ /**
235
+ * Handles the start of a new message from the AI agent.
236
+ * @param event Event containing the message start data
237
+ */
238
+ _handleMessageStart(event) {
239
+ const aiMessage = {
240
+ body: '',
241
+ sender: this._getAIUser(),
242
+ id: event.data.messageId,
243
+ time: Date.now() / 1000,
244
+ type: 'msg',
245
+ raw_time: false
246
+ };
247
+ this._currentStreamingMessage = aiMessage;
248
+ this.messageAdded(aiMessage);
249
+ }
250
+ /**
251
+ * Handles streaming message chunks from the AI agent.
252
+ * @param event Event containing the message chunk data
253
+ */
254
+ _handleMessageChunk(event) {
255
+ if (this._currentStreamingMessage &&
256
+ this._currentStreamingMessage.id === event.data.messageId) {
257
+ this._currentStreamingMessage.body = event.data.fullContent;
258
+ this.messageAdded(this._currentStreamingMessage);
259
+ }
260
+ }
261
+ /**
262
+ * Handles the completion of a message from the AI agent.
263
+ * @param event Event containing the message completion data
264
+ */
265
+ _handleMessageComplete(event) {
266
+ if (this._currentStreamingMessage &&
267
+ this._currentStreamingMessage.id === event.data.messageId) {
268
+ this._currentStreamingMessage.body = event.data.content;
269
+ this.messageAdded(this._currentStreamingMessage);
270
+ this._currentStreamingMessage = null;
271
+ }
272
+ }
273
+ /**
274
+ * Handles the start of a tool call execution.
275
+ * @param event Event containing the tool call start data
276
+ */
277
+ _handleToolCallStartEvent(event) {
278
+ const toolCallMessageId = UUID.uuid4();
279
+ const toolCallMessage = {
280
+ body: `<details class="jp-ai-tool-call jp-ai-tool-pending">
281
+ <summary class="jp-ai-tool-header">
282
+ <div class="jp-ai-tool-icon">⚡</div>
283
+ <div class="jp-ai-tool-title">${event.data.toolName}</div>
284
+ <div class="jp-ai-tool-status jp-ai-tool-status-pending">Running...</div>
285
+ </summary>
286
+ <div class="jp-ai-tool-body">
287
+ <div class="jp-ai-tool-section">
288
+ <div class="jp-ai-tool-label">Input</div>
289
+ <pre class="jp-ai-tool-code"><code>${JSON.stringify(event.data.input, null, 2)}</code></pre>
290
+ </div>
291
+ </div>
292
+ </details>`,
293
+ sender: this._getAIUser(),
294
+ id: toolCallMessageId,
295
+ time: Date.now() / 1000,
296
+ type: 'msg',
297
+ raw_time: false
298
+ };
299
+ if (event.data.callId) {
300
+ this._pendingToolCalls.set(event.data.callId, toolCallMessageId);
301
+ }
302
+ this.messageAdded(toolCallMessage);
303
+ }
304
+ /**
305
+ * Handles the completion of a tool call execution.
306
+ * @param event Event containing the tool call completion data
307
+ */
308
+ _handleToolCallCompleteEvent(event) {
309
+ const messageId = this._pendingToolCalls.get(event.data.callId);
310
+ if (messageId) {
311
+ const existingMessageIndex = this.messages.findIndex(msg => msg.id === messageId);
312
+ if (existingMessageIndex !== -1) {
313
+ const existingMessage = this.messages[existingMessageIndex];
314
+ const inputJson = existingMessage.body.match(/<code>([\s\S]*?)<\/code>/)?.[1] || '';
315
+ const statusClass = event.data.isError
316
+ ? 'jp-ai-tool-error'
317
+ : 'jp-ai-tool-completed';
318
+ const statusText = event.data.isError ? 'Error' : 'Completed';
319
+ const statusColor = event.data.isError
320
+ ? 'jp-ai-tool-status-error'
321
+ : 'jp-ai-tool-status-completed';
322
+ const updatedMessage = {
323
+ ...existingMessage,
324
+ body: `<details class="jp-ai-tool-call ${statusClass}">
325
+ <summary class="jp-ai-tool-header">
326
+ <div class="jp-ai-tool-icon">⚡</div>
327
+ <div class="jp-ai-tool-title">${event.data.toolName}</div>
328
+ <div class="jp-ai-tool-status ${statusColor}">${statusText}</div>
329
+ </summary>
330
+ <div class="jp-ai-tool-body">
331
+ <div class="jp-ai-tool-section">
332
+ <div class="jp-ai-tool-label">Input</div>
333
+ <pre class="jp-ai-tool-code"><code>${inputJson}</code></pre>
334
+ </div>
335
+ <div class="jp-ai-tool-section">
336
+ <div class="jp-ai-tool-label">${event.data.isError ? 'Error' : 'Result'}</div>
337
+ <pre class="jp-ai-tool-code"><code>${event.data.output}</code></pre>
338
+ </div>
339
+ </div>
340
+ </details>`
341
+ };
342
+ this.messageAdded(updatedMessage);
343
+ this._pendingToolCalls.delete(event.data.callId);
344
+ }
345
+ }
346
+ }
347
+ /**
348
+ * Handles tool approval requests from the AI agent.
349
+ * @param event Event containing the tool approval request data
350
+ */
351
+ _handleToolApprovalRequired(event) {
352
+ // Handle single tool approval - either update existing tool call message or create new approval message
353
+ if (event.data.callId) {
354
+ const messageId = this._pendingToolCalls.get(event.data.callId);
355
+ if (messageId) {
356
+ const existingMessageIndex = this.messages.findIndex(msg => msg.id === messageId);
357
+ if (existingMessageIndex !== -1) {
358
+ const existingMessage = this.messages[existingMessageIndex];
359
+ const assistantName = this._getAIUser().display_name;
360
+ const updatedMessage = {
361
+ ...existingMessage,
362
+ body: `<details class="jp-ai-tool-call jp-ai-tool-pending" open>
363
+ <summary class="jp-ai-tool-header">
364
+ <div class="jp-ai-tool-icon">⚡</div>
365
+ <div class="jp-ai-tool-title">${event.data.toolName}</div>
366
+ <div class="jp-ai-tool-status jp-ai-tool-status-pending">Needs Approval</div>
367
+ </summary>
368
+ <div class="jp-ai-tool-body">
369
+ <div class="jp-ai-tool-section">
370
+ <div class="jp-ai-tool-label">${assistantName} wants to execute this tool. Do you approve?</div>
371
+ <pre class="jp-ai-tool-code"><code>${JSON.stringify(event.data.toolInput, null, 2)}</code></pre>
372
+ </div>
373
+ [APPROVAL_BUTTONS:${event.data.interruptionId}]
374
+ </div>
375
+ </details>`
376
+ };
377
+ this.messageAdded(updatedMessage);
378
+ this.updateWriters([]);
379
+ return;
380
+ }
381
+ }
382
+ }
383
+ // Fallback: create separate approval message
384
+ const approvalMessageId = UUID.uuid4();
385
+ const assistantName = this._getAIUser().display_name;
386
+ const approvalMessage = {
387
+ body: `**🤖 Tool Approval Required: ${event.data.toolName}**
388
+
389
+ ${assistantName} wants to execute this tool. Do you approve?
390
+
391
+ ${JSON.stringify(event.data.toolInput, null, 2)}
392
+
393
+ [APPROVAL_BUTTONS:${event.data.interruptionId}]`,
394
+ sender: this._getAIUser(),
395
+ id: approvalMessageId,
396
+ time: Date.now() / 1000,
397
+ type: 'msg',
398
+ raw_time: false
399
+ };
400
+ this.messageAdded(approvalMessage);
401
+ this.updateWriters([]); // Stop showing "AI is writing"
402
+ }
403
+ /**
404
+ * Handles grouped tool approval requests from the AI agent.
405
+ * @param event Event containing the grouped tool approval request data
406
+ */
407
+ _handleGroupedApprovalRequired(event) {
408
+ const assistantName = this._getAIUser().display_name;
409
+ const approvalMessageId = UUID.uuid4();
410
+ const toolsList = event.data.approvals
411
+ .map((info, index) => `**${index + 1}. ${info.toolName}**\n${JSON.stringify(info.toolInput, null, 2)}\n`)
412
+ .join('\n\n');
413
+ const approvalMessage = {
414
+ body: `**🤖 Multiple Tool Approvals Required**
415
+
416
+ ${assistantName} wants to execute ${event.data.approvals.length} tools. Do you approve?
417
+
418
+ ${toolsList}
419
+
420
+ [GROUP_APPROVAL_BUTTONS:${event.data.groupId}:${event.data.approvals.map(info => info.interruptionId).join(',')}]`,
421
+ sender: this._getAIUser(),
422
+ id: approvalMessageId,
423
+ time: Date.now() / 1000,
424
+ type: 'msg',
425
+ raw_time: false
426
+ };
427
+ this.messageAdded(approvalMessage);
428
+ this.updateWriters([]); // Stop showing "AI is writing"
429
+ }
430
+ /**
431
+ * Handles error events from the AI agent.
432
+ * @param event Event containing the error information
433
+ */
434
+ _handleErrorEvent(event) {
435
+ const errorMessage = {
436
+ body: `Error generating response: ${event.data.error.message}`,
437
+ sender: this._getAIUser(),
438
+ id: UUID.uuid4(),
439
+ time: Date.now() / 1000,
440
+ type: 'msg',
441
+ raw_time: false
442
+ };
443
+ this.messageAdded(errorMessage);
444
+ }
445
+ /**
446
+ * Processes file attachments and returns their content as formatted strings.
447
+ * @param attachments Array of file attachments to process
448
+ * @returns Array of formatted attachment contents
449
+ */
450
+ async _processAttachments(attachments) {
451
+ const contents = [];
452
+ for (const attachment of attachments) {
453
+ try {
454
+ const fileContent = await this._readFileAttachment(attachment);
455
+ if (fileContent) {
456
+ // Get file extension for syntax highlighting
457
+ const fileExtension = PathExt.extname(attachment.value).toLowerCase();
458
+ const language = fileExtension === '.ipynb' ? 'json' : '';
459
+ contents.push(`**File: ${attachment.value}**\n\`\`\`${language}\n${fileContent}\n\`\`\``);
460
+ }
461
+ }
462
+ catch (error) {
463
+ console.warn(`Failed to read attachment ${attachment.value}:`, error);
464
+ contents.push(`**File: ${attachment.value}** (Could not read file)`);
465
+ }
466
+ }
467
+ return contents;
468
+ }
469
+ /**
470
+ * Reads the content of a file attachment.
471
+ * @param attachment The file attachment to read
472
+ * @returns File content as string or null if unable to read
473
+ */
474
+ async _readFileAttachment(attachment) {
475
+ // Handle both 'file' and 'notebook' types since both have a 'value' path
476
+ if (attachment.type !== 'file' && attachment.type !== 'notebook') {
477
+ return null;
478
+ }
479
+ try {
480
+ const model = await this.input.documentManager?.services.contents.get(attachment.value);
481
+ if (!model?.content) {
482
+ return null;
483
+ }
484
+ if (model.type === 'file') {
485
+ // Regular file content
486
+ return model.content;
487
+ }
488
+ else if (model.type === 'notebook') {
489
+ // Clear outputs from notebook cells before sending to LLM
490
+ // TODO: make this configurable?
491
+ const cells = model.content.cells.map((cell) => {
492
+ const cleanCell = { ...cell };
493
+ if (cleanCell.outputs) {
494
+ cleanCell.outputs = [];
495
+ }
496
+ if (cleanCell.execution_count) {
497
+ cleanCell.execution_count = null;
498
+ }
499
+ return cleanCell;
500
+ });
501
+ const notebookModel = {
502
+ cells,
503
+ metadata: model.metadata || {},
504
+ nbformat: model.nbformat || 4,
505
+ nbformat_minor: model.nbformat_minor || 4
506
+ };
507
+ return JSON.stringify(notebookModel);
508
+ }
509
+ return null;
510
+ }
511
+ catch (error) {
512
+ console.warn(`Failed to read file ${attachment.value}:`, error);
513
+ return null;
514
+ }
515
+ }
516
+ /**
517
+ * Updates the status display of a grouped approval message.
518
+ * @param messageId The message ID to update
519
+ * @param status The status text to display
520
+ * @param isSuccess Whether the action was successful
521
+ */
522
+ _updateGroupedApprovalStatus(messageId, status, isSuccess) {
523
+ const existingMessageIndex = this.messages.findIndex(msg => msg.id === messageId);
524
+ if (existingMessageIndex !== -1) {
525
+ const existingMessage = this.messages[existingMessageIndex];
526
+ // Extract tool count and names from existing message
527
+ const toolCountMatch = existingMessage.body.match(/execute (\d+) tools/);
528
+ const toolCount = toolCountMatch ? toolCountMatch[1] : 'multiple';
529
+ const statusIcon = isSuccess ? '✅' : '❌';
530
+ const statusClass = isSuccess ? 'approved' : 'rejected';
531
+ const updatedMessage = {
532
+ ...existingMessage,
533
+ body: `**${statusIcon} Group Tool Approval: ${status}**
534
+
535
+ The request to execute ${toolCount} tools has been **${statusClass}**.
536
+
537
+ <div class="jp-ai-group-approval-${statusClass}">
538
+ Status: ${status}
539
+ </div>`
540
+ };
541
+ this.messageAdded(updatedMessage);
542
+ }
543
+ }
544
+ /**
545
+ * Updates the status display of a tool call box.
546
+ * @param messageId The message ID to update
547
+ * @param status The status text to display
548
+ * @param isSuccess Whether the action was successful
549
+ */
550
+ _updateToolCallBoxStatus(messageId, status, isSuccess) {
551
+ const existingMessageIndex = this.messages.findIndex(msg => msg.id === messageId);
552
+ if (existingMessageIndex !== -1) {
553
+ const existingMessage = this.messages[existingMessageIndex];
554
+ // Extract tool name and input from existing message
555
+ const toolNameMatch = existingMessage.body.match(/<div class="jp-ai-tool-title">([^<]+)<\/div>/);
556
+ const toolName = toolNameMatch ? toolNameMatch[1] : 'Unknown Tool';
557
+ const codeMatch = existingMessage.body.match(/<code>([\s\S]*?)<\/code>/);
558
+ const toolInput = codeMatch ? codeMatch[1] : '{}';
559
+ // Determine styling based on status
560
+ const statusClass = isSuccess
561
+ ? 'jp-ai-tool-completed'
562
+ : 'jp-ai-tool-error';
563
+ const statusColor = isSuccess
564
+ ? 'jp-ai-tool-status-completed'
565
+ : 'jp-ai-tool-status-error';
566
+ const updatedMessage = {
567
+ ...existingMessage,
568
+ body: `<details class="jp-ai-tool-call ${statusClass}">
569
+ <summary class="jp-ai-tool-header">
570
+ <div class="jp-ai-tool-icon">⚡</div>
571
+ <div class="jp-ai-tool-title">${toolName}</div>
572
+ <div class="jp-ai-tool-status ${statusColor}">${status}</div>
573
+ </summary>
574
+ <div class="jp-ai-tool-body">
575
+ <div class="jp-ai-tool-section">
576
+ <div class="jp-ai-tool-label">Input</div>
577
+ <pre class="jp-ai-tool-code"><code>${toolInput}</code></pre>
578
+ </div>
579
+ </div>
580
+ </details>`
581
+ };
582
+ this.messageAdded(updatedMessage);
583
+ }
584
+ }
585
+ // Private fields
586
+ _settingsModel;
587
+ _user;
588
+ _pendingToolCalls = new Map();
589
+ _agentManager;
590
+ _currentStreamingMessage = null;
591
+ }
@@ -0,0 +1,93 @@
1
+ import { CompletionHandler, IInlineCompletionContext, IInlineCompletionList, IInlineCompletionProvider } from '@jupyterlab/completer';
2
+ import { ISecretsManager } from 'jupyter-secrets-manager';
3
+ import { AISettingsModel } from '../models/settings-model';
4
+ import { type ICompletionProviderRegistry } from '../tokens';
5
+ /**
6
+ * Configuration interface for provider-specific completion behavior
7
+ */
8
+ export interface IProviderCompletionConfig {
9
+ /**
10
+ * Temperature setting for the provider
11
+ */
12
+ temperature?: number;
13
+ /**
14
+ * Whether the provider supports fill-in-the-middle completion
15
+ */
16
+ supportsFillInMiddle?: boolean;
17
+ /**
18
+ * Whether to set filterText for this provider
19
+ */
20
+ useFilterText?: boolean;
21
+ /**
22
+ * Custom prompt formatter for provider-specific requirements
23
+ */
24
+ customPromptFormat?: (prompt: string, suffix: string) => string;
25
+ /**
26
+ * Function to clean up provider-specific artifacts from completion text
27
+ */
28
+ cleanupCompletion?: (completion: string) => string;
29
+ }
30
+ /**
31
+ * The generic completion provider to register to the completion provider manager.
32
+ */
33
+ export declare class AICompletionProvider implements IInlineCompletionProvider {
34
+ /**
35
+ * Construct a new completion provider.
36
+ */
37
+ constructor(options: AICompletionProvider.IOptions);
38
+ /**
39
+ * The unique identifier of the provider.
40
+ */
41
+ readonly identifier = "@jupyterlite/ai:completer";
42
+ /**
43
+ * Get the current completer name based on settings.
44
+ */
45
+ get name(): string;
46
+ /**
47
+ * Get the system prompt for the completion.
48
+ */
49
+ get systemPrompt(): string;
50
+ /**
51
+ * Fetch completion items based on the request and context.
52
+ */
53
+ fetch(request: CompletionHandler.IRequest, context: IInlineCompletionContext): Promise<IInlineCompletionList>;
54
+ /**
55
+ * Update the language model based on current settings.
56
+ */
57
+ private _updateModel;
58
+ /**
59
+ * Extract context from notebook cells
60
+ */
61
+ private _extractNotebookContext;
62
+ /**
63
+ * Get provider-specific completion configuration from registry
64
+ */
65
+ private _getProviderCompletionConfig;
66
+ private _settingsModel;
67
+ private _completionProviderRegistry?;
68
+ private _model;
69
+ private _secretsManager?;
70
+ }
71
+ export declare namespace AICompletionProvider {
72
+ /**
73
+ * The options for the constructor of the completion provider.
74
+ */
75
+ interface IOptions {
76
+ /**
77
+ * The AI settings model.
78
+ */
79
+ settingsModel: AISettingsModel;
80
+ /**
81
+ * The completion provider registry.
82
+ */
83
+ completionProviderRegistry?: ICompletionProviderRegistry;
84
+ /**
85
+ * The secrets manager.
86
+ */
87
+ secretsManager?: ISecretsManager;
88
+ /**
89
+ * The token used to request the secrets manager.
90
+ */
91
+ token: symbol;
92
+ }
93
+ }