@jupyterlite/ai 0.9.1 → 0.11.0

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 (71) hide show
  1. package/README.md +5 -214
  2. package/lib/agent.d.ts +58 -66
  3. package/lib/agent.js +291 -310
  4. package/lib/approval-buttons.d.ts +19 -82
  5. package/lib/approval-buttons.js +36 -289
  6. package/lib/chat-model-registry.d.ts +6 -0
  7. package/lib/chat-model-registry.js +4 -1
  8. package/lib/chat-model.d.ts +26 -54
  9. package/lib/chat-model.js +277 -303
  10. package/lib/components/clear-button.d.ts +6 -1
  11. package/lib/components/clear-button.js +10 -6
  12. package/lib/components/completion-status.d.ts +5 -0
  13. package/lib/components/completion-status.js +5 -4
  14. package/lib/components/model-select.d.ts +6 -1
  15. package/lib/components/model-select.js +13 -16
  16. package/lib/components/stop-button.d.ts +6 -1
  17. package/lib/components/stop-button.js +12 -8
  18. package/lib/components/token-usage-display.d.ts +5 -0
  19. package/lib/components/token-usage-display.js +2 -2
  20. package/lib/components/tool-select.d.ts +6 -1
  21. package/lib/components/tool-select.js +10 -9
  22. package/lib/index.d.ts +1 -0
  23. package/lib/index.js +61 -81
  24. package/lib/models/settings-model.d.ts +1 -1
  25. package/lib/models/settings-model.js +40 -26
  26. package/lib/providers/built-in-providers.js +38 -19
  27. package/lib/providers/models.d.ts +3 -3
  28. package/lib/providers/provider-registry.d.ts +3 -4
  29. package/lib/providers/provider-registry.js +1 -4
  30. package/lib/tokens.d.ts +5 -6
  31. package/lib/tools/commands.d.ts +2 -1
  32. package/lib/tools/commands.js +36 -49
  33. package/lib/widgets/ai-settings.d.ts +6 -0
  34. package/lib/widgets/ai-settings.js +72 -71
  35. package/lib/widgets/main-area-chat.d.ts +2 -0
  36. package/lib/widgets/main-area-chat.js +5 -2
  37. package/lib/widgets/provider-config-dialog.d.ts +2 -0
  38. package/lib/widgets/provider-config-dialog.js +34 -34
  39. package/package.json +13 -13
  40. package/schema/settings-model.json +3 -2
  41. package/src/agent.ts +360 -372
  42. package/src/approval-buttons.ts +43 -389
  43. package/src/chat-model-registry.ts +9 -1
  44. package/src/chat-model.ts +399 -370
  45. package/src/completion/completion-provider.ts +2 -3
  46. package/src/components/clear-button.tsx +18 -6
  47. package/src/components/completion-status.tsx +18 -4
  48. package/src/components/model-select.tsx +25 -16
  49. package/src/components/stop-button.tsx +22 -9
  50. package/src/components/token-usage-display.tsx +14 -2
  51. package/src/components/tool-select.tsx +27 -9
  52. package/src/index.ts +78 -134
  53. package/src/models/settings-model.ts +41 -27
  54. package/src/providers/built-in-providers.ts +38 -19
  55. package/src/providers/models.ts +3 -3
  56. package/src/providers/provider-registry.ts +4 -8
  57. package/src/tokens.ts +5 -6
  58. package/src/tools/commands.ts +40 -53
  59. package/src/widgets/ai-settings.tsx +153 -84
  60. package/src/widgets/main-area-chat.ts +8 -2
  61. package/src/widgets/provider-config-dialog.tsx +54 -41
  62. package/style/base.css +24 -73
  63. package/lib/mcp/browser.d.ts +0 -68
  64. package/lib/mcp/browser.js +0 -138
  65. package/lib/tools/file.d.ts +0 -36
  66. package/lib/tools/file.js +0 -351
  67. package/lib/tools/notebook.d.ts +0 -40
  68. package/lib/tools/notebook.js +0 -779
  69. package/src/mcp/browser.ts +0 -220
  70. package/src/tools/file.ts +0 -438
  71. package/src/tools/notebook.ts +0 -986
