ndi-cli 0.4.0__py3-none-any.whl

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/__init__.py ADDED
@@ -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"
ndi_cli/_cli.py ADDED
@@ -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())
ndi_cli/_config.py ADDED
@@ -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