@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,779 @@
1
+ import { CodeCell, MarkdownCell } from '@jupyterlab/cells';
2
+ import { DocumentWidget } from '@jupyterlab/docregistry';
3
+ import { NotebookPanel } from '@jupyterlab/notebook';
4
+ import { tool } from '@openai/agents';
5
+ import { z } from 'zod';
6
+ /**
7
+ * Find a kernel name that matches the specified language
8
+ */
9
+ async function findKernelByLanguage(kernelSpecManager, language) {
10
+ try {
11
+ await kernelSpecManager.ready;
12
+ const specs = kernelSpecManager.specs;
13
+ if (!specs || !specs.kernelspecs) {
14
+ return 'python3'; // Final fallback
15
+ }
16
+ // If no language specified, return the default kernel
17
+ if (!language) {
18
+ return specs.default || Object.keys(specs.kernelspecs)[0] || 'python3';
19
+ }
20
+ // Normalize the language name for comparison
21
+ const normalizedLanguage = language.toLowerCase().trim();
22
+ // Find kernels that match the requested language
23
+ for (const [kernelName, kernelSpec] of Object.entries(specs.kernelspecs)) {
24
+ if (!kernelSpec) {
25
+ continue;
26
+ }
27
+ const kernelLanguage = kernelSpec.language?.toLowerCase() || '';
28
+ // Direct language match
29
+ if (kernelLanguage === normalizedLanguage) {
30
+ return kernelName;
31
+ }
32
+ }
33
+ // No matching kernel found, return default
34
+ console.warn(`No kernel found for language '${language}', using default`);
35
+ return specs.default || Object.keys(specs.kernelspecs)[0] || 'python3';
36
+ }
37
+ catch (error) {
38
+ console.warn('Failed to find kernel by language:', error);
39
+ return 'python3';
40
+ }
41
+ }
42
+ /**
43
+ * Helper function to get a notebook widget by path or use the active one
44
+ */
45
+ async function getNotebookWidget(notebookPath, docManager, notebookTracker) {
46
+ if (notebookPath) {
47
+ // Open specific notebook by path using document manager
48
+ let widget = docManager.findWidget(notebookPath);
49
+ if (!widget) {
50
+ widget = docManager.openOrReveal(notebookPath);
51
+ }
52
+ if (!(widget instanceof NotebookPanel)) {
53
+ throw new Error(`Widget for ${notebookPath} is not a notebook panel`);
54
+ }
55
+ return widget ?? null;
56
+ }
57
+ else {
58
+ // Use current active notebook
59
+ return notebookTracker?.currentWidget || null;
60
+ }
61
+ }
62
+ /**
63
+ * Create a notebook creation tool
64
+ */
65
+ export function createNotebookCreationTool(docManager, kernelSpecManager) {
66
+ return tool({
67
+ name: 'create_notebook',
68
+ description: 'Create a new Jupyter notebook with a kernel for the specified programming language',
69
+ parameters: z.object({
70
+ language: z
71
+ .string()
72
+ .optional()
73
+ .nullable()
74
+ .describe('The programming language for the notebook (e.g., python, r, julia, javascript, etc.). Will use system default if not specified.'),
75
+ name: z
76
+ .string()
77
+ .optional()
78
+ .nullable()
79
+ .describe('Optional name for the notebook file (without .ipynb extension)')
80
+ }),
81
+ execute: async (input) => {
82
+ const kernel = await findKernelByLanguage(kernelSpecManager, input.language);
83
+ const { name } = input;
84
+ if (!name) {
85
+ throw new Error('A name must be provided to create a notebook');
86
+ }
87
+ try {
88
+ // TODO: handle cwd / path?
89
+ const fileName = name.endsWith('.ipynb') ? name : `${name}.ipynb`;
90
+ // Create untitled notebook first
91
+ const notebookModel = await docManager.newUntitled({
92
+ type: 'notebook'
93
+ });
94
+ // Rename to desired filename
95
+ await docManager.services.contents.rename(notebookModel.path, fileName);
96
+ // Create widget with specific kernel
97
+ const notebook = docManager.createNew(fileName, 'default', {
98
+ name: kernel
99
+ });
100
+ if (!(notebook instanceof DocumentWidget)) {
101
+ throw new Error('Failed to create notebook widget');
102
+ }
103
+ await notebook.context.ready;
104
+ await notebook.context.save();
105
+ docManager.openOrReveal(fileName);
106
+ return {
107
+ success: true,
108
+ message: `Successfully created notebook ${fileName} with ${kernel} kernel${input.language ? ` for ${input.language}` : ''}`,
109
+ notebookPath: fileName,
110
+ notebookName: fileName,
111
+ kernel,
112
+ language: input.language
113
+ };
114
+ }
115
+ catch (error) {
116
+ return {
117
+ success: false,
118
+ error: `Failed to create notebook: ${error.message}`
119
+ };
120
+ }
121
+ }
122
+ });
123
+ }
124
+ /**
125
+ * Create a tool for adding cells to a specific notebook
126
+ */
127
+ export function createAddCellTool(docManager, notebookTracker) {
128
+ return tool({
129
+ name: 'add_cell',
130
+ description: 'Add a cell to the current notebook with optional content',
131
+ parameters: z.object({
132
+ notebookPath: z
133
+ .string()
134
+ .optional()
135
+ .nullable()
136
+ .describe('Path to the notebook file. If not provided, uses the currently active notebook'),
137
+ content: z
138
+ .string()
139
+ .optional()
140
+ .nullable()
141
+ .describe('Content to add to the cell'),
142
+ cellType: z
143
+ .enum(['code', 'markdown', 'raw'])
144
+ .default('code')
145
+ .describe('Type of cell to add'),
146
+ position: z
147
+ .enum(['above', 'below'])
148
+ .default('below')
149
+ .describe('Position relative to current cell')
150
+ }),
151
+ async execute({ notebookPath, content, cellType = 'code', position = 'below' }) {
152
+ try {
153
+ const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
154
+ if (!currentWidget) {
155
+ return {
156
+ success: false,
157
+ error: notebookPath
158
+ ? `Failed to open notebook at path: ${notebookPath}`
159
+ : 'No active notebook and no notebook path provided'
160
+ };
161
+ }
162
+ const notebook = currentWidget.content;
163
+ const model = notebook.model;
164
+ if (!model) {
165
+ return {
166
+ success: false,
167
+ error: 'No notebook model available'
168
+ };
169
+ }
170
+ // Check if we should replace the first empty cell instead of adding
171
+ const shouldReplaceFirstCell = model.cells.length === 1 &&
172
+ model.cells.get(0).sharedModel.getSource().trim() === '';
173
+ if (shouldReplaceFirstCell) {
174
+ // Replace the first empty cell by removing it and adding new one
175
+ model.sharedModel.deleteCell(0);
176
+ }
177
+ // Create the new cell using shared model
178
+ const newCellData = {
179
+ cell_type: cellType,
180
+ source: content || '',
181
+ metadata: cellType === 'code' ? { trusted: true } : {}
182
+ };
183
+ model.sharedModel.addCell(newCellData);
184
+ // Execute markdown cells after creation to render them
185
+ if (cellType === 'markdown' && content) {
186
+ const cellIndex = model.cells.length - 1;
187
+ const cellWidget = notebook.widgets[cellIndex];
188
+ if (cellWidget && cellWidget instanceof MarkdownCell) {
189
+ try {
190
+ await cellWidget.ready;
191
+ cellWidget.rendered = true;
192
+ }
193
+ catch (error) {
194
+ console.warn('Failed to render markdown cell:', error);
195
+ }
196
+ }
197
+ }
198
+ return {
199
+ success: true,
200
+ message: `${cellType} cell added successfully`,
201
+ content: content || '',
202
+ cellType,
203
+ position
204
+ };
205
+ }
206
+ catch (error) {
207
+ return {
208
+ success: false,
209
+ error: `Failed to add ${cellType} cell: ${error.message}`
210
+ };
211
+ }
212
+ }
213
+ });
214
+ }
215
+ /**
216
+ * Create a tool for getting notebook information
217
+ */
218
+ export function createGetNotebookInfoTool(docManager, notebookTracker) {
219
+ return tool({
220
+ name: 'get_notebook_info',
221
+ description: 'Get information about a notebook including number of cells and active cell index',
222
+ parameters: z.object({
223
+ notebookPath: z
224
+ .string()
225
+ .optional()
226
+ .nullable()
227
+ .describe('Path to the notebook file. If not provided, uses the currently active notebook')
228
+ }),
229
+ execute: async (input) => {
230
+ const { notebookPath } = input;
231
+ try {
232
+ const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
233
+ if (!currentWidget) {
234
+ return JSON.stringify({
235
+ success: false,
236
+ error: notebookPath
237
+ ? `Failed to open notebook at path: ${notebookPath}`
238
+ : 'No active notebook and no notebook path provided'
239
+ });
240
+ }
241
+ const notebook = currentWidget.content;
242
+ const model = notebook.model;
243
+ if (!model) {
244
+ return JSON.stringify({
245
+ success: false,
246
+ error: 'No notebook model available'
247
+ });
248
+ }
249
+ const cellCount = model.cells.length;
250
+ const activeCellIndex = notebook.activeCellIndex;
251
+ const activeCell = notebook.activeCell;
252
+ const activeCellType = activeCell?.model.type || 'unknown';
253
+ return JSON.stringify({
254
+ success: true,
255
+ notebookName: currentWidget.title.label,
256
+ notebookPath: currentWidget.context.path,
257
+ cellCount,
258
+ activeCellIndex,
259
+ activeCellType,
260
+ isDirty: model.dirty
261
+ });
262
+ }
263
+ catch (error) {
264
+ return JSON.stringify({
265
+ success: false,
266
+ error: `Failed to get notebook info: ${error.message}`
267
+ });
268
+ }
269
+ }
270
+ });
271
+ }
272
+ /**
273
+ * Create a tool for getting cell information by index
274
+ */
275
+ export function createGetCellInfoTool(docManager, notebookTracker) {
276
+ return tool({
277
+ name: 'get_cell_info',
278
+ description: 'Get information about a specific cell including its type, source content, and outputs',
279
+ parameters: z.object({
280
+ notebookPath: z
281
+ .string()
282
+ .optional()
283
+ .nullable()
284
+ .describe('Path to the notebook file. If not provided, uses the currently active notebook'),
285
+ cellIndex: z
286
+ .number()
287
+ .optional()
288
+ .nullable()
289
+ .describe('Index of the cell to get information for (0-based). If not provided, uses the currently active cell')
290
+ }),
291
+ execute: async (input) => {
292
+ const { notebookPath } = input;
293
+ let { cellIndex } = input;
294
+ try {
295
+ const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
296
+ if (!currentWidget) {
297
+ return JSON.stringify({
298
+ success: false,
299
+ error: notebookPath
300
+ ? `Failed to open notebook at path: ${notebookPath}`
301
+ : 'No active notebook and no notebook path provided'
302
+ });
303
+ }
304
+ const notebook = currentWidget.content;
305
+ const model = notebook.model;
306
+ if (!model) {
307
+ return JSON.stringify({
308
+ success: false,
309
+ error: 'No notebook model available'
310
+ });
311
+ }
312
+ if (cellIndex === undefined || cellIndex === null) {
313
+ cellIndex = notebook.activeCellIndex;
314
+ }
315
+ if (cellIndex < 0 || cellIndex >= model.cells.length) {
316
+ return JSON.stringify({
317
+ success: false,
318
+ error: `Invalid cell index: ${cellIndex}. Notebook has ${model.cells.length} cells.`
319
+ });
320
+ }
321
+ const cell = model.cells.get(cellIndex);
322
+ const cellType = cell.type;
323
+ const sharedModel = cell.sharedModel;
324
+ const source = sharedModel.getSource();
325
+ // Get outputs for code cells
326
+ let outputs = [];
327
+ if (cellType === 'code') {
328
+ const rawOutputs = sharedModel.toJSON().outputs;
329
+ outputs = Array.isArray(rawOutputs) ? rawOutputs : [];
330
+ }
331
+ return JSON.stringify({
332
+ success: true,
333
+ cellId: cell.id,
334
+ cellIndex,
335
+ cellType,
336
+ source,
337
+ outputs,
338
+ executionCount: cellType === 'code' ? cell.executionCount : null
339
+ });
340
+ }
341
+ catch (error) {
342
+ return JSON.stringify({
343
+ success: false,
344
+ error: `Failed to get cell info: ${error.message}`
345
+ });
346
+ }
347
+ }
348
+ });
349
+ }
350
+ /**
351
+ * Create a tool for setting cell content and type
352
+ */
353
+ export function createSetCellContentTool(docManager, commands, notebookTracker) {
354
+ return tool({
355
+ name: 'set_cell_content',
356
+ description: 'Set the content of a specific cell and return both the previous and new content',
357
+ parameters: z.object({
358
+ notebookPath: z
359
+ .string()
360
+ .optional()
361
+ .nullable()
362
+ .describe('Path to the notebook file. If not provided, uses the currently active notebook'),
363
+ cellId: z
364
+ .string()
365
+ .optional()
366
+ .nullable()
367
+ .describe('ID of the cell to modify. If provided, takes precedence over cellIndex'),
368
+ cellIndex: z
369
+ .number()
370
+ .optional()
371
+ .nullable()
372
+ .describe('Index of the cell to modify (0-based). Used if cellId is not provided. If neither is provided, targets the active cell'),
373
+ content: z.string().describe('New content for the cell')
374
+ }),
375
+ execute: async (input) => {
376
+ const { notebookPath, cellId, cellIndex, content } = input;
377
+ try {
378
+ const notebookWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
379
+ if (!notebookWidget) {
380
+ return JSON.stringify({
381
+ success: false,
382
+ error: notebookPath
383
+ ? `Failed to open notebook at path: ${notebookPath}`
384
+ : 'No active notebook and no notebook path provided'
385
+ });
386
+ }
387
+ const notebook = notebookWidget.content;
388
+ const targetNotebookPath = notebookWidget.context.path;
389
+ const model = notebook.model;
390
+ if (!model) {
391
+ return JSON.stringify({
392
+ success: false,
393
+ error: 'No notebook model available'
394
+ });
395
+ }
396
+ // Determine target cell index
397
+ let targetCellIndex;
398
+ if (cellId !== undefined && cellId !== null) {
399
+ // Find cell by ID
400
+ targetCellIndex = -1;
401
+ for (let i = 0; i < model.cells.length; i++) {
402
+ if (model.cells.get(i).id === cellId) {
403
+ targetCellIndex = i;
404
+ break;
405
+ }
406
+ }
407
+ if (targetCellIndex === -1) {
408
+ return JSON.stringify({
409
+ success: false,
410
+ error: `Cell with ID '${cellId}' not found in notebook`
411
+ });
412
+ }
413
+ }
414
+ else if (cellIndex !== undefined && cellIndex !== null) {
415
+ // Use provided cell index
416
+ if (cellIndex < 0 || cellIndex >= model.cells.length) {
417
+ return JSON.stringify({
418
+ success: false,
419
+ error: `Invalid cell index: ${cellIndex}. Notebook has ${model.cells.length} cells.`
420
+ });
421
+ }
422
+ targetCellIndex = cellIndex;
423
+ }
424
+ else {
425
+ // Use active cell
426
+ targetCellIndex = notebook.activeCellIndex;
427
+ if (targetCellIndex === -1 || targetCellIndex >= model.cells.length) {
428
+ return JSON.stringify({
429
+ success: false,
430
+ error: 'No active cell or invalid active cell index'
431
+ });
432
+ }
433
+ }
434
+ // Get the target cell
435
+ const targetCell = model.cells.get(targetCellIndex);
436
+ if (!targetCell) {
437
+ return JSON.stringify({
438
+ success: false,
439
+ error: `Cell at index ${targetCellIndex} not found`
440
+ });
441
+ }
442
+ const sharedModel = targetCell.sharedModel;
443
+ // Get previous content and type
444
+ const previousContent = sharedModel.getSource();
445
+ const previousCellType = targetCell.type;
446
+ const retrievedCellId = targetCell.id;
447
+ sharedModel.setSource(content);
448
+ // Show the cell diff using jupyterlab-cell-diff if available
449
+ const showDiffCommandId = 'jupyterlab-cell-diff:show-codemirror';
450
+ void commands.execute(showDiffCommandId, {
451
+ originalSource: previousContent,
452
+ newSource: content,
453
+ cellId: retrievedCellId,
454
+ showActionButtons: true,
455
+ openDiff: true,
456
+ notebookPath: targetNotebookPath
457
+ });
458
+ return JSON.stringify({
459
+ success: true,
460
+ message: cellId !== undefined && cellId !== null
461
+ ? `Cell with ID '${cellId}' content replaced successfully`
462
+ : cellIndex !== undefined && cellIndex !== null
463
+ ? `Cell ${targetCellIndex} content replaced successfully`
464
+ : 'Active cell content replaced successfully',
465
+ notebookPath: targetNotebookPath,
466
+ cellId: retrievedCellId,
467
+ cellIndex: targetCellIndex,
468
+ previousContent,
469
+ previousCellType,
470
+ newContent: content,
471
+ wasActiveCell: cellId === undefined && cellIndex === undefined
472
+ });
473
+ }
474
+ catch (error) {
475
+ return JSON.stringify({
476
+ success: false,
477
+ error: `Failed to replace cell content: ${error.message}`
478
+ });
479
+ }
480
+ }
481
+ });
482
+ }
483
+ /**
484
+ * Create a tool for running a specific cell
485
+ */
486
+ export function createRunCellTool(docManager, notebookTracker) {
487
+ return tool({
488
+ name: 'run_cell',
489
+ description: 'Run a specific cell in the notebook by index',
490
+ parameters: z.object({
491
+ notebookPath: z
492
+ .string()
493
+ .optional()
494
+ .nullable()
495
+ .describe('Path to the notebook file. If not provided, uses the currently active notebook'),
496
+ cellIndex: z.number().describe('Index of the cell to run (0-based)'),
497
+ recordTiming: z
498
+ .boolean()
499
+ .default(true)
500
+ .describe('Whether to record execution timing')
501
+ }),
502
+ needsApproval: true,
503
+ execute: async (input) => {
504
+ const { notebookPath, cellIndex, recordTiming = true } = input;
505
+ try {
506
+ const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
507
+ if (!currentWidget) {
508
+ return JSON.stringify({
509
+ success: false,
510
+ error: notebookPath
511
+ ? `Failed to open notebook at path: ${notebookPath}`
512
+ : 'No active notebook and no notebook path provided'
513
+ });
514
+ }
515
+ const notebook = currentWidget.content;
516
+ const model = notebook.model;
517
+ if (!model) {
518
+ return JSON.stringify({
519
+ success: false,
520
+ error: 'No notebook model available'
521
+ });
522
+ }
523
+ if (cellIndex < 0 || cellIndex >= model.cells.length) {
524
+ return JSON.stringify({
525
+ success: false,
526
+ error: `Invalid cell index: ${cellIndex}. Notebook has ${model.cells.length} cells.`
527
+ });
528
+ }
529
+ // Get the target cell widget
530
+ const cellWidget = notebook.widgets[cellIndex];
531
+ if (!cellWidget) {
532
+ return JSON.stringify({
533
+ success: false,
534
+ error: `Cell widget at index ${cellIndex} not found`
535
+ });
536
+ }
537
+ // Execute using shared model approach (non-disruptive)
538
+ try {
539
+ if (cellWidget instanceof CodeCell) {
540
+ // Use direct CodeCell.execute() method
541
+ const sessionCtx = currentWidget.sessionContext;
542
+ await CodeCell.execute(cellWidget, sessionCtx, {
543
+ recordTiming,
544
+ deletedCells: model.deletedCells
545
+ });
546
+ const codeModel = cellWidget.model;
547
+ return JSON.stringify({
548
+ success: true,
549
+ message: `Cell ${cellIndex} executed successfully`,
550
+ cellIndex,
551
+ executionCount: codeModel.executionCount,
552
+ hasOutput: codeModel.outputs.length > 0
553
+ });
554
+ }
555
+ else {
556
+ // For non-code cells, just return success
557
+ return JSON.stringify({
558
+ success: true,
559
+ message: `Cell ${cellIndex} is not a code cell, no execution needed`,
560
+ cellIndex,
561
+ cellType: cellWidget.model.type
562
+ });
563
+ }
564
+ }
565
+ catch (error) {
566
+ return JSON.stringify({
567
+ success: false,
568
+ error: `Failed to execute cell: ${error.message}`,
569
+ cellIndex
570
+ });
571
+ }
572
+ }
573
+ catch (error) {
574
+ return JSON.stringify({
575
+ success: false,
576
+ error: `Failed to run cell: ${error.message}`
577
+ });
578
+ }
579
+ }
580
+ });
581
+ }
582
+ /**
583
+ * Create a tool for deleting a specific cell
584
+ */
585
+ export function createDeleteCellTool(docManager, notebookTracker) {
586
+ return tool({
587
+ name: 'delete_cell',
588
+ description: 'Delete a specific cell from the notebook by index',
589
+ parameters: z.object({
590
+ notebookPath: z
591
+ .string()
592
+ .optional()
593
+ .nullable()
594
+ .describe('Path to the notebook file. If not provided, uses the currently active notebook'),
595
+ cellIndex: z.number().describe('Index of the cell to delete (0-based)')
596
+ }),
597
+ execute: async (input) => {
598
+ const { notebookPath, cellIndex } = input;
599
+ try {
600
+ const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
601
+ if (!currentWidget) {
602
+ return JSON.stringify({
603
+ success: false,
604
+ error: notebookPath
605
+ ? `Failed to open notebook at path: ${notebookPath}`
606
+ : 'No active notebook and no notebook path provided'
607
+ });
608
+ }
609
+ const notebook = currentWidget.content;
610
+ const model = notebook.model;
611
+ if (!model) {
612
+ return JSON.stringify({
613
+ success: false,
614
+ error: 'No notebook model available'
615
+ });
616
+ }
617
+ if (cellIndex < 0 || cellIndex >= model.cells.length) {
618
+ return JSON.stringify({
619
+ success: false,
620
+ error: `Invalid cell index: ${cellIndex}. Notebook has ${model.cells.length} cells.`
621
+ });
622
+ }
623
+ // Validate cell exists
624
+ const targetCell = model.cells.get(cellIndex);
625
+ if (!targetCell) {
626
+ return JSON.stringify({
627
+ success: false,
628
+ error: `Cell at index ${cellIndex} not found`
629
+ });
630
+ }
631
+ // Delete cell using shared model (non-disruptive)
632
+ model.sharedModel.deleteCell(cellIndex);
633
+ return JSON.stringify({
634
+ success: true,
635
+ message: `Cell ${cellIndex} deleted successfully`,
636
+ cellIndex,
637
+ remainingCells: model.cells.length
638
+ });
639
+ }
640
+ catch (error) {
641
+ return JSON.stringify({
642
+ success: false,
643
+ error: `Failed to delete cell: ${error.message}`
644
+ });
645
+ }
646
+ }
647
+ });
648
+ }
649
+ /**
650
+ * Create a tool for executing code in the active cell (non-disruptive alternative to mcp__ide__executeCode)
651
+ */
652
+ export function createExecuteActiveCellTool(docManager, notebookTracker) {
653
+ return tool({
654
+ name: 'execute_active_cell',
655
+ description: 'Execute the currently active cell in the notebook without disrupting user focus',
656
+ parameters: z.object({
657
+ notebookPath: z
658
+ .string()
659
+ .optional()
660
+ .nullable()
661
+ .describe('Path to the notebook file. If not provided, uses the currently active notebook'),
662
+ code: z
663
+ .string()
664
+ .optional()
665
+ .nullable()
666
+ .describe('Optional: set cell content before executing'),
667
+ recordTiming: z
668
+ .boolean()
669
+ .default(true)
670
+ .describe('Whether to record execution timing')
671
+ }),
672
+ execute: async (input) => {
673
+ const { notebookPath, code, recordTiming = true } = input;
674
+ try {
675
+ const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
676
+ if (!currentWidget) {
677
+ return JSON.stringify({
678
+ success: false,
679
+ error: notebookPath
680
+ ? `Failed to open notebook at path: ${notebookPath}`
681
+ : 'No active notebook and no notebook path provided'
682
+ });
683
+ }
684
+ const notebook = currentWidget.content;
685
+ const model = notebook.model;
686
+ const activeCellIndex = notebook.activeCellIndex;
687
+ if (!model || activeCellIndex === -1) {
688
+ return JSON.stringify({
689
+ success: false,
690
+ error: 'No notebook model or active cell available'
691
+ });
692
+ }
693
+ const activeCell = model.cells.get(activeCellIndex);
694
+ if (!activeCell) {
695
+ return JSON.stringify({
696
+ success: false,
697
+ error: 'Active cell not found'
698
+ });
699
+ }
700
+ // Set code content if provided
701
+ if (code) {
702
+ activeCell.sharedModel.setSource(code);
703
+ }
704
+ // Get the cell widget for execution
705
+ const cellWidget = notebook.widgets[activeCellIndex];
706
+ if (!cellWidget || !(cellWidget instanceof CodeCell)) {
707
+ return JSON.stringify({
708
+ success: false,
709
+ error: 'Active cell is not a code cell'
710
+ });
711
+ }
712
+ // Execute using shared model approach (non-disruptive)
713
+ const sessionCtx = currentWidget.sessionContext;
714
+ await CodeCell.execute(cellWidget, sessionCtx, {
715
+ recordTiming,
716
+ deletedCells: model.deletedCells
717
+ });
718
+ const codeModel = cellWidget.model;
719
+ return JSON.stringify({
720
+ success: true,
721
+ message: 'Code executed successfully in active cell',
722
+ cellIndex: activeCellIndex,
723
+ executionCount: codeModel.executionCount,
724
+ hasOutput: codeModel.outputs.length > 0,
725
+ code: code || activeCell.sharedModel.getSource()
726
+ });
727
+ }
728
+ catch (error) {
729
+ return JSON.stringify({
730
+ success: false,
731
+ error: `Failed to execute code: ${error.message}`
732
+ });
733
+ }
734
+ }
735
+ });
736
+ }
737
+ /**
738
+ * Create a tool for saving a specific notebook
739
+ */
740
+ export function createSaveNotebookTool(docManager, notebookTracker) {
741
+ return tool({
742
+ name: 'save_notebook',
743
+ description: 'Save a specific notebook to disk',
744
+ parameters: z.object({
745
+ notebookPath: z
746
+ .string()
747
+ .optional()
748
+ .nullable()
749
+ .describe('Path to the notebook file. If not provided, uses the currently active notebook')
750
+ }),
751
+ execute: async (input) => {
752
+ const { notebookPath } = input;
753
+ try {
754
+ const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
755
+ if (!currentWidget) {
756
+ return JSON.stringify({
757
+ success: false,
758
+ error: notebookPath
759
+ ? `Failed to open notebook at path: ${notebookPath}`
760
+ : 'No active notebook and no notebook path provided'
761
+ });
762
+ }
763
+ await currentWidget.context.save();
764
+ return JSON.stringify({
765
+ success: true,
766
+ message: 'Notebook saved successfully',
767
+ notebookName: currentWidget.title.label,
768
+ notebookPath: currentWidget.context.path
769
+ });
770
+ }
771
+ catch (error) {
772
+ return JSON.stringify({
773
+ success: false,
774
+ error: `Failed to save notebook: ${error.message}`
775
+ });
776
+ }
777
+ }
778
+ });
779
+ }