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.
Files changed (46) hide show
  1. sinapsis_cli/__init__.py +13 -0
  2. sinapsis_cli/commands/__init__.py +0 -0
  3. sinapsis_cli/commands/cloud/__init__.py +0 -0
  4. sinapsis_cli/commands/cloud/_agent_selection.py +112 -0
  5. sinapsis_cli/commands/cloud/_secrets_render.py +15 -0
  6. sinapsis_cli/commands/cloud/_webhook_render.py +19 -0
  7. sinapsis_cli/commands/cloud/agents.py +137 -0
  8. sinapsis_cli/commands/cloud/api_keys.py +155 -0
  9. sinapsis_cli/commands/cloud/files.py +135 -0
  10. sinapsis_cli/commands/cloud/jobs.py +532 -0
  11. sinapsis_cli/commands/cloud/packages.py +164 -0
  12. sinapsis_cli/commands/cloud/schedules.py +392 -0
  13. sinapsis_cli/commands/cloud/secrets.py +96 -0
  14. sinapsis_cli/commands/cloud/templates.py +95 -0
  15. sinapsis_cli/commands/cloud/webhooks.py +156 -0
  16. sinapsis_cli/commands/common/__init__.py +0 -0
  17. sinapsis_cli/commands/common/auth.py +219 -0
  18. sinapsis_cli/commands/common/profiles.py +156 -0
  19. sinapsis_cli/commands/common/telemetry.py +150 -0
  20. sinapsis_cli/commands/local_api/__init__.py +0 -0
  21. sinapsis_cli/commands/local_api/jobs.py +284 -0
  22. sinapsis_cli/commands/local_venv/__init__.py +0 -0
  23. sinapsis_cli/commands/local_venv/_templates_render.py +56 -0
  24. sinapsis_cli/commands/local_venv/jobs.py +76 -0
  25. sinapsis_cli/commands/local_venv/templates.py +47 -0
  26. sinapsis_cli/composition.py +215 -0
  27. sinapsis_cli/config.py +446 -0
  28. sinapsis_cli/execution.py +77 -0
  29. sinapsis_cli/main.py +185 -0
  30. sinapsis_cli/main_multi.py +152 -0
  31. sinapsis_cli/shared/__init__.py +3 -0
  32. sinapsis_cli/shared/jobs.py +134 -0
  33. sinapsis_cli/shared/terminal.py +8 -0
  34. sinapsis_cli/shared/writer.py +427 -0
  35. sinapsis_cli/state.py +310 -0
  36. sinapsis_cli/telemetry/__init__.py +7 -0
  37. sinapsis_cli/telemetry/collector.py +84 -0
  38. sinapsis_cli/telemetry/core.py +331 -0
  39. sinapsis_cli/telemetry/scheduler.py +234 -0
  40. sinapsis_cli/telemetry/transport.py +150 -0
  41. sinapsis_cli-1.0.0.dist-info/METADATA +386 -0
  42. sinapsis_cli-1.0.0.dist-info/RECORD +46 -0
  43. sinapsis_cli-1.0.0.dist-info/WHEEL +4 -0
  44. sinapsis_cli-1.0.0.dist-info/entry_points.txt +5 -0
  45. sinapsis_cli-1.0.0.dist-info/licenses/LICENSE-APACHE +202 -0
  46. sinapsis_cli-1.0.0.dist-info/licenses/LICENSE-MIT +21 -0
