traceyard-cli 0.1.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.
- traceyard_cli/__init__.py +3 -0
- traceyard_cli/adapters.py +93 -0
- traceyard_cli/agent.py +168 -0
- traceyard_cli/app.py +457 -0
- traceyard_cli/config.py +182 -0
- traceyard_cli/events.py +214 -0
- traceyard_cli/queue.py +127 -0
- traceyard_cli/repository.py +175 -0
- traceyard_cli-0.1.0.dist-info/METADATA +97 -0
- traceyard_cli-0.1.0.dist-info/RECORD +13 -0
- traceyard_cli-0.1.0.dist-info/WHEEL +4 -0
- traceyard_cli-0.1.0.dist-info/entry_points.txt +2 -0
- traceyard_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
traceyard_cli/app.py
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
"""Traceyard CLI command surface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Annotated, Any, Never, cast
|
|
10
|
+
from uuid import uuid4
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
import typer
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
from .adapters import adapt_payload
|
|
17
|
+
from .agent import configured_capture_mode, install_hooks
|
|
18
|
+
from .agent import doctor as run_doctor
|
|
19
|
+
from .config import CliConfig, NativeCredentialStore, load_config, save_config
|
|
20
|
+
from .events import AgentEvent, CaptureMode, Provider, build_event
|
|
21
|
+
from .queue import EncryptedEventQueue, QueuedEvent
|
|
22
|
+
from .repository import initialize_repository, repository_status, validate_project
|
|
23
|
+
|
|
24
|
+
app = typer.Typer(
|
|
25
|
+
help="Traceyard repository memory and agent collector.",
|
|
26
|
+
no_args_is_help=True,
|
|
27
|
+
invoke_without_command=True,
|
|
28
|
+
)
|
|
29
|
+
repo_app = typer.Typer(help="Manage the current repository.", no_args_is_help=True)
|
|
30
|
+
agent_app = typer.Typer(help="Manage local agent adapters.", no_args_is_help=True)
|
|
31
|
+
auth_app = typer.Typer(help="Manage collector authentication.", no_args_is_help=True)
|
|
32
|
+
queue_app = typer.Typer(help="Inspect or clear queued agent events.", no_args_is_help=True)
|
|
33
|
+
app.add_typer(repo_app, name="repo")
|
|
34
|
+
app.add_typer(agent_app, name="agent")
|
|
35
|
+
app.add_typer(auth_app, name="auth")
|
|
36
|
+
agent_app.add_typer(queue_app, name="queue")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _emit(value: dict[str, Any], *, json_output: bool) -> None:
|
|
40
|
+
if json_output:
|
|
41
|
+
typer.echo(json.dumps(value, sort_keys=True))
|
|
42
|
+
return
|
|
43
|
+
typer.echo(value.get("message", value.get("status", "ok")))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _fail(message: str, *, code: int, json_output: bool, details: object = None) -> Never:
|
|
47
|
+
payload = {"status": "error", "message": message, "exit_code": code}
|
|
48
|
+
if details is not None:
|
|
49
|
+
payload["details"] = details
|
|
50
|
+
_emit(payload, json_output=json_output)
|
|
51
|
+
raise typer.Exit(code)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _login(token: str, base_url: str, json_output: bool) -> None:
|
|
55
|
+
store = NativeCredentialStore()
|
|
56
|
+
if not store.available():
|
|
57
|
+
_fail(
|
|
58
|
+
"No native credential vault is available. Set TRACEYARD_TOKEN for noninteractive use.",
|
|
59
|
+
code=3,
|
|
60
|
+
json_output=json_output,
|
|
61
|
+
)
|
|
62
|
+
try:
|
|
63
|
+
store.set_token(token)
|
|
64
|
+
save_config(CliConfig(base_url=base_url.rstrip("/")))
|
|
65
|
+
except (OSError, RuntimeError, ValueError) as error:
|
|
66
|
+
_fail(str(error), code=3, json_output=json_output)
|
|
67
|
+
_emit(
|
|
68
|
+
{"status": "ok", "message": "Collector credential stored in the OS vault."},
|
|
69
|
+
json_output=json_output,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@app.command("login")
|
|
74
|
+
def login(
|
|
75
|
+
token: Annotated[
|
|
76
|
+
str | None,
|
|
77
|
+
typer.Option(envvar="TRACEYARD_TOKEN", help="Scoped collector token."),
|
|
78
|
+
] = None,
|
|
79
|
+
token_stdin: Annotated[
|
|
80
|
+
bool, typer.Option("--token-stdin", help="Read token from standard input.")
|
|
81
|
+
] = False,
|
|
82
|
+
base_url: Annotated[
|
|
83
|
+
str, typer.Option(help="Traceyard API origin.")
|
|
84
|
+
] = "https://app.traceyard.dev",
|
|
85
|
+
json_output: Annotated[bool, typer.Option("--json")] = False,
|
|
86
|
+
) -> None:
|
|
87
|
+
"""Store a scoped collector credential in the native OS vault."""
|
|
88
|
+
value = sys.stdin.readline().strip() if token_stdin else token
|
|
89
|
+
if not value:
|
|
90
|
+
_fail(
|
|
91
|
+
"A token is required via --token, --token-stdin, or TRACEYARD_TOKEN.",
|
|
92
|
+
code=2,
|
|
93
|
+
json_output=json_output,
|
|
94
|
+
)
|
|
95
|
+
assert value is not None
|
|
96
|
+
_login(value, base_url, json_output)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@auth_app.command("login")
|
|
100
|
+
def auth_login(
|
|
101
|
+
token: Annotated[str | None, typer.Option(envvar="TRACEYARD_TOKEN")] = None,
|
|
102
|
+
token_stdin: Annotated[bool, typer.Option("--token-stdin")] = False,
|
|
103
|
+
base_url: Annotated[str, typer.Option()] = "https://app.traceyard.dev",
|
|
104
|
+
json_output: Annotated[bool, typer.Option("--json")] = False,
|
|
105
|
+
) -> None:
|
|
106
|
+
value = sys.stdin.readline().strip() if token_stdin else token
|
|
107
|
+
if not value:
|
|
108
|
+
_fail("A token is required.", code=2, json_output=json_output)
|
|
109
|
+
assert value is not None
|
|
110
|
+
_login(value, base_url, json_output)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@auth_app.command("status")
|
|
114
|
+
def auth_status(json_output: Annotated[bool, typer.Option("--json")] = False) -> None:
|
|
115
|
+
available = NativeCredentialStore().get_token() is not None
|
|
116
|
+
_emit(
|
|
117
|
+
{
|
|
118
|
+
"status": "authenticated" if available else "unauthenticated",
|
|
119
|
+
"base_url": load_config().base_url,
|
|
120
|
+
},
|
|
121
|
+
json_output=json_output,
|
|
122
|
+
)
|
|
123
|
+
if not available:
|
|
124
|
+
raise typer.Exit(4)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@auth_app.command("logout")
|
|
128
|
+
def logout(json_output: Annotated[bool, typer.Option("--json")] = False) -> None:
|
|
129
|
+
NativeCredentialStore().delete_token()
|
|
130
|
+
_emit(
|
|
131
|
+
{"status": "ok", "message": "Collector credential removed."},
|
|
132
|
+
json_output=json_output,
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@repo_app.command("init")
|
|
137
|
+
def repo_init(
|
|
138
|
+
path: Annotated[Path, typer.Option(exists=True, file_okay=False, resolve_path=True)] = Path(
|
|
139
|
+
"."
|
|
140
|
+
),
|
|
141
|
+
name: Annotated[str | None, typer.Option()] = None,
|
|
142
|
+
json_output: Annotated[bool, typer.Option("--json")] = False,
|
|
143
|
+
) -> None:
|
|
144
|
+
try:
|
|
145
|
+
created = initialize_repository(path, name=name)
|
|
146
|
+
except (OSError, ValueError) as error:
|
|
147
|
+
_fail(str(error), code=5, json_output=json_output)
|
|
148
|
+
_emit(
|
|
149
|
+
{
|
|
150
|
+
"status": "ok",
|
|
151
|
+
"message": "Repository initialized.",
|
|
152
|
+
"created": [str(item) for item in created],
|
|
153
|
+
},
|
|
154
|
+
json_output=json_output,
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@repo_app.command("validate")
|
|
159
|
+
def repo_validate(
|
|
160
|
+
path: Annotated[Path, typer.Option(exists=True, file_okay=False, resolve_path=True)] = Path(
|
|
161
|
+
"."
|
|
162
|
+
),
|
|
163
|
+
json_output: Annotated[bool, typer.Option("--json")] = False,
|
|
164
|
+
) -> None:
|
|
165
|
+
result = validate_project(path / "PROJECT.md")
|
|
166
|
+
payload = {
|
|
167
|
+
"status": "ok" if result.valid else "invalid",
|
|
168
|
+
"valid": result.valid,
|
|
169
|
+
"diagnostics": result.diagnostics,
|
|
170
|
+
}
|
|
171
|
+
_emit(payload, json_output=json_output)
|
|
172
|
+
if not result.valid:
|
|
173
|
+
raise typer.Exit(6)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@repo_app.command("status")
|
|
177
|
+
def repo_status(
|
|
178
|
+
path: Annotated[Path, typer.Option(exists=True, file_okay=False, resolve_path=True)] = Path(
|
|
179
|
+
"."
|
|
180
|
+
),
|
|
181
|
+
json_output: Annotated[bool, typer.Option("--json")] = False,
|
|
182
|
+
) -> None:
|
|
183
|
+
status = repository_status(path)
|
|
184
|
+
_emit(
|
|
185
|
+
{"status": "ok" if status["valid"] else "invalid", **status},
|
|
186
|
+
json_output=json_output,
|
|
187
|
+
)
|
|
188
|
+
if not status["valid"]:
|
|
189
|
+
raise typer.Exit(6)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@agent_app.command("install")
|
|
193
|
+
def agent_install(
|
|
194
|
+
provider: Annotated[str, typer.Option(help="codex, claude_code, cursor, or all")] = "all",
|
|
195
|
+
capture_mode: Annotated[
|
|
196
|
+
str, typer.Option(help="metadata_only, summary, or explicit full")
|
|
197
|
+
] = "metadata_only",
|
|
198
|
+
path: Annotated[Path, typer.Option(exists=True, file_okay=False, resolve_path=True)] = Path(
|
|
199
|
+
"."
|
|
200
|
+
),
|
|
201
|
+
json_output: Annotated[bool, typer.Option("--json")] = False,
|
|
202
|
+
) -> None:
|
|
203
|
+
try:
|
|
204
|
+
if capture_mode not in {"metadata_only", "summary", "full"}:
|
|
205
|
+
raise ValueError("Unsupported capture mode")
|
|
206
|
+
installed = install_hooks(provider, path, cast(CaptureMode, capture_mode))
|
|
207
|
+
except (OSError, ValueError) as error:
|
|
208
|
+
_fail(str(error), code=5, json_output=json_output)
|
|
209
|
+
_emit(
|
|
210
|
+
{
|
|
211
|
+
"status": "ok",
|
|
212
|
+
"message": "Agent adapter metadata installed.",
|
|
213
|
+
"installed": [str(item) for item in installed],
|
|
214
|
+
},
|
|
215
|
+
json_output=json_output,
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
@agent_app.command("doctor")
|
|
220
|
+
def agent_doctor(
|
|
221
|
+
path: Annotated[Path, typer.Option(exists=True, file_okay=False, resolve_path=True)] = Path(
|
|
222
|
+
"."
|
|
223
|
+
),
|
|
224
|
+
json_output: Annotated[bool, typer.Option("--json")] = False,
|
|
225
|
+
) -> None:
|
|
226
|
+
result = run_doctor(NativeCredentialStore(), path)
|
|
227
|
+
_emit(result, json_output=json_output)
|
|
228
|
+
if result["status"] != "ok":
|
|
229
|
+
raise typer.Exit(7)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
@agent_app.command("emit", hidden=True)
|
|
233
|
+
def agent_emit(
|
|
234
|
+
provider: Annotated[str, typer.Option(help="codex, claude_code, or cursor")],
|
|
235
|
+
json_output: Annotated[bool, typer.Option("--json")] = False,
|
|
236
|
+
) -> None:
|
|
237
|
+
"""Accept one provider hook payload on stdin and queue a normalized event."""
|
|
238
|
+
try:
|
|
239
|
+
raw = json.load(sys.stdin)
|
|
240
|
+
if not isinstance(raw, dict) or provider not in {
|
|
241
|
+
"codex",
|
|
242
|
+
"claude_code",
|
|
243
|
+
"cursor",
|
|
244
|
+
}:
|
|
245
|
+
raise ValueError("invalid provider hook payload")
|
|
246
|
+
event, inserted = _queue_provider_payload(cast(Provider, provider), raw)
|
|
247
|
+
except (OSError, ValueError, json.JSONDecodeError) as error:
|
|
248
|
+
_fail(str(error), code=7, json_output=json_output)
|
|
249
|
+
if json_output:
|
|
250
|
+
_emit(
|
|
251
|
+
{"status": "ok", "queued": inserted, "event_id": event.event_id},
|
|
252
|
+
json_output=True,
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
@agent_app.command("stream", hidden=True)
|
|
257
|
+
def agent_stream(
|
|
258
|
+
provider: Annotated[str, typer.Option(help="cursor")],
|
|
259
|
+
json_output: Annotated[bool, typer.Option("--json")] = False,
|
|
260
|
+
) -> None:
|
|
261
|
+
"""Consume provider NDJSON without retaining prompts or tool payloads."""
|
|
262
|
+
if provider != "cursor":
|
|
263
|
+
_fail("stream input is supported for cursor", code=2, json_output=json_output)
|
|
264
|
+
queued = 0
|
|
265
|
+
try:
|
|
266
|
+
for line in sys.stdin:
|
|
267
|
+
payload = json.loads(line)
|
|
268
|
+
if not isinstance(payload, dict):
|
|
269
|
+
continue
|
|
270
|
+
_event, inserted = _queue_provider_payload("cursor", payload)
|
|
271
|
+
queued += int(inserted)
|
|
272
|
+
except (OSError, ValueError, json.JSONDecodeError) as error:
|
|
273
|
+
_fail(str(error), code=7, json_output=json_output)
|
|
274
|
+
if json_output:
|
|
275
|
+
_emit({"status": "ok", "queued": queued}, json_output=True)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _queue_provider_payload(provider: Provider, raw: dict[str, Any]) -> tuple[AgentEvent, bool]:
|
|
279
|
+
adapted = adapt_payload(provider, raw)
|
|
280
|
+
capture_mode = configured_capture_mode(provider)
|
|
281
|
+
event = build_event(
|
|
282
|
+
provider=adapted.provider,
|
|
283
|
+
session_id=adapted.session_id,
|
|
284
|
+
root=adapted.root,
|
|
285
|
+
status=adapted.status,
|
|
286
|
+
occurred_at=datetime.now(UTC),
|
|
287
|
+
summary=adapted.summary,
|
|
288
|
+
capture_mode=capture_mode,
|
|
289
|
+
prompt=raw.get("prompt") if isinstance(raw.get("prompt"), str) else None,
|
|
290
|
+
transcript=raw.get("transcript") if isinstance(raw.get("transcript"), str) else None,
|
|
291
|
+
tool_data=raw.get("tool_data") if isinstance(raw.get("tool_data"), dict) else None,
|
|
292
|
+
)
|
|
293
|
+
token = NativeCredentialStore().get_token()
|
|
294
|
+
if token is None:
|
|
295
|
+
raise ValueError("collector credential is missing; run `traceyard login`")
|
|
296
|
+
return event, EncryptedEventQueue(token).enqueue(event.as_dict())
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
@queue_app.command("inspect")
|
|
300
|
+
def queue_inspect(json_output: Annotated[bool, typer.Option("--json")] = False) -> None:
|
|
301
|
+
token = NativeCredentialStore().get_token()
|
|
302
|
+
if token is None:
|
|
303
|
+
_fail("Collector credential is missing.", code=4, json_output=json_output)
|
|
304
|
+
result = EncryptedEventQueue(token).inspect()
|
|
305
|
+
_emit({"status": "ok", **result}, json_output=json_output)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
@queue_app.command("clear")
|
|
309
|
+
def queue_clear(
|
|
310
|
+
include_quarantine: Annotated[bool, typer.Option("--include-quarantine")] = False,
|
|
311
|
+
json_output: Annotated[bool, typer.Option("--json")] = False,
|
|
312
|
+
) -> None:
|
|
313
|
+
token = NativeCredentialStore().get_token()
|
|
314
|
+
if token is None:
|
|
315
|
+
_fail("Collector credential is missing.", code=4, json_output=json_output)
|
|
316
|
+
cleared = EncryptedEventQueue(token).clear(include_quarantine=include_quarantine)
|
|
317
|
+
_emit({"status": "ok", "cleared": cleared}, json_output=json_output)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
@app.command("sync")
|
|
321
|
+
def sync(
|
|
322
|
+
path: Annotated[Path, typer.Option(exists=True, file_okay=False, resolve_path=True)] = Path(
|
|
323
|
+
"."
|
|
324
|
+
),
|
|
325
|
+
json_output: Annotated[bool, typer.Option("--json")] = False,
|
|
326
|
+
) -> None:
|
|
327
|
+
operation_id = str(uuid4())
|
|
328
|
+
status = repository_status(path)
|
|
329
|
+
if not status["valid"]:
|
|
330
|
+
_fail(
|
|
331
|
+
"PROJECT.md is invalid; run `traceyard repo validate`.",
|
|
332
|
+
code=6,
|
|
333
|
+
json_output=json_output,
|
|
334
|
+
details=status["diagnostics"],
|
|
335
|
+
)
|
|
336
|
+
store = NativeCredentialStore()
|
|
337
|
+
token = store.get_token()
|
|
338
|
+
if token is None:
|
|
339
|
+
_fail(
|
|
340
|
+
"Collector credential is missing; run `traceyard login`.",
|
|
341
|
+
code=4,
|
|
342
|
+
json_output=json_output,
|
|
343
|
+
)
|
|
344
|
+
config = load_config()
|
|
345
|
+
queue = EncryptedEventQueue(token)
|
|
346
|
+
batch = queue.batch(limit=100)
|
|
347
|
+
if not batch:
|
|
348
|
+
_emit(
|
|
349
|
+
{"status": "ok", "message": "Nothing queued.", "repository": status},
|
|
350
|
+
json_output=json_output,
|
|
351
|
+
)
|
|
352
|
+
return
|
|
353
|
+
try:
|
|
354
|
+
response = httpx.post(
|
|
355
|
+
f"{config.base_url}/ingest/v1/agent-events",
|
|
356
|
+
headers={
|
|
357
|
+
"Authorization": f"Bearer {token}",
|
|
358
|
+
"X-Correlation-ID": operation_id,
|
|
359
|
+
"X-Request-ID": operation_id,
|
|
360
|
+
},
|
|
361
|
+
json={"events": [item.payload for item in batch]},
|
|
362
|
+
timeout=15,
|
|
363
|
+
)
|
|
364
|
+
response.raise_for_status()
|
|
365
|
+
except httpx.HTTPError:
|
|
366
|
+
queue.retry(
|
|
367
|
+
tuple(item.sequence for item in batch),
|
|
368
|
+
attempts=max(item.attempts for item in batch),
|
|
369
|
+
)
|
|
370
|
+
_fail(
|
|
371
|
+
"Sync failed; local data remains unchanged. Check connectivity and run again.",
|
|
372
|
+
code=8,
|
|
373
|
+
json_output=json_output,
|
|
374
|
+
)
|
|
375
|
+
try:
|
|
376
|
+
accepted, retryable, rejected = _partition_sync_results(batch, response.json())
|
|
377
|
+
except ValueError, TypeError, json.JSONDecodeError:
|
|
378
|
+
queue.retry(
|
|
379
|
+
tuple(item.sequence for item in batch),
|
|
380
|
+
attempts=max(item.attempts for item in batch),
|
|
381
|
+
)
|
|
382
|
+
_fail(
|
|
383
|
+
"Sync returned an invalid response; queued data was retained.",
|
|
384
|
+
code=8,
|
|
385
|
+
json_output=json_output,
|
|
386
|
+
)
|
|
387
|
+
queue.acknowledge(accepted + rejected)
|
|
388
|
+
if retryable:
|
|
389
|
+
queue.retry(retryable, attempts=max(item.attempts for item in batch))
|
|
390
|
+
if rejected:
|
|
391
|
+
_fail(
|
|
392
|
+
"Sync rejected one or more invalid events; inspect collector diagnostics.",
|
|
393
|
+
code=9,
|
|
394
|
+
json_output=json_output,
|
|
395
|
+
details={
|
|
396
|
+
"accepted": len(accepted),
|
|
397
|
+
"rejected": len(rejected),
|
|
398
|
+
"retryable": len(retryable),
|
|
399
|
+
},
|
|
400
|
+
)
|
|
401
|
+
_emit(
|
|
402
|
+
{
|
|
403
|
+
"status": "ok",
|
|
404
|
+
"message": "Sync completed.",
|
|
405
|
+
"operation_id": operation_id,
|
|
406
|
+
"repository": status,
|
|
407
|
+
},
|
|
408
|
+
json_output=json_output,
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _partition_sync_results(
|
|
413
|
+
batch: tuple[QueuedEvent, ...], response: object
|
|
414
|
+
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
|
|
415
|
+
if not isinstance(response, dict) or not isinstance(response.get("results"), list):
|
|
416
|
+
raise TypeError("invalid response")
|
|
417
|
+
by_id = {str(item.event_id): item.sequence for item in batch}
|
|
418
|
+
accepted: list[int] = []
|
|
419
|
+
retryable: list[int] = []
|
|
420
|
+
rejected: list[int] = []
|
|
421
|
+
seen: set[str] = set()
|
|
422
|
+
for result in response["results"]:
|
|
423
|
+
if not isinstance(result, dict):
|
|
424
|
+
raise TypeError("invalid item result")
|
|
425
|
+
event_id = str(result.get("event_id", ""))
|
|
426
|
+
if event_id not in by_id or event_id in seen:
|
|
427
|
+
raise ValueError("unmatched item result")
|
|
428
|
+
seen.add(event_id)
|
|
429
|
+
outcome = result.get("outcome")
|
|
430
|
+
if outcome in {"accepted", "duplicate"}:
|
|
431
|
+
accepted.append(by_id[event_id])
|
|
432
|
+
elif outcome == "rejected" and result.get("retryable") is True:
|
|
433
|
+
retryable.append(by_id[event_id])
|
|
434
|
+
elif outcome == "rejected":
|
|
435
|
+
rejected.append(by_id[event_id])
|
|
436
|
+
else:
|
|
437
|
+
raise ValueError("invalid item outcome")
|
|
438
|
+
if seen != set(by_id):
|
|
439
|
+
raise ValueError("missing item result")
|
|
440
|
+
return tuple(accepted), tuple(retryable), tuple(rejected)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
@app.callback()
|
|
444
|
+
def root(
|
|
445
|
+
version: Annotated[bool, typer.Option("--version", is_eager=True)] = False,
|
|
446
|
+
) -> None:
|
|
447
|
+
if version:
|
|
448
|
+
typer.echo(__version__)
|
|
449
|
+
raise typer.Exit()
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def main() -> None:
|
|
453
|
+
app()
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
if __name__ == "__main__":
|
|
457
|
+
main()
|
traceyard_cli/config.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""Restricted local configuration and native credential storage."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import platform
|
|
9
|
+
import shutil
|
|
10
|
+
import stat
|
|
11
|
+
import subprocess
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Protocol
|
|
15
|
+
|
|
16
|
+
SERVICE_NAME = "traceyard-cli"
|
|
17
|
+
TOKEN_ACCOUNT = "collector-token"
|
|
18
|
+
DEFAULT_BASE_URL = "https://app.traceyard.dev"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def config_home() -> Path:
|
|
22
|
+
override = os.environ.get("TRACEYARD_CONFIG_HOME")
|
|
23
|
+
if override:
|
|
24
|
+
return Path(override).expanduser()
|
|
25
|
+
system = platform.system()
|
|
26
|
+
if system == "Windows":
|
|
27
|
+
return Path(os.environ.get("APPDATA", Path.home() / "AppData/Roaming")) / "Traceyard"
|
|
28
|
+
if system == "Darwin":
|
|
29
|
+
return Path.home() / "Library/Application Support/Traceyard"
|
|
30
|
+
return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "traceyard"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True, slots=True)
|
|
34
|
+
class CliConfig:
|
|
35
|
+
base_url: str = DEFAULT_BASE_URL
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def load_config() -> CliConfig:
|
|
39
|
+
path = config_home() / "config.json"
|
|
40
|
+
if not path.exists():
|
|
41
|
+
return CliConfig()
|
|
42
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
43
|
+
return CliConfig(base_url=str(data.get("base_url", DEFAULT_BASE_URL)))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def save_config(config: CliConfig) -> None:
|
|
47
|
+
root = config_home()
|
|
48
|
+
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
49
|
+
os.chmod(root, stat.S_IRWXU)
|
|
50
|
+
path = root / "config.json"
|
|
51
|
+
path.write_text(json.dumps({"base_url": config.base_url}, indent=2) + "\n", encoding="utf-8")
|
|
52
|
+
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class CredentialStore(Protocol):
|
|
56
|
+
def set_token(self, token: str) -> None: ...
|
|
57
|
+
def get_token(self) -> str | None: ...
|
|
58
|
+
def delete_token(self) -> None: ...
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class NativeCredentialStore:
|
|
62
|
+
"""Use the OS credential vault; credential material is never written to config files."""
|
|
63
|
+
|
|
64
|
+
def available(self) -> bool:
|
|
65
|
+
system = platform.system()
|
|
66
|
+
return (
|
|
67
|
+
(system == "Darwin" and shutil.which("security") is not None)
|
|
68
|
+
or (system == "Linux" and shutil.which("secret-tool") is not None)
|
|
69
|
+
or (system == "Windows" and shutil.which("powershell") is not None)
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
def set_token(self, token: str) -> None:
|
|
73
|
+
if not token.strip():
|
|
74
|
+
raise ValueError("token must not be empty")
|
|
75
|
+
if platform.system() == "Darwin":
|
|
76
|
+
self._run(
|
|
77
|
+
[
|
|
78
|
+
"security",
|
|
79
|
+
"add-generic-password",
|
|
80
|
+
"-U",
|
|
81
|
+
"-s",
|
|
82
|
+
SERVICE_NAME,
|
|
83
|
+
"-a",
|
|
84
|
+
TOKEN_ACCOUNT,
|
|
85
|
+
"-w",
|
|
86
|
+
token,
|
|
87
|
+
]
|
|
88
|
+
)
|
|
89
|
+
return
|
|
90
|
+
if platform.system() == "Linux":
|
|
91
|
+
self._run(
|
|
92
|
+
[
|
|
93
|
+
"secret-tool",
|
|
94
|
+
"store",
|
|
95
|
+
"--label=Traceyard collector",
|
|
96
|
+
"service",
|
|
97
|
+
SERVICE_NAME,
|
|
98
|
+
"account",
|
|
99
|
+
TOKEN_ACCOUNT,
|
|
100
|
+
],
|
|
101
|
+
input_text=token,
|
|
102
|
+
)
|
|
103
|
+
return
|
|
104
|
+
if platform.system() == "Windows":
|
|
105
|
+
script = (
|
|
106
|
+
"$v=[Console]::In.ReadToEnd();"
|
|
107
|
+
"$b=[Text.Encoding]::UTF8.GetBytes($v);"
|
|
108
|
+
"$p=[Security.Cryptography.ProtectedData]::Protect($b,$null,'CurrentUser');"
|
|
109
|
+
"[Convert]::ToBase64String($p)"
|
|
110
|
+
)
|
|
111
|
+
result = subprocess.run(
|
|
112
|
+
["powershell", "-NoProfile", "-NonInteractive", "-Command", script],
|
|
113
|
+
input=token,
|
|
114
|
+
check=False,
|
|
115
|
+
capture_output=True,
|
|
116
|
+
text=True,
|
|
117
|
+
)
|
|
118
|
+
if result.returncode != 0 or not result.stdout.strip():
|
|
119
|
+
raise RuntimeError("The Windows credential protector rejected the operation")
|
|
120
|
+
root = config_home()
|
|
121
|
+
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
122
|
+
path = root / "credential.dpapi"
|
|
123
|
+
path.write_text(result.stdout.strip(), encoding="ascii")
|
|
124
|
+
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
|
|
125
|
+
return
|
|
126
|
+
raise RuntimeError("No supported native credential vault is available")
|
|
127
|
+
|
|
128
|
+
def get_token(self) -> str | None:
|
|
129
|
+
environment_token = os.environ.get("TRACEYARD_TOKEN")
|
|
130
|
+
if environment_token:
|
|
131
|
+
return environment_token
|
|
132
|
+
if not self.available():
|
|
133
|
+
return None
|
|
134
|
+
if platform.system() == "Windows":
|
|
135
|
+
path = config_home() / "credential.dpapi"
|
|
136
|
+
if not path.is_file():
|
|
137
|
+
return None
|
|
138
|
+
try:
|
|
139
|
+
encrypted = base64.b64decode(path.read_text(encoding="ascii"), validate=True)
|
|
140
|
+
except OSError, ValueError:
|
|
141
|
+
return None
|
|
142
|
+
script = (
|
|
143
|
+
"$v=[Console]::In.ReadToEnd();$p=[Convert]::FromBase64String($v);"
|
|
144
|
+
"$b=[Security.Cryptography.ProtectedData]::Unprotect($p,$null,'CurrentUser');"
|
|
145
|
+
"[Text.Encoding]::UTF8.GetString($b)"
|
|
146
|
+
)
|
|
147
|
+
result = subprocess.run(
|
|
148
|
+
["powershell", "-NoProfile", "-NonInteractive", "-Command", script],
|
|
149
|
+
input=base64.b64encode(encrypted).decode("ascii"),
|
|
150
|
+
check=False,
|
|
151
|
+
capture_output=True,
|
|
152
|
+
text=True,
|
|
153
|
+
)
|
|
154
|
+
return result.stdout if result.returncode == 0 and result.stdout else None
|
|
155
|
+
command = (
|
|
156
|
+
["security", "find-generic-password", "-s", SERVICE_NAME, "-a", TOKEN_ACCOUNT, "-w"]
|
|
157
|
+
if platform.system() == "Darwin"
|
|
158
|
+
else ["secret-tool", "lookup", "service", SERVICE_NAME, "account", TOKEN_ACCOUNT]
|
|
159
|
+
)
|
|
160
|
+
result = subprocess.run(command, check=False, capture_output=True, text=True)
|
|
161
|
+
return result.stdout.strip() if result.returncode == 0 and result.stdout.strip() else None
|
|
162
|
+
|
|
163
|
+
def delete_token(self) -> None:
|
|
164
|
+
if platform.system() == "Windows":
|
|
165
|
+
(config_home() / "credential.dpapi").unlink(missing_ok=True)
|
|
166
|
+
return
|
|
167
|
+
if not self.available():
|
|
168
|
+
return
|
|
169
|
+
command = (
|
|
170
|
+
["security", "delete-generic-password", "-s", SERVICE_NAME, "-a", TOKEN_ACCOUNT]
|
|
171
|
+
if platform.system() == "Darwin"
|
|
172
|
+
else ["secret-tool", "clear", "service", SERVICE_NAME, "account", TOKEN_ACCOUNT]
|
|
173
|
+
)
|
|
174
|
+
subprocess.run(command, check=False, capture_output=True, text=True)
|
|
175
|
+
|
|
176
|
+
@staticmethod
|
|
177
|
+
def _run(command: list[str], *, input_text: str | None = None) -> None:
|
|
178
|
+
result = subprocess.run(
|
|
179
|
+
command, input=input_text, check=False, capture_output=True, text=True
|
|
180
|
+
)
|
|
181
|
+
if result.returncode != 0:
|
|
182
|
+
raise RuntimeError("The operating-system credential vault rejected the operation")
|