@jupyterlite/ai 0.8.0 → 0.9.0-a0

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 +233 -0
  2. package/lib/agent.js +604 -0
  3. package/lib/chat-model.d.ts +195 -0
  4. package/lib/chat-model.js +590 -0
  5. package/lib/completion/completion-provider.d.ts +83 -0
  6. package/lib/completion/completion-provider.js +209 -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 +4 -5
  24. package/lib/index.js +322 -167
  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 +69 -0
  28. package/lib/models/settings-model.js +295 -0
  29. package/lib/providers/built-in-providers.d.ts +9 -0
  30. package/lib/providers/built-in-providers.js +192 -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 +157 -86
  36. package/lib/tokens.js +16 -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 +40 -0
  42. package/lib/tools/notebook.js +762 -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 +39 -0
  46. package/lib/widgets/ai-settings.js +506 -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 +13 -0
  50. package/lib/widgets/provider-config-dialog.js +104 -0
  51. package/package.json +150 -41
  52. package/schema/settings-model.json +153 -0
  53. package/src/agent.ts +800 -0
  54. package/src/chat-model.ts +770 -0
  55. package/src/completion/completion-provider.ts +308 -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 +468 -238
  65. package/src/mcp/browser.ts +213 -0
  66. package/src/models/settings-model.ts +409 -0
  67. package/src/providers/built-in-providers.ts +216 -0
  68. package/src/providers/models.ts +79 -0
  69. package/src/providers/provider-registry.ts +189 -0
  70. package/src/tokens.ts +203 -90
  71. package/src/tools/commands.ts +151 -0
  72. package/src/tools/file.ts +307 -0
  73. package/src/tools/notebook.ts +964 -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 +1100 -0
  77. package/src/widgets/chat-wrapper.tsx +543 -0
  78. package/src/widgets/provider-config-dialog.tsx +256 -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,964 @@
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 { 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
+ .default('below')
201
+ .describe('Position relative to current cell')
202
+ }),
203
+ async execute({
204
+ notebookPath,
205
+ content,
206
+ cellType = 'code',
207
+ position = 'below'
208
+ }) {
209
+ try {
210
+ const currentWidget = await getNotebookWidget(
211
+ notebookPath,
212
+ docManager,
213
+ notebookTracker
214
+ );
215
+ if (!currentWidget) {
216
+ return {
217
+ success: false,
218
+ error: notebookPath
219
+ ? `Failed to open notebook at path: ${notebookPath}`
220
+ : 'No active notebook and no notebook path provided'
221
+ };
222
+ }
223
+
224
+ const notebook = currentWidget.content;
225
+ const model = notebook.model;
226
+
227
+ if (!model) {
228
+ return {
229
+ success: false,
230
+ error: 'No notebook model available'
231
+ };
232
+ }
233
+
234
+ // Check if we should replace the first empty cell instead of adding
235
+ const shouldReplaceFirstCell =
236
+ model.cells.length === 1 &&
237
+ model.cells.get(0).sharedModel.getSource().trim() === '';
238
+
239
+ if (shouldReplaceFirstCell) {
240
+ // Replace the first empty cell by removing it and adding new one
241
+ model.sharedModel.deleteCell(0);
242
+ }
243
+
244
+ // Create the new cell using shared model
245
+ const newCellData = {
246
+ cell_type: cellType,
247
+ source: content || '',
248
+ metadata: cellType === 'code' ? { trusted: true } : {}
249
+ };
250
+
251
+ model.sharedModel.addCell(newCellData);
252
+
253
+ // Execute markdown cells after creation to render them
254
+ if (cellType === 'markdown' && content) {
255
+ const cellIndex = model.cells.length - 1;
256
+ const cellWidget = notebook.widgets[cellIndex];
257
+ if (cellWidget && cellWidget instanceof MarkdownCell) {
258
+ try {
259
+ await cellWidget.ready;
260
+ cellWidget.rendered = true;
261
+ } catch (error) {
262
+ console.warn('Failed to render markdown cell:', error);
263
+ }
264
+ }
265
+ }
266
+
267
+ return {
268
+ success: true,
269
+ message: `${cellType} cell added successfully`,
270
+ content: content || '',
271
+ cellType,
272
+ position
273
+ };
274
+ } catch (error) {
275
+ return {
276
+ success: false,
277
+ error: `Failed to add ${cellType} cell: ${(error as Error).message}`
278
+ };
279
+ }
280
+ }
281
+ });
282
+ }
283
+
284
+ /**
285
+ * Create a tool for getting notebook information
286
+ */
287
+ export function createGetNotebookInfoTool(
288
+ docManager: IDocumentManager,
289
+ notebookTracker?: INotebookTracker
290
+ ): ITool {
291
+ return tool({
292
+ name: 'get_notebook_info',
293
+ description:
294
+ 'Get information about a notebook including number of cells and active cell index',
295
+ parameters: z.object({
296
+ notebookPath: z
297
+ .string()
298
+ .optional()
299
+ .nullable()
300
+ .describe(
301
+ 'Path to the notebook file. If not provided, uses the currently active notebook'
302
+ )
303
+ }),
304
+ execute: async (input: { notebookPath?: string | null }) => {
305
+ const { notebookPath } = input;
306
+
307
+ try {
308
+ const currentWidget = await getNotebookWidget(
309
+ notebookPath,
310
+ docManager,
311
+ notebookTracker
312
+ );
313
+ if (!currentWidget) {
314
+ return JSON.stringify({
315
+ success: false,
316
+ error: notebookPath
317
+ ? `Failed to open notebook at path: ${notebookPath}`
318
+ : 'No active notebook and no notebook path provided'
319
+ });
320
+ }
321
+
322
+ const notebook = currentWidget.content;
323
+ const model = notebook.model;
324
+
325
+ if (!model) {
326
+ return JSON.stringify({
327
+ success: false,
328
+ error: 'No notebook model available'
329
+ });
330
+ }
331
+
332
+ const cellCount = model.cells.length;
333
+ const activeCellIndex = notebook.activeCellIndex;
334
+ const activeCell = notebook.activeCell;
335
+ const activeCellType = activeCell?.model.type || 'unknown';
336
+
337
+ return JSON.stringify({
338
+ success: true,
339
+ notebookName: currentWidget.title.label,
340
+ notebookPath: currentWidget.context.path,
341
+ cellCount,
342
+ activeCellIndex,
343
+ activeCellType,
344
+ isDirty: model.dirty
345
+ });
346
+ } catch (error) {
347
+ return JSON.stringify({
348
+ success: false,
349
+ error: `Failed to get notebook info: ${(error as Error).message}`
350
+ });
351
+ }
352
+ }
353
+ });
354
+ }
355
+
356
+ /**
357
+ * Create a tool for getting cell information by index
358
+ */
359
+ export function createGetCellInfoTool(
360
+ docManager: IDocumentManager,
361
+ notebookTracker?: INotebookTracker
362
+ ): ITool {
363
+ return tool({
364
+ name: 'get_cell_info',
365
+ description:
366
+ 'Get information about a specific cell including its type, source content, and outputs',
367
+ parameters: z.object({
368
+ notebookPath: z
369
+ .string()
370
+ .optional()
371
+ .nullable()
372
+ .describe(
373
+ 'Path to the notebook file. If not provided, uses the currently active notebook'
374
+ ),
375
+ cellIndex: z
376
+ .number()
377
+ .describe('Index of the cell to get information for (0-based)')
378
+ }),
379
+ execute: async (input: {
380
+ notebookPath?: string | null;
381
+ cellIndex: number;
382
+ }) => {
383
+ const { notebookPath, cellIndex } = input;
384
+
385
+ try {
386
+ const currentWidget = await getNotebookWidget(
387
+ notebookPath,
388
+ docManager,
389
+ notebookTracker
390
+ );
391
+ if (!currentWidget) {
392
+ return JSON.stringify({
393
+ success: false,
394
+ error: notebookPath
395
+ ? `Failed to open notebook at path: ${notebookPath}`
396
+ : 'No active notebook and no notebook path provided'
397
+ });
398
+ }
399
+
400
+ const notebook = currentWidget.content;
401
+ const model = notebook.model;
402
+
403
+ if (!model) {
404
+ return JSON.stringify({
405
+ success: false,
406
+ error: 'No notebook model available'
407
+ });
408
+ }
409
+
410
+ if (cellIndex < 0 || cellIndex >= model.cells.length) {
411
+ return JSON.stringify({
412
+ success: false,
413
+ error: `Invalid cell index: ${cellIndex}. Notebook has ${model.cells.length} cells.`
414
+ });
415
+ }
416
+
417
+ const cell = model.cells.get(cellIndex);
418
+ const cellType = cell.type;
419
+ const sharedModel = cell.sharedModel;
420
+ const source = sharedModel.getSource();
421
+
422
+ // Get outputs for code cells
423
+ let outputs: any[] = [];
424
+ if (cellType === 'code') {
425
+ const rawOutputs = sharedModel.toJSON().outputs;
426
+ outputs = Array.isArray(rawOutputs) ? rawOutputs : [];
427
+ }
428
+
429
+ return JSON.stringify({
430
+ success: true,
431
+ cellId: cell.id,
432
+ cellIndex,
433
+ cellType,
434
+ source,
435
+ outputs,
436
+ executionCount:
437
+ cellType === 'code' ? (cell as any).executionCount : null
438
+ });
439
+ } catch (error) {
440
+ return JSON.stringify({
441
+ success: false,
442
+ error: `Failed to get cell info: ${(error as Error).message}`
443
+ });
444
+ }
445
+ }
446
+ });
447
+ }
448
+
449
+ /**
450
+ * Create a tool for setting cell content and type
451
+ */
452
+ export function createSetCellContentTool(
453
+ docManager: IDocumentManager,
454
+ notebookTracker?: INotebookTracker
455
+ ): ITool {
456
+ return tool({
457
+ name: 'set_cell_content',
458
+ description:
459
+ 'Set the content of a specific cell and return both the previous and new content',
460
+ parameters: z.object({
461
+ notebookPath: z
462
+ .string()
463
+ .optional()
464
+ .nullable()
465
+ .describe(
466
+ 'Path to the notebook file. If not provided, uses the currently active notebook'
467
+ ),
468
+ cellId: z
469
+ .string()
470
+ .optional()
471
+ .nullable()
472
+ .describe(
473
+ 'ID of the cell to modify. If provided, takes precedence over cellIndex'
474
+ ),
475
+ cellIndex: z
476
+ .number()
477
+ .optional()
478
+ .nullable()
479
+ .describe(
480
+ 'Index of the cell to modify (0-based). Used if cellId is not provided. If neither is provided, targets the active cell'
481
+ ),
482
+ content: z.string().describe('New content for the cell')
483
+ }),
484
+ execute: async (input: {
485
+ notebookPath?: string | null;
486
+ cellId?: string | null;
487
+ cellIndex?: number | null;
488
+ content: string;
489
+ }) => {
490
+ const { notebookPath, cellId, cellIndex, content } = input;
491
+
492
+ try {
493
+ const currentWidget = await getNotebookWidget(
494
+ notebookPath,
495
+ docManager,
496
+ notebookTracker
497
+ );
498
+ if (!currentWidget) {
499
+ return JSON.stringify({
500
+ success: false,
501
+ error: notebookPath
502
+ ? `Failed to open notebook at path: ${notebookPath}`
503
+ : 'No active notebook and no notebook path provided'
504
+ });
505
+ }
506
+
507
+ const notebook = currentWidget.content;
508
+ const model = notebook.model;
509
+
510
+ if (!model) {
511
+ return JSON.stringify({
512
+ success: false,
513
+ error: 'No notebook model available'
514
+ });
515
+ }
516
+
517
+ // Determine target cell index
518
+ let targetCellIndex: number;
519
+ if (cellId !== undefined && cellId !== null) {
520
+ // Find cell by ID
521
+ targetCellIndex = -1;
522
+ for (let i = 0; i < model.cells.length; i++) {
523
+ if (model.cells.get(i).id === cellId) {
524
+ targetCellIndex = i;
525
+ break;
526
+ }
527
+ }
528
+ if (targetCellIndex === -1) {
529
+ return JSON.stringify({
530
+ success: false,
531
+ error: `Cell with ID '${cellId}' not found in notebook`
532
+ });
533
+ }
534
+ } else if (cellIndex !== undefined && cellIndex !== null) {
535
+ // Use provided cell index
536
+ if (cellIndex < 0 || cellIndex >= model.cells.length) {
537
+ return JSON.stringify({
538
+ success: false,
539
+ error: `Invalid cell index: ${cellIndex}. Notebook has ${model.cells.length} cells.`
540
+ });
541
+ }
542
+ targetCellIndex = cellIndex;
543
+ } else {
544
+ // Use active cell
545
+ targetCellIndex = notebook.activeCellIndex;
546
+ if (targetCellIndex === -1 || targetCellIndex >= model.cells.length) {
547
+ return JSON.stringify({
548
+ success: false,
549
+ error: 'No active cell or invalid active cell index'
550
+ });
551
+ }
552
+ }
553
+
554
+ // Get the target cell
555
+ const targetCell = model.cells.get(targetCellIndex);
556
+ if (!targetCell) {
557
+ return JSON.stringify({
558
+ success: false,
559
+ error: `Cell at index ${targetCellIndex} not found`
560
+ });
561
+ }
562
+
563
+ const sharedModel = targetCell.sharedModel;
564
+
565
+ // Get previous content and type
566
+ const previousContent = sharedModel.getSource();
567
+ const previousCellType = targetCell.type;
568
+ const retrievedCellId = targetCell.id;
569
+
570
+ sharedModel.setSource(content);
571
+
572
+ return JSON.stringify({
573
+ success: true,
574
+ message:
575
+ cellId !== undefined && cellId !== null
576
+ ? `Cell with ID '${cellId}' content replaced successfully`
577
+ : cellIndex !== undefined && cellIndex !== null
578
+ ? `Cell ${targetCellIndex} content replaced successfully`
579
+ : 'Active cell content replaced successfully',
580
+ notebookPath: currentWidget.context.path,
581
+ cellId: retrievedCellId,
582
+ cellIndex: targetCellIndex,
583
+ previousContent,
584
+ previousCellType,
585
+ newContent: content,
586
+ wasActiveCell: cellId === undefined && cellIndex === undefined
587
+ });
588
+ } catch (error) {
589
+ return JSON.stringify({
590
+ success: false,
591
+ error: `Failed to replace cell content: ${(error as Error).message}`
592
+ });
593
+ }
594
+ }
595
+ });
596
+ }
597
+
598
+ /**
599
+ * Create a tool for running a specific cell
600
+ */
601
+ export function createRunCellTool(
602
+ docManager: IDocumentManager,
603
+ notebookTracker?: INotebookTracker
604
+ ): ITool {
605
+ return tool({
606
+ name: 'run_cell',
607
+ description: 'Run a specific cell in the notebook by index',
608
+ parameters: z.object({
609
+ notebookPath: z
610
+ .string()
611
+ .optional()
612
+ .nullable()
613
+ .describe(
614
+ 'Path to the notebook file. If not provided, uses the currently active notebook'
615
+ ),
616
+ cellIndex: z.number().describe('Index of the cell to run (0-based)'),
617
+ recordTiming: z
618
+ .boolean()
619
+ .default(true)
620
+ .describe('Whether to record execution timing')
621
+ }),
622
+ needsApproval: true,
623
+ execute: async (input: {
624
+ notebookPath?: string | null;
625
+ cellIndex: number;
626
+ recordTiming?: boolean;
627
+ }) => {
628
+ const { notebookPath, cellIndex, recordTiming = true } = input;
629
+
630
+ try {
631
+ const currentWidget = await getNotebookWidget(
632
+ notebookPath,
633
+ docManager,
634
+ notebookTracker
635
+ );
636
+ if (!currentWidget) {
637
+ return JSON.stringify({
638
+ success: false,
639
+ error: notebookPath
640
+ ? `Failed to open notebook at path: ${notebookPath}`
641
+ : 'No active notebook and no notebook path provided'
642
+ });
643
+ }
644
+
645
+ const notebook = currentWidget.content;
646
+ const model = notebook.model;
647
+
648
+ if (!model) {
649
+ return JSON.stringify({
650
+ success: false,
651
+ error: 'No notebook model available'
652
+ });
653
+ }
654
+
655
+ if (cellIndex < 0 || cellIndex >= model.cells.length) {
656
+ return JSON.stringify({
657
+ success: false,
658
+ error: `Invalid cell index: ${cellIndex}. Notebook has ${model.cells.length} cells.`
659
+ });
660
+ }
661
+
662
+ // Get the target cell widget
663
+ const cellWidget = notebook.widgets[cellIndex];
664
+ if (!cellWidget) {
665
+ return JSON.stringify({
666
+ success: false,
667
+ error: `Cell widget at index ${cellIndex} not found`
668
+ });
669
+ }
670
+
671
+ // Execute using shared model approach (non-disruptive)
672
+ try {
673
+ if (cellWidget instanceof CodeCell) {
674
+ // Use direct CodeCell.execute() method
675
+ const sessionCtx = currentWidget.sessionContext;
676
+ await CodeCell.execute(cellWidget, sessionCtx, {
677
+ recordTiming,
678
+ deletedCells: model.deletedCells
679
+ });
680
+
681
+ const codeModel = cellWidget.model as ICodeCellModel;
682
+ return JSON.stringify({
683
+ success: true,
684
+ message: `Cell ${cellIndex} executed successfully`,
685
+ cellIndex,
686
+ executionCount: codeModel.executionCount,
687
+ hasOutput: codeModel.outputs.length > 0
688
+ });
689
+ } else {
690
+ // For non-code cells, just return success
691
+ return JSON.stringify({
692
+ success: true,
693
+ message: `Cell ${cellIndex} is not a code cell, no execution needed`,
694
+ cellIndex,
695
+ cellType: cellWidget.model.type
696
+ });
697
+ }
698
+ } catch (error) {
699
+ return JSON.stringify({
700
+ success: false,
701
+ error: `Failed to execute cell: ${(error as Error).message}`,
702
+ cellIndex
703
+ });
704
+ }
705
+ } catch (error) {
706
+ return JSON.stringify({
707
+ success: false,
708
+ error: `Failed to run cell: ${(error as Error).message}`
709
+ });
710
+ }
711
+ }
712
+ });
713
+ }
714
+
715
+ /**
716
+ * Create a tool for deleting a specific cell
717
+ */
718
+ export function createDeleteCellTool(
719
+ docManager: IDocumentManager,
720
+ notebookTracker?: INotebookTracker
721
+ ): ITool {
722
+ return tool({
723
+ name: 'delete_cell',
724
+ description: 'Delete a specific cell from the notebook by index',
725
+ parameters: z.object({
726
+ notebookPath: z
727
+ .string()
728
+ .optional()
729
+ .nullable()
730
+ .describe(
731
+ 'Path to the notebook file. If not provided, uses the currently active notebook'
732
+ ),
733
+ cellIndex: z.number().describe('Index of the cell to delete (0-based)')
734
+ }),
735
+ execute: async (input: {
736
+ notebookPath?: string | null;
737
+ cellIndex: number;
738
+ }) => {
739
+ const { notebookPath, cellIndex } = input;
740
+
741
+ try {
742
+ const currentWidget = await getNotebookWidget(
743
+ notebookPath,
744
+ docManager,
745
+ notebookTracker
746
+ );
747
+ if (!currentWidget) {
748
+ return JSON.stringify({
749
+ success: false,
750
+ error: notebookPath
751
+ ? `Failed to open notebook at path: ${notebookPath}`
752
+ : 'No active notebook and no notebook path provided'
753
+ });
754
+ }
755
+
756
+ const notebook = currentWidget.content;
757
+ const model = notebook.model;
758
+
759
+ if (!model) {
760
+ return JSON.stringify({
761
+ success: false,
762
+ error: 'No notebook model available'
763
+ });
764
+ }
765
+
766
+ if (cellIndex < 0 || cellIndex >= model.cells.length) {
767
+ return JSON.stringify({
768
+ success: false,
769
+ error: `Invalid cell index: ${cellIndex}. Notebook has ${model.cells.length} cells.`
770
+ });
771
+ }
772
+
773
+ // Validate cell exists
774
+ const targetCell = model.cells.get(cellIndex);
775
+ if (!targetCell) {
776
+ return JSON.stringify({
777
+ success: false,
778
+ error: `Cell at index ${cellIndex} not found`
779
+ });
780
+ }
781
+
782
+ // Delete cell using shared model (non-disruptive)
783
+ model.sharedModel.deleteCell(cellIndex);
784
+
785
+ return JSON.stringify({
786
+ success: true,
787
+ message: `Cell ${cellIndex} deleted successfully`,
788
+ cellIndex,
789
+ remainingCells: model.cells.length
790
+ });
791
+ } catch (error) {
792
+ return JSON.stringify({
793
+ success: false,
794
+ error: `Failed to delete cell: ${(error as Error).message}`
795
+ });
796
+ }
797
+ }
798
+ });
799
+ }
800
+
801
+ /**
802
+ * Create a tool for executing code in the active cell (non-disruptive alternative to mcp__ide__executeCode)
803
+ */
804
+ export function createExecuteActiveCellTool(
805
+ docManager: IDocumentManager,
806
+ notebookTracker?: INotebookTracker
807
+ ): ITool {
808
+ return tool({
809
+ name: 'execute_active_cell',
810
+ description:
811
+ 'Execute the currently active cell in the notebook without disrupting user focus',
812
+ parameters: z.object({
813
+ notebookPath: z
814
+ .string()
815
+ .optional()
816
+ .nullable()
817
+ .describe(
818
+ 'Path to the notebook file. If not provided, uses the currently active notebook'
819
+ ),
820
+ code: z
821
+ .string()
822
+ .optional()
823
+ .nullable()
824
+ .describe('Optional: set cell content before executing'),
825
+ recordTiming: z
826
+ .boolean()
827
+ .default(true)
828
+ .describe('Whether to record execution timing')
829
+ }),
830
+ execute: async (input: {
831
+ notebookPath?: string | null;
832
+ code?: string | null;
833
+ recordTiming?: boolean;
834
+ }) => {
835
+ const { notebookPath, code, recordTiming = true } = input;
836
+
837
+ try {
838
+ const currentWidget = await getNotebookWidget(
839
+ notebookPath,
840
+ docManager,
841
+ notebookTracker
842
+ );
843
+ if (!currentWidget) {
844
+ return JSON.stringify({
845
+ success: false,
846
+ error: notebookPath
847
+ ? `Failed to open notebook at path: ${notebookPath}`
848
+ : 'No active notebook and no notebook path provided'
849
+ });
850
+ }
851
+
852
+ const notebook = currentWidget.content;
853
+ const model = notebook.model;
854
+ const activeCellIndex = notebook.activeCellIndex;
855
+
856
+ if (!model || activeCellIndex === -1) {
857
+ return JSON.stringify({
858
+ success: false,
859
+ error: 'No notebook model or active cell available'
860
+ });
861
+ }
862
+
863
+ const activeCell = model.cells.get(activeCellIndex);
864
+ if (!activeCell) {
865
+ return JSON.stringify({
866
+ success: false,
867
+ error: 'Active cell not found'
868
+ });
869
+ }
870
+
871
+ // Set code content if provided
872
+ if (code) {
873
+ activeCell.sharedModel.setSource(code);
874
+ }
875
+
876
+ // Get the cell widget for execution
877
+ const cellWidget = notebook.widgets[activeCellIndex];
878
+ if (!cellWidget || !(cellWidget instanceof CodeCell)) {
879
+ return JSON.stringify({
880
+ success: false,
881
+ error: 'Active cell is not a code cell'
882
+ });
883
+ }
884
+
885
+ // Execute using shared model approach (non-disruptive)
886
+ const sessionCtx = currentWidget.sessionContext;
887
+ await CodeCell.execute(cellWidget, sessionCtx, {
888
+ recordTiming,
889
+ deletedCells: model.deletedCells
890
+ });
891
+
892
+ const codeModel = cellWidget.model as ICodeCellModel;
893
+ return JSON.stringify({
894
+ success: true,
895
+ message: 'Code executed successfully in active cell',
896
+ cellIndex: activeCellIndex,
897
+ executionCount: codeModel.executionCount,
898
+ hasOutput: codeModel.outputs.length > 0,
899
+ code: code || activeCell.sharedModel.getSource()
900
+ });
901
+ } catch (error) {
902
+ return JSON.stringify({
903
+ success: false,
904
+ error: `Failed to execute code: ${(error as Error).message}`
905
+ });
906
+ }
907
+ }
908
+ });
909
+ }
910
+
911
+ /**
912
+ * Create a tool for saving a specific notebook
913
+ */
914
+ export function createSaveNotebookTool(
915
+ docManager: IDocumentManager,
916
+ notebookTracker?: INotebookTracker
917
+ ): ITool {
918
+ return tool({
919
+ name: 'save_notebook',
920
+ description: 'Save a specific notebook to disk',
921
+ parameters: z.object({
922
+ notebookPath: z
923
+ .string()
924
+ .optional()
925
+ .nullable()
926
+ .describe(
927
+ 'Path to the notebook file. If not provided, uses the currently active notebook'
928
+ )
929
+ }),
930
+ execute: async (input: { notebookPath?: string | null }) => {
931
+ const { notebookPath } = input;
932
+
933
+ try {
934
+ const currentWidget = await getNotebookWidget(
935
+ notebookPath,
936
+ docManager,
937
+ notebookTracker
938
+ );
939
+ if (!currentWidget) {
940
+ return JSON.stringify({
941
+ success: false,
942
+ error: notebookPath
943
+ ? `Failed to open notebook at path: ${notebookPath}`
944
+ : 'No active notebook and no notebook path provided'
945
+ });
946
+ }
947
+
948
+ await currentWidget.context.save();
949
+
950
+ return JSON.stringify({
951
+ success: true,
952
+ message: 'Notebook saved successfully',
953
+ notebookName: currentWidget.title.label,
954
+ notebookPath: currentWidget.context.path
955
+ });
956
+ } catch (error) {
957
+ return JSON.stringify({
958
+ success: false,
959
+ error: `Failed to save notebook: ${(error as Error).message}`
960
+ });
961
+ }
962
+ }
963
+ });
964
+ }