sinapsis_cli 1.0.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.
- sinapsis_cli/__init__.py +13 -0
- sinapsis_cli/commands/__init__.py +0 -0
- sinapsis_cli/commands/cloud/__init__.py +0 -0
- sinapsis_cli/commands/cloud/_agent_selection.py +112 -0
- sinapsis_cli/commands/cloud/_secrets_render.py +15 -0
- sinapsis_cli/commands/cloud/_webhook_render.py +19 -0
- sinapsis_cli/commands/cloud/agents.py +137 -0
- sinapsis_cli/commands/cloud/api_keys.py +155 -0
- sinapsis_cli/commands/cloud/files.py +135 -0
- sinapsis_cli/commands/cloud/jobs.py +532 -0
- sinapsis_cli/commands/cloud/packages.py +164 -0
- sinapsis_cli/commands/cloud/schedules.py +392 -0
- sinapsis_cli/commands/cloud/secrets.py +96 -0
- sinapsis_cli/commands/cloud/templates.py +95 -0
- sinapsis_cli/commands/cloud/webhooks.py +156 -0
- sinapsis_cli/commands/common/__init__.py +0 -0
- sinapsis_cli/commands/common/auth.py +219 -0
- sinapsis_cli/commands/common/profiles.py +156 -0
- sinapsis_cli/commands/common/telemetry.py +150 -0
- sinapsis_cli/commands/local_api/__init__.py +0 -0
- sinapsis_cli/commands/local_api/jobs.py +284 -0
- sinapsis_cli/commands/local_venv/__init__.py +0 -0
- sinapsis_cli/commands/local_venv/_templates_render.py +56 -0
- sinapsis_cli/commands/local_venv/jobs.py +76 -0
- sinapsis_cli/commands/local_venv/templates.py +47 -0
- sinapsis_cli/composition.py +215 -0
- sinapsis_cli/config.py +446 -0
- sinapsis_cli/execution.py +77 -0
- sinapsis_cli/main.py +185 -0
- sinapsis_cli/main_multi.py +152 -0
- sinapsis_cli/shared/__init__.py +3 -0
- sinapsis_cli/shared/jobs.py +134 -0
- sinapsis_cli/shared/terminal.py +8 -0
- sinapsis_cli/shared/writer.py +427 -0
- sinapsis_cli/state.py +310 -0
- sinapsis_cli/telemetry/__init__.py +7 -0
- sinapsis_cli/telemetry/collector.py +84 -0
- sinapsis_cli/telemetry/core.py +331 -0
- sinapsis_cli/telemetry/scheduler.py +234 -0
- sinapsis_cli/telemetry/transport.py +150 -0
- sinapsis_cli-1.0.0.dist-info/METADATA +386 -0
- sinapsis_cli-1.0.0.dist-info/RECORD +46 -0
- sinapsis_cli-1.0.0.dist-info/WHEEL +4 -0
- sinapsis_cli-1.0.0.dist-info/entry_points.txt +5 -0
- sinapsis_cli-1.0.0.dist-info/licenses/LICENSE-APACHE +202 -0
- sinapsis_cli-1.0.0.dist-info/licenses/LICENSE-MIT +21 -0
sinapsis_cli/config.py
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
"""CLI configuration and execution profiles."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from sinapsis_sdk.cloud_api._config import ConfigStore
|
|
10
|
+
|
|
11
|
+
DEFAULT_CLOUD_URL = "https://api.sinapsis.tech"
|
|
12
|
+
DEFAULT_LOCAL_URL = "http://localhost:8000"
|
|
13
|
+
DEFAULT_VENV = ".venv"
|
|
14
|
+
DEFAULT_PROFILE = "local"
|
|
15
|
+
|
|
16
|
+
PROFILE_ENV_VAR = "SINAPSIS_PROFILE"
|
|
17
|
+
LEGACY_EXECUTION_ENV_VARS = ("SINAPSIS_EXECUTION_MODE", "SINAPSIS_EXECUTE_MODE")
|
|
18
|
+
|
|
19
|
+
_PROFILE_NAME_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ExecutionBackend(str, Enum):
|
|
23
|
+
"""Execution backends supported by the CLI."""
|
|
24
|
+
|
|
25
|
+
LOCAL_VENV = "local-venv"
|
|
26
|
+
LOCAL_API = "local-api"
|
|
27
|
+
CLOUD = "cloud"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
_BACKEND_ALIASES = {
|
|
31
|
+
"local": ExecutionBackend.LOCAL_VENV,
|
|
32
|
+
"local-venv": ExecutionBackend.LOCAL_VENV,
|
|
33
|
+
"local_api": ExecutionBackend.LOCAL_API,
|
|
34
|
+
"local-api": ExecutionBackend.LOCAL_API,
|
|
35
|
+
"cloud": ExecutionBackend.CLOUD,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
_DEFAULT_PROFILE_FOR_BACKEND = {
|
|
39
|
+
ExecutionBackend.LOCAL_VENV: "local",
|
|
40
|
+
ExecutionBackend.LOCAL_API: "local-api",
|
|
41
|
+
ExecutionBackend.CLOUD: "cloud",
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class Profile:
|
|
47
|
+
"""Configuration for a Sinapsis execution profile.
|
|
48
|
+
|
|
49
|
+
A profile is a named execution environment. ``backend`` determines the
|
|
50
|
+
base command composition, while ``command_sets`` can add optional command
|
|
51
|
+
providers without changing other profiles.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
name: str
|
|
55
|
+
backend: ExecutionBackend
|
|
56
|
+
api_url: str | None = None
|
|
57
|
+
venv: str | None = None
|
|
58
|
+
authenticated: bool = False
|
|
59
|
+
command_sets: tuple[str, ...] = ()
|
|
60
|
+
|
|
61
|
+
def __post_init__(self) -> None:
|
|
62
|
+
normalized_name = validate_profile_name(self.name)
|
|
63
|
+
object.__setattr__(self, "name", normalized_name)
|
|
64
|
+
|
|
65
|
+
if not isinstance(self.backend, ExecutionBackend):
|
|
66
|
+
object.__setattr__(self, "backend", validate_backend(self.backend))
|
|
67
|
+
|
|
68
|
+
if self.api_url is not None:
|
|
69
|
+
normalized_url = self.api_url.strip().rstrip("/")
|
|
70
|
+
object.__setattr__(self, "api_url", normalized_url or None)
|
|
71
|
+
|
|
72
|
+
if self.venv is not None and not self.venv.strip():
|
|
73
|
+
object.__setattr__(self, "venv", None)
|
|
74
|
+
|
|
75
|
+
normalized_command_sets = tuple(
|
|
76
|
+
dict.fromkeys(command_set.strip() for command_set in self.command_sets if command_set.strip())
|
|
77
|
+
)
|
|
78
|
+
object.__setattr__(self, "command_sets", normalized_command_sets)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class CLIConfig:
|
|
83
|
+
"""Sinapsis CLI configuration."""
|
|
84
|
+
|
|
85
|
+
default_profile: str = DEFAULT_PROFILE
|
|
86
|
+
profiles: dict[str, Profile] | None = None
|
|
87
|
+
|
|
88
|
+
def __post_init__(self) -> None:
|
|
89
|
+
if self.profiles is None:
|
|
90
|
+
self.profiles = _default_profiles()
|
|
91
|
+
|
|
92
|
+
if self.default_profile not in self.profiles:
|
|
93
|
+
self.default_profile = DEFAULT_PROFILE
|
|
94
|
+
|
|
95
|
+
if self.default_profile not in self.profiles:
|
|
96
|
+
self.default_profile = next(iter(self.profiles))
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def profile(self) -> Profile:
|
|
100
|
+
"""Return the configured default profile."""
|
|
101
|
+
return self.get_profile(self.default_profile)
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def execute_mode(self) -> str:
|
|
105
|
+
"""Return the legacy execution-mode value for compatibility."""
|
|
106
|
+
return legacy_mode_for_backend(self.profile.backend)
|
|
107
|
+
|
|
108
|
+
@execute_mode.setter
|
|
109
|
+
def execute_mode(self, mode: str) -> None:
|
|
110
|
+
"""Set the default profile using a legacy execution-mode value."""
|
|
111
|
+
backend = validate_backend(mode)
|
|
112
|
+
self.default_profile = find_profile_for_backend(self, backend).name
|
|
113
|
+
|
|
114
|
+
def get_profile(self, name: str) -> Profile:
|
|
115
|
+
"""Return a profile by name.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
name: Profile name.
|
|
119
|
+
|
|
120
|
+
Raises:
|
|
121
|
+
ValueError: If the requested profile does not exist.
|
|
122
|
+
"""
|
|
123
|
+
assert self.profiles is not None
|
|
124
|
+
|
|
125
|
+
try:
|
|
126
|
+
return self.profiles[name]
|
|
127
|
+
except KeyError as exception:
|
|
128
|
+
available = ", ".join(sorted(self.profiles))
|
|
129
|
+
raise ValueError(f"Unknown profile {name!r}. Available profiles: {available}") from exception
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def validate_profile_name(name: str) -> str:
|
|
133
|
+
"""Validate and normalize a profile name."""
|
|
134
|
+
normalized = name.strip()
|
|
135
|
+
|
|
136
|
+
if not normalized or not _PROFILE_NAME_PATTERN.fullmatch(normalized):
|
|
137
|
+
raise ValueError(
|
|
138
|
+
"Profile names must start with a letter or number and contain only letters, numbers, '.', '_', or '-'."
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
return normalized
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def validate_backend(value: str | ExecutionBackend) -> ExecutionBackend:
|
|
145
|
+
"""Validate and normalize an execution backend."""
|
|
146
|
+
if isinstance(value, ExecutionBackend):
|
|
147
|
+
return value
|
|
148
|
+
|
|
149
|
+
normalized = value.strip().lower()
|
|
150
|
+
|
|
151
|
+
try:
|
|
152
|
+
return _BACKEND_ALIASES[normalized]
|
|
153
|
+
except KeyError as exception:
|
|
154
|
+
available = ", ".join(backend.value for backend in ExecutionBackend)
|
|
155
|
+
raise ValueError(f"Unknown execution backend {value!r}. Available backends: {available}") from exception
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def validate_execute_mode(mode: str) -> str:
|
|
159
|
+
"""Validate a legacy execution mode and return its canonical value."""
|
|
160
|
+
return legacy_mode_for_backend(validate_backend(mode))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def legacy_mode_for_backend(backend: ExecutionBackend) -> str:
|
|
164
|
+
"""Return the legacy execution-mode name for a backend."""
|
|
165
|
+
if backend is ExecutionBackend.LOCAL_VENV:
|
|
166
|
+
return "local"
|
|
167
|
+
return backend.value
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _default_profiles() -> dict[str, Profile]:
|
|
171
|
+
"""Return the built-in execution profiles."""
|
|
172
|
+
return {
|
|
173
|
+
"local": Profile(
|
|
174
|
+
name="local",
|
|
175
|
+
backend=ExecutionBackend.LOCAL_VENV,
|
|
176
|
+
venv=DEFAULT_VENV,
|
|
177
|
+
authenticated=False,
|
|
178
|
+
),
|
|
179
|
+
"cloud": Profile(
|
|
180
|
+
name="cloud",
|
|
181
|
+
backend=ExecutionBackend.CLOUD,
|
|
182
|
+
api_url=DEFAULT_CLOUD_URL,
|
|
183
|
+
authenticated=True,
|
|
184
|
+
),
|
|
185
|
+
"local-api": Profile(
|
|
186
|
+
name="local-api",
|
|
187
|
+
backend=ExecutionBackend.LOCAL_API,
|
|
188
|
+
api_url=DEFAULT_LOCAL_URL,
|
|
189
|
+
authenticated=False,
|
|
190
|
+
),
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def load_config() -> CLIConfig:
|
|
195
|
+
"""Load CLI configuration from the shared SDK configuration file.
|
|
196
|
+
|
|
197
|
+
The loader accepts both the profile-aware schema and the previous
|
|
198
|
+
``execute_mode``/``base_url`` schema. Saving the configuration writes the
|
|
199
|
+
new schema while preserving unrelated SDK settings.
|
|
200
|
+
"""
|
|
201
|
+
store = ConfigStore()
|
|
202
|
+
data = store.load_raw()
|
|
203
|
+
if not isinstance(data, dict):
|
|
204
|
+
data = {}
|
|
205
|
+
|
|
206
|
+
profiles = _load_profiles(data.get("profiles"))
|
|
207
|
+
defaults = _default_profiles()
|
|
208
|
+
defaults.update(profiles)
|
|
209
|
+
|
|
210
|
+
default_profile = data.get("default_profile")
|
|
211
|
+
|
|
212
|
+
if not isinstance(default_profile, str) or default_profile not in defaults:
|
|
213
|
+
default_profile = _legacy_default_profile(data, defaults)
|
|
214
|
+
|
|
215
|
+
return CLIConfig(default_profile=default_profile, profiles=defaults)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def save_config(config: CLIConfig) -> None:
|
|
219
|
+
"""Persist CLI configuration while preserving SDK configuration."""
|
|
220
|
+
store = ConfigStore()
|
|
221
|
+
data = store.load_raw()
|
|
222
|
+
if not isinstance(data, dict):
|
|
223
|
+
data = {}
|
|
224
|
+
|
|
225
|
+
assert config.profiles is not None
|
|
226
|
+
|
|
227
|
+
if config.default_profile not in config.profiles:
|
|
228
|
+
raise ValueError(f"Default profile {config.default_profile!r} does not exist.")
|
|
229
|
+
|
|
230
|
+
data["default_profile"] = config.default_profile
|
|
231
|
+
|
|
232
|
+
# Remove fields from the previous CLI profile model when rewriting.
|
|
233
|
+
data.pop("active_profile", None)
|
|
234
|
+
data.pop("execute_mode", None)
|
|
235
|
+
|
|
236
|
+
profiles: dict[str, dict[str, Any]] = {}
|
|
237
|
+
|
|
238
|
+
for name, profile in config.profiles.items():
|
|
239
|
+
profile_data: dict[str, Any] = {
|
|
240
|
+
"backend": profile.backend.value,
|
|
241
|
+
"authenticated": profile.authenticated,
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if profile.api_url is not None:
|
|
245
|
+
profile_data["api_url"] = profile.api_url.rstrip("/")
|
|
246
|
+
|
|
247
|
+
if profile.venv is not None:
|
|
248
|
+
profile_data["venv"] = profile.venv
|
|
249
|
+
|
|
250
|
+
if profile.command_sets:
|
|
251
|
+
profile_data["command_sets"] = list(profile.command_sets)
|
|
252
|
+
|
|
253
|
+
profiles[name] = profile_data
|
|
254
|
+
|
|
255
|
+
data["profiles"] = profiles
|
|
256
|
+
store.save_raw(data)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def get_execution_profile(profile_name: str | None = None, *, config: CLIConfig | None = None) -> Profile:
|
|
260
|
+
"""Resolve the effective execution profile.
|
|
261
|
+
|
|
262
|
+
Resolution order is: explicit profile, ``SINAPSIS_PROFILE``, legacy
|
|
263
|
+
execution-mode environment variables, then the configured default profile.
|
|
264
|
+
"""
|
|
265
|
+
config = config or load_config()
|
|
266
|
+
|
|
267
|
+
if profile_name is not None:
|
|
268
|
+
return config.get_profile(profile_name)
|
|
269
|
+
|
|
270
|
+
environment_profile = os.getenv(PROFILE_ENV_VAR)
|
|
271
|
+
if environment_profile and environment_profile.strip():
|
|
272
|
+
return config.get_profile(environment_profile.strip())
|
|
273
|
+
|
|
274
|
+
for variable in LEGACY_EXECUTION_ENV_VARS:
|
|
275
|
+
value = os.getenv(variable)
|
|
276
|
+
if not value or not value.strip():
|
|
277
|
+
continue
|
|
278
|
+
|
|
279
|
+
candidate = value.strip()
|
|
280
|
+
if config.profiles and candidate in config.profiles:
|
|
281
|
+
return config.get_profile(candidate)
|
|
282
|
+
|
|
283
|
+
return find_profile_for_backend(config, validate_backend(candidate))
|
|
284
|
+
|
|
285
|
+
return config.profile
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def get_execution_mode() -> str:
|
|
289
|
+
"""Return the effective legacy execution-mode value."""
|
|
290
|
+
return legacy_mode_for_backend(get_execution_profile().backend)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def find_profile_for_backend(config: CLIConfig, backend: ExecutionBackend) -> Profile:
|
|
294
|
+
"""Find the preferred profile for a backend."""
|
|
295
|
+
assert config.profiles is not None
|
|
296
|
+
|
|
297
|
+
canonical_name = _DEFAULT_PROFILE_FOR_BACKEND[backend]
|
|
298
|
+
canonical = config.profiles.get(canonical_name)
|
|
299
|
+
if canonical is not None and canonical.backend is backend:
|
|
300
|
+
return canonical
|
|
301
|
+
|
|
302
|
+
matches = [profile for profile in config.profiles.values() if profile.backend is backend]
|
|
303
|
+
|
|
304
|
+
if len(matches) == 1:
|
|
305
|
+
return matches[0]
|
|
306
|
+
|
|
307
|
+
if not matches:
|
|
308
|
+
raise ValueError(f"No configured profile uses backend {backend.value!r}.")
|
|
309
|
+
|
|
310
|
+
names = ", ".join(sorted(profile.name for profile in matches))
|
|
311
|
+
raise ValueError(
|
|
312
|
+
f"Multiple profiles use backend {backend.value!r}: {names}. "
|
|
313
|
+
f"Select one with {PROFILE_ENV_VAR} or an explicit profile name."
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def set_default_profile(name: str) -> CLIConfig:
|
|
318
|
+
"""Set and persist the default profile."""
|
|
319
|
+
config = load_config()
|
|
320
|
+
config.get_profile(name)
|
|
321
|
+
config.default_profile = name
|
|
322
|
+
save_config(config)
|
|
323
|
+
return config
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def set_execute_mode(mode: str) -> CLIConfig:
|
|
327
|
+
"""Set the default profile from a legacy execution-mode value."""
|
|
328
|
+
config = load_config()
|
|
329
|
+
profile = find_profile_for_backend(config, validate_backend(mode))
|
|
330
|
+
config.default_profile = profile.name
|
|
331
|
+
save_config(config)
|
|
332
|
+
return config
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def set_profile(profile: Profile) -> CLIConfig:
|
|
336
|
+
"""Create or replace an execution profile."""
|
|
337
|
+
validate_profile_name(profile.name)
|
|
338
|
+
config = load_config()
|
|
339
|
+
assert config.profiles is not None
|
|
340
|
+
config.profiles[profile.name] = profile
|
|
341
|
+
save_config(config)
|
|
342
|
+
return config
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def delete_profile(name: str) -> CLIConfig:
|
|
346
|
+
"""Delete an execution profile.
|
|
347
|
+
|
|
348
|
+
Raises:
|
|
349
|
+
ValueError: If the profile does not exist or is the default profile.
|
|
350
|
+
"""
|
|
351
|
+
config = load_config()
|
|
352
|
+
assert config.profiles is not None
|
|
353
|
+
|
|
354
|
+
if name == config.default_profile:
|
|
355
|
+
raise ValueError(f"Cannot delete the default profile {name!r}. Choose another default profile first.")
|
|
356
|
+
|
|
357
|
+
if name not in config.profiles:
|
|
358
|
+
raise ValueError(f"Unknown profile {name!r}.")
|
|
359
|
+
|
|
360
|
+
del config.profiles[name]
|
|
361
|
+
save_config(config)
|
|
362
|
+
return config
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _legacy_default_profile(data: dict[str, Any], profiles: dict[str, Profile]) -> str:
|
|
366
|
+
"""Resolve the default profile from the previous configuration schema."""
|
|
367
|
+
legacy = data.get("active_profile") or data.get("execute_mode")
|
|
368
|
+
|
|
369
|
+
if isinstance(legacy, str):
|
|
370
|
+
if legacy in profiles:
|
|
371
|
+
return legacy
|
|
372
|
+
|
|
373
|
+
try:
|
|
374
|
+
backend = validate_backend(legacy)
|
|
375
|
+
except ValueError:
|
|
376
|
+
backend = ExecutionBackend.LOCAL_VENV
|
|
377
|
+
|
|
378
|
+
canonical_name = _DEFAULT_PROFILE_FOR_BACKEND[backend]
|
|
379
|
+
if canonical_name in profiles:
|
|
380
|
+
return canonical_name
|
|
381
|
+
|
|
382
|
+
if DEFAULT_PROFILE in profiles:
|
|
383
|
+
return DEFAULT_PROFILE
|
|
384
|
+
|
|
385
|
+
return next(iter(profiles))
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _load_profiles(raw_profiles: object) -> dict[str, Profile]:
|
|
389
|
+
"""Load profiles from raw configuration data."""
|
|
390
|
+
profiles: dict[str, Profile] = {}
|
|
391
|
+
|
|
392
|
+
if not isinstance(raw_profiles, dict):
|
|
393
|
+
return profiles
|
|
394
|
+
|
|
395
|
+
for name, values in raw_profiles.items():
|
|
396
|
+
if not isinstance(name, str) or not isinstance(values, dict):
|
|
397
|
+
continue
|
|
398
|
+
|
|
399
|
+
try:
|
|
400
|
+
validate_profile_name(name)
|
|
401
|
+
except ValueError:
|
|
402
|
+
continue
|
|
403
|
+
|
|
404
|
+
raw_backend = values.get("backend") or values.get("execution_mode")
|
|
405
|
+
|
|
406
|
+
if raw_backend is None:
|
|
407
|
+
raw_backend = name if name in _BACKEND_ALIASES else None
|
|
408
|
+
|
|
409
|
+
if not isinstance(raw_backend, str):
|
|
410
|
+
continue
|
|
411
|
+
|
|
412
|
+
try:
|
|
413
|
+
backend = validate_backend(raw_backend)
|
|
414
|
+
except ValueError:
|
|
415
|
+
continue
|
|
416
|
+
|
|
417
|
+
api_url = values.get("api_url", values.get("base_url"))
|
|
418
|
+
if not isinstance(api_url, str) or not api_url.strip():
|
|
419
|
+
api_url = None
|
|
420
|
+
else:
|
|
421
|
+
api_url = api_url.rstrip("/")
|
|
422
|
+
|
|
423
|
+
venv = values.get("venv")
|
|
424
|
+
if not isinstance(venv, str) or not venv.strip():
|
|
425
|
+
venv = None
|
|
426
|
+
|
|
427
|
+
authenticated = values.get("authenticated", backend is ExecutionBackend.CLOUD)
|
|
428
|
+
|
|
429
|
+
raw_command_sets = values.get("command_sets", ())
|
|
430
|
+
command_sets: tuple[str, ...]
|
|
431
|
+
|
|
432
|
+
if isinstance(raw_command_sets, (list, tuple)):
|
|
433
|
+
command_sets = tuple(item for item in raw_command_sets if isinstance(item, str) and item.strip())
|
|
434
|
+
else:
|
|
435
|
+
command_sets = ()
|
|
436
|
+
|
|
437
|
+
profiles[name] = Profile(
|
|
438
|
+
name=name,
|
|
439
|
+
backend=backend,
|
|
440
|
+
api_url=api_url,
|
|
441
|
+
venv=venv,
|
|
442
|
+
authenticated=bool(authenticated),
|
|
443
|
+
command_sets=command_sets,
|
|
444
|
+
)
|
|
445
|
+
|
|
446
|
+
return profiles
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Execution context shared by profile-aware CLI commands."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
import typer
|
|
6
|
+
from sinapsis_sdk.cloud_api._config import ConfigStore
|
|
7
|
+
from sinapsis_sdk.cloud_api._credentials import create_credential_store
|
|
8
|
+
from sinapsis_sdk.cloud_api.client import CloudSinapsisAPIClient
|
|
9
|
+
from sinapsis_sdk.cloud_api.cloud_config import CloudAPIConfig
|
|
10
|
+
from sinapsis_sdk.common.base_config import BaseAPIConfig
|
|
11
|
+
from sinapsis_sdk.local_api.client import SinapsisAPIClient
|
|
12
|
+
|
|
13
|
+
from sinapsis_cli.config import ExecutionBackend, Profile
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class ExecutionContext:
|
|
18
|
+
"""Resolved execution environment for one CLI invocation."""
|
|
19
|
+
|
|
20
|
+
profile: Profile
|
|
21
|
+
explicit_profile: bool = False
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def profile_name(self) -> str:
|
|
25
|
+
"""Return the selected profile name."""
|
|
26
|
+
return self.profile.name
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def api_url(self) -> str:
|
|
30
|
+
"""Return the profile API URL.
|
|
31
|
+
|
|
32
|
+
Raises:
|
|
33
|
+
ValueError: If the selected profile is not API-backed.
|
|
34
|
+
"""
|
|
35
|
+
if self.profile.api_url is None:
|
|
36
|
+
raise ValueError(f"Profile {self.profile.name!r} does not define an API URL.")
|
|
37
|
+
|
|
38
|
+
return self.profile.api_url
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def get_execution_context(context: typer.Context) -> ExecutionContext:
|
|
42
|
+
"""Return the execution context attached to a Typer command."""
|
|
43
|
+
if isinstance(context.obj, ExecutionContext):
|
|
44
|
+
return context.obj
|
|
45
|
+
|
|
46
|
+
raise RuntimeError("Sinapsis execution context was not initialized.")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def build_api_config(execution: ExecutionContext, *, api_url: str | None = None) -> CloudAPIConfig:
|
|
50
|
+
"""Build an SDK API configuration for the selected profile.
|
|
51
|
+
|
|
52
|
+
The profile owns the API endpoint; timeout comes from ``ConfigStore``.
|
|
53
|
+
Supabase configuration remains readable for legacy settings only.
|
|
54
|
+
"""
|
|
55
|
+
current = ConfigStore().load()
|
|
56
|
+
target_url = (api_url or execution.api_url).rstrip("/")
|
|
57
|
+
|
|
58
|
+
return CloudAPIConfig(api_url=target_url, timeout=current.timeout)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def create_api_client(
|
|
62
|
+
execution: ExecutionContext, *, api_url: str | None = None
|
|
63
|
+
) -> CloudSinapsisAPIClient | SinapsisAPIClient:
|
|
64
|
+
"""Create the appropriate SDK client for the selected profile."""
|
|
65
|
+
if execution.profile.backend == ExecutionBackend.LOCAL_API:
|
|
66
|
+
return SinapsisAPIClient(config=BaseAPIConfig(api_url=(api_url or execution.api_url).rstrip("/")))
|
|
67
|
+
|
|
68
|
+
if execution.profile.backend == ExecutionBackend.CLOUD:
|
|
69
|
+
return CloudSinapsisAPIClient(
|
|
70
|
+
config=build_api_config(execution, api_url=api_url),
|
|
71
|
+
credential_store=create_credential_store(),
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
raise ValueError(f"Unsupported profile type: {execution.profile.type!r}")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
__all__ = ["ExecutionContext", "build_api_config", "create_api_client", "get_execution_context"]
|
sinapsis_cli/main.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Main entry point for the profile-aware Sinapsis CLI."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
import time
|
|
5
|
+
from typing import Annotated, Any
|
|
6
|
+
|
|
7
|
+
import rich.box
|
|
8
|
+
import typer
|
|
9
|
+
import typer.rich_utils
|
|
10
|
+
from rich.panel import Panel
|
|
11
|
+
|
|
12
|
+
from sinapsis_cli.composition import compose_profile_commands, register_global_commands
|
|
13
|
+
from sinapsis_cli.config import CLIConfig, get_execution_profile, load_config
|
|
14
|
+
from sinapsis_cli.execution import ExecutionContext
|
|
15
|
+
from sinapsis_cli.state import migrate_legacy_job_state
|
|
16
|
+
|
|
17
|
+
state = {"verbose": False}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class BorderlessPanel(Panel):
|
|
21
|
+
"""Rich panel that preserves its title without visible borders."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, renderable: Any, *args: Any, **kwargs: Any) -> None:
|
|
24
|
+
super().__init__(renderable, *args, **kwargs)
|
|
25
|
+
self.box = rich.box.Box(" \n \n \n \n \n \n \n \n")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
typer.rich_utils.Panel = BorderlessPanel
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
_PROFILE_PREFIX_FLAGS = {"--verbose", "-v"}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def create_app(execution: ExecutionContext) -> typer.Typer:
|
|
35
|
+
"""Create the CLI tree for one resolved execution profile."""
|
|
36
|
+
app = typer.Typer(
|
|
37
|
+
name="sinapsis",
|
|
38
|
+
help=(
|
|
39
|
+
"[bold #00F5FF on #1E1B4B] ⚡ SINAPSIS CLI "
|
|
40
|
+
"[/bold #00F5FF on #1E1B4B]\n\n"
|
|
41
|
+
f"[bold #FF79C6]Profile: {execution.profile_name}. "
|
|
42
|
+
f"({execution.profile.backend.value})[/bold #FF79C6]"
|
|
43
|
+
f" Use `sinapsis profiles loca|cloud|local-api' to change."
|
|
44
|
+
f"\n\talternatively use `sinapsis local|cloud|local-api' to run with a different profile`"
|
|
45
|
+
"\n\tNOTE: commands available depend on profile being used. "
|
|
46
|
+
),
|
|
47
|
+
no_args_is_help=True,
|
|
48
|
+
rich_markup_mode="rich",
|
|
49
|
+
pretty_exceptions_show_locals=False,
|
|
50
|
+
subcommand_metavar="[PROFILE] COMMAND [ARGS]...",
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
@app.callback()
|
|
54
|
+
def main_callback(
|
|
55
|
+
ctx: typer.Context,
|
|
56
|
+
verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Show full traceback on errors.")] = False,
|
|
57
|
+
) -> None:
|
|
58
|
+
"""Run commands using the resolved execution profile."""
|
|
59
|
+
ctx.obj = execution
|
|
60
|
+
state["verbose"] = verbose
|
|
61
|
+
|
|
62
|
+
register_global_commands(app, execution)
|
|
63
|
+
compose_profile_commands(app, execution)
|
|
64
|
+
return app
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def resolve_invocation(arguments: list[str], *, config: CLIConfig | None = None) -> tuple[ExecutionContext, list[str]]:
|
|
68
|
+
"""Resolve an optional positional profile and return remaining CLI args."""
|
|
69
|
+
config = config or load_config()
|
|
70
|
+
migrate_legacy_job_state(config)
|
|
71
|
+
remaining = list(arguments)
|
|
72
|
+
|
|
73
|
+
candidate_index = _profile_candidate_index(remaining)
|
|
74
|
+
explicit_profile = False
|
|
75
|
+
profile_name: str | None = None
|
|
76
|
+
|
|
77
|
+
if candidate_index is not None:
|
|
78
|
+
candidate = remaining[candidate_index]
|
|
79
|
+
if config.profiles is not None and candidate in config.profiles:
|
|
80
|
+
profile_name = candidate
|
|
81
|
+
del remaining[candidate_index]
|
|
82
|
+
explicit_profile = True
|
|
83
|
+
|
|
84
|
+
profile = get_execution_profile(profile_name, config=config)
|
|
85
|
+
|
|
86
|
+
return (ExecutionContext(profile=profile, explicit_profile=explicit_profile), remaining)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _profile_candidate_index(arguments: list[str]) -> int | None:
|
|
90
|
+
"""Return the index where an optional profile token may appear."""
|
|
91
|
+
index = 0
|
|
92
|
+
|
|
93
|
+
while index < len(arguments) and arguments[index] in _PROFILE_PREFIX_FLAGS:
|
|
94
|
+
index += 1
|
|
95
|
+
|
|
96
|
+
if index >= len(arguments):
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
if arguments[index].startswith("-"):
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
return index
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def run(arguments: list[str] | None = None, *, prog_name: str = "sinx") -> None:
|
|
106
|
+
"""Resolve a profile, run the command, and record only safe opt-in metadata."""
|
|
107
|
+
raw_arguments = list(sys.argv[1:] if arguments is None else arguments)
|
|
108
|
+
started = time.monotonic()
|
|
109
|
+
remaining = raw_arguments
|
|
110
|
+
backend = "other"
|
|
111
|
+
outcome = "error"
|
|
112
|
+
try:
|
|
113
|
+
execution, remaining = resolve_invocation(raw_arguments)
|
|
114
|
+
backend = execution.profile.backend.value
|
|
115
|
+
selected_app = create_app(execution)
|
|
116
|
+
selected_app(args=remaining, prog_name=prog_name)
|
|
117
|
+
outcome = "success"
|
|
118
|
+
except SystemExit as exception:
|
|
119
|
+
outcome = "success" if exception.code in (0, None) else "error"
|
|
120
|
+
raise
|
|
121
|
+
except Exception as exception:
|
|
122
|
+
if state.get("verbose"):
|
|
123
|
+
raise
|
|
124
|
+
typer.secho(f"Error: {exception}", fg=typer.colors.RED, err=True)
|
|
125
|
+
raise SystemExit(1) from exception
|
|
126
|
+
finally:
|
|
127
|
+
# A short-lived CLI must never upload telemetry, scan site-packages,
|
|
128
|
+
# or write SQLite from the execution thread. A detached *local*
|
|
129
|
+
# collector receives only allowlisted metadata (never raw arguments).
|
|
130
|
+
try:
|
|
131
|
+
from sinapsis_cli.telemetry.collector import spawn_collector
|
|
132
|
+
|
|
133
|
+
spawn_collector(remaining, backend=backend, outcome=outcome,
|
|
134
|
+
duration_ms=int((time.monotonic()-started)*1000),
|
|
135
|
+
venv=execution.profile.venv if 'execution' in locals() else None)
|
|
136
|
+
except Exception: # noqa: BLE001
|
|
137
|
+
pass # Optional telemetry must not alter command behavior.
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def main() -> None:
|
|
141
|
+
try:
|
|
142
|
+
run(prog_name="sinx")
|
|
143
|
+
except Exception as e:
|
|
144
|
+
if state.get("verbose"):
|
|
145
|
+
raise e
|
|
146
|
+
typer.secho(f"Error: {e}", fg=typer.colors.RED, err=True)
|
|
147
|
+
sys.exit(1)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def main_cloud() -> None:
|
|
151
|
+
try:
|
|
152
|
+
run(["cloud", *sys.argv[1:]], prog_name="sinx-cloud")
|
|
153
|
+
except Exception as e:
|
|
154
|
+
if state.get("verbose"):
|
|
155
|
+
raise e
|
|
156
|
+
typer.secho(f"Error: {e}", fg=typer.colors.RED, err=True)
|
|
157
|
+
sys.exit(1)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def main_local_venv() -> None:
|
|
161
|
+
try:
|
|
162
|
+
run(["local", *sys.argv[1:]], prog_name="sinx-venv")
|
|
163
|
+
except Exception as e:
|
|
164
|
+
if state.get("verbose"):
|
|
165
|
+
raise e
|
|
166
|
+
typer.secho(f"Error: {e}", fg=typer.colors.RED, err=True)
|
|
167
|
+
sys.exit(1)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def main_local_api() -> None:
|
|
171
|
+
try:
|
|
172
|
+
run(["local-api", *sys.argv[1:]], prog_name="sinx-api")
|
|
173
|
+
except Exception as e:
|
|
174
|
+
if state.get("verbose"):
|
|
175
|
+
raise e
|
|
176
|
+
typer.secho(f"Error: {e}", fg=typer.colors.RED, err=True)
|
|
177
|
+
sys.exit(1)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# # Compatibility for callers that import ``sinapsis_cli.main:app`` directly.
|
|
181
|
+
# app = create_app(ExecutionContext(profile=get_execution_profile()))
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
if __name__ == "__main__":
|
|
185
|
+
main()
|