forked from notebook-intelligence/notebook-intelligence
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
1883 lines (1654 loc) · 56.4 KB
/
index.ts
File metadata and controls
1883 lines (1654 loc) · 56.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Mehmet Bektas <mbektasgh@outlook.com>
import {
JupyterFrontEnd,
JupyterFrontEndPlugin,
JupyterLab
} from '@jupyterlab/application';
import { IDocumentManager } from '@jupyterlab/docmanager';
import { DocumentWidget, IDocumentWidget } from '@jupyterlab/docregistry';
import { Dialog, ICommandPalette } from '@jupyterlab/apputils';
import { IMainMenu } from '@jupyterlab/mainmenu';
import { IEditorLanguageRegistry } from '@jupyterlab/codemirror';
import { CodeCell } from '@jupyterlab/cells';
import { ISharedNotebook } from '@jupyter/ydoc';
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import {
CompletionHandler,
ICompletionProviderManager,
IInlineCompletionContext,
IInlineCompletionItem,
IInlineCompletionList,
IInlineCompletionProvider
} from '@jupyterlab/completer';
import { NotebookPanel } from '@jupyterlab/notebook';
import { CodeEditor } from '@jupyterlab/codeeditor';
import { FileEditorWidget } from '@jupyterlab/fileeditor';
import { IDefaultFileBrowser } from '@jupyterlab/filebrowser';
import { ContentsManager, KernelSpecManager } from '@jupyterlab/services';
import { LabIcon } from '@jupyterlab/ui-components';
import { Menu, Panel, Widget } from '@lumino/widgets';
import { CommandRegistry } from '@lumino/commands';
import { IStatusBar } from '@jupyterlab/statusbar';
import {
ChatSidebar,
ConfigurationDialogBody,
GitHubCopilotLoginDialogBody,
GitHubCopilotStatusBarItem,
InlinePromptWidget,
RunChatCompletionType
} from './chat-sidebar';
import { NBIAPI, GitHubCopilotLoginStatus } from './api';
import {
BackendMessageType,
GITHUB_COPILOT_PROVIDER_ID,
IActiveDocumentInfo,
ICellContents,
INotebookIntelligence,
ITelemetryEmitter,
ITelemetryEvent,
ITelemetryListener,
RequestDataType,
TelemetryEventType
} from './tokens';
import sparklesSvgstr from '../style/icons/sparkles.svg';
import copilotSvgstr from '../style/icons/copilot.svg';
import {
applyCodeToSelectionInEditor,
cellOutputAsText,
compareSelections,
extractLLMGeneratedCode,
getSelectionInEditor,
getTokenCount,
getWholeNotebookContent,
isSelectionEmpty,
markdownToComment,
waitForDuration
} from './utils';
import { UUID } from '@lumino/coreutils';
import * as path from 'path';
namespace CommandIDs {
export const chatuserInput = 'lab-notebook-intelligence:chat-user-input';
export const insertAtCursor = 'lab-notebook-intelligence:insert-at-cursor';
export const addCodeAsNewCell =
'lab-notebook-intelligence:add-code-as-new-cell';
export const createNewFile = 'lab-notebook-intelligence:create-new-file';
export const createNewNotebookFromPython =
'lab-notebook-intelligence:create-new-notebook-from-py';
export const renameNotebook = 'lab-notebook-intelligence:rename-notebook';
export const addCodeCellToNotebook =
'lab-notebook-intelligence:add-code-cell-to-notebook';
export const addMarkdownCellToNotebook =
'lab-notebook-intelligence:add-markdown-cell-to-notebook';
export const editorGenerateCode =
'lab-notebook-intelligence:editor-generate-code';
export const editorExplainThisCode =
'lab-notebook-intelligence:editor-explain-this-code';
export const editorFixThisCode =
'lab-notebook-intelligence:editor-fix-this-code';
export const editorExplainThisOutput =
'lab-notebook-intelligence:editor-explain-this-output';
export const editorTroubleshootThisOutput =
'lab-notebook-intelligence:editor-troubleshoot-this-output';
export const openGitHubCopilotLoginDialog =
'lab-notebook-intelligence:open-github-copilot-login-dialog';
export const openConfigurationDialog =
'lab-notebook-intelligence:open-configuration-dialog';
export const addMarkdownCellToActiveNotebook =
'lab-notebook-intelligence:add-markdown-cell-to-active-notebook';
export const addCodeCellToActiveNotebook =
'lab-notebook-intelligence:add-code-cell-to-active-notebook';
export const deleteCellAtIndex =
'lab-notebook-intelligence:delete-cell-at-index';
export const insertCellAtIndex =
'lab-notebook-intelligence:insert-cell-at-index';
export const getCellTypeAndSource =
'lab-notebook-intelligence:get-cell-type-and-source';
export const setCellTypeAndSource =
'lab-notebook-intelligence:set-cell-type-and-source';
export const getNumberOfCells =
'lab-notebook-intelligence:get-number-of-cells';
export const getCellOutput = 'lab-notebook-intelligence:get-cell-output';
export const runCellAtIndex = 'lab-notebook-intelligence:run-cell-at-index';
export const getCurrentFileContent =
'lab-notebook-intelligence:get-current-file-content';
export const setCurrentFileContent =
'lab-notebook-intelligence:set-current-file-content';
export const openMCPConfigEditor =
'lab-notebook-intelligence:open-mcp-config-editor';
}
const DOCUMENT_WATCH_INTERVAL = 1000;
const MAX_TOKENS = 4096;
const githubCopilotIcon = new LabIcon({
name: 'lab-notebook-intelligence:github-copilot-icon',
svgstr: copilotSvgstr
});
const sparkleIcon = new LabIcon({
name: 'lab-notebook-intelligence:sparkles-icon',
svgstr: sparklesSvgstr
});
const emptyNotebookContent: any = {
cells: [],
metadata: {},
nbformat: 4,
nbformat_minor: 5
};
const BACKEND_TELEMETRY_LISTENER_NAME = 'backend-telemetry-listener';
class ActiveDocumentWatcher {
static initialize(
app: JupyterLab,
languageRegistry: IEditorLanguageRegistry
) {
ActiveDocumentWatcher._languageRegistry = languageRegistry;
app.shell.currentChanged?.connect((_sender, args) => {
ActiveDocumentWatcher.watchDocument(args.newValue);
});
ActiveDocumentWatcher.activeDocumentInfo.activeWidget =
app.shell.currentWidget;
ActiveDocumentWatcher.handleWatchDocument();
}
static watchDocument(widget: Widget) {
if (ActiveDocumentWatcher.activeDocumentInfo.activeWidget === widget) {
return;
}
clearInterval(ActiveDocumentWatcher._watchTimer);
ActiveDocumentWatcher.activeDocumentInfo.activeWidget = widget;
ActiveDocumentWatcher._watchTimer = setInterval(() => {
ActiveDocumentWatcher.handleWatchDocument();
}, DOCUMENT_WATCH_INTERVAL);
ActiveDocumentWatcher.handleWatchDocument();
}
static handleWatchDocument() {
const activeDocumentInfo = ActiveDocumentWatcher.activeDocumentInfo;
const previousDocumentInfo = {
...activeDocumentInfo,
...{ activeWidget: null }
};
const activeWidget = activeDocumentInfo.activeWidget;
if (activeWidget instanceof NotebookPanel) {
const np = activeWidget as NotebookPanel;
activeDocumentInfo.filename = np.sessionContext.name;
activeDocumentInfo.filePath = np.sessionContext.path;
activeDocumentInfo.language =
(np.model?.sharedModel?.metadata?.kernelspec?.language as string) ||
'python';
const { activeCellIndex, activeCell } = np.content;
activeDocumentInfo.activeCellIndex = activeCellIndex;
activeDocumentInfo.selection = activeCell?.editor?.getSelection();
} else if (activeWidget) {
const dw = activeWidget as DocumentWidget;
const contentsModel = dw.context?.contentsModel;
if (contentsModel?.format === 'text') {
const fileName = contentsModel.name;
const filePath = contentsModel.path;
const language =
ActiveDocumentWatcher._languageRegistry.findByMIME(
contentsModel.mimetype
) || ActiveDocumentWatcher._languageRegistry.findByFileName(fileName);
activeDocumentInfo.language = language?.name || 'unknown';
activeDocumentInfo.filename = fileName;
activeDocumentInfo.filePath = filePath;
if (activeWidget instanceof FileEditorWidget) {
const fe = activeWidget as FileEditorWidget;
activeDocumentInfo.selection = fe.content.editor?.getSelection();
} else {
activeDocumentInfo.selection = undefined;
}
} else {
activeDocumentInfo.filename = '';
activeDocumentInfo.filePath = '';
activeDocumentInfo.language = '';
}
}
if (
ActiveDocumentWatcher.documentInfoChanged(
previousDocumentInfo,
activeDocumentInfo
)
) {
ActiveDocumentWatcher.fireActiveDocumentChangedEvent();
}
}
private static documentInfoChanged(
lhs: IActiveDocumentInfo,
rhs: IActiveDocumentInfo
): boolean {
if (!lhs || !rhs) {
return true;
}
return (
lhs.filename !== rhs.filename ||
lhs.filePath !== rhs.filePath ||
lhs.language !== rhs.language ||
lhs.activeCellIndex !== rhs.activeCellIndex ||
!compareSelections(lhs.selection, rhs.selection)
);
}
static getActiveSelectionContent(): string {
const activeDocumentInfo = ActiveDocumentWatcher.activeDocumentInfo;
const activeWidget = activeDocumentInfo.activeWidget;
if (activeWidget instanceof NotebookPanel) {
const np = activeWidget as NotebookPanel;
const editor = np.content.activeCell.editor;
if (isSelectionEmpty(editor.getSelection())) {
return getWholeNotebookContent(np);
} else {
return getSelectionInEditor(editor);
}
} else if (activeWidget instanceof FileEditorWidget) {
const fe = activeWidget as FileEditorWidget;
const editor = fe.content.editor;
if (isSelectionEmpty(editor.getSelection())) {
return editor.model.sharedModel.getSource();
} else {
return getSelectionInEditor(editor);
}
} else {
const dw = activeWidget as DocumentWidget;
const content = dw?.context?.model?.toString();
const maxContext = 0.5 * MAX_TOKENS;
return content.substring(0, maxContext);
}
}
static getCurrentCellContents(): ICellContents {
const activeDocumentInfo = ActiveDocumentWatcher.activeDocumentInfo;
const activeWidget = activeDocumentInfo.activeWidget;
if (activeWidget instanceof NotebookPanel) {
const np = activeWidget as NotebookPanel;
const activeCell = np.content.activeCell;
const input = activeCell.model.sharedModel.source.trim();
let output = '';
if (activeCell instanceof CodeCell) {
output = cellOutputAsText(np.content.activeCell as CodeCell);
}
return { input, output };
}
return null;
}
static fireActiveDocumentChangedEvent() {
document.dispatchEvent(
new CustomEvent('copilotSidebar:activeDocumentChanged', {
detail: {
activeDocumentInfo: ActiveDocumentWatcher.activeDocumentInfo
}
})
);
}
static activeDocumentInfo: IActiveDocumentInfo = {
language: 'python',
filename: 'nb-doesnt-exist.ipynb',
filePath: 'nb-doesnt-exist.ipynb',
activeWidget: null,
activeCellIndex: -1,
selection: null
};
private static _watchTimer: any;
private static _languageRegistry: IEditorLanguageRegistry;
}
class NBIInlineCompletionProvider
implements IInlineCompletionProvider<IInlineCompletionItem>
{
private _NBCellContextState: {
activeCellIndex: number;
preContent: string;
postContent: string;
};
constructor(telemetryEmitter: TelemetryEmitter) {
this._telemetryEmitter = telemetryEmitter;
this._NBCellContextState = {
activeCellIndex: -1,
preContent: '',
postContent: ''
};
}
get schema(): ISettingRegistry.IProperty {
return {
default: {
debouncerDelay: 100,
timeout: 15000
}
};
}
private calculateCellContext(context: IInlineCompletionContext): {
preContent: string;
postContent: string;
} {
if (!(context.widget instanceof NotebookPanel)) {
return { preContent: '', postContent: '' };
}
const notebook = context.widget.content;
const activeCellIndex = notebook.activeCellIndex;
// Check if the active cell has changed
if (this._NBCellContextState.activeCellIndex === activeCellIndex) {
// Return cached content if the active cell hasn't changed
return {
preContent: this._NBCellContextState.preContent,
postContent: this._NBCellContextState.postContent
};
}
// Recalculate pre and post content
let preContent = '';
let postContent = '';
// const activeCell = notebook.activeCell;
let activeCellReached = false;
for (let i = 0; i < notebook.widgets.length; i++) {
const cell = notebook.widgets[i];
const cellModel = cell.model.sharedModel;
if (i === activeCellIndex) {
activeCellReached = true;
} else if (!activeCellReached) {
if (cellModel.cell_type === 'code') {
preContent += cellModel.source + '\n';
} else if (cellModel.cell_type === 'markdown') {
preContent += markdownToComment(cellModel.source) + '\n';
}
} else {
if (cellModel.cell_type === 'code') {
postContent += cellModel.source + '\n';
} else if (cellModel.cell_type === 'markdown') {
postContent += markdownToComment(cellModel.source) + '\n';
}
}
}
// Update the state
this._NBCellContextState.activeCellIndex = activeCellIndex;
this._NBCellContextState.preContent = preContent;
this._NBCellContextState.postContent = postContent;
return { preContent, postContent };
}
fetch(
request: CompletionHandler.IRequest,
context: IInlineCompletionContext
): Promise<IInlineCompletionList<IInlineCompletionItem>> {
let preContent = '';
let postContent = '';
const preCursor = request.text.substring(0, request.offset);
const postCursor = request.text.substring(request.offset);
const language = ActiveDocumentWatcher.activeDocumentInfo.language;
let editorType = 'file-editor';
if (context.widget instanceof NotebookPanel) {
editorType = 'notebook';
({ preContent, postContent } = this.calculateCellContext(context));
}
const nbiConfig = NBIAPI.config;
const inlineCompletionsEnabled =
nbiConfig.inlineCompletionModel.provider === GITHUB_COPILOT_PROVIDER_ID
? NBIAPI.getLoginStatus() === GitHubCopilotLoginStatus.LoggedIn
: nbiConfig.inlineCompletionModel.provider !== 'none';
this._telemetryEmitter.emitTelemetryEvent({
type: TelemetryEventType.InlineCompletionRequest,
data: {
inlineCompletionModel: {
provider: NBIAPI.config.inlineCompletionModel.provider,
model: NBIAPI.config.inlineCompletionModel.model
},
editorType
}
});
return new Promise((resolve, reject) => {
const items: IInlineCompletionItem[] = [];
if (!inlineCompletionsEnabled) {
resolve({ items });
return;
}
if (this._lastRequestInfo) {
NBIAPI.sendWebSocketMessage(
this._lastRequestInfo.messageId,
RequestDataType.CancelInlineCompletionRequest,
{ chatId: this._lastRequestInfo.chatId }
);
// TODO: handle fast-typers
if (
this._lastRequestInfo.completion &&
preCursor.length > 0 &&
preCursor[preCursor.length - 1] ===
this._lastRequestInfo.completion[0]
) {
// if the last element of the preCursor is the first element of the completion
// we do not need to make a completion request on the assumption that the
// user is about to type the rest of the completion
resolve({
items: [
{ insertText: this._lastRequestInfo.completion.substring(1) }
]
});
this._lastRequestInfo.completion =
this._lastRequestInfo.completion.substring(1);
return;
}
}
const messageId = UUID.uuid4();
const chatId = UUID.uuid4();
this._lastRequestInfo = {
chatId,
messageId,
completion: '',
requestTime: new Date()
};
NBIAPI.inlineCompletionsRequest(
chatId,
messageId,
preContent + preCursor,
postCursor + postContent,
language,
ActiveDocumentWatcher.activeDocumentInfo.filename,
{
emit: (response: any) => {
if (
response.type === BackendMessageType.StreamMessage &&
response.id === this._lastRequestInfo.messageId
) {
items.push({
insertText: response.data.completions
});
this._lastRequestInfo.completion = response.data.completions;
const timeElapsed =
(new Date().getTime() -
this._lastRequestInfo.requestTime.getTime()) /
1000;
this._telemetryEmitter.emitTelemetryEvent({
type: TelemetryEventType.InlineCompletionResponse,
data: {
inlineCompletionModel: {
provider: NBIAPI.config.inlineCompletionModel.provider,
model: NBIAPI.config.inlineCompletionModel.model
},
timeElapsed
}
});
resolve({ items });
} else {
reject();
}
}
}
);
});
}
get name(): string {
return 'Notebook Intelligence';
}
get identifier(): string {
return '@notebook-intelligence/lab-notebook-intelligence';
}
get icon(): LabIcon.ILabIcon {
return NBIAPI.config.usingGitHubCopilotModel
? githubCopilotIcon
: sparkleIcon;
}
private _lastRequestInfo: {
chatId: string;
messageId: string;
completion: string;
requestTime: Date;
} = null;
private _telemetryEmitter: TelemetryEmitter;
}
class TelemetryEmitter implements ITelemetryEmitter {
registerTelemetryListener(listener: ITelemetryListener) {
const listenerName = listener.name;
if (listenerName !== BACKEND_TELEMETRY_LISTENER_NAME) {
console.warn(
`Notebook Intelligence telemetry listener '${listenerName}' registered. Make sure it is from a trusted source.`
);
}
let listenerAlreadyExists = false;
this._listeners.forEach(existingListener => {
if (existingListener.name === listenerName) {
listenerAlreadyExists = true;
}
});
if (listenerAlreadyExists) {
console.error(
`Notebook Intelligence telemetry listener '${listenerName}' already exists!`
);
return;
}
this._listeners.add(listener);
}
unregisterTelemetryListener(listener: ITelemetryListener) {
this._listeners.delete(listener);
}
emitTelemetryEvent(event: ITelemetryEvent) {
this._listeners.forEach(listener => {
listener.onTelemetryEvent(event);
});
}
private _listeners: Set<ITelemetryListener> = new Set<ITelemetryListener>();
}
class MCPConfigEditor {
constructor(docManager: IDocumentManager) {
this._docManager = docManager;
}
async open() {
const contents = new ContentsManager();
const newJSONFile = await contents.newUntitled({
ext: '.json'
});
const mcpConfig = await NBIAPI.getMCPConfigFile();
try {
await contents.delete(this._tmpMCPConfigFilename);
} catch (error) {
// ignore
}
await contents.save(newJSONFile.path, {
content: JSON.stringify(mcpConfig, null, 2),
format: 'text',
type: 'file'
});
await contents.rename(newJSONFile.path, this._tmpMCPConfigFilename);
this._docWidget = this._docManager.openOrReveal(
this._tmpMCPConfigFilename,
'Editor'
);
this._addListeners();
// tab closed
this._docWidget.disposed.connect((_, args) => {
this._removeListeners();
contents.delete(this._tmpMCPConfigFilename);
});
this._isOpen = true;
}
close() {
if (!this._isOpen) {
return;
}
this._isOpen = false;
this._docWidget.dispose();
this._docWidget = null;
}
get isOpen(): boolean {
return this._isOpen;
}
private _addListeners() {
this._docWidget.context.model.stateChanged.connect(
this._onStateChanged,
this
);
}
private _removeListeners() {
this._docWidget.context.model.stateChanged.disconnect(
this._onStateChanged,
this
);
}
private _onStateChanged(model: any, args: any) {
if (args.name === 'dirty' && args.newValue === false) {
this._onSave();
}
}
private async _onSave() {
const mcpConfig = this._docWidget.context.model.toJSON();
await NBIAPI.setMCPConfigFile(mcpConfig);
await NBIAPI.fetchCapabilities();
}
private _docManager: IDocumentManager;
private _docWidget: IDocumentWidget = null;
private _tmpMCPConfigFilename = 'nbi.mcp.temp.json';
private _isOpen = false;
}
/**
* Initialization data for the @qbraid/lab-notebook-intelligence extension.
*/
const plugin: JupyterFrontEndPlugin<INotebookIntelligence> = {
id: '@qbraid/lab-notebook-intelligence:plugin',
description: 'Notebook Intelligence',
autoStart: true,
requires: [
ICompletionProviderManager,
IDocumentManager,
IDefaultFileBrowser,
IEditorLanguageRegistry,
ICommandPalette,
IMainMenu
],
optional: [ISettingRegistry, IStatusBar],
provides: INotebookIntelligence,
activate: async (
app: JupyterFrontEnd,
completionManager: ICompletionProviderManager,
docManager: IDocumentManager,
defaultBrowser: IDefaultFileBrowser,
languageRegistry: IEditorLanguageRegistry,
palette: ICommandPalette,
mainMenu: IMainMenu,
settingRegistry: ISettingRegistry | null,
statusBar: IStatusBar | null
) => {
console.log(
'JupyterLab extension @qbraid/lab-notebook-intelligence is activated!'
);
const telemetryEmitter = new TelemetryEmitter();
telemetryEmitter.registerTelemetryListener({
name: BACKEND_TELEMETRY_LISTENER_NAME,
onTelemetryEvent: event => {
NBIAPI.emitTelemetryEvent(event);
}
});
const extensionService: INotebookIntelligence = {
registerTelemetryListener: (listener: ITelemetryListener) => {
telemetryEmitter.registerTelemetryListener(listener);
},
unregisterTelemetryListener: (listener: ITelemetryListener) => {
telemetryEmitter.unregisterTelemetryListener(listener);
}
};
await NBIAPI.initialize();
// Create dynamic MCP config after API is initialized
console.log('Creating dynamic MCP config...');
try {
await NBIAPI.createDynamicMCPConfig();
console.log('Dynamic MCP config created successfully!');
} catch (error) {
console.error('Failed to create dynamic MCP config:', error);
}
let openPopover: InlinePromptWidget | null = null;
let mcpConfigEditor: MCPConfigEditor | null = null;
completionManager.registerInlineProvider(
new NBIInlineCompletionProvider(telemetryEmitter)
);
if (settingRegistry) {
settingRegistry
.load(plugin.id)
.then(settings => {
//
})
.catch(reason => {
console.error(
'Failed to load settings for @lab-notebook-intelligence/lab-notebook-intelligence.',
reason
);
});
}
const waitForFileToBeActive = async (
filePath: string
): Promise<boolean> => {
const isNotebook = filePath.endsWith('.ipynb');
return new Promise<boolean>((resolve, reject) => {
const checkIfActive = () => {
const activeFilePath =
ActiveDocumentWatcher.activeDocumentInfo.filePath;
const filePathToCheck = filePath;
const currentWidget = app.shell.currentWidget;
if (
activeFilePath === filePathToCheck &&
((isNotebook &&
currentWidget instanceof NotebookPanel &&
currentWidget.content.activeCell &&
currentWidget.content.activeCell.node.contains(
document.activeElement
)) ||
(!isNotebook &&
currentWidget instanceof FileEditorWidget &&
currentWidget.content.editor.hasFocus()))
) {
resolve(true);
} else {
setTimeout(checkIfActive, 200);
}
};
checkIfActive();
waitForDuration(10000).then(() => {
resolve(false);
});
});
};
const panel = new Panel();
panel.id = 'lab-notebook-intelligence-tab';
panel.title.caption = 'Notebook Intelligence';
const sidebarIcon = new LabIcon({
name: 'ui-components:palette',
svgstr: sparklesSvgstr
});
panel.title.icon = sidebarIcon;
const sidebar = new ChatSidebar({
getActiveDocumentInfo: (): IActiveDocumentInfo => {
return ActiveDocumentWatcher.activeDocumentInfo;
},
getActiveSelectionContent: (): string => {
return ActiveDocumentWatcher.getActiveSelectionContent();
},
getCurrentCellContents: (): ICellContents => {
return ActiveDocumentWatcher.getCurrentCellContents();
},
openFile: (path: string) => {
docManager.openOrReveal(path);
},
getApp(): JupyterFrontEnd {
return app;
},
getTelemetryEmitter(): ITelemetryEmitter {
return telemetryEmitter;
},
getFileContent: async (filepath: string): Promise<string> => {
try {
const contentManager = new ContentsManager();
const file = await contentManager.get(filepath); // Fetch file content
return JSON.stringify(file.content); // Return the file content
} catch (error) {
console.error('Failed to get file content:', error);
return null; // Return null if an error occurs
}
}
});
panel.addWidget(sidebar);
app.shell.add(panel, 'left', { rank: 1000 });
app.shell.activateById(panel.id);
app.commands.addCommand(CommandIDs.chatuserInput, {
execute: args => {
NBIAPI.sendChatUserInput(args.id as string, args.data);
}
});
app.commands.addCommand(CommandIDs.insertAtCursor, {
execute: args => {
const currentWidget = app.shell.currentWidget;
if (currentWidget instanceof NotebookPanel) {
const activeCell = currentWidget.content.activeCell;
if (activeCell) {
applyCodeToSelectionInEditor(
activeCell.editor,
args.code as string
);
return;
}
} else if (currentWidget instanceof FileEditorWidget) {
applyCodeToSelectionInEditor(
currentWidget.content.editor,
args.code as string
);
return;
}
app.commands.execute('apputils:notify', {
message:
'Failed to insert at cursor. Open a notebook or file to insert the code.',
type: 'error',
options: { autoClose: true }
});
}
});
app.commands.addCommand(CommandIDs.addCodeAsNewCell, {
execute: args => {
const currentWidget = app.shell.currentWidget;
if (currentWidget instanceof NotebookPanel) {
let activeCellIndex = currentWidget.content.activeCellIndex;
activeCellIndex =
activeCellIndex === -1
? currentWidget.content.widgets.length
: activeCellIndex + 1;
currentWidget.model?.sharedModel.insertCell(activeCellIndex, {
cell_type: 'code',
metadata: { trusted: true },
source: args.code as string
});
currentWidget.content.activeCellIndex = activeCellIndex;
} else {
app.commands.execute('apputils:notify', {
message: 'Open a notebook to insert the code as new cell',
type: 'error',
options: { autoClose: true }
});
}
}
});
app.commands.addCommand(CommandIDs.createNewFile, {
execute: async args => {
const contents = new ContentsManager();
const newPyFile = await contents.newUntitled({
ext: '.py',
path: defaultBrowser?.model.path
});
contents.save(newPyFile.path, {
content: extractLLMGeneratedCode(args.code as string),
format: 'text',
type: 'file'
});
docManager.openOrReveal(newPyFile.path);
await waitForFileToBeActive(newPyFile.path);
return newPyFile;
}
});
app.commands.addCommand(CommandIDs.createNewNotebookFromPython, {
execute: async args => {
let pythonKernelSpec = null;
const contents = new ContentsManager();
const kernels = new KernelSpecManager();
await kernels.ready;
const kernelspecs = kernels.specs?.kernelspecs;
if (kernelspecs) {
for (const key in kernelspecs) {
const kernelspec = kernelspecs[key];
if (kernelspec?.language === 'python') {
pythonKernelSpec = kernelspec;
break;
}
}
}
const newNBFile = await contents.newUntitled({
ext: '.ipynb',
path: defaultBrowser?.model.path
});
const nbFileContent = structuredClone(emptyNotebookContent);
if (pythonKernelSpec) {
nbFileContent.metadata = {
kernelspec: {
language: 'python',
name: pythonKernelSpec.name,
display_name: pythonKernelSpec.display_name
}
};
}
if (args.code) {
nbFileContent.cells.push({
cell_type: 'code',
metadata: { trusted: true },
source: [args.code as string],
outputs: []
});
}
contents.save(newNBFile.path, {
content: nbFileContent,
format: 'json',
type: 'notebook'
});
docManager.openOrReveal(newNBFile.path);
await waitForFileToBeActive(newNBFile.path);
return newNBFile;
}
});
app.commands.addCommand(CommandIDs.renameNotebook, {
execute: async args => {
const activeWidget = app.shell.currentWidget;
if (activeWidget instanceof NotebookPanel) {
const oldPath = activeWidget.context.path;
const oldParentPath = path.dirname(oldPath);
let newPath = path.join(oldParentPath, args.newName as string);
if (path.extname(newPath) !== '.ipynb') {
newPath += '.ipynb';
}
if (path.dirname(newPath) !== oldParentPath) {
return 'Failed to rename notebook. New path is outside the old parent directory';
}
try {
await app.serviceManager.contents.rename(oldPath, newPath);
return 'Successfully renamed notebook';
} catch (error) {
return `Failed to rename notebook: ${error}`;
}
} else {
return 'Cannot rename non notebook files';
}
}
});
const isNewEmptyNotebook = (model: ISharedNotebook) => {
return (
model.cells.length === 1 &&
model.cells[0].cell_type === 'code' &&
model.cells[0].source === ''