@jupyterlite/ai 0.10.0 → 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.
@@ -1,704 +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 'ai';
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
- title: 'Create Notebook',
68
- description: 'Create a new Jupyter notebook with a kernel for the specified programming language',
69
- inputSchema: 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
- return {
86
- success: false,
87
- error: 'A name must be provided to create a notebook'
88
- };
89
- }
90
- // TODO: handle cwd / path?
91
- const fileName = name.endsWith('.ipynb') ? name : `${name}.ipynb`;
92
- // Create untitled notebook first
93
- const notebookModel = await docManager.newUntitled({
94
- type: 'notebook'
95
- });
96
- // Rename to desired filename
97
- await docManager.services.contents.rename(notebookModel.path, fileName);
98
- // Create widget with specific kernel
99
- const notebook = docManager.createNew(fileName, 'default', {
100
- name: kernel
101
- });
102
- if (!(notebook instanceof DocumentWidget)) {
103
- return {
104
- success: false,
105
- error: 'Failed to create notebook widget'
106
- };
107
- }
108
- await notebook.context.ready;
109
- await notebook.context.save();
110
- docManager.openOrReveal(fileName);
111
- return {
112
- success: true,
113
- message: `Successfully created notebook ${fileName} with ${kernel} kernel${input.language ? ` for ${input.language}` : ''}`,
114
- notebookPath: fileName,
115
- notebookName: fileName,
116
- kernel,
117
- language: input.language
118
- };
119
- }
120
- });
121
- }
122
- /**
123
- * Create a tool for adding cells to a specific notebook
124
- */
125
- export function createAddCellTool(docManager, notebookTracker) {
126
- return tool({
127
- title: 'Add Cell',
128
- description: 'Add a cell to the current notebook with optional content',
129
- inputSchema: z.object({
130
- notebookPath: z
131
- .string()
132
- .optional()
133
- .nullable()
134
- .describe('Path to the notebook file. If not provided, uses the currently active notebook'),
135
- content: z
136
- .string()
137
- .optional()
138
- .nullable()
139
- .describe('Content to add to the cell'),
140
- cellType: z
141
- .enum(['code', 'markdown', 'raw'])
142
- .default('code')
143
- .describe('Type of cell to add'),
144
- position: z
145
- .enum(['above', 'below'])
146
- .optional()
147
- .default('below')
148
- .describe('Position relative to current cell')
149
- }),
150
- execute: async ({ notebookPath, content, cellType = 'code', position = 'below' }) => {
151
- const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
152
- if (!currentWidget) {
153
- return {
154
- success: false,
155
- error: notebookPath
156
- ? `Failed to open notebook at path: ${notebookPath}`
157
- : 'No active notebook and no notebook path provided'
158
- };
159
- }
160
- const notebook = currentWidget.content;
161
- const model = notebook.model;
162
- if (!model) {
163
- return {
164
- success: false,
165
- error: 'No notebook model available'
166
- };
167
- }
168
- // Check if we should replace the first empty cell instead of adding
169
- const shouldReplaceFirstCell = model.cells.length === 1 &&
170
- model.cells.get(0).sharedModel.getSource().trim() === '';
171
- if (shouldReplaceFirstCell) {
172
- // Replace the first empty cell by removing it and adding new one
173
- model.sharedModel.deleteCell(0);
174
- }
175
- // Create the new cell using shared model
176
- const newCellData = {
177
- cell_type: cellType,
178
- source: content || '',
179
- metadata: cellType === 'code' ? { trusted: true } : {}
180
- };
181
- model.sharedModel.addCell(newCellData);
182
- // Execute markdown cells after creation to render them
183
- if (cellType === 'markdown' && content) {
184
- const cellIndex = model.cells.length - 1;
185
- const cellWidget = notebook.widgets[cellIndex];
186
- if (cellWidget && cellWidget instanceof MarkdownCell) {
187
- try {
188
- await cellWidget.ready;
189
- cellWidget.rendered = true;
190
- }
191
- catch (error) {
192
- console.warn('Failed to render markdown cell:', error);
193
- }
194
- }
195
- }
196
- return {
197
- success: true,
198
- message: `${cellType} cell added successfully`,
199
- content: content || '',
200
- cellType,
201
- position
202
- };
203
- }
204
- });
205
- }
206
- /**
207
- * Create a tool for getting notebook information
208
- */
209
- export function createGetNotebookInfoTool(docManager, notebookTracker) {
210
- return tool({
211
- title: 'Get Notebook Info',
212
- description: 'Get information about a notebook including number of cells and active cell index',
213
- inputSchema: z.object({
214
- notebookPath: z
215
- .string()
216
- .optional()
217
- .nullable()
218
- .describe('Path to the notebook file. If not provided, uses the currently active notebook')
219
- }),
220
- execute: async (input) => {
221
- const { notebookPath } = input;
222
- const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
223
- if (!currentWidget) {
224
- return JSON.stringify({
225
- success: false,
226
- error: notebookPath
227
- ? `Failed to open notebook at path: ${notebookPath}`
228
- : 'No active notebook and no notebook path provided'
229
- });
230
- }
231
- const notebook = currentWidget.content;
232
- const model = notebook.model;
233
- if (!model) {
234
- return JSON.stringify({
235
- success: false,
236
- error: 'No notebook model available'
237
- });
238
- }
239
- const cellCount = model.cells.length;
240
- const activeCellIndex = notebook.activeCellIndex;
241
- const activeCell = notebook.activeCell;
242
- const activeCellType = activeCell?.model.type || 'unknown';
243
- return JSON.stringify({
244
- success: true,
245
- notebookName: currentWidget.title.label,
246
- notebookPath: currentWidget.context.path,
247
- cellCount,
248
- activeCellIndex,
249
- activeCellType,
250
- isDirty: model.dirty
251
- });
252
- }
253
- });
254
- }
255
- /**
256
- * Create a tool for getting cell information by index
257
- */
258
- export function createGetCellInfoTool(docManager, notebookTracker) {
259
- return tool({
260
- title: 'Get Cell Info',
261
- description: 'Get information about a specific cell including its type, source content, and outputs',
262
- inputSchema: z.object({
263
- notebookPath: z
264
- .string()
265
- .optional()
266
- .nullable()
267
- .describe('Path to the notebook file. If not provided, uses the currently active notebook'),
268
- cellIndex: z
269
- .number()
270
- .optional()
271
- .nullable()
272
- .describe('Index of the cell to get information for (0-based). If not provided, uses the currently active cell')
273
- }),
274
- execute: async (input) => {
275
- const { notebookPath } = input;
276
- let { cellIndex } = input;
277
- const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
278
- if (!currentWidget) {
279
- return JSON.stringify({
280
- success: false,
281
- error: notebookPath
282
- ? `Failed to open notebook at path: ${notebookPath}`
283
- : 'No active notebook and no notebook path provided'
284
- });
285
- }
286
- const notebook = currentWidget.content;
287
- const model = notebook.model;
288
- if (!model) {
289
- return JSON.stringify({
290
- success: false,
291
- error: 'No notebook model available'
292
- });
293
- }
294
- if (cellIndex === undefined || cellIndex === null) {
295
- cellIndex = notebook.activeCellIndex;
296
- }
297
- if (cellIndex < 0 || cellIndex >= model.cells.length) {
298
- return JSON.stringify({
299
- success: false,
300
- error: `Invalid cell index: ${cellIndex}. Notebook has ${model.cells.length} cells.`
301
- });
302
- }
303
- const cell = model.cells.get(cellIndex);
304
- const cellType = cell.type;
305
- const sharedModel = cell.sharedModel;
306
- const source = sharedModel.getSource();
307
- // Get outputs for code cells
308
- let outputs = [];
309
- if (cellType === 'code') {
310
- const rawOutputs = sharedModel.toJSON().outputs;
311
- outputs = Array.isArray(rawOutputs) ? rawOutputs : [];
312
- }
313
- return JSON.stringify({
314
- success: true,
315
- cellId: cell.id,
316
- cellIndex,
317
- cellType,
318
- source,
319
- outputs,
320
- executionCount: cellType === 'code' ? cell.executionCount : null
321
- });
322
- }
323
- });
324
- }
325
- /**
326
- * Create a tool for setting cell content and type
327
- */
328
- export function createSetCellContentTool(docManager, notebookTracker, diffManager) {
329
- return tool({
330
- title: 'Set Cell Content',
331
- description: 'Set the content of a specific cell and return both the previous and new content',
332
- inputSchema: z.object({
333
- notebookPath: z
334
- .string()
335
- .optional()
336
- .nullable()
337
- .describe('Path to the notebook file. If not provided, uses the currently active notebook'),
338
- cellId: z
339
- .string()
340
- .optional()
341
- .nullable()
342
- .describe('ID of the cell to modify. If provided, takes precedence over cellIndex'),
343
- cellIndex: z
344
- .number()
345
- .optional()
346
- .nullable()
347
- .describe('Index of the cell to modify (0-based). Used if cellId is not provided. If neither is provided, targets the active cell'),
348
- content: z.string().describe('New content for the cell')
349
- }),
350
- execute: async (input) => {
351
- const { notebookPath, cellId, cellIndex, content } = input;
352
- const notebookWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
353
- if (!notebookWidget) {
354
- return JSON.stringify({
355
- success: false,
356
- error: notebookPath
357
- ? `Failed to open notebook at path: ${notebookPath}`
358
- : 'No active notebook and no notebook path provided'
359
- });
360
- }
361
- const notebook = notebookWidget.content;
362
- const targetNotebookPath = notebookWidget.context.path;
363
- const model = notebook.model;
364
- if (!model) {
365
- return JSON.stringify({
366
- success: false,
367
- error: 'No notebook model available'
368
- });
369
- }
370
- // Determine target cell index
371
- let targetCellIndex;
372
- if (cellId !== undefined && cellId !== null) {
373
- // Find cell by ID
374
- targetCellIndex = -1;
375
- for (let i = 0; i < model.cells.length; i++) {
376
- if (model.cells.get(i).id === cellId) {
377
- targetCellIndex = i;
378
- break;
379
- }
380
- }
381
- if (targetCellIndex === -1) {
382
- return JSON.stringify({
383
- success: false,
384
- error: `Cell with ID '${cellId}' not found in notebook`
385
- });
386
- }
387
- }
388
- else if (cellIndex !== undefined && cellIndex !== null) {
389
- // Use provided cell index
390
- if (cellIndex < 0 || cellIndex >= model.cells.length) {
391
- return JSON.stringify({
392
- success: false,
393
- error: `Invalid cell index: ${cellIndex}. Notebook has ${model.cells.length} cells.`
394
- });
395
- }
396
- targetCellIndex = cellIndex;
397
- }
398
- else {
399
- // Use active cell
400
- targetCellIndex = notebook.activeCellIndex;
401
- if (targetCellIndex === -1 || targetCellIndex >= model.cells.length) {
402
- return JSON.stringify({
403
- success: false,
404
- error: 'No active cell or invalid active cell index'
405
- });
406
- }
407
- }
408
- // Get the target cell
409
- const targetCell = model.cells.get(targetCellIndex);
410
- if (!targetCell) {
411
- return JSON.stringify({
412
- success: false,
413
- error: `Cell at index ${targetCellIndex} not found`
414
- });
415
- }
416
- const sharedModel = targetCell.sharedModel;
417
- // Get previous content and type
418
- const previousContent = sharedModel.getSource();
419
- const previousCellType = targetCell.type;
420
- const retrievedCellId = targetCell.id;
421
- sharedModel.setSource(content);
422
- // Show the cell diff using the diff manager if available
423
- if (diffManager) {
424
- await diffManager.showCellDiff({
425
- original: previousContent,
426
- modified: content,
427
- cellId: retrievedCellId,
428
- notebookPath: targetNotebookPath
429
- });
430
- }
431
- return JSON.stringify({
432
- success: true,
433
- message: cellId !== undefined && cellId !== null
434
- ? `Cell with ID '${cellId}' content replaced successfully`
435
- : cellIndex !== undefined && cellIndex !== null
436
- ? `Cell ${targetCellIndex} content replaced successfully`
437
- : 'Active cell content replaced successfully',
438
- notebookPath: targetNotebookPath,
439
- cellId: retrievedCellId,
440
- cellIndex: targetCellIndex,
441
- previousContent,
442
- previousCellType,
443
- newContent: content,
444
- wasActiveCell: cellId === undefined && cellIndex === undefined
445
- });
446
- }
447
- });
448
- }
449
- /**
450
- * Create a tool for running a specific cell
451
- */
452
- export function createRunCellTool(docManager, notebookTracker) {
453
- return tool({
454
- title: 'Run Cell',
455
- description: 'Run a specific cell in the notebook by index',
456
- inputSchema: z.object({
457
- notebookPath: z
458
- .string()
459
- .optional()
460
- .nullable()
461
- .describe('Path to the notebook file. If not provided, uses the currently active notebook'),
462
- cellIndex: z.number().describe('Index of the cell to run (0-based)'),
463
- recordTiming: z
464
- .boolean()
465
- .default(true)
466
- .describe('Whether to record execution timing')
467
- }),
468
- needsApproval: true,
469
- execute: async (input) => {
470
- const { notebookPath, cellIndex, recordTiming = true } = input;
471
- const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
472
- if (!currentWidget) {
473
- return JSON.stringify({
474
- success: false,
475
- error: notebookPath
476
- ? `Failed to open notebook at path: ${notebookPath}`
477
- : 'No active notebook and no notebook path provided'
478
- });
479
- }
480
- const notebook = currentWidget.content;
481
- const model = notebook.model;
482
- if (!model) {
483
- return JSON.stringify({
484
- success: false,
485
- error: 'No notebook model available'
486
- });
487
- }
488
- if (cellIndex < 0 || cellIndex >= model.cells.length) {
489
- return JSON.stringify({
490
- success: false,
491
- error: `Invalid cell index: ${cellIndex}. Notebook has ${model.cells.length} cells.`
492
- });
493
- }
494
- // Get the target cell widget
495
- const cellWidget = notebook.widgets[cellIndex];
496
- if (!cellWidget) {
497
- return JSON.stringify({
498
- success: false,
499
- error: `Cell widget at index ${cellIndex} not found`
500
- });
501
- }
502
- // Execute using shared model approach (non-disruptive)
503
- if (cellWidget instanceof CodeCell) {
504
- // Use direct CodeCell.execute() method
505
- const sessionCtx = currentWidget.sessionContext;
506
- await CodeCell.execute(cellWidget, sessionCtx, {
507
- recordTiming,
508
- deletedCells: model.deletedCells
509
- });
510
- const codeModel = cellWidget.model;
511
- return JSON.stringify({
512
- success: true,
513
- message: `Cell ${cellIndex} executed successfully`,
514
- cellIndex,
515
- executionCount: codeModel.executionCount,
516
- hasOutput: codeModel.outputs.length > 0
517
- });
518
- }
519
- else {
520
- // For non-code cells, just return success
521
- return JSON.stringify({
522
- success: true,
523
- message: `Cell ${cellIndex} is not a code cell, no execution needed`,
524
- cellIndex,
525
- cellType: cellWidget.model.type
526
- });
527
- }
528
- }
529
- });
530
- }
531
- /**
532
- * Create a tool for deleting a specific cell
533
- */
534
- export function createDeleteCellTool(docManager, notebookTracker) {
535
- return tool({
536
- title: 'Delete Cell',
537
- description: 'Delete a specific cell from the notebook by index',
538
- inputSchema: z.object({
539
- notebookPath: z
540
- .string()
541
- .optional()
542
- .nullable()
543
- .describe('Path to the notebook file. If not provided, uses the currently active notebook'),
544
- cellIndex: z.number().describe('Index of the cell to delete (0-based)')
545
- }),
546
- execute: async (input) => {
547
- const { notebookPath, cellIndex } = input;
548
- const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
549
- if (!currentWidget) {
550
- return JSON.stringify({
551
- success: false,
552
- error: notebookPath
553
- ? `Failed to open notebook at path: ${notebookPath}`
554
- : 'No active notebook and no notebook path provided'
555
- });
556
- }
557
- const notebook = currentWidget.content;
558
- const model = notebook.model;
559
- if (!model) {
560
- return JSON.stringify({
561
- success: false,
562
- error: 'No notebook model available'
563
- });
564
- }
565
- if (cellIndex < 0 || cellIndex >= model.cells.length) {
566
- return JSON.stringify({
567
- success: false,
568
- error: `Invalid cell index: ${cellIndex}. Notebook has ${model.cells.length} cells.`
569
- });
570
- }
571
- // Validate cell exists
572
- const targetCell = model.cells.get(cellIndex);
573
- if (!targetCell) {
574
- return JSON.stringify({
575
- success: false,
576
- error: `Cell at index ${cellIndex} not found`
577
- });
578
- }
579
- // Delete cell using shared model (non-disruptive)
580
- model.sharedModel.deleteCell(cellIndex);
581
- return JSON.stringify({
582
- success: true,
583
- message: `Cell ${cellIndex} deleted successfully`,
584
- cellIndex,
585
- remainingCells: model.cells.length
586
- });
587
- }
588
- });
589
- }
590
- /**
591
- * Create a tool for executing code in the active cell (non-disruptive alternative to mcp__ide__executeCode)
592
- */
593
- export function createExecuteActiveCellTool(docManager, notebookTracker) {
594
- return tool({
595
- title: 'Execute Active Cell',
596
- description: 'Execute the currently active cell in the notebook without disrupting user focus',
597
- inputSchema: z.object({
598
- notebookPath: z
599
- .string()
600
- .optional()
601
- .nullable()
602
- .describe('Path to the notebook file. If not provided, uses the currently active notebook'),
603
- code: z
604
- .string()
605
- .optional()
606
- .nullable()
607
- .describe('Optional: set cell content before executing'),
608
- recordTiming: z
609
- .boolean()
610
- .default(true)
611
- .describe('Whether to record execution timing')
612
- }),
613
- execute: async (input) => {
614
- const { notebookPath, code, recordTiming = true } = input;
615
- const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
616
- if (!currentWidget) {
617
- return JSON.stringify({
618
- success: false,
619
- error: notebookPath
620
- ? `Failed to open notebook at path: ${notebookPath}`
621
- : 'No active notebook and no notebook path provided'
622
- });
623
- }
624
- const notebook = currentWidget.content;
625
- const model = notebook.model;
626
- const activeCellIndex = notebook.activeCellIndex;
627
- if (!model || activeCellIndex === -1) {
628
- return JSON.stringify({
629
- success: false,
630
- error: 'No notebook model or active cell available'
631
- });
632
- }
633
- const activeCell = model.cells.get(activeCellIndex);
634
- if (!activeCell) {
635
- return JSON.stringify({
636
- success: false,
637
- error: 'Active cell not found'
638
- });
639
- }
640
- // Set code content if provided
641
- if (code) {
642
- activeCell.sharedModel.setSource(code);
643
- }
644
- // Get the cell widget for execution
645
- const cellWidget = notebook.widgets[activeCellIndex];
646
- if (!cellWidget || !(cellWidget instanceof CodeCell)) {
647
- return JSON.stringify({
648
- success: false,
649
- error: 'Active cell is not a code cell'
650
- });
651
- }
652
- // Execute using shared model approach (non-disruptive)
653
- const sessionCtx = currentWidget.sessionContext;
654
- await CodeCell.execute(cellWidget, sessionCtx, {
655
- recordTiming,
656
- deletedCells: model.deletedCells
657
- });
658
- const codeModel = cellWidget.model;
659
- return JSON.stringify({
660
- success: true,
661
- message: 'Code executed successfully in active cell',
662
- cellIndex: activeCellIndex,
663
- executionCount: codeModel.executionCount,
664
- hasOutput: codeModel.outputs.length > 0,
665
- code: code || activeCell.sharedModel.getSource()
666
- });
667
- }
668
- });
669
- }
670
- /**
671
- * Create a tool for saving a specific notebook
672
- */
673
- export function createSaveNotebookTool(docManager, notebookTracker) {
674
- return tool({
675
- title: 'Save Notebook',
676
- description: 'Save a specific notebook to disk',
677
- inputSchema: z.object({
678
- notebookPath: z
679
- .string()
680
- .optional()
681
- .nullable()
682
- .describe('Path to the notebook file. If not provided, uses the currently active notebook')
683
- }),
684
- execute: async (input) => {
685
- const { notebookPath } = input;
686
- const currentWidget = await getNotebookWidget(notebookPath, docManager, notebookTracker);
687
- if (!currentWidget) {
688
- return JSON.stringify({
689
- success: false,
690
- error: notebookPath
691
- ? `Failed to open notebook at path: ${notebookPath}`
692
- : 'No active notebook and no notebook path provided'
693
- });
694
- }
695
- await currentWidget.context.save();
696
- return JSON.stringify({
697
- success: true,
698
- message: 'Notebook saved successfully',
699
- notebookName: currentWidget.title.label,
700
- notebookPath: currentWidget.context.path
701
- });
702
- }
703
- });
704
- }