@@ -1,779 +0,0 @@
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
- .optional()
149
- .default('below')
150
- .describe('Position relative to current cell')
151
- }),
152
- async execute({ notebookPath, content, cellType = 'code', position = 'below' }) {
153
- try {
154
- const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
155
- if (!currentWidget) {
156
- return {
157
- success: false,
158
- error: notebookPath
159
- ? `Failed to open notebook at path: ${notebookPath}`
160
- : 'No active notebook and no notebook path provided'
161
- };
162
- }
163
- const notebook = currentWidget.content;
164
- const model = notebook.model;
165
- if (!model) {
166
- return {
167
- success: false,
168
- error: 'No notebook model available'
169
- };
170
- }
171
- // Check if we should replace the first empty cell instead of adding
172
- const shouldReplaceFirstCell = model.cells.length === 1 &&
173
- model.cells.get(0).sharedModel.getSource().trim() === '';
174
- if (shouldReplaceFirstCell) {
175
- // Replace the first empty cell by removing it and adding new one
176
- model.sharedModel.deleteCell(0);
177
- }
178
- // Create the new cell using shared model
179
- const newCellData = {
180
- cell_type: cellType,
181
- source: content || '',
182
- metadata: cellType === 'code' ? { trusted: true } : {}
183
- };
184
- model.sharedModel.addCell(newCellData);
185
- // Execute markdown cells after creation to render them
186
- if (cellType === 'markdown' && content) {
187
- const cellIndex = model.cells.length - 1;
188
- const cellWidget = notebook.widgets[cellIndex];
189
- if (cellWidget && cellWidget instanceof MarkdownCell) {
190
- try {
191
- await cellWidget.ready;
192
- cellWidget.rendered = true;
193
- }
194
- catch (error) {
195
- console.warn('Failed to render markdown cell:', error);
196
- }
197
- }
198
- }
199
- return {
200
- success: true,
201
- message: `${cellType} cell added successfully`,
202
- content: content || '',
203
- cellType,
204
- position
205
- };
206
- }
207
- catch (error) {
208
- return {
209
- success: false,
210
- error: `Failed to add ${cellType} cell: ${error.message}`
211
- };
212
- }
213
- }
214
- });
215
- }
216
- /**
217
- * Create a tool for getting notebook information
218
- */
219
- export function createGetNotebookInfoTool(docManager, notebookTracker) {
220
- return tool({
221
- name: 'get_notebook_info',
222
- description: 'Get information about a notebook including number of cells and active cell index',
223
- parameters: z.object({
224
- notebookPath: z
225
- .string()
226
- .optional()
227
- .nullable()
228
- .describe('Path to the notebook file. If not provided, uses the currently active notebook')
229
- }),
230
- execute: async (input) => {
231
- const { notebookPath } = input;
232
- try {
233
- const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
234
- if (!currentWidget) {
235
- return JSON.stringify({
236
- success: false,
237
- error: notebookPath
238
- ? `Failed to open notebook at path: ${notebookPath}`
239
- : 'No active notebook and no notebook path provided'
240
- });
241
- }
242
- const notebook = currentWidget.content;
243
- const model = notebook.model;
244
- if (!model) {
245
- return JSON.stringify({
246
- success: false,
247
- error: 'No notebook model available'
248
- });
249
- }
250
- const cellCount = model.cells.length;
251
- const activeCellIndex = notebook.activeCellIndex;
252
- const activeCell = notebook.activeCell;
253
- const activeCellType = activeCell?.model.type || 'unknown';
254
- return JSON.stringify({
255
- success: true,
256
- notebookName: currentWidget.title.label,
257
- notebookPath: currentWidget.context.path,
258
- cellCount,
259
- activeCellIndex,
260
- activeCellType,
261
- isDirty: model.dirty
262
- });
263
- }
264
- catch (error) {
265
- return JSON.stringify({
266
- success: false,
267
- error: `Failed to get notebook info: ${error.message}`
268
- });
269
- }
270
- }
271
- });
272
- }
273
- /**
274
- * Create a tool for getting cell information by index
275
- */
276
- export function createGetCellInfoTool(docManager, notebookTracker) {
277
- return tool({
278
- name: 'get_cell_info',
279
- description: 'Get information about a specific cell including its type, source content, and outputs',
280
- parameters: z.object({
281
- notebookPath: z
282
- .string()
283
- .optional()
284
- .nullable()
285
- .describe('Path to the notebook file. If not provided, uses the currently active notebook'),
286
- cellIndex: z
287
- .number()
288
- .optional()
289
- .nullable()
290
- .describe('Index of the cell to get information for (0-based). If not provided, uses the currently active cell')
291
- }),
292
- execute: async (input) => {
293
- const { notebookPath } = input;
294
- let { cellIndex } = input;
295
- try {
296
- const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
297
- if (!currentWidget) {
298
- return JSON.stringify({
299
- success: false,
300
- error: notebookPath
301
- ? `Failed to open notebook at path: ${notebookPath}`
302
- : 'No active notebook and no notebook path provided'
303
- });
304
- }
305
- const notebook = currentWidget.content;
306
- const model = notebook.model;
307
- if (!model) {
308
- return JSON.stringify({
309
- success: false,
310
- error: 'No notebook model available'
311
- });
312
- }
313
- if (cellIndex === undefined || cellIndex === null) {
314
- cellIndex = notebook.activeCellIndex;
315
- }
316
- if (cellIndex < 0 || cellIndex >= model.cells.length) {
317
- return JSON.stringify({
318
- success: false,
319
- error: `Invalid cell index: ${cellIndex}. Notebook has ${model.cells.length} cells.`
320
- });
321
- }
322
- const cell = model.cells.get(cellIndex);
323
- const cellType = cell.type;
324
- const sharedModel = cell.sharedModel;
325
- const source = sharedModel.getSource();
326
- // Get outputs for code cells
327
- let outputs = [];
328
- if (cellType === 'code') {
329
- const rawOutputs = sharedModel.toJSON().outputs;
330
- outputs = Array.isArray(rawOutputs) ? rawOutputs : [];
331
- }
332
- return JSON.stringify({
333
- success: true,
334
- cellId: cell.id,
335
- cellIndex,
336
- cellType,
337
- source,
338
- outputs,
339
- executionCount: cellType === 'code' ? cell.executionCount : null
340
- });
341
- }
342
- catch (error) {
343
- return JSON.stringify({
344
- success: false,
345
- error: `Failed to get cell info: ${error.message}`
346
- });
347
- }
348
- }
349
- });
350
- }
351
- /**
352
- * Create a tool for setting cell content and type
353
- */
354
- export function createSetCellContentTool(docManager, notebookTracker, diffManager) {
355
- return tool({
356
- name: 'set_cell_content',
357
- description: 'Set the content of a specific cell and return both the previous and new content',
358
- parameters: z.object({
359
- notebookPath: z
360
- .string()
361
- .optional()
362
- .nullable()
363
- .describe('Path to the notebook file. If not provided, uses the currently active notebook'),
364
- cellId: z
365
- .string()
366
- .optional()
367
- .nullable()
368
- .describe('ID of the cell to modify. If provided, takes precedence over cellIndex'),
369
- cellIndex: z
370
- .number()
371
- .optional()
372
- .nullable()
373
- .describe('Index of the cell to modify (0-based). Used if cellId is not provided. If neither is provided, targets the active cell'),
374
- content: z.string().describe('New content for the cell')
375
- }),
376
- execute: async (input) => {
377
- const { notebookPath, cellId, cellIndex, content } = input;
378
- try {
379
- const notebookWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
380
- if (!notebookWidget) {
381
- return JSON.stringify({
382
- success: false,
383
- error: notebookPath
384
- ? `Failed to open notebook at path: ${notebookPath}`
385
- : 'No active notebook and no notebook path provided'
386
- });
387
- }
388
- const notebook = notebookWidget.content;
389
- const targetNotebookPath = notebookWidget.context.path;
390
- const model = notebook.model;
391
- if (!model) {
392
- return JSON.stringify({
393
- success: false,
394
- error: 'No notebook model available'
395
- });
396
- }
397
- // Determine target cell index
398
- let targetCellIndex;
399
- if (cellId !== undefined && cellId !== null) {
400
- // Find cell by ID
401
- targetCellIndex = -1;
402
- for (let i = 0; i < model.cells.length; i++) {
403
- if (model.cells.get(i).id === cellId) {
404
- targetCellIndex = i;
405
- break;
406
- }
407
- }
408
- if (targetCellIndex === -1) {
409
- return JSON.stringify({
410
- success: false,
411
- error: `Cell with ID '${cellId}' not found in notebook`
412
- });
413
- }
414
- }
415
- else if (cellIndex !== undefined && cellIndex !== null) {
416
- // Use provided cell index
417
- if (cellIndex < 0 || cellIndex >= model.cells.length) {
418
- return JSON.stringify({
419
- success: false,
420
- error: `Invalid cell index: ${cellIndex}. Notebook has ${model.cells.length} cells.`
421
- });
422
- }
423
- targetCellIndex = cellIndex;
424
- }
425
- else {
426
- // Use active cell
427
- targetCellIndex = notebook.activeCellIndex;
428
- if (targetCellIndex === -1 || targetCellIndex >= model.cells.length) {
429
- return JSON.stringify({
430
- success: false,
431
- error: 'No active cell or invalid active cell index'
432
- });
433
- }
434
- }
435
- // Get the target cell
436
- const targetCell = model.cells.get(targetCellIndex);
437
- if (!targetCell) {
438
- return JSON.stringify({
439
- success: false,
440
- error: `Cell at index ${targetCellIndex} not found`
441
- });
442
- }
443
- const sharedModel = targetCell.sharedModel;
444
- // Get previous content and type
445
- const previousContent = sharedModel.getSource();
446
- const previousCellType = targetCell.type;
447
- const retrievedCellId = targetCell.id;
448
- sharedModel.setSource(content);
449
- // Show the cell diff using the diff manager if available
450
- if (diffManager) {
451
- await diffManager.showCellDiff({
452
- original: previousContent,
453
- modified: content,
454
- cellId: retrievedCellId,
455
- notebookPath: targetNotebookPath
456
- });
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
- }