Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
804 lines (738 loc) · 28.2 KB
/
Copy pathcli.py
File metadata and controls
804 lines (738 loc) · 28.2 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
from __future__ import annotations
import asyncio
import hashlib
from importlib.metadata import PackageNotFoundError, version
import logging
import json
import os
import re
from pathlib import Path
import sys
from typing import Any
import duckdb
import typer
from .agent.cli import agent_app
from .web.db_bridge import (
SUPPORTED_ENGINES,
PostgresConnectorSettings,
SnowflakeConnectorSettings,
)
from .web.launcher import SqlroomsHttpServer, _pick_free_port
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger(__name__)
class SqlroomsGroup(typer.core.TyperGroup):
def parse_args(self, ctx, args):
if args and args[0] in self.commands:
args = ["", *args]
return super().parse_args(ctx, args)
app = typer.Typer(
cls=SqlroomsGroup,
add_completion=False,
pretty_exceptions_enable=False,
invoke_without_command=True,
)
if sys.platform.startswith("win"):
_config_base = Path(os.environ.get("APPDATA", "")) / "sqlrooms"
else:
_config_base = Path.home() / ".config" / "sqlrooms"
DEFAULT_CONFIG_PATH = _config_base / "config.toml"
DEFAULT_HTTP_PORT = 3000
CAPABILITY_PROFILE_NAMES = ("default", "experimental", "document-charts-maps")
DEFAULT_CAPABILITY_PROFILE = "default"
EXPERIMENTAL_CAPABILITY_PROFILE = "experimental"
def _get_cli_version() -> str:
package_json = Path(__file__).resolve().parents[1] / "package.json"
try:
payload = json.loads(package_json.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
pass
else:
package_version = payload.get("version")
if isinstance(package_version, str):
return package_version
try:
return version("sqlrooms")
except PackageNotFoundError:
return "unknown"
def _version_callback(value: bool) -> None:
if value:
typer.echo(f"sqlrooms {_get_cli_version()}")
raise typer.Exit()
def _configure_logging(*, debug: bool) -> None:
logging.getLogger().setLevel(logging.DEBUG if debug else logging.INFO)
def _resolve_http_port(
host: str,
port: int | None,
) -> int:
if port is not None:
return port
selected_port = _pick_free_port(host, DEFAULT_HTTP_PORT)
if selected_port != DEFAULT_HTTP_PORT:
logger.info(
"Port %s is in use, using HTTP port %s instead",
DEFAULT_HTTP_PORT,
selected_port,
)
return selected_port
def _normalize_config_string(value: Any) -> str | None:
if isinstance(value, (int, float)):
return str(value)
if not isinstance(value, str):
return None
normalized = value.strip()
return normalized or None
def _resolve_config_path(explicit_path: str | None, no_config: bool) -> Path | None:
if no_config:
return None
if explicit_path:
candidate = Path(explicit_path).expanduser()
if candidate.exists():
return candidate
raise RuntimeError(f"SQLRooms config file not found: {candidate}")
if DEFAULT_CONFIG_PATH.exists():
return DEFAULT_CONFIG_PATH
return None
def _read_toml(path: Path) -> dict[str, Any]:
try:
import tomllib # type: ignore[attr-defined]
except ModuleNotFoundError:
import tomli as tomllib # type: ignore[no-redef]
with path.open("rb") as fh:
data = tomllib.load(fh)
if not isinstance(data, dict):
raise RuntimeError(f"SQLRooms config must be a TOML object: {path}")
return data
def _load_capability_profile(path: Path | None) -> str | None:
"""Load the optional production capability profile from ``[app]``."""
if path is None:
return None
raw = _read_toml(path)
app_config = raw.get("app")
if app_config is None:
return None
if not isinstance(app_config, dict):
raise RuntimeError("'app' must be an object in SQLRooms config.")
profile = _normalize_config_string(app_config.get("profile"))
if app_config.get("profile") is not None and profile is None:
raise RuntimeError("'app.profile' must be a non-empty string.")
return profile
def _resolve_capability_profile(
explicit_profile: str | None,
config_profile: str | None,
*,
experimental: bool,
) -> str:
"""Resolve CLI/config selection and the legacy ``--experimental`` alias."""
if experimental:
if (
explicit_profile is not None
and explicit_profile.strip() != EXPERIMENTAL_CAPABILITY_PROFILE
):
raise RuntimeError(
f"--experimental conflicts with capability profile "
f"'{explicit_profile.strip()}'. "
"Use --profile experimental or remove one of the selections."
)
return EXPERIMENTAL_CAPABILITY_PROFILE
selected = explicit_profile if explicit_profile is not None else config_profile
if selected is not None:
selected = selected.strip()
if selected not in CAPABILITY_PROFILE_NAMES:
expected = ", ".join(CAPABILITY_PROFILE_NAMES)
raise RuntimeError(
f"Unknown SQLRooms capability profile '{selected}'. "
f"Expected one of: {expected}."
)
return selected or DEFAULT_CAPABILITY_PROFILE
def _require_config_string(
payload: dict[str, Any], key: str, *, connector_id: str, engine: str
) -> str:
value = _normalize_config_string(payload.get(key))
if value:
return value
raise RuntimeError(
f"Connector '{connector_id}' ({engine}) requires non-empty '{key}' in config."
)
def _load_connector_config(
path: Path | None,
) -> list[PostgresConnectorSettings | SnowflakeConnectorSettings]:
if path is None:
return []
raw = _read_toml(path)
db = raw.get("db")
if not isinstance(db, dict):
db = {}
connectors = db.get("connectors") or []
if not isinstance(connectors, list):
raise RuntimeError("'db.connectors' must be an array in SQLRooms config.")
out: list[PostgresConnectorSettings | SnowflakeConnectorSettings] = []
seen_ids: set[str] = set()
for idx, item in enumerate(connectors):
if not isinstance(item, dict):
raise RuntimeError(f"Connector entry at index {idx} must be an object.")
engine = _normalize_config_string(item.get("engine"))
if engine not in SUPPORTED_ENGINES:
raise RuntimeError(
f"Connector entry at index {idx} has unsupported engine: {engine!r}"
)
connection_id = _require_config_string(
item, "id", connector_id=f"#{idx}", engine=engine
)
if connection_id in seen_ids:
raise RuntimeError(f"Duplicate connector id in config: {connection_id}")
seen_ids.add(connection_id)
title = _normalize_config_string(item.get("title")) or connection_id
if engine == "postgres":
out.append(
PostgresConnectorSettings(
host=_normalize_config_string(item.get("host")) or "localhost",
port=_normalize_config_string(item.get("port")) or "5432",
database=_normalize_config_string(item.get("database")) or "",
user=_normalize_config_string(item.get("user")) or "",
password=_normalize_config_string(item.get("password")),
connection_id=connection_id,
title=title,
)
)
continue
out.append(
SnowflakeConnectorSettings(
account=_normalize_config_string(item.get("account")),
user=_normalize_config_string(item.get("user")),
password=_normalize_config_string(item.get("password")),
warehouse=_normalize_config_string(item.get("warehouse")),
database=_normalize_config_string(item.get("database")),
schema=_normalize_config_string(item.get("schema")),
role=_normalize_config_string(item.get("role")),
authenticator=_normalize_config_string(item.get("authenticator")),
connection_id=connection_id,
title=title,
)
)
logger.debug("Loaded SQLRooms connector config from %s", path)
return out
def _load_ai_runtime_config(
path: Path | None,
) -> tuple[
str | None,
str | None,
dict[str, dict[str, Any]],
list[dict[str, Any]],
dict[str, Any],
]:
if path is None:
return (None, None, {}, [], {})
raw = _read_toml(path)
ai = raw.get("ai")
if not isinstance(ai, dict):
return (None, None, {}, [], {})
default_provider = _normalize_config_string(ai.get("default_provider"))
default_model = _normalize_config_string(ai.get("default_model"))
providers_raw = ai.get("providers") or []
if not isinstance(providers_raw, list):
raise RuntimeError("'ai.providers' must be an array in SQLRooms config.")
providers: dict[str, dict[str, Any]] = {}
for idx, item in enumerate(providers_raw):
if not isinstance(item, dict):
raise RuntimeError(f"AI provider entry at index {idx} must be an object.")
provider_id = _require_config_string(
item, "id", connector_id=f"ai#{idx}", engine="ai"
)
if provider_id in providers:
raise RuntimeError(f"Duplicate AI provider id in config: {provider_id}")
base_url = _normalize_config_string(item.get("base_url")) or ""
api_key = _normalize_config_string(item.get("api_key")) or ""
api_key_env = _normalize_config_string(item.get("api_key_env"))
if api_key_env and not api_key:
api_key = os.environ.get(api_key_env, "")
models_raw = item.get("models") or []
if not isinstance(models_raw, list):
raise RuntimeError(
f"AI provider '{provider_id}' has invalid 'models' (must be an array)."
)
models = []
for model in models_raw:
model_name = _normalize_config_string(model)
if model_name:
models.append({"modelName": model_name})
providers[provider_id] = {
"baseUrl": base_url,
"apiKey": api_key,
"models": models,
}
custom_models_raw = ai.get("custom_models") or []
if not isinstance(custom_models_raw, list):
raise RuntimeError("'ai.custom_models' must be an array in SQLRooms config.")
custom_models: list[dict[str, Any]] = []
for idx, item in enumerate(custom_models_raw):
if not isinstance(item, dict):
raise RuntimeError(
f"AI custom model entry at index {idx} must be an object."
)
model_name = _normalize_config_string(
item.get("model_name") or item.get("modelName")
)
base_url = _normalize_config_string(item.get("base_url") or item.get("baseUrl"))
if not model_name or not base_url:
raise RuntimeError(
f"AI custom model entry at index {idx} requires 'model_name' and 'base_url'."
)
custom_models.append(
{
"modelName": model_name,
"baseUrl": base_url,
"apiKey": _normalize_config_string(item.get("api_key")) or "",
}
)
model_parameters_raw = ai.get("model_parameters") or {}
if not isinstance(model_parameters_raw, dict):
raise RuntimeError(
"'ai.model_parameters' must be an object in SQLRooms config."
)
model_parameters: dict[str, Any] = {}
if "max_steps" in model_parameters_raw:
max_steps = model_parameters_raw.get("max_steps")
if not isinstance(max_steps, int):
raise RuntimeError("'ai.model_parameters.max_steps' must be an integer.")
model_parameters["maxSteps"] = max_steps
additional_instruction = model_parameters_raw.get(
"additional_instruction",
model_parameters_raw.get("additionalInstruction"),
)
if isinstance(additional_instruction, str):
model_parameters["additionalInstruction"] = additional_instruction
if (
default_provider
and default_provider not in providers
and default_provider != "custom"
):
raise RuntimeError(
f"AI default_provider '{default_provider}' is not defined under ai.providers."
)
if not default_provider and providers:
default_provider = next(iter(providers.keys()))
if not default_model and default_provider:
provider = providers.get(default_provider, {})
models = provider.get("models") or []
if models:
default_model = models[0].get("modelName")
if default_provider == "custom" and not default_model and custom_models:
default_model = custom_models[0].get("modelName")
logger.debug("Loaded SQLRooms AI config from %s", path)
return (default_provider, default_model, providers, custom_models, model_parameters)
@app.command("export")
def export_project(
db_path: str = typer.Argument(
...,
help="DuckDB project file to export from.",
),
out_dir: str = typer.Option(
"./out",
"--dir",
help="Output directory for exported artifacts.",
),
meta_namespace: str = typer.Option(
"__sqlrooms",
"--meta-namespace",
help="Namespace for SQLRooms meta tables.",
),
):
"""
Export app-builder files stored in persisted UI state to a directory.
"""
out = Path(out_dir).expanduser().resolve()
out.mkdir(parents=True, exist_ok=True)
con = duckdb.connect(db_path)
try:
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", meta_namespace):
typer.echo(
f"Invalid --meta-namespace value: {meta_namespace!r}",
err=True,
)
raise typer.Exit(code=1)
ui_ref = f'"{meta_namespace}"."ui_state"'
row = con.execute(
f"SELECT payload_json FROM {ui_ref} WHERE key = 'default' LIMIT 1"
).fetchone()
if not row:
typer.echo("No persisted ui_state found; nothing to export.")
return
payload = row[0]
if isinstance(payload, str):
try:
payload = json.loads(payload)
except json.JSONDecodeError as exc:
typer.echo(
f"Failed to parse payload_json from {ui_ref}: {exc}",
err=True,
)
raise typer.Exit(code=1) from exc
if not isinstance(payload, dict):
typer.echo(
"Invalid payload_json format: expected a JSON object.",
err=True,
)
raise typer.Exit(code=1)
app_project = (payload or {}).get("appProject") or {}
config = app_project.get("config") or {}
apps_by_sheet = config.get("appsBySheetId") or {}
exported = 0
for sheet_id, sheet_app in apps_by_sheet.items():
files = (sheet_app or {}).get("files") or {}
if not isinstance(files, dict) or len(files) == 0:
continue
safe_sheet_id = "".join(
ch for ch in str(sheet_id) if ch.isalnum() or ch in ("-", "_")
)
if not safe_sheet_id:
safe_sheet_id = hashlib.sha1(str(sheet_id).encode("utf-8")).hexdigest()[
:8
]
name = str((sheet_app or {}).get("name") or sheet_id)
safe_name = "".join(
ch for ch in name if ch.isalnum() or ch in ("-", "_", " ")
).strip()
safe_name = safe_name.replace(" ", "-") or safe_sheet_id
root = out / f"{safe_name}-{safe_sheet_id[:8]}"
root_resolved = root.resolve()
try:
root_resolved.relative_to(out)
except ValueError:
typer.echo(
f"Unsafe export root path resolved outside output dir: {root_resolved}",
err=True,
)
raise typer.Exit(code=1)
root.mkdir(parents=True, exist_ok=True)
meta = {
"sheetId": sheet_id,
"name": name,
"prompt": (sheet_app or {}).get("prompt", ""),
"template": (sheet_app or {}).get("template", ""),
"updatedAt": (sheet_app or {}).get("updatedAt"),
}
(root / "app.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
for path, content in files.items():
rel = Path(str(path).lstrip("/"))
target = (root / rel).resolve()
try:
target.relative_to(root_resolved)
except ValueError:
typer.echo(
f"Skipping unsafe export path outside target directory: {path!r}",
err=True,
)
continue
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(str(content), encoding="utf-8")
exported += 1
if exported == 0:
typer.echo("No app-builder files found in ui_state.")
return
typer.echo(f"Exported artifacts to {out}")
finally:
con.close()
@app.callback(invoke_without_command=True)
def main(
ctx: typer.Context,
show_version: bool = typer.Option(
False,
"--version",
callback=_version_callback,
is_eager=True,
help="Show the sqlrooms CLI version and exit.",
),
db_path: str | None = typer.Argument(
None,
help="DuckDB database to use (positional). Pass a filepath to persist, or ':memory:' for an in-memory DB (no file).",
),
db_path_option: str | None = typer.Option(
None,
"--db-path",
"-d",
help="DuckDB database to use (flag). Pass a filepath to persist, or ':memory:' for an in-memory DB (no file).",
show_default=False,
),
host: str = typer.Option("127.0.0.1", "--host", help="HTTP host for the UI."),
port: int | None = typer.Option(
None,
"--port",
help="HTTP port for the UI. If omitted, 3000 or the next free port is chosen automatically.",
),
ws_port: int | None = typer.Option(
None,
"--ws-port",
help="Removed: use --port for the shared listener.",
),
config: str | None = typer.Option(
None,
"--config",
envvar="SQLROOMS_CONFIG",
help="Path to a SQLRooms TOML config file. Defaults to ~/.config/sqlrooms/config.toml (%%APPDATA%%\\sqlrooms\\config.toml on Windows).",
),
no_config: bool = typer.Option(
False,
"--no-config",
help="Disable loading settings from config file.",
),
no_open_browser: bool = typer.Option(
False, "--no-open-browser", help="Skip automatically opening the browser."
),
ui: str = typer.Option(
None,
"--ui",
help="Optional path to a custom UI bundle directory (Vite dist). If omitted, uses the bundled default UI.",
),
no_ui: bool = typer.Option(
False,
"--no-ui",
help="Start only the HTTP API server and DuckDB websocket backend; do not serve the bundled/static UI.",
),
experimental: bool = typer.Option(
False,
"--experimental",
help="Compatibility alias for --profile experimental.",
),
capability_profile: str | None = typer.Option(
None,
"--profile",
help="Named capability profile: default, experimental, or document-charts-maps. Overrides [app].profile from the config file.",
),
experimental_sync: bool = typer.Option(
False,
"--experimental-sync",
help="Enable experimental sync (CRDT) over WebSocket (Loro). Requires the experimental capability profile.",
),
legacy_sync: bool = typer.Option(
False,
"--sync",
hidden=True,
),
ai_devtools: bool = typer.Option(
False,
"--ai-devtools",
envvar="SQLROOMS_AI_DEVTOOLS",
help="Enable the AI session devtools button in the UI, including production-built UI bundles.",
),
claude: bool = typer.Option(
False,
"--claude",
"--claude-code",
help="Open or create a database in an AI-free browser workspace and launch interactive Claude Code.",
),
execution_mode: str = typer.Option(
"embedded",
"--execution-mode",
help="Model execution owner: embedded or external. Independent of --profile.",
),
mcp: bool = typer.Option(
False,
"--mcp",
help="Enable the authenticated MCP endpoint on the shared HTTP listener.",
),
mcp_port: int | None = typer.Option(
None,
"--mcp-port",
help="Removed: use --port for the shared listener.",
),
debug: bool = typer.Option(
False,
"--debug",
help="Enable verbose debug logging, including HTTP access logs and DuckDB query timing.",
),
meta_db: str | None = typer.Option(
None,
"--meta-db",
help="Optional path to a dedicated DuckDB file for SQLRooms meta state (UI state + CRDT snapshots). If omitted, stores meta tables in the main DB.",
),
meta_namespace: str = typer.Option(
"__sqlrooms",
"--meta-namespace",
help="Namespace used for SQLRooms meta tables. If --meta-db is provided, this is the ATTACH alias; otherwise it's a schema in the main DB.",
),
external_url: str | None = typer.Option(
None,
"--external-url",
envvar="SQLROOMS_EXTERNAL_URL",
help="Public HTTP base URL to expose in runtime config, e.g. https://my-sprite.sprites.dev.",
),
external_ws_url: str | None = typer.Option(
None,
"--external-ws-url",
envvar="SQLROOMS_EXTERNAL_WS_URL",
help="Optional page-origin DuckDB proxy URL, e.g. wss://my-sprite.sprites.dev/ws/duckdb. Split endpoints are unsupported; normally derived from --external-url.",
),
):
"""
Launch a local SQLRooms project for adding data and building documents with Mosaic charts and dashboards.
Example: sqlrooms ./my-project.duckdb
- Serves HTTP, DuckDB WebSockets and optional MCP on one port.
- Serves the document UI with persisted state stored in DuckDB.
"""
if ctx.invoked_subcommand:
return
_configure_logging(debug=debug)
if os.environ.get("SQLROOMS_MANAGED_LOG"):
from logging.handlers import RotatingFileHandler
handler = RotatingFileHandler(
os.environ["SQLROOMS_MANAGED_LOG"], maxBytes=1024 * 1024, backupCount=2
)
logging.getLogger().handlers = [handler]
if legacy_sync:
typer.echo(
"--sync has been renamed to --experimental-sync and is not part of the public launch surface.",
err=True,
)
raise typer.Exit(code=1)
if execution_mode not in {"embedded", "external"}:
raise typer.BadParameter(
"Expected embedded or external", param_hint="--execution-mode"
)
claude_resources = None
if claude:
from .web.claude import claude_prerequisites
execution_mode = "external"
mcp = True
try:
claude_resources = claude_prerequisites()
except RuntimeError as exc:
typer.echo(str(exc), err=True)
raise typer.Exit(code=1) from exc
if mcp and no_ui:
typer.echo(
"--mcp requires the browser UI and cannot be used with --no-ui.", err=True
)
raise typer.Exit(code=1)
try:
config_path = _resolve_config_path(config, no_config=no_config)
config_capability_profile = _load_capability_profile(config_path)
resolved_capability_profile = _resolve_capability_profile(
capability_profile,
config_capability_profile,
experimental=experimental,
)
connector_settings = _load_connector_config(config_path)
(
llm_provider,
llm_model,
ai_providers,
ai_custom_models,
ai_model_parameters,
) = (
_load_ai_runtime_config(config_path)
if execution_mode == "embedded"
else (None, None, {}, [], {})
)
except Exception as exc:
typer.echo(str(exc), err=True)
raise typer.Exit(code=1) from exc
if (
experimental_sync
and resolved_capability_profile != EXPERIMENTAL_CAPABILITY_PROFILE
):
typer.echo(
"--experimental-sync requires --experimental or --profile experimental.",
err=True,
)
raise typer.Exit(code=1)
resolved_db_path = db_path if db_path is not None else db_path_option
if resolved_db_path is None or not resolved_db_path.strip():
typer.echo(
"Please provide a DuckDB project file, e.g. `sqlrooms ./my-project.duckdb`, "
"or pass `--db-path :memory:` for a temporary in-memory session.",
err=True,
)
raise typer.Exit(code=1)
# config_path may be None when the file doesn't exist yet; for saving we
# still want a writable target unless the user explicitly opted out.
save_config_path = (
config_path if config_path else (None if no_config else DEFAULT_CONFIG_PATH)
)
if ws_port is not None or mcp_port is not None:
typer.echo(
"--ws-port and --mcp-port were removed. Use --port; DuckDB is at /ws/duckdb and MCP at /mcp. Restart and reconfigure older clients.",
err=True,
)
raise typer.Exit(code=1)
selected_port = _resolve_http_port(host, port)
selected_api_key = (
str(ai_providers.get(llm_provider or "", {}).get("apiKey") or "")
if llm_provider
else ""
)
server = SqlroomsHttpServer(
db_path=resolved_db_path,
host=host,
port=selected_port,
ws_port=ws_port,
sync_enabled=experimental_sync,
capability_profile=resolved_capability_profile,
meta_db=meta_db,
meta_namespace=meta_namespace,
llm_provider=llm_provider,
llm_model=llm_model,
api_key=selected_api_key,
ai_providers=ai_providers,
ai_custom_models=ai_custom_models,
ai_model_parameters=ai_model_parameters,
connector_settings=connector_settings,
open_browser=not no_open_browser,
ui_dir=ui,
serve_ui=not no_ui,
config_path=save_config_path,
external_url=external_url,
external_ws_url=external_ws_url,
ai_devtools=ai_devtools,
execution_mode=execution_mode,
mcp_enabled=mcp,
mcp_port=mcp_port,
debug=debug,
)
try:
if claude_resources:
from .web.claude import run_claude_session
executable, plugin = claude_resources
exit_code = asyncio.run(
server.start(
session=lambda: run_claude_session(server, executable, plugin)
)
)
if exit_code:
raise typer.Exit(code=exit_code)
else:
asyncio.run(server.start())
except RuntimeError as exc:
typer.echo(str(exc), err=True)
raise typer.Exit(code=1) from exc
except KeyboardInterrupt:
sys.stderr.write("\nShutting down...\n")
app.add_typer(agent_app, name="agent")
@app.command(
"server",
context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
)
def server_command(
ctx: typer.Context,
db_path: str = typer.Option(
..., "--db-path", "-d", help="DuckDB database path or :memory:."
),
port: int | None = typer.Option(
None, "--port", help="Shared HTTP, WebSocket and MCP port."
),
):
"""Run the same workspace runtime without UI assets or browser launch.
Additional launcher options (including --host and --meta-db) are
forwarded to the normal launcher. Use `sqlrooms --help` for that full list.
A database literally named server can be opened as ./server.
"""
args = ["--db-path", db_path, "--no-ui", "--no-open-browser"]
if port is not None:
args += ["--port", str(port)]
exit_code = typer.main.get_command(app).main(
args=[*args, *ctx.args], standalone_mode=False
)
if isinstance(exit_code, int) and exit_code:
raise typer.Exit(code=exit_code)