sinapsis_cli/state.py ADDED
@@ -0,0 +1,310 @@
1
+ """Persistent local state for the Sinapsis CLI."""
2
+
3
+ import json
4
+ import os
5
+ from dataclasses import asdict, dataclass
6
+ from datetime import UTC, datetime
7
+ from pathlib import Path
8
+ from uuid import UUID
9
+
10
+ APP_NAME = "sinapsis"
11
+ STATE_DIR = Path(os.environ.get("SINAPSIS_STATE_DIR", Path.home() / ".local" / "state" / APP_NAME))
12
+ STATE_FILE = STATE_DIR / "state.json"
13
+
14
+ MAX_RECENT_JOBS = 20
15
+
16
+
17
+ @dataclass
18
+ class JobRecord:
19
+ """Local metadata about a job submitted through the CLI."""
20
+
21
+ job_id: str
22
+ source: str | None
23
+ target: str | None
24
+ profile: str | None
25
+ backend: str | None
26
+ submitted_at: str
27
+
28
+
29
+ @dataclass
30
+ class CLIState:
31
+ """Persistent state maintained by the CLI."""
32
+
33
+ last_job_ids: dict[str, str] | None = None
34
+ jobs: list[JobRecord] | None = None
35
+ legacy_last_job_id: str | None = None
36
+ last_agent_selections: dict[str, dict[str, str]] | None = None
37
+
38
+ def __post_init__(self) -> None:
39
+ if self.last_job_ids is None:
40
+ self.last_job_ids = {}
41
+ if self.jobs is None:
42
+ self.jobs = []
43
+ if self.last_agent_selections is None:
44
+ self.last_agent_selections = {}
45
+
46
+
47
+ def load_state() -> CLIState:
48
+ """Load CLI state from disk.
49
+
50
+ Missing or invalid state is treated as empty state. The previous single
51
+ ``last_job_id`` field is retained in memory as a migration fallback.
52
+ """
53
+ if not STATE_FILE.exists():
54
+ return CLIState()
55
+
56
+ try:
57
+ data = json.loads(STATE_FILE.read_text(encoding="utf-8"))
58
+ except (OSError, json.JSONDecodeError):
59
+ return CLIState()
60
+
61
+ if not isinstance(data, dict):
62
+ return CLIState()
63
+
64
+ last_job_ids: dict[str, str] = {}
65
+ raw_last_job_ids = data.get("last_job_ids", {})
66
+
67
+ if isinstance(raw_last_job_ids, dict):
68
+ for profile, job_id in raw_last_job_ids.items():
69
+ if isinstance(profile, str) and isinstance(job_id, str):
70
+ last_job_ids[profile] = job_id
71
+
72
+ legacy_last_job_id = data.get("last_job_id")
73
+ if not isinstance(legacy_last_job_id, str):
74
+ legacy_last_job_id = None
75
+
76
+ jobs: list[JobRecord] = []
77
+ raw_jobs = data.get("jobs", [])
78
+
79
+ if isinstance(raw_jobs, list):
80
+ for item in raw_jobs:
81
+ if not isinstance(item, dict):
82
+ continue
83
+
84
+ job_id = item.get("job_id")
85
+ submitted_at = item.get("submitted_at")
86
+
87
+ if not isinstance(job_id, str) or not isinstance(submitted_at, str):
88
+ continue
89
+
90
+ source = item.get("source")
91
+ target = item.get("target")
92
+ profile = item.get("profile")
93
+ backend = item.get("backend")
94
+
95
+ jobs.append(
96
+ JobRecord(
97
+ job_id=job_id,
98
+ source=source if isinstance(source, str) else None,
99
+ target=target if isinstance(target, str) else None,
100
+ profile=profile if isinstance(profile, str) else None,
101
+ backend=backend if isinstance(backend, str) else None,
102
+ submitted_at=submitted_at,
103
+ )
104
+ )
105
+
106
+ selections: dict[str, dict[str, str]] = {}
107
+ raw_selections = data.get("last_agent_selections", {})
108
+ if isinstance(raw_selections, dict):
109
+ for profile, entry in raw_selections.items():
110
+ if not isinstance(profile, str) or not isinstance(entry, dict):
111
+ continue
112
+ try:
113
+ agent_id = UUID(str(entry["agent_id"]))
114
+ version_id = UUID(str(entry["agent_version_id"]))
115
+ except (ValueError, TypeError, KeyError, AttributeError):
116
+ continue
117
+ selections[profile] = {"agent_id": str(agent_id), "agent_version_id": str(version_id)}
118
+
119
+ return CLIState(
120
+ last_job_ids=last_job_ids,
121
+ jobs=jobs,
122
+ legacy_last_job_id=legacy_last_job_id,
123
+ last_agent_selections=selections,
124
+ )
125
+
126
+
127
+ def save_state(state: CLIState) -> None:
128
+ """Persist CLI state to disk."""
129
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
130
+
131
+ data = {
132
+ "last_job_ids": state.last_job_ids or {},
133
+ "last_agent_selections": state.last_agent_selections or {},
134
+ "jobs": [asdict(job) for job in state.jobs or []],
135
+ }
136
+
137
+ STATE_FILE.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
138
+
139
+
140
+ def record_job(
141
+ job_id: str, *, source: str | Path | None = None, target: str | None, profile: str, backend: str
142
+ ) -> JobRecord:
143
+ """Record a newly submitted job for a profile."""
144
+ state = load_state()
145
+
146
+ record = JobRecord(
147
+ job_id=job_id,
148
+ source=str(source) if source is not None else None,
149
+ target=target,
150
+ profile=profile,
151
+ backend=backend,
152
+ submitted_at=datetime.now(UTC).isoformat(),
153
+ )
154
+
155
+ candidates = [record, *(job for job in state.jobs or [] if job.job_id != job_id)]
156
+
157
+ # Retention is profile-scoped so activity in one environment does not
158
+ # evict another profile's recent jobs. Legacy unscoped records share their
159
+ # own bucket.
160
+ retained: list[JobRecord] = []
161
+ counts: dict[str | None, int] = {}
162
+
163
+ for candidate in candidates:
164
+ bucket = candidate.profile
165
+ count = counts.get(bucket, 0)
166
+ if count >= MAX_RECENT_JOBS:
167
+ continue
168
+
169
+ retained.append(candidate)
170
+ counts[bucket] = count + 1
171
+
172
+ state.jobs = retained
173
+
174
+ assert state.last_job_ids is not None
175
+ state.last_job_ids[profile] = job_id
176
+
177
+ save_state(state)
178
+ return record
179
+
180
+
181
+ def get_last_job_id(profile: str | None = None) -> str | None:
182
+ """Return the most recently submitted job ID.
183
+
184
+ If ``profile`` is supplied, only that profile's history is considered.
185
+ Legacy state falls back to the previous global last-job value when the
186
+ referenced record was not assigned to a profile.
187
+ """
188
+ state = load_state()
189
+
190
+ if profile is None:
191
+ jobs = state.jobs or []
192
+ return jobs[0].job_id if jobs else state.legacy_last_job_id
193
+
194
+ assert state.last_job_ids is not None
195
+ job_id = state.last_job_ids.get(profile)
196
+ if job_id is not None:
197
+ return job_id
198
+
199
+ return None
200
+
201
+
202
+ def get_job(job_id: str, *, state: CLIState | None = None) -> JobRecord | None:
203
+ """Return a locally recorded job by ID."""
204
+ state = state or load_state()
205
+
206
+ for job in state.jobs or []:
207
+ if job.job_id == job_id:
208
+ return job
209
+
210
+ return None
211
+
212
+
213
+ def list_jobs(profile: str | None = None) -> list[JobRecord]:
214
+ """Return locally recorded jobs, newest first."""
215
+ jobs = list(load_state().jobs or [])
216
+
217
+ if profile is None:
218
+ return jobs
219
+
220
+ return [job for job in jobs if job.profile == profile]
221
+
222
+
223
+ def clear_jobs(profile: str) -> None:
224
+ """Remove job history for one profile."""
225
+ state = load_state()
226
+ state.jobs = [job for job in state.jobs or [] if job.profile != profile]
227
+
228
+ assert state.last_job_ids is not None
229
+ state.last_job_ids.pop(profile, None)
230
+ save_state(state)
231
+
232
+
233
+ def migrate_legacy_job_state(config) -> None:
234
+ """Assign legacy unscoped API jobs to profiles when ownership is unambiguous.
235
+
236
+ Legacy records did not persist a profile or backend. A record is migrated
237
+ only when its target URL matches exactly one configured API-backed profile.
238
+ Ambiguous records are intentionally left untouched rather than guessed.
239
+ """
240
+ state = load_state()
241
+ profiles = getattr(config, "profiles", None) or {}
242
+ changed = False
243
+
244
+ for job in state.jobs or []:
245
+ if job.profile is not None or job.target is None:
246
+ continue
247
+
248
+ matches = [profile for profile in profiles.values() if getattr(profile, "api_url", None) == job.target]
249
+
250
+ if len(matches) != 1:
251
+ continue
252
+
253
+ profile = matches[0]
254
+ job.profile = profile.name
255
+ job.backend = profile.backend.value
256
+ changed = True
257
+
258
+ if state.legacy_last_job_id == job.job_id:
259
+ assert state.last_job_ids is not None
260
+ state.last_job_ids.setdefault(profile.name, job.job_id)
261
+
262
+ if changed:
263
+ save_state(state)
264
+
265
+
266
+ def clear_state() -> None:
267
+ """Remove all locally stored CLI state."""
268
+ if STATE_FILE.exists():
269
+ STATE_FILE.unlink()
270
+
271
+
272
+ def record_agent_selection(profile: str, agent_id: UUID, agent_version_id: UUID) -> None:
273
+ """Remember a verified, immutable agent/version pair per Cloud profile."""
274
+ state = load_state()
275
+ assert state.last_agent_selections is not None
276
+ state.last_agent_selections[profile] = {
277
+ "agent_id": str(agent_id),
278
+ "agent_version_id": str(agent_version_id),
279
+ }
280
+ save_state(state)
281
+
282
+
283
+ def get_agent_selection(profile: str) -> tuple[UUID, UUID] | None:
284
+ """Retrieve the last successfully selected agent and version."""
285
+ selections = load_state().last_agent_selections or {}
286
+ entry = selections.get(profile)
287
+ if entry is None:
288
+ return None
289
+ return UUID(entry["agent_id"]), UUID(entry["agent_version_id"])
290
+
291
+
292
+ @dataclass(frozen=True, slots=True)
293
+ class SavedAgentSelection:
294
+ """Legacy read shape for a persisted saved-agent selection."""
295
+
296
+ agent_id: str
297
+ agent_version_id: str
298
+
299
+
300
+ def record_saved_agent(scope: str, agent_id: str | UUID, agent_version_id: str | UUID) -> None:
301
+ """Compatibility wrapper: reuse the canonical agent-selection state."""
302
+ record_agent_selection(scope, UUID(str(agent_id)), UUID(str(agent_version_id)))
303
+
304
+
305
+ def get_saved_agent(scope: str) -> SavedAgentSelection | None:
306
+ """Compatibility wrapper: reuse the canonical agent-selection state."""
307
+ pair = get_agent_selection(scope)
308
+ if pair is None:
309
+ return None
310
+ return SavedAgentSelection(agent_id=str(pair[0]), agent_version_id=str(pair[1]))
@@ -0,0 +1,7 @@
1
+ """Opt-in, privacy-scoped local CLI telemetry."""
2
+
3
+ from sinapsis_cli.telemetry.core import (
4
+ record_cli_invocation, record_inventory_if_due,
5
+ )
6
+
7
+ __all__ = ["record_cli_invocation", "record_inventory_if_due"]
@@ -0,0 +1,84 @@
1
+ """Detached, local-only event collector for short-lived CLI processes.
2
+
3
+ The foreground CLI never scans installed distributions, writes SQLite, or
4
+ performs HTTP telemetry operations. It passes only an allowlisted command
5
+ category to this subprocess; raw command arguments are never passed onward.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import os
11
+ import subprocess
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ from sinapsis_cli.telemetry.core import collection_enabled, record_cli_invocation, record_inventory_if_due, safe_command
16
+
17
+ _ALLOWED_BACKENDS = frozenset({'cloud', 'local-api', 'local-venv', 'other'})
18
+
19
+
20
+ def spawn_collector(
21
+ args: list[str], *, backend: str, outcome: str, duration_ms: int, venv: str | None = None,
22
+ ) -> bool:
23
+ """Spawn an independent, local writer; never block to await its completion.
24
+
25
+ The spawned process performs no network calls and exits after bounded
26
+ local database writes. A process crash before its write is durable may
27
+ lose this event; successfully queued events are retried until acknowledged.
28
+ """
29
+ if not collection_enabled():
30
+ return False
31
+ command = safe_command(args)
32
+ if command is None:
33
+ return False
34
+ argv = [
35
+ sys.executable, '-m', 'sinapsis_cli.telemetry.collector', 'write',
36
+ '--command', command,
37
+ '--backend', backend if backend in _ALLOWED_BACKENDS else 'other',
38
+ '--outcome', 'success' if outcome == 'success' else 'error',
39
+ '--duration-ms', str(max(0, min(duration_ms, 86400000))),
40
+ ]
41
+ if venv:
42
+ argv.extend(('--venv', str(Path(venv).expanduser().resolve())))
43
+ # Do not forward the original raw CLI arguments; all child arguments are
44
+ # validated fixed categories, durations, and optionally a *local-only*
45
+ # selected virtual-environment path. Its path never enters event payloads.
46
+ kwargs: dict[str, object] = {'stdin': subprocess.DEVNULL,
47
+ 'stdout': subprocess.DEVNULL,
48
+ 'stderr': subprocess.DEVNULL,
49
+ 'close_fds': True}
50
+ if os.name == 'nt':
51
+ kwargs['creationflags'] = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP
52
+ else:
53
+ kwargs['start_new_session'] = True
54
+ try:
55
+ subprocess.Popen(argv, **kwargs)
56
+ return True
57
+ except (OSError, ValueError):
58
+ return False
59
+
60
+
61
+ def main() -> int:
62
+ """Write a sanitized command event and a cached local environment inventory."""
63
+ parser = argparse.ArgumentParser(description=__doc__)
64
+ parser.add_argument('action', choices=['write'])
65
+ parser.add_argument('--command', required=True)
66
+ parser.add_argument('--backend', choices=sorted(_ALLOWED_BACKENDS), required=True)
67
+ parser.add_argument('--outcome', choices=['success', 'error'], required=True)
68
+ parser.add_argument('--duration-ms', type=int, required=True)
69
+ parser.add_argument('--venv', type=Path)
70
+ args = parser.parse_args()
71
+ if not collection_enabled():
72
+ return 0
73
+ # Re-validate the category in case a process invokes this directly.
74
+ allowed = safe_command(args.command.split('.', 1))
75
+ if allowed != args.command:
76
+ return 1
77
+ record_cli_invocation(args.command.split('.'), backend=args.backend, outcome=args.outcome,
78
+ duration_ms=args.duration_ms)
79
+ record_inventory_if_due(venv=args.venv)
80
+ return 0
81
+
82
+
83
+ if __name__ == '__main__':
84
+ raise SystemExit(main())