-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathcli.py
More file actions
3433 lines (3175 loc) · 138 KB
/
Copy pathcli.py
File metadata and controls
3433 lines (3175 loc) · 138 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
#!/usr/bin/env python3
"""CLI entry point for ``ug``."""
from __future__ import annotations
import os
import shutil
import subprocess
from collections.abc import Iterator
from contextlib import contextmanager
from importlib import metadata
from typing import Annotated
import typer
from rich.panel import Panel
from typer._click import Context as ClickContext
from typer.core import TyperCommand
from ucode.agents import (
TOOL_SPECS,
LaunchOptions,
check_gateway_endpoint,
configure_selected_tools,
configure_single_tool,
configure_tool,
ensure_bootstrap_dependencies,
ensure_provider_state,
explicit_model_arg_value,
install_databricks_ai_tools_for_agents,
install_tool_binary,
normalize_tool,
provider_permission_error,
resolve_gemini_provider_model,
resolve_launch_model,
resolve_provider_models,
validate_all_tools,
validate_tool,
)
from ucode.agents import claude as claude_agent
from ucode.agents import codex as codex_agent
from ucode.agents import (
launch as launch_agent,
)
from ucode.agents.codex import revert_legacy_shared_config
from ucode.agents.pi import PI_SETTINGS_BACKUP_PATH, PI_SETTINGS_PATH
from ucode.config_io import is_dry_run, restore_file, set_dry_run
from ucode.databricks import (
apply_pat_environment,
build_shared_base_urls,
discover_claude_models,
discover_codex_models,
discover_gemini_models,
discover_model_services,
ensure_databricks_auth,
ensure_pat_bearer,
find_profile_name_for_host,
get_databricks_profiles,
get_databricks_token,
install_databricks_cli,
is_model_provider_feature_unavailable,
is_workspace_admin,
list_profile_entries,
list_tool_provider_services,
normalize_workspace_url,
probe_unity_gateway_capabilities,
resolve_pat_token,
resolve_provider_launch_model,
run_databricks_login,
)
from ucode.managed_budget import (
budget_usage_percent,
recommendation_line,
render_budget_panel,
)
from ucode.managed_config import (
ManagedConfigResult,
get_model_recommendation,
load_managed_state,
refresh_managed_config,
)
from ucode.managed_resolve import (
managed_claude_family_models,
managed_default_model,
managed_enabled_tools,
managed_launch_model,
managed_provider_family_models,
managed_provider_service,
managed_supplies_models,
managed_unservable_models,
recommended_agent,
resolve_state,
)
from ucode.managed_wizard import (
publish_command,
setup_budget_policy_command,
setup_command,
setup_help_command,
setup_mcp_command,
setup_skills_command,
show_command,
)
from ucode.mcp import (
MCP_CLIENTS,
SKILLS_MCP_KIND,
add_mcp_command,
add_skills_command,
apply_managed_mcp_servers,
available_mcp_clients,
configure_mcp_command,
configure_skills_mcp_command,
configured_mcp_clients,
purge_cross_workspace_mcp_residue,
remove_mcp_command,
remove_skills_command,
revert_mcp_configs,
skill_locations_for_client,
)
from ucode.skills_download import (
configure_skills_download_command,
download_managed_skills_on_launch,
)
from ucode.smart_routing import v2 as smart_routing_v2
from ucode.smart_routing.claude_hooks import FIRST_PROMPT_SOCKET_ENV, ROUTE_FIRST_PROMPT_EVENT
from ucode.state import (
STATE_PATH,
clear_state,
get_provider_service,
load_full_state,
load_state,
save_state,
set_current_workspace,
set_provider_service,
)
from ucode.tracing import configure_tracing_command
from ucode.ui import (
console,
heading,
print_err,
print_heading,
print_kv,
print_note,
print_section,
print_success,
print_warning,
prompt_for_selection,
prompt_for_tools,
prompt_for_workspace,
prompt_yes_no,
set_verbosity,
spinner,
status_badge,
)
from ucode.usage import usage as usage_report
_DISCOVERY_CONSUMERS: dict[str, tuple[str, ...]] = {
"claude": ("claude", "opencode", "copilot", "pi"),
"codex": ("codex", "copilot", "pi"),
"gemini": ("gemini", "opencode", "pi"),
"oss": ("opencode",),
}
def _policy_summary_lines(managed: dict) -> list[str]:
"""Rich-markup lines describing the admin's tiered spend policy, or empty when it sets none."""
policy = managed.get("budget_policy")
if not isinstance(policy, dict):
return []
name = str(policy.get("display_name") or "coding-agents-default")
lines = [f"[bold]Policy:[/bold] [cyan]{name}[/cyan]"]
tiers = policy.get("tiers")
for tier in tiers if isinstance(tiers, list) else []:
if not isinstance(tier, dict):
continue
pct_raw = tier.get("spending_percentage")
pct = (
f"{float(pct_raw) * 100:g}%"
if isinstance(pct_raw, int | float) and not isinstance(pct_raw, bool)
else "?"
)
# A tier whose agent enum this build doesn't know is dropped during normalization, so it
# arrives unset rather than as a tool name TOOL_SPECS could resolve.
agent = tier.get("default_agent")
agent_display = TOOL_SPECS[agent]["display"] if agent in TOOL_SPECS else "?"
model = str(tier.get("default_model") or "?")
lines.append(
f" [dim]·[/dim] [bold]at {pct}[/bold] → {agent_display} · [magenta]{model}[/magenta]"
)
return lines
def _print_managed_summary(
managed: dict, state: dict, tool: str | None, *, abridged: bool = False
) -> None:
"""Show which of the admin's settings are in force.
With ``tool`` set (launch path) the per-agent Agent/Provider/Model lines are included;
with ``tool=None`` (e.g. ``ug configure`` under a managed config) they are skipped
since no single agent has been chosen yet.
``abridged`` prints only what changes launch-to-launch — the agent and model this run will use,
and the policy in force — with a pointer to ``ug status`` for the rest. Bare ``ucode`` runs
every session, so re-enumerating the workspace's full MCP/skills/tier list each time is noise;
the full box stays for ``status`` and ``configure``, where the reader asked to see it.
"""
if abridged:
_print_managed_summary_abridged(managed, state, tool)
return
lines = [f"[bold]Workspace:[/bold] [cyan]{state.get('workspace', '?')}[/cyan]"]
if tool is not None:
lines.append(f"[bold]Agent:[/bold] [green]{TOOL_SPECS[tool]['display']}[/green]")
enabled = [t for t in (managed.get("enabled_agents") or {}) if t in TOOL_SPECS]
if enabled:
lines.append(
f"[bold]Enabled agents:[/bold] {', '.join(TOOL_SPECS[t]['display'] for t in enabled)}"
)
if tool is not None:
provider = managed_provider_service(managed, tool)
if provider:
lines.append(f"[bold]Provider:[/bold] [magenta]{provider}[/magenta]")
model = managed_default_model(managed, tool)
if model:
lines.append(f"[bold]Model:[/bold] [magenta]{model}[/magenta]")
# Always listed, including when empty: "none configured" tells a developer their admin set none,
# which a missing row leaves ambiguous. Shown as the admin configured them — registering them
# locally is a separate change, hence "pending".
mcp_names = [
str(server.get("name"))
for server in (managed.get("mcp_servers") or [])
if isinstance(server, dict) and server.get("name")
]
if mcp_names:
lines.append(f"[bold]MCPs:[/bold] {', '.join(mcp_names)} [dim](pending)[/dim]")
else:
lines.append("[bold]MCPs:[/bold] [dim]none configured[/dim]")
skill_names = [str(name) for name in ((managed.get("skills") or {}).get("names") or []) if name]
if skill_names:
lines.append(f"[bold]Skills:[/bold] {', '.join(skill_names)} [dim](pending)[/dim]")
else:
lines.append("[bold]Skills:[/bold] [dim]none configured[/dim]")
lines.extend(_policy_summary_lines(managed))
console.print(
Panel("\n".join(lines), title="Workspace-managed config", style="green", expand=False)
)
def _print_managed_summary_abridged(managed: dict, state: dict, tool: str | None) -> None:
"""One-line launch banner: which agent (and model) this managed run is launching.
Bare ``ucode`` runs every session, so the full box's MCP/skills/policy enumeration is noise
each time; ``ug status`` still shows all of it. See ``_print_managed_summary``'s ``abridged``
note. ``tool`` is always set on the launch path, but is guarded for callers that pass None."""
if tool is None:
print_note("Using managed config.")
return
agent = TOOL_SPECS[tool]["display"]
model = managed_default_model(managed, tool)
model_suffix = f" with [magenta]{model}[/magenta]" if model else ""
# "as the default agent" only when this really is the config's default: a budget tier can
# override the default and launch a different agent, and the tier note in `_launch_tool` already
# explains that case — so claiming "default" here would contradict it.
role = " as the default agent" if tool == managed.get("default_agent") else ""
console.print(
f"[dim]•[/dim] Using managed config — launching [green]{agent}[/green]{role}{model_suffix}"
)
def _confirm_managed_config_applied(managed: dict, workspace: str) -> None:
print_success("A managed config is published for your workspace — you're all set.")
_print_managed_summary(managed, {"workspace": workspace}, tool=None)
print_note("Run `ug` to launch with your managed settings.")
def _print_discovery_diagnostics(state: dict) -> None:
"""Surface per-source reasons after a failed discovery so the user knows
which API call returned what — instead of the generic 'no agents' line."""
reasons = state.get("_discovery_reasons") or {}
if not reasons:
return
labels = {
"claude": "Claude models",
"codex": "Codex models",
"gemini": "Gemini models",
"oss": "OSS models",
}
for source, reason in reasons.items():
consumers = ", ".join(_DISCOVERY_CONSUMERS.get(source, ()))
label = labels.get(source, source)
if reason:
print_note(f"{label} (needed for: {consumers}): {reason}")
else:
print_note(f"{label} (needed for: {consumers}): no models returned")
print_note("Re-run with `UCODE_DEBUG=1` to log raw discovery responses to ~/.ucode/debug.log.")
def _prompt_for_configuration(tool: str | None = None) -> tuple[str, str | None]:
if tool is None:
desc = "Configure your Databricks workspace"
else:
desc = f"Configure {TOOL_SPECS[tool]['display']} to use your Databricks endpoint."
with spinner("Loading Databricks workspaces and profiles..."):
profiles = get_databricks_profiles()
return prompt_for_workspace(desc, profiles)
def _parse_agents_option(agents: str) -> list[str]:
tools: list[str] = []
for raw_tool in agents.split(","):
raw_tool = raw_tool.strip()
if not raw_tool:
continue
tool = normalize_tool(raw_tool)
if tool not in tools:
tools.append(tool)
if not tools:
raise RuntimeError(
"No agents provided for --agents. Use a comma-separated list like `--agents claude,codex`."
)
return tools
def _parse_skill_locations(location: str | None) -> list[str]:
"""Parse a comma-separated `--location` into `<catalog>.<schema>` refs,
dropping duplicates while preserving order. `None`/empty yields `[]` (the
schema-less, utility-tools-only connection)."""
locations: list[str] = []
for raw in (location or "").split(","):
raw = raw.strip()
if not raw:
continue
parts = raw.split(".")
if len(parts) != 2 or not all(part.strip() for part in parts):
raise RuntimeError(f"--location entries must be `<catalog>.<schema>`, got `{raw}`.")
if raw not in locations:
locations.append(raw)
return locations
def _parse_workspaces_option(workspaces: str) -> list[tuple[str, str | None]]:
"""Parse `--workspaces` into [(url, profile_name | None), ...].
`--workspaces` supplies bare URLs; the matching profile (if any) is
resolved later via `find_profile_name_for_host`.
"""
workspace_entries: list[tuple[str, str | None]] = []
seen: set[str] = set()
for raw_workspace in workspaces.split(","):
raw_workspace = raw_workspace.strip()
if not raw_workspace:
continue
try:
workspace = normalize_workspace_url(raw_workspace)
except ValueError as exc:
raise RuntimeError(str(exc)) from exc
if workspace not in seen:
seen.add(workspace)
workspace_entries.append((workspace, None))
if not workspace_entries:
raise RuntimeError(
"No workspaces provided for --workspaces. Use a comma-separated list like "
"`--workspaces https://workspace.databricks.com`."
)
return workspace_entries
def _parse_profiles_option(profiles: str) -> list[tuple[str, str | None]]:
"""Parse `--profiles` into [(url, profile_name), ...].
Each name must be an existing Databricks CLI profile; its host supplies
the workspace URL. Auth behaves the same as `--workspaces`: OAuth login is
forced unless `--use-pat` is also passed."""
available = {str(p.get("name")): p for p in list_profile_entries() if p.get("name")}
workspace_entries: list[tuple[str, str | None]] = []
seen: set[str] = set()
for raw_name in profiles.split(","):
name = raw_name.strip()
if not name:
continue
entry = available.get(name)
if entry is None:
known = ", ".join(sorted(available)) or "none"
raise RuntimeError(
f"Databricks CLI profile '{name}' was not found (available: {known}). "
"Check `databricks auth profiles` or add the profile to ~/.databrickscfg."
)
host = str(entry.get("host") or "").strip()
if not host:
raise RuntimeError(
f"Databricks CLI profile '{name}' has no host configured in ~/.databrickscfg."
)
try:
workspace = normalize_workspace_url(host)
except ValueError as exc:
raise RuntimeError(str(exc)) from exc
if workspace not in seen:
seen.add(workspace)
workspace_entries.append((workspace, name))
if not workspace_entries:
raise RuntimeError(
"No profiles provided for --profiles. Use a comma-separated list like "
"`--profiles DEFAULT`."
)
return workspace_entries
def configure_shared_state(
workspace: str,
profile: str | None = None,
tools: list[str] | None = None,
force_login: bool = False,
use_pat: bool | None = None,
skip_model_discovery: bool = False,
skip_preflight: bool = False,
fable_enabled: bool | None = None,
databricks_ai_tools_enabled: bool | None = None,
) -> dict:
"""Log into Databricks, verify AI Gateway, fetch model lists, persist state.
If tools is provided, only fetch models for those tools. Otherwise fetch all.
If force_login is True, always run databricks auth login (used by explicit configure).
If use_pat is True (explicit `configure --profiles <name> --use-pat`), the
profile's personal access token from ~/.databrickscfg is used instead of
OAuth and no interactive login ever runs. ``None`` means "inherit": a
launch re-run keeps the mode the workspace was configured with.
``profile`` is the Databricks CLI profile name to address — passed via
``--profile`` to every CLI invocation so ambiguous `~/.databrickscfg`
entries (e.g. DEFAULT and a named profile both pointing at the same host)
don't error out. If ``None``, we resolve it from the host after login.
If skip_preflight is True, skip the entire preflight block below — auth
validation, the AI Gateway probe, and model discovery — trusting a prior
``ug configure``. The PAT/bearer is already exported (``apply_pat_environment``
in ``_launch_tool``) and the gateway was verified by that earlier configure.
Only the local profile resolution and the shared state assembly still run;
the saved model lists are preserved.
``fable_enabled`` opts the premium Claude Fable family into Claude Code's
``ANTHROPIC_DEFAULT_FABLE_MODEL`` pin (default off). ``None`` means "inherit":
a launch re-run keeps whatever the workspace was configured with; ``True``/
``False`` come from an explicit ``configure --enable-fable``/``--disable-fable``.
"""
workspace = normalize_workspace_url(workspace)
prior_state = load_state()
previous_workspace = prior_state.get("workspace")
if use_pat is None:
use_pat = bool(prior_state.get("use_pat")) and previous_workspace == workspace
if fable_enabled is None:
fable_enabled = bool(prior_state.get("fable_enabled")) and previous_workspace == workspace
if databricks_ai_tools_enabled is None:
# Opt-out: on by default. With no flag, keep this workspace's prior
# choice but don't inherit another workspace's opt-out.
disabled = (
prior_state.get("databricks_ai_tools_enabled") is False
and previous_workspace == workspace
)
databricks_ai_tools_enabled = not disabled
fetch_all = tools is None
# Assemble the shared workspace state that doesn't depend on model discovery:
# workspace, profile, auth mode, base URLs. `profile` may still be None here;
# each path below resolves it once, where a host->profile lookup is reliable
# (the skip branch trusts the prior configure; the preflight resolves after
# login). --skip-preflight persists exactly this and returns, trusting a prior
# `ug configure` — it already validated auth + the AI Gateway and saved the
# model lists (carried over by load_state, left untouched).
state = load_state()
state["workspace"] = workspace
if profile:
state["profile"] = profile
else:
state.pop("profile", None)
# UC discovery is now always-on; drop any flag persisted by older versions.
state.pop("uc_enabled", None)
# Persist the auth mode so launches rebuild the same (PAT-based) agent
# auth command; an explicit re-configure without --use-pat clears it.
if use_pat:
state["use_pat"] = True
else:
state.pop("use_pat", None)
# Persist the Fable opt-in so launches keep pinning the family; an explicit
# `configure --disable-fable` (fable_enabled=False) clears it.
if fable_enabled:
state["fable_enabled"] = True
else:
state.pop("fable_enabled", None)
state["databricks_ai_tools_enabled"] = databricks_ai_tools_enabled
state["base_urls"] = build_shared_base_urls(workspace)
if skip_preflight:
# A prior `ug configure` created the profile; resolve it locally (no
# login needed) and persist it so launches disambiguate.
if profile is None:
profile = find_profile_name_for_host(workspace)
if profile:
state["profile"] = profile
save_state(state)
# Scrub MCP entries ucode wrote for a previous workspace.
if previous_workspace and previous_workspace != workspace:
purge_cross_workspace_mcp_residue(state, workspace)
# Diagnostic reasons are transient (attached after save_state so they
# don't land on disk). No discovery ran, so there is nothing to report.
state["_discovery_reasons"] = {"claude": None, "gemini": None, "codex": None, "oss": None}
return state
# ── Preflight (bypassed above under --skip-preflight): validate Databricks
# auth + the AI Gateway, then discover the available models. ──
if use_pat:
if not profile:
raise RuntimeError(
"--use-pat requires a Databricks CLI profile. Pass one via `--profiles <name>`."
)
pat = resolve_pat_token(profile)
if not pat:
raise RuntimeError(
f"--use-pat: profile '{profile}' has no personal access token in "
"~/.databrickscfg (its auth_type must be `pat`). Add a `token = <PAT>` "
f"entry under [{profile}], or re-run without --use-pat to use OAuth."
)
# Export the PAT for this process and launched agent subprocesses so
# every token fetch takes the static-bearer path. ensure_pat_bearer
# keeps a non-empty pre-set bearer (CI escape hatch) but treats an
# empty one as absent, so it never shadows the PAT. Pass the validated
# token to avoid re-reading ~/.databrickscfg.
ensure_pat_bearer(profile, pat)
ensure_databricks_auth(workspace, profile)
elif force_login:
run_databricks_login(workspace, profile)
else:
ensure_databricks_auth(workspace, profile)
# After login the profile exists in ~/.databrickscfg, so a host->profile
# lookup is reliable even when it returned nothing above.
if profile is None:
profile = find_profile_name_for_host(workspace)
if profile:
state["profile"] = profile
with spinner("Verifying Unity AI Gateway..."):
token = get_databricks_token(workspace, profile)
model_service_probe = probe_unity_gateway_capabilities(workspace, token)
if model_service_probe.resource_available:
print_success("Unity AI Gateway connected")
else:
print_warning(f"Model service: {model_service_probe.detail}")
want_claude = (
fetch_all or "claude" in tools or "opencode" in tools or "copilot" in tools or "pi" in tools
)
want_gemini = fetch_all or "gemini" in tools or "opencode" in tools or "pi" in tools
want_codex = fetch_all or "codex" in tools or "copilot" in tools or "pi" in tools
# Codex smart routing can select OSS models such as GLM, so a Codex-only
# configure must persist that discovered family too.
want_oss = fetch_all or "opencode" in tools or "codex" in tools
claude_reason: str | None = None
gemini_reason: str | None = None
codex_reason: str | None = None
oss_reason: str | None = None
claude_models = {}
gemini_models = []
codex_models = []
oss_models = []
opencode_models: dict[str, list[str]] = {}
web_search_model: str | None = None
if skip_model_discovery:
# Provider mode: the agent routes through a Model Provider Service and
# pins no Databricks model, so the full family discovery is unused. Web
# search (claude only) still needs one Responses-capable model, so fetch
# just that with a single call.
if want_claude:
with spinner("Fetching web search model..."):
ws_models, _ = discover_codex_models(workspace, token)
if ws_models:
web_search_model = ws_models[0]
else:
# UC-first, best-effort: one UC model-services call yields all families
# as `system.ai.<model-name>` ids, bucketed by name. If a family comes
# back empty (workspace without UC model-services, or the listing
# failed), fall back to the per-family AI Gateway listing for that
# family only.
with spinner("Fetching available models..."):
ms_claude, ms_codex, ms_gemini, ms_oss, ms_reason = discover_model_services(
workspace, token
)
if want_claude:
claude_models, claude_reason = ms_claude, ms_reason
if not claude_models:
claude_models, claude_reason = discover_claude_models(workspace, token)
# Fable is opt-in (`configure --enable-fable`). Unless enabled,
# drop it from the discovered bundle entirely so it never becomes
# part of any agent's config — not claude's family pins, nor the
# opencode/pi/copilot model lists built from claude_models.
if not fable_enabled:
claude_models.pop("fable", None)
if want_gemini:
gemini_models, gemini_reason = ms_gemini, ms_reason
if not gemini_models:
gemini_models, gemini_reason = discover_gemini_models(workspace, token)
if want_codex:
codex_models, codex_reason = ms_codex, ms_reason
if not codex_models:
codex_models, codex_reason = discover_codex_models(workspace, token)
if want_oss:
oss_models, oss_reason = ms_oss, ms_reason
if claude_models:
opencode_models["anthropic"] = list(claude_models.values())
if gemini_models:
opencode_models["gemini"] = gemini_models
if oss_models:
opencode_models["oss"] = oss_models
if skip_model_discovery:
# Don't clobber any previously-discovered Databricks model lists; provider
# mode just doesn't refresh or use them. Persist the web-search model so
# claude's web_search MCP keeps working through the normal gateway.
if web_search_model:
state["web_search_model"] = web_search_model
else:
if want_claude:
state["claude_models"] = claude_models
if want_gemini:
state["gemini_models"] = gemini_models
if want_codex:
state["codex_models"] = codex_models
if want_oss:
state["oss_models"] = oss_models
if fetch_all or "opencode" in tools:
state["opencode_models"] = opencode_models
save_state(state)
# Scrub MCP entries that ucode wrote for the previous workspace so the new
# workspace's agent configs aren't stale.
if previous_workspace and previous_workspace != workspace:
purge_cross_workspace_mcp_residue(state, workspace)
# Diagnostic reasons are transient — attach after save_state so they don't
# land on disk but are available to the caller for this run.
state["_discovery_reasons"] = {
"claude": claude_reason,
"gemini": gemini_reason,
"codex": codex_reason,
"oss": oss_reason,
}
return state
def _configure_shared_workspace_states(
workspaces: list[tuple[str, str | None]],
tools: list[str] | None,
*,
force_login: bool,
use_pat: bool = False,
fable_enabled: bool | None = None,
databricks_ai_tools_enabled: bool | None = None,
) -> list[dict]:
if not workspaces:
raise RuntimeError("At least one workspace must be provided.")
states: list[dict] = []
for workspace, profile in workspaces:
states.append(
configure_shared_state(
workspace,
profile=profile,
tools=tools,
force_login=force_login,
use_pat=use_pat,
fable_enabled=fable_enabled,
databricks_ai_tools_enabled=databricks_ai_tools_enabled,
)
)
return states
def _provider_summary(tool: str, state: dict) -> str:
"""Short label for the Configuration Complete box: 'Databricks' when no
Model Provider Service is configured, otherwise the external provider type
backing this tool (claude routes to Anthropic, codex to OpenAI)."""
if not get_provider_service(state, tool):
return "Databricks"
return {"claude": "Anthropic", "codex": "OpenAI"}.get(tool, "Model Provider Service")
def _maybe_select_provider_service(tool: str, state: dict) -> dict:
"""Interactively let the user route claude/codex through a Model Provider
Service instead of Databricks models, and persist (or clear) the choice.
No-op for tools other than claude/codex/gemini. Falls back to Databricks when no
matching provider services are found or the listing fails.
"""
if tool not in ("claude", "codex", "gemini"):
return state
display = TOOL_SPECS[tool]["display"]
def _use_databricks() -> dict:
new_state = set_provider_service(state, tool, None)
save_state(new_state)
return new_state
# Probe first so we only offer the picker when it's actually usable. The
# interactive path always reaches here, so explain any fallback rather than
# silently dropping back to Databricks.
token = get_databricks_token(state["workspace"], state.get("profile"))
with spinner("Checking for model provider services..."):
names, reason = list_tool_provider_services(tool, state["workspace"], token)
if reason is not None:
# Most workspaces don't have the feature enabled — that's the common case,
# so fall back to Databricks silently. Only surface unexpected failures.
if not is_model_provider_feature_unavailable(reason):
print_warning(f"Could not list model provider services: {reason}")
print_note("Falling back to Databricks models.")
return _use_databricks()
if not names:
# Feature is on but no service matches this tool's provider type.
print_note(f"Using Databricks models for {display}.")
return _use_databricks()
choice = prompt_for_selection(
f"How should {display} get its models?",
[
("databricks", "Databricks Hosted"),
("mps", "External Models"),
],
)
if choice is None:
raise KeyboardInterrupt
if choice == "databricks":
return _use_databricks()
selected = prompt_for_selection(
"Select a model provider service:", [(name, name) for name in names]
)
if selected is None:
raise KeyboardInterrupt
state = set_provider_service(state, tool, selected)
save_state(state)
print_success(f"{display} will route through {selected}")
return state
def configure_workspace_command(
tool: str | None = None,
selected_tools: list[str] | None = None,
workspaces: list[tuple[str, str | None]] | None = None,
*,
prompt_optional_updates: bool = True,
use_pat: bool = False,
skip_validate: bool = False,
skip_unavailable: bool = False,
fable_enabled: bool | None = None,
databricks_ai_tools_enabled: bool | None = None,
offer_optional_setup: bool = False,
) -> int:
if tool is not None and selected_tools is not None:
raise RuntimeError("Use either --agent or --agents, not both.")
# The Databricks-vs-Model-Provider-Service picker is shown only on the fully
# interactive path (`ug configure` with no --agent/--agents). Naming agents
# explicitly signals the non-interactive flow, which stays on Databricks.
offer_provider = tool is None and selected_tools is None
workspace_entries = workspaces or [_prompt_for_configuration(tool)]
if tool is not None:
states = _configure_shared_workspace_states(
workspace_entries,
[tool],
force_login=True,
use_pat=use_pat,
fable_enabled=fable_enabled,
databricks_ai_tools_enabled=databricks_ai_tools_enabled,
)
state = states[0]
state = configure_single_tool(tool, state)
install_databricks_ai_tools_for_agents([tool], state)
spec = TOOL_SPECS[tool]
console.print(
Panel(
f"[bold]Workspace:[/bold] [cyan]{state['workspace']}[/cyan]\n"
f"[bold]{spec['display']}:[/bold] [green]configured[/green] "
f"[dim](Provider: {_provider_summary(tool, state)})[/dim]",
title="Configuration Complete",
style="green",
expand=False,
)
)
if skip_validate:
print_note(f"Skipping {spec['display']} validation (--skip-validate).")
return 0
with spinner(f"Validating {spec['display']}..."):
ok, err = validate_tool(tool)
if ok:
print_success(f"{spec['display']} is working")
else:
print_err(f"{spec['display']}: {provider_permission_error(tool, state, err)}")
managed = bool(state.get("managed_configs", {}).get(tool))
restore_file(spec["config_path"], spec["backup_path"], managed)
available_tools = [t for t in (state.get("available_tools") or []) if t != tool]
state["available_tools"] = available_tools
save_state(state)
raise RuntimeError(f"{spec['display']} validation failed — config reverted.")
return 0
states = _configure_shared_workspace_states(
workspace_entries,
selected_tools,
force_login=True,
use_pat=use_pat,
fable_enabled=fable_enabled,
databricks_ai_tools_enabled=databricks_ai_tools_enabled,
)
state = states[0]
save_state(state)
available_on_workspace: list[str] = []
tools_to_check = selected_tools or list(TOOL_SPECS)
for tool_name in tools_to_check:
with spinner(f"Checking {TOOL_SPECS[tool_name]['display']} availability..."):
if check_gateway_endpoint(state, tool_name):
available_on_workspace.append(tool_name)
if not available_on_workspace:
print_err("No coding agents are available on this workspace.")
_print_discovery_diagnostics(state)
return 1
if selected_tools is None:
picked = prompt_for_tools([(t, TOOL_SPECS[t]["display"]) for t in available_on_workspace])
else:
unavailable_tools = [
tool_name for tool_name in selected_tools if tool_name not in available_on_workspace
]
if unavailable_tools:
_print_discovery_diagnostics(state)
displays = ", ".join(
TOOL_SPECS[tool_name]["display"] for tool_name in unavailable_tools
)
if not skip_unavailable:
raise RuntimeError(
f"Requested agent(s) not available on this workspace: {displays}. "
"Pass --skip-unavailable to configure the available ones instead."
)
print_warning(f"Skipping agent(s) not available on this workspace: {displays}.")
picked = [tool_name for tool_name in selected_tools if tool_name in available_on_workspace]
if not picked:
print_note("No coding agents selected — nothing to configure.")
return 0
for tool_name in picked:
install_tool_binary(
tool_name,
strict=False,
update_existing=True,
prompt_optional_updates=prompt_optional_updates,
)
# Offer the provider picker for the chosen claude/codex tools only on the
# interactive path (no --agents); otherwise stay on the Databricks path.
if offer_provider:
for tool_name in picked:
state = _maybe_select_provider_service(tool_name, state)
if offer_optional_setup:
state = configure_selected_tools(state, picked, install_ai_tools=False)
else:
state = configure_selected_tools(state, picked)
summary_lines = [f"[bold]Workspace:[/bold] [cyan]{state['workspace']}[/cyan]"]
for tool_name in picked:
spec = TOOL_SPECS[tool_name]
summary_lines.append(
f"[bold]{spec['display']}:[/bold] [green]configured[/green] "
f"[dim](Provider: {_provider_summary(tool_name, state)})[/dim]"
)
console.print(
Panel(
"\n".join(summary_lines),
title="Configuration Complete",
style="green",
expand=False,
)
)
if skip_validate:
print_note("Skipping agent validation (--skip-validate).")
else:
# Limit validation to just-configured tools so we don't re-validate
# previously-configured tools the user didn't touch this run.
validate_state = {**state, "available_tools": picked}
validate_all_tools(validate_state)
if offer_optional_setup and not is_dry_run():
_configure_optional_setup(state, picked)
return 0
def status() -> int:
state = load_state()
workspace = state.get("workspace")
managed_configs = state.get("managed_configs") or {}
mcp_servers = state.get("mcp_servers") or []
configured_tools = set(state.get("available_tools") or managed_configs.keys())
console.print(heading("ug status"))
console.print(
f" {status_badge('Configured', 'ok') if workspace else status_badge('Not Configured', 'warn')}"
)
print_heading("Provider")
print_kv("Workspace URL", workspace or "not configured")
profile = state.get("profile")
if profile:
print_kv("CLI profile", profile)
if workspace:
managed = load_managed_state(workspace)
if managed:
_print_managed_summary(managed, state, None)
print_heading("Coding Agents")
for tool, spec in TOOL_SPECS.items():
configured = tool in configured_tools
base_url = (
state.get("base_urls", {}).get(tool, "not configured")
if configured
else "not configured"
)
config_path = spec["config_path"]
print_kv("Coding Agent", spec["display"])
print_kv("Configured", "yes" if configured else "no")
provider_service = get_provider_service(state, tool)
if configured and provider_service:
print_kv("Model Provider Service", provider_service)
print_kv("Base URL", base_url)
if configured and tool in MCP_CLIENTS:
tool_mcp_servers = [
str(server.get("name"))
for server in mcp_servers
if tool in (server.get("clients") or [])
and server.get("name")
and server.get("kind") != SKILLS_MCP_KIND
]
print_kv("MCP list command", str(MCP_CLIENTS[tool]["list_command"]))
print_kv(
"MCP servers",
", ".join(tool_mcp_servers) if tool_mcp_servers else "none saved by ug",
)
print_kv("Config file", str(config_path) if config_path.exists() else "missing")
if tool == "claude":
managed_path, managed_status, backup_status = claude_agent.managed_settings_status(
state
)
print_kv("OS-managed settings", managed_status)
print_kv("Managed settings file", str(managed_path) if managed_path else "unsupported")
print_kv("Managed settings backup", backup_status)
elif tool == "codex":
managed_path, managed_status, backup_status = codex_agent.managed_config_status(state)
print_kv("OS-managed settings", managed_status)
print_kv("Managed settings file", str(managed_path) if managed_path else "unsupported")
print_kv("Managed settings backup", backup_status)
console.print()
print_heading("Skills")
skill_mcp_entry = next((s for s in mcp_servers if s.get("kind") == SKILLS_MCP_KIND), None)
if not skill_mcp_entry:
print_kv("Skills", "not configured")
else:
configured_clients = [
client for client in (skill_mcp_entry.get("clients") or []) if client in MCP_CLIENTS
]
scopes = {
client: skill_locations_for_client(skill_mcp_entry, client)
for client in configured_clients
}
# Collapse to one line when every agent shares a scope; split per agent when they diverge.
if len({tuple(locations) for locations in scopes.values()}) <= 1:
locations = next(
iter(scopes.values()), list(skill_mcp_entry.get("skill_locations") or [])
)
print_kv(
"Skill MCP Locations",
", ".join(locations) if locations else "none — utility tools only",
)
configured_agents = [
str(MCP_CLIENTS[client]["display"]) for client in configured_clients
]
print_kv("Configured", ", ".join(configured_agents) if configured_agents else "none")
else:
for client, locations in scopes.items():
print_kv(
f"{MCP_CLIENTS[client]['display']} skill MCP locations",
", ".join(locations) if locations else "none — utility tools only",
)
print_heading("Tracing")
tracing = state.get("tracing") or {}
if tracing.get("enabled"):
print_kv("MLflow tracing", "enabled")
print_kv("Tracking URI", str(tracing.get("tracking_uri") or "unknown"))
print_kv(
"Experiment",
f"{tracing.get('experiment_name')} (id {tracing.get('experiment_id')})",
)
uc_destination = tracing.get("uc_destination")
if uc_destination:
print_kv("Unity Catalog", str(uc_destination))
sql_warehouse_id = tracing.get("sql_warehouse_id")
if sql_warehouse_id: