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