ndi-cli 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ndi_cli-0.4.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nace AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
ndi_cli-0.4.0/PKG-INFO ADDED
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.4
2
+ Name: ndi-cli
3
+ Version: 0.4.0
4
+ Summary: NDI platform CLI: document operations, jobs, workspaces, and the agent workspace tools
5
+ Keywords: ndi,cli,document-intelligence,coding-agents
6
+ Author: Nace AI
7
+ Author-email: Nace AI <engineering@nace.ai>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Classifier: Typing :: Typed
18
+ Requires-Dist: ndi-sdk>=0.20,<1
19
+ Requires-Python: >=3.11, <3.14
20
+ Project-URL: Homepage, https://ndi-api.nace.ai
21
+ Description-Content-Type: text/markdown
22
+
23
+ # ndi-cli
24
+
25
+ `ndi` — the NDI platform CLI. Document operations, jobs, and workspace
26
+ lifecycle wrap the same `/v1` methods as `ndi-sdk`. The six workspace tools
27
+ also run inside an agent sandbox; every other verb is refused there.
28
+
29
+ ## Setup
30
+
31
+ ```bash
32
+ ndi login # browser device-code; writes ~/.ndi/config.toml
33
+ export NDI_BASE_URL="https://ndi-api.nace.ai" # optional; default shown
34
+ export NDI_WORKSPACE_ID="<workspace uuid>" # or: ndi workspace use <id>
35
+ ```
36
+
37
+ `$NDI_API_KEY` still wins over the file. `$NDI_CONFIG_PATH` overrides the
38
+ config location. Workspace-scoped verbs also take `--workspace ID`.
39
+
40
+ ## Commands
41
+
42
+ | Command | Use |
43
+ |---|---|
44
+ | `ndi login` | Authorize and save the API key |
45
+ | `ndi version` | CLI + SDK versions |
46
+ | `ndi upload FILE` | Stage bytes; prints `ndi://upload/<id>` |
47
+ | `ndi parse SOURCE` | Markdown / text / blocks |
48
+ | `ndi extract SOURCE -s SCHEMA` | Structured extract (`--validate` checks a schema with no job) |
49
+ | `ndi split SOURCE --class id:label` | Logical sections |
50
+ | `ndi classify SOURCE --class id:label` | Labels (refuses `jobid://`) |
51
+ | `ndi ground SOURCE --target id=TEXT` | Locate quoted text |
52
+ | `ndi job ID` / `ndi jobs` / `ndi cancel ID` | Inspect or cancel jobs |
53
+ | `ndi workspace create\|list\|get\|stats\|delete\|use` | Workspace lifecycle |
54
+ | `ndi files upload\|list\|get\|delete` | Workspace files (`--ingest` uploads then queues ingestion) |
55
+ | `ndi ingest` | Queue ingestion |
56
+ | `ndi deep-search QUERY` / `ndi fact-search QUERY` | Agentic / single-shot search |
57
+ | `ndi folder-metadata` / `file-metadata` / `read-file` / `ask-file` / `run-sql` / `hybrid-search` | Read-only workspace tools (the sandbox surface) |
58
+
59
+ ## Sources
60
+
61
+ `SOURCE` for document ops:
62
+
63
+ - local file — uploaded, then the handle is used
64
+ - directory — supported files, one job each (`-j N`, default 4)
65
+ - `https://...` — fetched by the server
66
+ - `ndi://upload/<uuid>` — a prior `ndi upload`
67
+ - `jobid://<uuid>` or a bare UUID — reuse a parse job (not classify)
68
+ - `ws://<file_id>` — a workspace file (needs a workspace)
69
+ - `-` — a `jobid://` / UUID line, or raw bytes with `--file-name`
70
+
71
+ ```bash
72
+ ndi parse a.pdf -o id | ndi extract - -s schema.json
73
+ ```
74
+
75
+ ## Output
76
+
77
+ Result content goes to **stdout**; status (`job <id> queued`, `saved …`) goes
78
+ to **stderr**. `-o auto|md|json|payload|id` picks the shape. `--json` is an
79
+ alias for `-o json`. `--save PATH` / `--out-dir DIR` write files. `--async`
80
+ submits and prints the job id.
81
+
82
+ API failures exit 1. Usage / config errors exit 2. Schema-validation
83
+ failures also show up to five field constraints, each limited to 500
84
+ characters; request input and unrelated error-detail fields are omitted.
85
+
86
+ See `SKILL.md` for the agent-facing guide to the six workspace tools.
@@ -0,0 +1,64 @@
1
+ # ndi-cli
2
+
3
+ `ndi` — the NDI platform CLI. Document operations, jobs, and workspace
4
+ lifecycle wrap the same `/v1` methods as `ndi-sdk`. The six workspace tools
5
+ also run inside an agent sandbox; every other verb is refused there.
6
+
7
+ ## Setup
8
+
9
+ ```bash
10
+ ndi login # browser device-code; writes ~/.ndi/config.toml
11
+ export NDI_BASE_URL="https://ndi-api.nace.ai" # optional; default shown
12
+ export NDI_WORKSPACE_ID="<workspace uuid>" # or: ndi workspace use <id>
13
+ ```
14
+
15
+ `$NDI_API_KEY` still wins over the file. `$NDI_CONFIG_PATH` overrides the
16
+ config location. Workspace-scoped verbs also take `--workspace ID`.
17
+
18
+ ## Commands
19
+
20
+ | Command | Use |
21
+ |---|---|
22
+ | `ndi login` | Authorize and save the API key |
23
+ | `ndi version` | CLI + SDK versions |
24
+ | `ndi upload FILE` | Stage bytes; prints `ndi://upload/<id>` |
25
+ | `ndi parse SOURCE` | Markdown / text / blocks |
26
+ | `ndi extract SOURCE -s SCHEMA` | Structured extract (`--validate` checks a schema with no job) |
27
+ | `ndi split SOURCE --class id:label` | Logical sections |
28
+ | `ndi classify SOURCE --class id:label` | Labels (refuses `jobid://`) |
29
+ | `ndi ground SOURCE --target id=TEXT` | Locate quoted text |
30
+ | `ndi job ID` / `ndi jobs` / `ndi cancel ID` | Inspect or cancel jobs |
31
+ | `ndi workspace create\|list\|get\|stats\|delete\|use` | Workspace lifecycle |
32
+ | `ndi files upload\|list\|get\|delete` | Workspace files (`--ingest` uploads then queues ingestion) |
33
+ | `ndi ingest` | Queue ingestion |
34
+ | `ndi deep-search QUERY` / `ndi fact-search QUERY` | Agentic / single-shot search |
35
+ | `ndi folder-metadata` / `file-metadata` / `read-file` / `ask-file` / `run-sql` / `hybrid-search` | Read-only workspace tools (the sandbox surface) |
36
+
37
+ ## Sources
38
+
39
+ `SOURCE` for document ops:
40
+
41
+ - local file — uploaded, then the handle is used
42
+ - directory — supported files, one job each (`-j N`, default 4)
43
+ - `https://...` — fetched by the server
44
+ - `ndi://upload/<uuid>` — a prior `ndi upload`
45
+ - `jobid://<uuid>` or a bare UUID — reuse a parse job (not classify)
46
+ - `ws://<file_id>` — a workspace file (needs a workspace)
47
+ - `-` — a `jobid://` / UUID line, or raw bytes with `--file-name`
48
+
49
+ ```bash
50
+ ndi parse a.pdf -o id | ndi extract - -s schema.json
51
+ ```
52
+
53
+ ## Output
54
+
55
+ Result content goes to **stdout**; status (`job <id> queued`, `saved …`) goes
56
+ to **stderr**. `-o auto|md|json|payload|id` picks the shape. `--json` is an
57
+ alias for `-o json`. `--save PATH` / `--out-dir DIR` write files. `--async`
58
+ submits and prints the job id.
59
+
60
+ API failures exit 1. Usage / config errors exit 2. Schema-validation
61
+ failures also show up to five field constraints, each limited to 500
62
+ characters; request input and unrelated error-detail fields are omitted.
63
+
64
+ See `SKILL.md` for the agent-facing guide to the six workspace tools.
@@ -0,0 +1,72 @@
1
+ [project]
2
+ name = "ndi-cli"
3
+ version = "0.4.0"
4
+ description = "NDI platform CLI: document operations, jobs, workspaces, and the agent workspace tools"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11,<3.14"
9
+ keywords = [
10
+ "ndi",
11
+ "cli",
12
+ "document-intelligence",
13
+ "coding-agents",
14
+ ]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Software Development :: Libraries :: Python Modules",
23
+ "Typing :: Typed",
24
+ ]
25
+ dependencies = ["ndi-sdk>=0.20,<1"]
26
+
27
+ [[project.authors]]
28
+ name = "Nace AI"
29
+ email = "engineering@nace.ai"
30
+
31
+ [project.urls]
32
+ Homepage = "https://ndi-api.nace.ai"
33
+
34
+ [project.scripts]
35
+ ndi = "ndi_cli._cli:main"
36
+
37
+ [tool.uv.sources.ndi-sdk]
38
+ workspace = true
39
+
40
+ [tool.ruff]
41
+ target-version = "py311"
42
+ line-length = 130
43
+ fix = true
44
+
45
+ [tool.ruff.lint]
46
+ ignore = [
47
+ "D",
48
+ "ANN",
49
+ "PLR0913",
50
+ ]
51
+
52
+ [tool.pytest.ini_options]
53
+ testpaths = ["tests"]
54
+ pythonpath = [
55
+ "src",
56
+ "tests",
57
+ ]
58
+ addopts = [
59
+ "--strict-markers",
60
+ "--tb=short",
61
+ ]
62
+
63
+ [dependency-groups]
64
+ dev = [
65
+ "pyrefly>=1.0.0,<2",
66
+ "pytest>=8.4.0",
67
+ "ruff>=0.12.0",
68
+ ]
69
+
70
+ [build-system]
71
+ requires = ["uv_build>=0.9.0,<0.10.0"]
72
+ build-backend = "uv_build"
@@ -0,0 +1,67 @@
1
+ [project]
2
+ name = "ndi-cli"
3
+ version = "0.4.0"
4
+ description = "NDI platform CLI: document operations, jobs, workspaces, and the agent workspace tools"
5
+ authors = [
6
+ { name = "Nace AI", email = "engineering@nace.ai" }
7
+ ]
8
+ readme = "README.md"
9
+ license = "MIT"
10
+ license-files = ["LICENSE"]
11
+ requires-python = ">=3.11,<3.14"
12
+ keywords = [
13
+ "ndi",
14
+ "cli",
15
+ "document-intelligence",
16
+ "coding-agents",
17
+ ]
18
+ classifiers = [
19
+ "Development Status :: 3 - Alpha",
20
+ "Intended Audience :: Developers",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Topic :: Software Development :: Libraries :: Python Modules",
26
+ "Typing :: Typed",
27
+ ]
28
+ dependencies = [
29
+ "ndi-sdk>=0.20,<1",
30
+ ]
31
+
32
+ [project.urls]
33
+ Homepage = "https://ndi-api.nace.ai"
34
+
35
+ [project.scripts]
36
+ ndi = "ndi_cli._cli:main"
37
+
38
+ [tool.uv.sources]
39
+ ndi-sdk = { workspace = true }
40
+
41
+ [dependency-groups]
42
+ dev = [
43
+ "pyrefly>=1.0.0,<2",
44
+ "pytest>=8.4.0",
45
+ "ruff>=0.12.0",
46
+ ]
47
+
48
+ [build-system]
49
+ requires = ["uv_build>=0.9.0,<0.10.0"]
50
+ build-backend = "uv_build"
51
+
52
+ [tool.ruff]
53
+ target-version = "py311"
54
+ line-length = 130
55
+ fix = true
56
+
57
+ [tool.ruff.lint]
58
+ ignore = [
59
+ "D",
60
+ "ANN",
61
+ "PLR0913",
62
+ ]
63
+
64
+ [tool.pytest.ini_options]
65
+ testpaths = ["tests"]
66
+ pythonpath = ["src", "tests"]
67
+ addopts = ["--strict-markers", "--tb=short"]
@@ -0,0 +1,9 @@
1
+ """``ndi`` — the NDI platform CLI.
2
+
3
+ Document operations, jobs, and workspace lifecycle wrap ``ndi-sdk`` ``/v1``
4
+ methods. The six workspace tools (``folder-metadata``, ``file-metadata``,
5
+ ``read-file``, ``ask-file``, ``run-sql``, ``hybrid-search``) remain the
6
+ in-sandbox surface.
7
+ """
8
+
9
+ __version__ = "0.4.0"
@@ -0,0 +1,166 @@
1
+ """``ndi`` entry point: workspace tools plus the platform verbs.
2
+
3
+ The six workspace tools stay available inside an agent sandbox. Every other
4
+ verb is refused when ``$NDI_CLI_SOCKET`` is set, before any client is built.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import os
11
+ import sys
12
+
13
+ from ndi_sdk.client import NdiClient
14
+ from ndi_sdk.errors import NdiError, NdiStatusError
15
+ from ndi_sdk.resources.tools import SyncTools
16
+
17
+ from ndi_cli import _docops, _jobs, _login, _tools, _workspace
18
+ from ndi_cli._config import ConfigError, resolve_settings
19
+ from ndi_cli._local import SOCKET_ENV, TOKEN_ENV, LocalTransport
20
+ from ndi_cli._tools import parse_pages
21
+
22
+ # qa-file runs a durable workflow that legitimately takes minutes; the metadata,
23
+ # read, and run-sql tools answer in seconds but share the generous bound.
24
+ DEFAULT_TIMEOUT_SECONDS = 900.0
25
+ _VALIDATION_ERROR_LIMIT = 5
26
+ _VALIDATION_ERROR_CHARS = 500
27
+
28
+
29
+ def main(argv: list[str] | None = None) -> int:
30
+ parser = _build_parser()
31
+ args = parser.parse_args(argv)
32
+ if args.command is None:
33
+ parser.print_help()
34
+ return 2
35
+ family = getattr(args, "family", None)
36
+ socket_path = os.environ.get(SOCKET_ENV)
37
+ # Presence, not truthiness: an empty $NDI_CLI_SOCKET still means "inside an
38
+ # agent run", and must not silently unlock the full platform CLI.
39
+ in_agent_run = socket_path is not None
40
+ workspace_flag = getattr(args, "workspace", None)
41
+ if workspace_flag is not None and not workspace_flag.strip():
42
+ print("error: --workspace needs a workspace id", file=sys.stderr)
43
+ return 2
44
+ if in_agent_run:
45
+ if family != "tool":
46
+ print(f"error: {args.command} is not available in an agent run", file=sys.stderr)
47
+ return 2
48
+ if workspace_flag:
49
+ print(
50
+ "error: --workspace is not permitted in an agent run — the run is pinned to $NDI_WORKSPACE_ID.", file=sys.stderr
51
+ )
52
+ return 2
53
+ if not socket_path:
54
+ print(f"error: ${SOCKET_ENV} is set but empty; the agent run has no CLI socket to talk to.", file=sys.stderr)
55
+ return 2
56
+ if family == "standalone":
57
+ try:
58
+ return args.run(args)
59
+ except ConfigError as exc:
60
+ print(f"error: {exc}", file=sys.stderr)
61
+ return 2
62
+ except ValueError as exc:
63
+ print(f"error: {exc}", file=sys.stderr)
64
+ return 2
65
+ try:
66
+ if os.environ.get("NDI_JOB_ID") and not in_agent_run:
67
+ raise ConfigError("The internal NDI CLI execution context is unavailable.")
68
+ if in_agent_run:
69
+ workspace_id = os.environ.get("NDI_WORKSPACE_ID", "")
70
+ transport = LocalTransport(socket_path, args.timeout, os.environ.get(TOKEN_ENV, ""))
71
+ response = args.run(SyncTools(transport), workspace_id, args)
72
+ return _print_tool(args, response)
73
+ settings = resolve_settings(
74
+ workspace_override=workspace_flag,
75
+ require_workspace=getattr(args, "needs_workspace", True),
76
+ )
77
+ timeout = getattr(args, "timeout", DEFAULT_TIMEOUT_SECONDS)
78
+ with NdiClient(api_key=settings.api_key, base_url=settings.base_url, timeout=timeout) as client:
79
+ if family == "tool":
80
+ return _print_tool(args, args.run(client.tools, settings.workspace_id, args))
81
+ return args.run(client, settings.workspace_id, args)
82
+ except ConfigError as exc:
83
+ print(f"error: {exc}", file=sys.stderr)
84
+ return 2
85
+ except NdiStatusError as exc:
86
+ code = f" [{exc.code}]" if exc.code else ""
87
+ print(f"error: {exc.status_code}{code} {exc.message}", file=sys.stderr)
88
+ for line in _validation_error_lines(exc.body.detail if exc.body else None):
89
+ print(f" - {line}", file=sys.stderr)
90
+ return 1
91
+ except NdiError as exc:
92
+ print(f"error: {exc}", file=sys.stderr)
93
+ return 1
94
+ except ValueError as exc:
95
+ print(f"error: {exc}", file=sys.stderr)
96
+ return 2
97
+
98
+
99
+ def _print_tool(args: argparse.Namespace, response) -> int:
100
+ if args.json:
101
+ print(response.model_dump_json(indent=2, exclude_none=True))
102
+ return 0
103
+ print(args.render(response))
104
+ return 0
105
+
106
+
107
+ def _validation_error_lines(detail: object) -> list[str]:
108
+ """Keep field constraints actionable without echoing request inputs or arbitrary detail."""
109
+ errors = detail.get("errors") if isinstance(detail, dict) else None
110
+ if not isinstance(errors, list):
111
+ return []
112
+ lines = []
113
+ for error in errors[:_VALIDATION_ERROR_LIMIT]:
114
+ if not isinstance(error, dict) or not isinstance(message := error.get("msg"), str) or not message.strip():
115
+ continue
116
+ location = error.get("loc")
117
+ if isinstance(location, (list, tuple)) and all(isinstance(part, (str, int)) for part in location):
118
+ if location and location[0] == "body":
119
+ location = location[1:]
120
+ field = ".".join(str(part) for part in location)
121
+ else:
122
+ field = ""
123
+ line = f"{field}: {message}" if field else message
124
+ truncated = len(line) > _VALIDATION_ERROR_CHARS
125
+ clipped = line[: _VALIDATION_ERROR_CHARS - 1] if truncated else line
126
+ clean = " ".join("".join(char if char.isprintable() else " " for char in clipped).split())
127
+ lines.append(clean + ("…" if truncated else ""))
128
+ if lines and len(errors) > _VALIDATION_ERROR_LIMIT:
129
+ lines.append(f"(+{len(errors) - _VALIDATION_ERROR_LIMIT} more validation errors)")
130
+ return lines
131
+
132
+
133
+ def _build_parser() -> argparse.ArgumentParser:
134
+ parser = argparse.ArgumentParser(
135
+ prog="ndi",
136
+ description=(
137
+ "NDI platform CLI. Login, document operations, jobs, and workspace lifecycle talk to /v1; "
138
+ "the six workspace tools also run inside an agent sandbox. Credentials come from "
139
+ "$NDI_API_KEY / $NDI_BASE_URL or ~/.ndi/config.toml."
140
+ ),
141
+ )
142
+ common = argparse.ArgumentParser(add_help=False)
143
+ common.add_argument("--json", action="store_true", help="Print the raw response JSON instead of the text rendering.")
144
+ common.add_argument("--workspace", metavar="ID", default=None, help="Override $NDI_WORKSPACE_ID for this call.")
145
+ common.add_argument(
146
+ "--timeout",
147
+ type=float,
148
+ default=DEFAULT_TIMEOUT_SECONDS,
149
+ metavar="SECONDS",
150
+ help=f"Per-request HTTP timeout (default {DEFAULT_TIMEOUT_SECONDS:.0f}s; ask-file and job waits can take minutes).",
151
+ )
152
+ sub = parser.add_subparsers(dest="command")
153
+ _login.add_parsers(sub)
154
+ _tools.add_parsers(sub, common)
155
+ _docops.add_parsers(sub, common)
156
+ _jobs.add_parsers(sub, common)
157
+ _workspace.add_parsers(sub, common)
158
+ return parser
159
+
160
+
161
+ def _parse_pages(spec: str | None) -> list[int] | None:
162
+ return parse_pages(spec)
163
+
164
+
165
+ if __name__ == "__main__":
166
+ raise SystemExit(main())
@@ -0,0 +1,94 @@
1
+ """Resolve the API key, base URL, and workspace the CLI talks to.
2
+
3
+ The agent-facing contract is that credentials never travel on the command line:
4
+
5
+ - ``$NDI_API_KEY`` — else ``api_key`` in ``~/.ndi/config.toml`` (the file
6
+ ``ndi login`` / ``ndi-mcp login`` writes; ``$NDI_CONFIG_PATH`` overrides its location).
7
+ - ``$NDI_BASE_URL`` — else ``base_url`` in the same file, else the SDK default.
8
+ - ``$NDI_WORKSPACE_ID`` — else ``workspace_id`` in the same file (``--workspace``
9
+ overrides either for one call). A missing workspace is a startup failure
10
+ with a hint, not a 404 on the first call.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import tomllib
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+
20
+ from ndi_sdk.client import API_KEY_ENV, BASE_URL_ENV
21
+
22
+ WORKSPACE_ENV = "NDI_WORKSPACE_ID"
23
+ CONFIG_PATH_ENV = "NDI_CONFIG_PATH"
24
+ DEFAULT_CONFIG_PATH = Path.home() / ".ndi" / "config.toml"
25
+
26
+ _CONFIG_KEYS = ("api_key", "base_url", "workspace_id")
27
+
28
+
29
+ class ConfigError(ValueError):
30
+ """A required setting could not be resolved."""
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class Settings:
35
+ api_key: str
36
+ workspace_id: str
37
+ base_url: str | None = None
38
+
39
+
40
+ def config_path() -> Path:
41
+ override = os.environ.get(CONFIG_PATH_ENV)
42
+ return Path(override) if override else DEFAULT_CONFIG_PATH
43
+
44
+
45
+ def resolve_settings(*, workspace_override: str | None = None, require_workspace: bool = True) -> Settings:
46
+ """Environment first, then the config file.
47
+
48
+ Raises:
49
+ ConfigError: When the API key or a required workspace id is missing.
50
+ """
51
+ api_key = os.environ.get(API_KEY_ENV)
52
+ base_url = os.environ.get(BASE_URL_ENV)
53
+ workspace_id = workspace_override or os.environ.get(WORKSPACE_ENV)
54
+ # A broken config file only matters when a required value has to come from
55
+ # it — then the error names the real cause instead of "no API key".
56
+ file_error: ConfigError | None = None
57
+ if not api_key or not base_url or not workspace_id:
58
+ try:
59
+ file_values = _read_config(config_path())
60
+ except ConfigError as exc:
61
+ file_error = exc
62
+ file_values = {}
63
+ api_key = api_key or file_values.get("api_key")
64
+ base_url = base_url or file_values.get("base_url")
65
+ workspace_id = workspace_id or file_values.get("workspace_id")
66
+ if not api_key:
67
+ raise file_error or ConfigError(f"no API key: set ${API_KEY_ENV} or run `ndi login` (or api_key in {config_path()})")
68
+ if require_workspace and not workspace_id:
69
+ raise file_error or ConfigError(f"no workspace: set ${WORKSPACE_ENV} (or workspace_id in {config_path()})")
70
+ return Settings(api_key=api_key, workspace_id=workspace_id or "", base_url=base_url)
71
+
72
+
73
+ def read_config_values(path: Path) -> dict[str, str]:
74
+ """The config file's own settings, or {} when it is missing or unreadable."""
75
+ try:
76
+ return _read_config(path)
77
+ except ConfigError:
78
+ return {}
79
+
80
+
81
+ def _read_config(path: Path) -> dict[str, str]:
82
+ if not path.is_file():
83
+ return {}
84
+ try:
85
+ with path.open("rb") as handle:
86
+ parsed = tomllib.load(handle)
87
+ except (tomllib.TOMLDecodeError, UnicodeDecodeError, OSError) as exc:
88
+ raise ConfigError(f"config file {path} is unreadable: {exc}") from exc
89
+ values: dict[str, str] = {}
90
+ for key in _CONFIG_KEYS:
91
+ value = parsed.get(key)
92
+ if isinstance(value, str) and value:
93
+ values[key] = value
94
+ return values