forked from plmbr/notebook-intelligence
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.py
More file actions
3448 lines (3121 loc) · 148 KB
/
Copy pathextension.py
File metadata and controls
3448 lines (3121 loc) · 148 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 asyncio
import atexit
import base64
from dataclasses import asdict, dataclass
import json
from os import path
import datetime as dt
import os
import shutil
import tempfile
import time
from typing import Optional, Union
import uuid
import threading
import logging
import tiktoken
from jupyter_server.extension.application import ExtensionApp
from jupyter_server.auth.decorator import ws_authenticated
from jupyter_server.base.handlers import APIHandler, JupyterHandler
from jupyter_server.base.websocket import WebSocketMixin
from jupyter_server.utils import url_path_join
import tornado
from tornado import websocket
from traitlets import Bool, Enum as TraitletEnum, Int, List, Unicode
from notebook_intelligence.api import CancelToken, ChatMode, ChatResponse, ChatRequest, ContextRequest, ContextRequestType, RequestDataType, RequestToolSelection, ResponseStreamData, ResponseStreamDataType, BackendMessageType, SignalImpl
from notebook_intelligence.ai_service_manager import AIServiceManager
from notebook_intelligence.cell_output import coerce_payload as _coerce_output_context, format_output_context as _format_output_context
from notebook_intelligence.feature_flags import (
CHAT_MODEL_OVERRIDES,
CLAUDE_CODE_TOOLS_ID,
CLAUDE_SETTINGS_OVERRIDES,
INLINE_COMPLETION_MODEL_OVERRIDES,
JUPYTER_UI_TOOLS_ID,
POLICY_FORCE_OFF,
POLICY_FORCE_ON,
POLICY_USER_CHOICE,
VALID_POLICIES,
apply_claude_policies,
apply_string_overrides,
is_force_off,
is_locked,
resolve_feature_flag,
)
from notebook_intelligence._claude_cli import validate_scope
from notebook_intelligence.mcp_config_validation import (
MCPConfigValidationError,
validate_mcp_config,
)
from notebook_intelligence.mcp_policy import (
reject_dangerous_env_keys,
validate_mcp_stdio_command,
)
from notebook_intelligence.claude import (
CLAUDE_BYPASS_PERMISSION_MODE,
ClaudeCodeChatParticipant,
DEFAULT_PERMISSION_MODE,
claude_bypass_disabled_by_managed_settings,
claude_managed_default_permission_mode,
fetch_claude_models,
model_info_from_id,
resolve_permission_mode,
)
from notebook_intelligence.claude_mcp_manager import ClaudeMCPManager
from notebook_intelligence.plugin_manager import PluginManager
from notebook_intelligence.tour_config import load_tour_config
from notebook_intelligence.claude_sessions import (
NBI_CONTEXT_PREFIX,
list_all_sessions as list_all_claude_sessions,
)
import notebook_intelligence.github_copilot as github_copilot
from notebook_intelligence.built_in_toolsets import built_in_toolsets
from notebook_intelligence.util import ThreadSafeWebSocketConnector, get_claude_config_dir, get_jupyter_root_dir, set_jupyter_root_dir, is_builtin_tool_enabled_in_env, is_provider_enabled_in_env, VALID_CODING_AGENT_LAUNCHERS, compute_effective_disabled_launchers, validate_coding_agent_launcher_ids, resolve_claude_cli_path, resolve_opencode_cli_path, resolve_pi_cli_path, resolve_copilot_cli_path, resolve_codex_cli_path, safe_anchor_uri, has_dangerous_text_codepoints, split_csv
from notebook_intelligence.context_factory import RuleContextFactory
from notebook_intelligence.skillset import SKILL_NAME_REGEX
ai_service_manager: AIServiceManager = None
log = logging.getLogger(__name__)
tiktoken_encoding = tiktoken.encoding_for_model('gpt-4o')
thread_safe_websocket_connector: ThreadSafeWebSocketConnector = None
def _token_count(text: str) -> int:
return len(tiktoken_encoding.encode(text))
def _truncate_context_content(content: str, token_budget: int) -> str:
if token_budget <= 0 or content == '':
return ''
encoded = tiktoken_encoding.encode(content)
if len(encoded) <= token_budget:
return content
truncated = tiktoken_encoding.decode(encoded[:token_budget]).rstrip()
if truncated == '':
return ''
return truncated + "\n...[truncated]"
def _build_additional_context_message(
file_path: str,
context_filename: str,
start_line: int,
end_line: int,
context_content: str,
current_cell_context: str = ''
) -> str:
message = (
f"This file was provided as additional context: '{context_filename}' "
f"at path '{file_path}', lines: {start_line} - {end_line}."
)
if current_cell_context:
message += f" {current_cell_context}"
if context_content != '':
message += f"\n\nFile contents:\n```\n{context_content}\n```"
return message
def _build_cell_output_features_response(
explain_error_policy: str,
output_followup_policy: str,
output_toolbar_policy: str,
nbi_config,
) -> dict:
explain_enabled, explain_locked = resolve_feature_flag(
explain_error_policy, nbi_config.enable_explain_error
)
followup_enabled, followup_locked = resolve_feature_flag(
output_followup_policy, nbi_config.enable_output_followup
)
toolbar_enabled, toolbar_locked = resolve_feature_flag(
output_toolbar_policy, nbi_config.enable_output_toolbar
)
return {
"explain_error": {"enabled": explain_enabled, "locked": explain_locked},
"output_followup": {
"enabled": followup_enabled,
"locked": followup_locked,
},
"output_toolbar": {
"enabled": toolbar_enabled,
"locked": toolbar_locked,
},
}
def _resolve_supports_vision(ai_service_manager) -> bool:
"""Whether the active chat model can render images.
In Claude Code mode the active model is Claude (always vision-capable),
not ``ai_service_manager.chat_model`` (which still reflects the user's
most recent non-Claude selection). Fall through to the regular chat
model's capability otherwise.
"""
if ai_service_manager.is_claude_code_mode:
return True
chat_model = ai_service_manager.chat_model
return chat_model.supports_vision if chat_model is not None else False
def _resolve_context_token_limit(ai_service_manager) -> int:
"""Token budget source for attachment/output context.
In Claude Code mode the active model is Claude, not
``ai_service_manager.chat_model`` — that property still reflects the
user's most recent non-Claude provider selection and is ``None`` on a
Claude-only setup. Falling through to the legacy 100-token floor in
that state shrank the context budget to 80 tokens, which silently
dropped cell-output attachments and truncated every attachment after
the first. Resolve the budget from the configured Claude model
instead (``model_info_from_id`` falls back to a 200K window for
unknown or default model ids).
"""
if ai_service_manager.is_claude_code_mode:
model_id = ai_service_manager.nbi_config.claude_settings.get('chat_model', '')
model_id = model_id.strip() if isinstance(model_id, str) else ''
return model_info_from_id(model_id)["context_window"]
chat_model = ai_service_manager.chat_model
return 100 if chat_model is None else chat_model.context_window
def _resolve_policy_with_env(env_var_name: str, traitlet_value: str) -> str:
"""Resolve a feature policy: env var wins if valid, else traitlet.
Raises ValueError on unrecognized env values so a typo can't silently
relax a force-off gate. Matches the polarity of `_resolve_bool_with_env`.
"""
env_value = os.environ.get(env_var_name, "").strip()
if not env_value:
return traitlet_value
if env_value in VALID_POLICIES:
return env_value
raise ValueError(
f"Invalid {env_var_name}={env_value!r}: "
f"must be one of {', '.join(VALID_POLICIES)}"
)
_TRUE_VALUES = frozenset({"true", "1", "yes", "on"})
_FALSE_VALUES = frozenset({"false", "0", "no", "off"})
_BOOL_ENV_VOCAB = "true, false, 1, 0, yes, no, on, off"
def _resolve_skills_manifest_sources(traitlet_value: str) -> list:
"""Resolve the multi-manifest wire format: env var wins, otherwise traitlet.
`NBI_SKILLS_MANIFEST` and the matching traitlet both accept either a
single source (URL or filesystem path) or a comma-separated list of
either. Whitespace is stripped, empty fragments are dropped, so an
operator who writes ``" ,,, "`` (or leaves the env empty) lands on
"no manifests configured" rather than constructing phantom entries.
Extracted so the resolver can be unit-tested independent of the
extension-class instantiation harness.
"""
raw = (
os.environ.get("NBI_SKILLS_MANIFEST", "").strip()
or (traitlet_value or "").strip()
)
return split_csv(raw)
def _resolve_csv_appended(env_var_name: str, traitlet_value):
"""Merge a traitlet List with the comma-separated env-var value (append).
Env *adds to* the traitlet list rather than replacing it — the use case
is per-pod profiles layering on an org-wide baseline. Tokens are split
via the shared ``util.split_csv`` helper and exact duplicates are
collapsed while preserving first-seen order.
"""
base = list(traitlet_value or [])
extras = split_csv(os.environ.get(env_var_name, ""))
return list(dict.fromkeys(base + extras))
def _resolve_bool_with_env(env_var_name: str, fallback: bool | None) -> bool:
"""Resolve a boolean admin gate: env var wins if recognized, else fallback.
Raises ValueError when the env var is set but unrecognized — silent
fall-back can flip a security gate either direction depending on the
fallback polarity, so a typo must surface at startup. ``None`` fallback
is coerced to ``False``.
"""
env_value = os.environ.get(env_var_name, "").strip().lower()
if not env_value:
return bool(fallback)
if env_value in _TRUE_VALUES:
return True
if env_value in _FALSE_VALUES:
return False
raise ValueError(
f"Invalid {env_var_name}={env_value!r}: must be one of {_BOOL_ENV_VOCAB}"
)
def _resolve_positive_int_with_env(env_var_name: str, traitlet_value: int) -> int:
"""Resolve a non-negative int tunable, falling back to the traitlet.
Unlike ``_resolve_bool_with_env`` this warns-and-clamps rather than
raising: int tunables are tuning parameters (size caps, intervals,
retention windows), and a typo in one is unambiguously "off-ish"
rather than security-gate-flipping. Negative values are clamped to
0 with a warning so callers see "feature disabled" rather than
silently treating the bad input as a positive cap.
"""
env_value = os.environ.get(env_var_name, "").strip()
resolved = traitlet_value
if env_value:
try:
resolved = int(env_value)
except ValueError:
log.warning(
"Ignoring invalid %s=%r: must be a non-negative integer",
env_var_name,
env_value,
)
resolved = traitlet_value
if resolved < 0:
log.warning(
"%s resolved to a negative value (%d); clamping to 0",
env_var_name,
resolved,
)
return 0
return resolved
# Single source of truth for the boolean policies. Each entry is
# ``(policy_name, env_var, traitlet_attr)``. Drives env-var resolution, the
# capabilities response, and the lock-rejection set in ConfigHandler.
#
# Adding a new policy requires updates in *seven* places — keep them all in
# sync or the policy will silently no-op:
# 1. A new tuple entry below.
# 2. A ``TraitletEnum`` declaration on ``NotebookIntelligence`` further
# down in this file.
# 3. A ``user_values`` entry in ``_build_feature_policies_response``
# (admin-only gates use ``True``).
# 4. (For backend gates) An ``is_force_off`` call in ``_setup_handlers``
# that sets the resolved bool on the handler class.
# 5. A row in the Admin policies table in ``README.md``.
# 6. A section in ``docs/admin-guide.md``.
# 7. ``FeaturePolicyName`` union + the ``names`` array in
# ``src/api.ts`` ``featurePolicies``. Admin-only gates also need an
# entry in the ``defaultOpen`` set if they should default visible.
FEATURE_POLICY_SPEC = (
("explain_error", "NBI_EXPLAIN_ERROR_POLICY", "explain_error_policy"),
("output_followup", "NBI_OUTPUT_FOLLOWUP_POLICY", "output_followup_policy"),
("output_toolbar", "NBI_OUTPUT_TOOLBAR_POLICY", "output_toolbar_policy"),
("claude_mode", "NBI_CLAUDE_MODE_POLICY", "claude_mode_policy"),
(
"claude_continue_conversation",
"NBI_CLAUDE_CONTINUE_CONVERSATION_POLICY",
"claude_continue_conversation_policy",
),
(
"claude_code_tools",
"NBI_CLAUDE_CODE_TOOLS_POLICY",
"claude_code_tools_policy",
),
(
"claude_jupyter_ui_tools",
"NBI_CLAUDE_JUPYTER_UI_TOOLS_POLICY",
"claude_jupyter_ui_tools_policy",
),
(
"claude_setting_source_user",
"NBI_CLAUDE_SETTING_SOURCE_USER_POLICY",
"claude_setting_source_user_policy",
),
(
"claude_setting_source_project",
"NBI_CLAUDE_SETTING_SOURCE_PROJECT_POLICY",
"claude_setting_source_project_policy",
),
(
"store_github_access_token",
"NBI_STORE_GITHUB_ACCESS_TOKEN_POLICY",
"store_github_access_token_policy",
),
(
"skills_management",
"NBI_SKILLS_MANAGEMENT_POLICY",
"skills_management_policy",
),
(
"claude_mcp_management",
"NBI_CLAUDE_MCP_MANAGEMENT_POLICY",
"claude_mcp_management_policy",
),
(
"claude_plugins_management",
"NBI_CLAUDE_PLUGINS_MANAGEMENT_POLICY",
"claude_plugins_management_policy",
),
(
"claude_bypass_permissions",
"NBI_CLAUDE_BYPASS_PERMISSIONS_POLICY",
"claude_bypass_permissions_policy",
),
(
"terminal_drag_drop",
"NBI_TERMINAL_DRAG_DROP_POLICY",
"terminal_drag_drop_policy",
),
(
"refresh_open_files_on_disk_change",
"NBI_REFRESH_OPEN_FILES_ON_DISK_CHANGE_POLICY",
"refresh_open_files_on_disk_change_policy",
),
)
FEATURE_POLICY_NAMES = tuple(name for name, _, _ in FEATURE_POLICY_SPEC)
# Fallback used when a policies dict hasn't been populated (handler classes
# before _setup_handlers, direct construction in tests). Everything defaults
# to user-choice except bypass, which must fail closed.
FEATURE_POLICY_DEFAULTS = {name: POLICY_USER_CHOICE for name in FEATURE_POLICY_NAMES}
FEATURE_POLICY_DEFAULTS["claude_bypass_permissions"] = POLICY_FORCE_OFF
# ``(setting_lock_name, env_var)`` pairs for the value-presence-locks. The
# claude_api_key entry maps to ANTHROPIC_API_KEY (the SDK's native convention)
# rather than an NBI-prefixed env var. Same for claude_base_url.
STRING_OVERRIDE_SPEC = (
("chat_model_provider", "NBI_CHAT_MODEL_PROVIDER"),
("chat_model_id", "NBI_CHAT_MODEL_ID"),
("inline_completion_model_provider", "NBI_INLINE_COMPLETION_MODEL_PROVIDER"),
("inline_completion_model_id", "NBI_INLINE_COMPLETION_MODEL_ID"),
("claude_chat_model", "NBI_CLAUDE_CHAT_MODEL"),
("claude_inline_completion_model", "NBI_CLAUDE_INLINE_COMPLETION_MODEL"),
("claude_api_key", "ANTHROPIC_API_KEY"),
("claude_base_url", "ANTHROPIC_BASE_URL"),
)
SETTING_LOCK_NAMES = tuple(name for name, _ in STRING_OVERRIDE_SPEC)
def _build_feature_policies_response(policies: dict, nbi_config) -> dict:
"""Resolve every boolean policy against the user's stored config.
Returns ``{name: {enabled, locked}}`` for every name in
FEATURE_POLICY_NAMES. The frontend iterates this dict, so adding a new
feature only needs an entry here plus a matching env-var resolution.
"""
claude_settings = nbi_config.claude_settings or {}
tools = claude_settings.get("tools") or []
sources = claude_settings.get("setting_sources") or []
user_values = {
"explain_error": nbi_config.enable_explain_error,
"output_followup": nbi_config.enable_output_followup,
"output_toolbar": nbi_config.enable_output_toolbar,
"claude_mode": bool(claude_settings.get("enabled", False)),
"claude_continue_conversation": bool(
claude_settings.get("continue_conversation", False)
),
"claude_code_tools": CLAUDE_CODE_TOOLS_ID in tools,
"claude_jupyter_ui_tools": JUPYTER_UI_TOOLS_ID in tools,
"claude_setting_source_user": "user" in sources,
"claude_setting_source_project": "project" in sources,
"store_github_access_token": bool(nbi_config.store_github_access_token),
# Admin-only gates; user has no toggle, so user_value is always
# True. The policy resolver still applies force-off / force-on
# correctly so admins can flip them. The frontend keys off
# `locked && !enabled` to know when to hide the feature.
"skills_management": True,
"claude_mcp_management": True,
"claude_plugins_management": True,
# Gates only whether the Bypass Permissions option is offered in
# the permission-mode selector; the user still arms it per
# session. force-on grants the same availability as user-choice
# and never auto-arms bypass. Defaults to force-off, the only
# policy with a non-user-choice default.
"claude_bypass_permissions": True,
"terminal_drag_drop": True,
"refresh_open_files_on_disk_change": nbi_config.refresh_open_files_on_disk_change,
}
response = {}
for name in FEATURE_POLICY_NAMES:
enabled, locked = resolve_feature_flag(
policies.get(name, FEATURE_POLICY_DEFAULTS[name]), user_values[name]
)
response[name] = {"enabled": enabled, "locked": locked}
# Defense in depth: Claude Code's enterprise managed settings can
# disable bypass independently of the NBI policy. Fold that into the
# one answer the frontend reads so the selector and the server's
# request clamp can't disagree.
if claude_bypass_disabled_by_managed_settings():
response["claude_bypass_permissions"] = {"enabled": False, "locked": True}
return response
def _resolve_default_permission_mode() -> str:
"""Starting permission mode for the selector in a new Claude session.
Honors managed settings' ``permissions.defaultMode`` except for bypass,
which never applies without the user arming it explicitly, no matter
who asks; a managed default of bypass collapses to default the same
way the reconnect reset does.
"""
managed_default = claude_managed_default_permission_mode()
if managed_default is None or managed_default == CLAUDE_BYPASS_PERMISSION_MODE:
return DEFAULT_PERMISSION_MODE
return managed_default
def _build_setting_locks_response(string_overrides: dict) -> dict:
"""Surface lock state for non-boolean settings (model pickers, API key, base URL).
The values themselves are still served through their existing capabilities
fields (chat_model, claude_settings, ...). This dict only carries the
locked flag so the frontend knows which inputs to disable.
"""
return {
name: {"locked": bool(string_overrides.get(name))}
for name in SETTING_LOCK_NAMES
}
def _scrub_credentials_for_wire(claude_settings: dict, string_overrides: dict) -> dict:
"""Strip the api_key from the capabilities response when locked by env.
The Anthropic SDK reads ANTHROPIC_API_KEY directly; surfacing the value
through the frontend would leak the credential.
"""
if not string_overrides.get("claude_api_key"):
return claude_settings
result = dict(claude_settings or {})
result["api_key"] = ""
return result
def _read_claude_spinner_verbs() -> Optional[dict]:
settings_path = os.path.join(get_claude_config_dir(), 'settings.json')
try:
with open(settings_path) as f:
data = json.load(f)
sv = data.get('spinnerVerbs')
if (
isinstance(sv, dict)
and sv.get('mode') == 'replace'
and isinstance(sv.get('verbs'), list)
and sv['verbs']
and all(isinstance(v, str) for v in sv['verbs'])
):
return sv
return None
except Exception:
return None
class GetCapabilitiesHandler(APIHandler):
disabled_tools = []
allow_enabling_tools_with_env = False
disabled_providers = []
allow_enabling_providers_with_env = False
disabled_coding_agent_launchers = []
allow_enabling_coding_agent_launchers_with_env = False
enable_chat_feedback = False
enable_chat_feedback_always_visible = False
additional_skipped_workspace_directories = []
feature_policies = {}
string_overrides = {}
# Resolved at extension init from NBI_TOUR_CONFIG_PATH (or the
# tour_config_path traitlet). Empty string disables the override.
tour_config_path = ""
@tornado.web.authenticated
def get(self):
ai_service_manager.nbi_config.load()
ai_service_manager.update_models_from_config()
nbi_config = ai_service_manager.nbi_config
def is_tool_enabled(tool: str) -> bool:
if self.disabled_tools is None:
return True
return tool not in self.disabled_tools or (self.allow_enabling_tools_with_env and is_builtin_tool_enabled_in_env(tool))
def is_provider_enabled(provider_id: str) -> bool:
if self.disabled_providers is None:
return True
return provider_id not in self.disabled_providers or \
(self.allow_enabling_providers_with_env and is_provider_enabled_in_env(provider_id))
# Frontend gets the resolved set (denylist plus the per-pod re-enable
# env, gated by the explicit opt-in flag). Computed once per request
# in `util.compute_effective_disabled_launchers` so tests can pin the
# contract without re-implementing it.
effective_disabled_launchers = compute_effective_disabled_launchers(
self.disabled_coding_agent_launchers,
self.allow_enabling_coding_agent_launchers_with_env,
)
allowed_builtin_toolsets = [{"id": toolset.id, "name": toolset.name, "description": toolset.description} for toolset in built_in_toolsets.values() if is_tool_enabled(toolset.id)]
llm_providers = [p for p in ai_service_manager.llm_providers.values() if is_provider_enabled(p.id)]
mcp_servers = ai_service_manager.get_mcp_servers()
mcp_server_tools = [{
"id": mcp_server.name,
"status": mcp_server.status,
"tools": [{"name": tool.name, "description": tool.description} for tool in mcp_server.get_tools()],
"prompts": [{"name": prompt.name, "description": prompt.description, "arguments": [{"name": argument.name, "description": argument.description, "required": argument.required} for argument in prompt.arguments]} for prompt in mcp_server.get_prompts()]
} for mcp_server in mcp_servers]
# sort by server id
mcp_server_tools.sort(key=lambda server: server["id"])
extensions = []
for extension_id, toolsets in ai_service_manager.get_extension_toolsets().items():
ts = []
for toolset in toolsets:
tools = []
for tool in toolset.tools:
tools.append({"name": tool.name, "description": tool.description})
# sort by tool name
tools.sort(key=lambda tool: tool["name"])
ts.append({
"id": toolset.id,
"name": toolset.name,
"description": toolset.description,
"tools": tools
})
# sort by toolset name
ts.sort(key=lambda toolset: toolset["name"])
extension = ai_service_manager.get_extension(extension_id)
extensions.append({
"id": extension_id,
"name": extension.name,
"toolsets": ts
})
# sort by extension id
extensions.sort(key=lambda extension: extension["id"])
response = {
"user_home_dir": os.path.expanduser('~'),
"nbi_user_config_dir": nbi_config.nbi_user_dir,
"using_github_copilot_service": nbi_config.using_github_copilot_service,
"llm_providers": [{"id": provider.id, "name": provider.name} for provider in llm_providers],
"chat_models": ai_service_manager.chat_model_ids,
"inline_completion_models": ai_service_manager.inline_completion_model_ids,
"embedding_models": ai_service_manager.embedding_model_ids,
"chat_model": nbi_config.chat_model,
"chat_model_supports_vision": _resolve_supports_vision(
ai_service_manager
),
"inline_completion_model": nbi_config.inline_completion_model,
"embedding_model": nbi_config.embedding_model,
"chat_participants": [],
"store_github_access_token": nbi_config.store_github_access_token,
"inline_completion_debouncer_delay": nbi_config.inline_completion_debouncer_delay,
"tool_config": {
"builtinToolsets": allowed_builtin_toolsets,
"mcpServers": mcp_server_tools,
"extensions": extensions
},
"mcp_server_settings": nbi_config.mcp_server_settings,
"claude_settings": _scrub_credentials_for_wire(
nbi_config.claude_settings, self.string_overrides
),
"spinner_verbs": _read_claude_spinner_verbs(),
"claude_models": ai_service_manager.claude_models,
# Drive launcher-tile visibility (issues #183, #260). Each flag
# gates one tile under the "Coding Agent" category. Detection is
# PATH-based with NBI_*_CLI_PATH env overrides.
"claude_cli_available": resolve_claude_cli_path() is not None,
"opencode_cli_available": resolve_opencode_cli_path() is not None,
"pi_cli_available": resolve_pi_cli_path() is not None,
"github_copilot_cli_available": resolve_copilot_cli_path() is not None,
"codex_cli_available": resolve_codex_cli_path() is not None,
"disabled_coding_agent_launchers": effective_disabled_launchers,
"default_chat_mode": nbi_config.default_chat_mode,
"chat_feedback_enabled": self.enable_chat_feedback,
"chat_feedback_always_visible": self.enable_chat_feedback_always_visible,
# Single source of truth lives on each domain's base handler so
# `_setup_handlers` only writes one site per flag.
"allow_github_skill_import": SkillsBaseHandler.allow_github_skill_import,
"additional_skipped_workspace_directories": self.additional_skipped_workspace_directories,
"allow_github_plugin_import": PluginsBaseHandler.allow_github_plugin_import,
"cell_output_features": _build_cell_output_features_response(
self.feature_policies.get("explain_error", POLICY_USER_CHOICE),
self.feature_policies.get("output_followup", POLICY_USER_CHOICE),
self.feature_policies.get("output_toolbar", POLICY_USER_CHOICE),
nbi_config,
),
"feature_policies": _build_feature_policies_response(
self.feature_policies, nbi_config
),
"setting_locks": _build_setting_locks_response(self.string_overrides),
# Starting mode for the permission-mode selector: managed
# settings' permissions.defaultMode when present and valid,
# else "default". Bypass never starts armed regardless of
# managed settings or policy, so it collapses to "default".
"claude_permission_default_mode": _resolve_default_permission_mode(),
}
for participant_id in ai_service_manager.chat_participants:
participant = ai_service_manager.chat_participants[participant_id]
# prevent duplicate participants
if participant.id in [p["id"] for p in response["chat_participants"]]:
continue
response["chat_participants"].append({
"id": participant.id,
"name": participant.name,
"description": participant.description,
"iconPath": participant.icon_path,
"commands": [command.name for command in participant.commands]
})
# Admin tour copy overrides. The loader fails closed: a missing,
# oversized, or malformed file returns {} and the frontend
# renders the built-in defaults. Reading on every capabilities
# call (rather than caching) lets an admin edit the file without
# restarting Jupyter; the file is small and the path is usually
# unset, so the cost is at most one stat call per request. The
# path itself is pre-resolved at initialize_handlers time.
response["tour_overrides"] = load_tour_config(self.tour_config_path)
self.finish(json.dumps(response))
class ConfigHandler(APIHandler):
feature_policies = {}
string_overrides = {}
@tornado.web.authenticated
def post(self):
data = json.loads(self.request.body)
valid_keys = set([
"default_chat_mode",
"chat_model",
"inline_completion_model",
"store_github_access_token",
"inline_completion_debouncer_delay",
"mcp_server_settings",
"claude_settings",
"enable_explain_error",
"enable_output_followup",
"enable_output_toolbar",
"refresh_open_files_on_disk_change",
])
# Top-level keys whose write is rejected outright when locked.
locked_keys = set()
if is_locked(self.feature_policies.get("explain_error", POLICY_USER_CHOICE)):
locked_keys.add("enable_explain_error")
if is_locked(self.feature_policies.get("output_followup", POLICY_USER_CHOICE)):
locked_keys.add("enable_output_followup")
if is_locked(self.feature_policies.get("output_toolbar", POLICY_USER_CHOICE)):
locked_keys.add("enable_output_toolbar")
if is_locked(self.feature_policies.get("store_github_access_token", POLICY_USER_CHOICE)):
locked_keys.add("store_github_access_token")
if is_locked(self.feature_policies.get("refresh_open_files_on_disk_change", POLICY_USER_CHOICE)):
locked_keys.add("refresh_open_files_on_disk_change")
# chat_model / inline_completion_model are locked when *either* of their
# provider/id env vars is set; the resolver below preserves the locked
# subfield so a user can still update the unlocked one.
chat_model_locked = bool(
self.string_overrides.get("chat_model_provider")
or self.string_overrides.get("chat_model_id")
)
inline_model_locked = bool(
self.string_overrides.get("inline_completion_model_provider")
or self.string_overrides.get("inline_completion_model_id")
)
has_model_change = False
has_claude_settings_change = False
for key in data:
if key in locked_keys:
continue
if key not in valid_keys:
continue
value = data[key]
# Re-apply the env override after the user's POST so locked fields
# stay pinned; non-locked fields keep the user's value.
if key == "chat_model":
value = apply_string_overrides(
value, self.string_overrides, CHAT_MODEL_OVERRIDES
)
if chat_model_locked and value == ai_service_manager.nbi_config.chat_model:
continue
has_model_change = True
elif key == "inline_completion_model":
value = apply_string_overrides(
value, self.string_overrides, INLINE_COMPLETION_MODEL_OVERRIDES
)
if (
inline_model_locked
and value == ai_service_manager.nbi_config.inline_completion_model
):
continue
has_model_change = True
elif key == "claude_settings":
value = apply_claude_policies(value, self.feature_policies)
value = apply_string_overrides(
value, self.string_overrides, CLAUDE_SETTINGS_OVERRIDES
)
# ANTHROPIC_API_KEY is a credential; don't persist it to
# config.json. The SDK reads it from process env directly when
# claude_settings.api_key is empty.
if self.string_overrides.get("claude_api_key"):
value = dict(value)
value["api_key"] = ""
ai_service_manager.nbi_config.set(key, value)
if key == "store_github_access_token":
if value:
github_copilot.store_github_access_token()
else:
github_copilot.delete_stored_github_access_token()
elif key == "mcp_server_settings":
disabled_mcp_servers = []
for server_id in value:
server_settings = value[server_id]
if server_settings.get("disabled") == True:
disabled_mcp_servers.append(server_id)
ai_service_manager.update_mcp_server_connections(disabled_mcp_servers)
elif key == "claude_settings":
has_claude_settings_change = True
default_chat_participant = ai_service_manager.default_chat_participant
if isinstance(default_chat_participant, ClaudeCodeChatParticipant):
# needed to disconnect
default_chat_participant.update_client_debounced()
ai_service_manager.nbi_config.save()
if has_model_change or has_claude_settings_change:
ai_service_manager.update_models_from_config()
if has_claude_settings_change:
default_chat_participant = ai_service_manager.default_chat_participant
if isinstance(default_chat_participant, ClaudeCodeChatParticipant):
# needed to reconnect / update
default_chat_participant.update_client_debounced()
self.finish(json.dumps({}))
class UpdateProviderModelsHandler(APIHandler):
@tornado.web.authenticated
def post(self):
data = json.loads(self.request.body)
if data.get("provider") == "ollama":
ai_service_manager.ollama_llm_provider.update_chat_model_list()
elif data.get("provider") == "claude":
claude_settings = ai_service_manager.nbi_config.claude_settings
fetch_claude_models(
api_key=claude_settings.get('api_key', None),
base_url=claude_settings.get('base_url', None)
)
self.finish(json.dumps({}))
class MCPConfigFileHandler(APIHandler):
@tornado.web.authenticated
def get(self):
ai_service_manager.nbi_config.load()
mcp_config = ai_service_manager.nbi_config.mcp.copy()
if "mcpServers" not in mcp_config:
mcp_config["mcpServers"] = {}
self.finish(json.dumps(mcp_config))
@tornado.web.authenticated
def post(self):
try:
data = json.loads(self.request.body)
except json.JSONDecodeError as exc:
# Surface the parse error via 400 rather than crashing
# downstream code with a confusing AttributeError when the
# JSON loader returns a primitive instead of a dict.
self.set_status(400)
self.finish(json.dumps({"status": "error", "message": f"Invalid JSON: {exc}"}))
return
try:
validate_mcp_config(data)
except MCPConfigValidationError as exc:
# Schema rejection: refuse the write entirely so a malformed
# payload cannot persist to disk or install destructive
# servers on the next reconcile.
self.set_status(400)
self.finish(json.dumps({"status": "error", "message": str(exc)}))
return
try:
# Validate stdio entries against the same admin allowlist
# that the in-process loader uses, so a rejected entry
# cannot persist to disk and re-trigger the load-time warn
# on every restart. Apply the same env-key denylist that
# blocks PATH / LD_PRELOAD / etc. bypasses.
allowlist = ai_service_manager.get_mcp_stdio_command_allowlist()
servers = data.get("mcpServers") if isinstance(data, dict) else None
if isinstance(servers, dict):
for name, server in servers.items():
if not isinstance(server, dict) or "command" not in server:
continue
validate_mcp_stdio_command(server.get("command", ""), allowlist)
reject_dangerous_env_keys(server.get("env"))
ai_service_manager.nbi_config.user_mcp = data
ai_service_manager.nbi_config.save()
ai_service_manager.nbi_config.load()
ai_service_manager.update_mcp_servers()
self.finish(json.dumps({"status": "ok"}))
except ValueError as exc:
# Policy rejection: surface as HTTP 400 so the Settings UI
# shows the operator's policy message instead of a generic
# 500. The body still uses the {status, message} envelope
# the frontend already parses.
self.set_status(400)
self.finish(json.dumps({"status": "error", "message": str(exc)}))
return
except Exception as e:
self.set_status(500)
self.finish(json.dumps({"status": "error", "message": str(e)}))
return
class ReloadMCPServersHandler(APIHandler):
@tornado.web.authenticated
def post(self):
ai_service_manager.nbi_config.load()
ai_service_manager.update_mcp_servers()
self.finish(json.dumps({
"mcpServers": [{"id": server.name} for server in ai_service_manager.get_mcp_servers()]
}))
class EmitTelemetryEventHandler(APIHandler):
@tornado.web.authenticated
def post(self):
event = json.loads(self.request.body)
log.debug(f"Telemetry event received: type={event.get('type')}, data={json.dumps(event.get('data', {}))}")
thread = threading.Thread(target=asyncio.run, args=(ai_service_manager.emit_telemetry_event(event),))
thread.start()
self.finish(json.dumps({}))
class GetGitHubLoginStatusHandler(APIHandler):
# The following decorator should be present on all verb methods (head, get, post,
# patch, put, delete, options) to ensure only authorized user can request the
# Jupyter server
@tornado.web.authenticated
def get(self):
self.finish(json.dumps(github_copilot.get_login_status()))
class PostGitHubLoginHandler(APIHandler):
@tornado.web.authenticated
def post(self):
device_verification_info = github_copilot.login()
if device_verification_info is None:
self.set_status(500)
self.finish(json.dumps({
"error": "Failed to get device verification info from GitHub Copilot"
}))
return
self.finish(json.dumps(device_verification_info))
class GetGitHubLogoutHandler(APIHandler):
@tornado.web.authenticated
def get(self):
self.finish(json.dumps(github_copilot.logout()))
class RulesListHandler(APIHandler):
@tornado.web.authenticated
def get(self):
"""Get list of all rules with their status."""
rule_manager = ai_service_manager.get_rule_manager()
if not rule_manager:
self.finish(json.dumps({"rules": [], "enabled": False}))
return
rules_summary = rule_manager.get_rules_summary()
all_rules = rule_manager.ruleset.get_all_rules()
rules_data = []
for rule in all_rules:
rules_data.append({
"filename": rule.filename,
"active": rule.active,
"mode": rule.mode,
"apply": rule.apply,
"priority": rule.priority,
"scope": rule.scope.__dict__,
"content_preview": rule.content[:200] + "..." if len(rule.content) > 200 else rule.content
})
response = {
"enabled": ai_service_manager.nbi_config.rules_enabled,
"rules": rules_data,
"summary": rules_summary
}
self.finish(json.dumps(response))
class RulesToggleHandler(APIHandler):
@tornado.web.authenticated
def put(self, rule_filename):
"""Toggle a rule's active state."""
data = json.loads(self.request.body)
active = data.get('active', True)
rule_manager = ai_service_manager.get_rule_manager()
if not rule_manager:
self.set_status(404)
self.finish(json.dumps({"error": "Rule system not enabled"}))
return
success = rule_manager.toggle_rule(rule_filename, active)
if success:
# Also update config
ai_service_manager.nbi_config.set_rule_active(rule_filename, active)
self.finish(json.dumps({"success": True}))
else:
self.set_status(404)
self.finish(json.dumps({"error": "Rule not found"}))
class RulesReloadHandler(APIHandler):
@tornado.web.authenticated
def post(self):
"""Reload rules from disk."""
rule_manager = ai_service_manager.get_rule_manager()
if not rule_manager:
self.set_status(404)
self.finish(json.dumps({"error": "Rule system not enabled"}))
return
try:
rule_manager.load_rules(force_reload=True)
summary = rule_manager.get_rules_summary()
self.finish(json.dumps({"success": True, "summary": summary}))
except Exception as e:
self.set_status(500)
self.finish(json.dumps({"error": str(e)}))
class PolicyGatedHandler(APIHandler):
"""APIHandler base used by all NBI management surfaces (Skills,
Claude-MCP, Plugins). Owns three concerns:
1. **Admin policy gate** in ``prepare()``. Short-circuits with 403
when the associated ``*_management_policy`` resolves to
``force-off``. Subclasses set ``policy_enabled_attr`` to the
class-attribute name holding the resolved bool (mutated in
``_setup_handlers``), and ``policy_disabled_message`` for the
user-facing error string.
2. **JSON request parsing** via ``_parse_json_body``. Returns the
decoded body or ``None`` after writing a 400; callers must ``if
data is None: return``.
3. **Domain-aware error mapping** via ``_error`` + the
``exception_status_map`` class attribute (exception class → HTTP
status). Most-specific class wins via MRO depth ordering.
Subclasses also typically expose a ``manager`` property that returns