tragac 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.
tragac/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """Tragac for Python: one line around your AI client.
2
+
3
+ import tragac
4
+ from openai import OpenAI
5
+
6
+ client = tragac.wrap(OpenAI(), customer_id=current_user.id)
7
+
8
+ The key is read from ``TRAGAC_KEY`` and is never logged. A Tragac problem never
9
+ breaks the founder's AI call: if Tragac cannot answer, the call runs as usual.
10
+ """
11
+
12
+ from .wrap import Blocked, flush, wrap
13
+
14
+ __all__ = ["wrap", "Blocked", "flush"]
15
+ __version__ = "0.1.0"
tragac/cli.py ADDED
@@ -0,0 +1,606 @@
1
+ """``tragac init``: one guided setup for a project's AI calls.
2
+
3
+ The steps follow the Connect page: check the key with one evaluate request,
4
+ detect the language, write ``TRAGAC_KEY`` into ``.env``, ignore ``.env`` in git,
5
+ offer to add one import line beside the project's AI client, then run the same
6
+ six checks the Connect page runs.
7
+
8
+ Two rules shape every step: the key is only ever written to ``.env`` and never
9
+ printed back, and no file is written without showing the change and getting a
10
+ yes. Nothing here calls an AI provider.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import getpass
16
+ import json
17
+ import os
18
+ import re
19
+ import sys
20
+ import urllib.error
21
+ import urllib.request
22
+ import uuid
23
+ from datetime import datetime, timezone
24
+
25
+ DEFAULT_API_BASE = "https://tragac.vercel.app"
26
+ EVALUATE_PATH = "/api/v1/evaluate"
27
+ USAGE_PATH = "/api/v1/usage"
28
+
29
+ #: The engine creates this one test customer on its own; setup makes no other data.
30
+ INIT_CUSTOMER_ID = "tragac-init-check"
31
+
32
+ CHECK_MODEL = "gpt-4o-mini"
33
+ CHECK_PROVIDER = "openai"
34
+ WAIT_SECONDS = 3.0
35
+ USAGE_TIMEOUT = 2.0
36
+ MASK_WIDTH = 16
37
+ USER_AGENT = "tragac-cli/0.1.0"
38
+ MAX_FILES = 2000
39
+ MAX_READ = 512 * 1024
40
+
41
+ SKIP_DIRS = {
42
+ "node_modules",
43
+ ".git",
44
+ ".next",
45
+ "dist",
46
+ "build",
47
+ "out",
48
+ "target",
49
+ "__pycache__",
50
+ ".venv",
51
+ "venv",
52
+ ".cache",
53
+ "coverage",
54
+ ".turbo",
55
+ ".vercel",
56
+ }
57
+
58
+ PYTHON_EXTENSIONS = (".py",)
59
+ NODE_EXTENSIONS = (".js", ".mjs", ".cjs", ".ts", ".mts", ".cts", ".tsx", ".jsx")
60
+
61
+ PYTHON_CLIENTS = re.compile(
62
+ r"^\s*(?:from\s+(openai|groq|together|anthropic)\b|import\s+(openai|groq|together|anthropic)\b)"
63
+ )
64
+ NODE_CLIENTS = re.compile(
65
+ r"(?:from\s+[\"'](openai|groq-sdk|@anthropic-ai/sdk)[\"']"
66
+ r"|require\(\s*[\"'](openai|groq-sdk|@anthropic-ai/sdk)[\"']\s*\))"
67
+ )
68
+
69
+ #: The six checks, in the Connect page's order, with a plain reason for a cross.
70
+ CHECKS = (
71
+ ("key", "Your key is accepted.", "Tragac did not accept the key. Check the project's keys."),
72
+ ("connection", "Tragac answered within 3 seconds.", "Tragac did not answer within 3 seconds. Try again in a moment."),
73
+ ("customer", "A customer can be identified.", "Tragac did not echo the test customer back."),
74
+ ("usage", "A usage report is accepted.", "Tragac did not accept the usage report."),
75
+ ("credits", "The customer's credits allow the call.", "The test request was blocked."),
76
+ ("visibility", "The request is stored in the project.", "Tragac made a decision but did not store it."),
77
+ )
78
+
79
+ USAGE_TEXT = """Tragac command line
80
+
81
+ tragac init Set this project up: check the key, write .env, wrap the AI
82
+ client, then run the six connection checks.
83
+
84
+ Not published: install it from this repository (pip install ./packages/python).
85
+ """
86
+
87
+
88
+ # -- the key -------------------------------------------------------------
89
+
90
+
91
+ def normalise_key(value):
92
+ """The key as given, trimmed. Never written anywhere but .env."""
93
+ return value.strip() if isinstance(value, str) else ""
94
+
95
+
96
+ def mask_key(key):
97
+ """The first eight characters, then a fixed mask. The key is never printed back."""
98
+ return key[:8] + "*" * MASK_WIDTH if key else ""
99
+
100
+
101
+ def key_kind(key):
102
+ """A test key is the default; anything else needs the word live to be used."""
103
+ if key.startswith("tg_test_"):
104
+ return "test"
105
+ if key.startswith("tg_live_"):
106
+ return "live"
107
+ return "other"
108
+
109
+
110
+ # -- language ------------------------------------------------------------
111
+
112
+
113
+ def detect_language(cwd):
114
+ """package.json means Node; requirements.txt or pyproject.toml means Python."""
115
+ def has(name):
116
+ return os.path.isfile(os.path.join(cwd, name))
117
+
118
+ return {
119
+ "node": has("package.json"),
120
+ "python": has("requirements.txt") or has("pyproject.toml"),
121
+ }
122
+
123
+
124
+ # -- .env and .gitignore -------------------------------------------------
125
+
126
+ ENV_LINE = re.compile(r"^[ \t]*(?:export[ \t]+)?TRAGAC_KEY[ \t]*=.*$", re.MULTILINE)
127
+ COVERED = {".env", "/.env", ".env*", "*.env", ".env.*", "*/.env"}
128
+
129
+
130
+ def with_key(text, key):
131
+ """The new .env text, or None when TRAGAC_KEY is already exactly that line."""
132
+ line = "TRAGAC_KEY=" + key
133
+
134
+ if not text:
135
+ return line + "\n"
136
+
137
+ existing = ENV_LINE.search(text)
138
+ if existing and existing.group(0) == line:
139
+ return None
140
+ if existing:
141
+ return ENV_LINE.sub(line, text, count=1)
142
+
143
+ separator = "" if text.endswith("\n") else "\n"
144
+ return text + separator + line + "\n"
145
+
146
+
147
+ def with_env_ignored(text):
148
+ """The new .gitignore text that ignores .env, or None when it already does."""
149
+ lines = [] if text is None else text.splitlines()
150
+ for line in lines:
151
+ trimmed = line.strip()
152
+ if trimmed and not trimmed.startswith("#") and not trimmed.startswith("!") and trimmed in COVERED:
153
+ return None
154
+
155
+ if not text:
156
+ return ".env\n"
157
+
158
+ separator = "" if text.endswith("\n") else "\n"
159
+ return text + separator + ".env\n"
160
+
161
+
162
+ def read_if_present(path):
163
+ try:
164
+ with open(path, "r", encoding="utf-8", newline="") as handle:
165
+ return handle.read()
166
+ except FileNotFoundError:
167
+ return None
168
+
169
+
170
+ # -- the AI client -------------------------------------------------------
171
+
172
+
173
+ def wrapper_line(language):
174
+ """The import line init adds, in the project's language."""
175
+ return "import tragac" if language == "python" else 'import tragac from "tragac";'
176
+
177
+
178
+ def wrap_call(language):
179
+ """Where to wrap the client, for the project's language."""
180
+ if language == "python":
181
+ return "client = tragac.wrap(your_client, customer_id=lambda: current_user.id)"
182
+ return "const client = tragac.wrap(yourClient, { customerId: () => currentUser.id });"
183
+
184
+
185
+ def client_import_in(text, language):
186
+ """The import that names an AI client in one file, or None."""
187
+ pattern = PYTHON_CLIENTS if language == "python" else NODE_CLIENTS
188
+ wrapper = wrapper_line(language)
189
+ lines = text.splitlines()
190
+
191
+ for index, line in enumerate(lines):
192
+ match = pattern.search(line)
193
+ if not match:
194
+ continue
195
+
196
+ groups = [group for group in match.groups() if group]
197
+ return {
198
+ "line": index + 1,
199
+ "text": line.strip(),
200
+ "provider": groups[0] if groups else "",
201
+ "already_imported": any(candidate.strip() == wrapper for candidate in lines),
202
+ }
203
+
204
+ return None
205
+
206
+
207
+ def find_client_import(cwd, language):
208
+ """Walk the project for the first AI client import, skipping build folders."""
209
+ extensions = PYTHON_EXTENSIONS if language == "python" else NODE_EXTENSIONS
210
+ matches = []
211
+ scanned = 0
212
+ stack = [cwd]
213
+
214
+ while stack and scanned < MAX_FILES:
215
+ directory = stack.pop()
216
+
217
+ try:
218
+ entries = sorted(os.listdir(directory))
219
+ except OSError:
220
+ continue
221
+
222
+ for name in entries:
223
+ full = os.path.join(directory, name)
224
+
225
+ if os.path.isdir(full):
226
+ if name not in SKIP_DIRS:
227
+ stack.append(full)
228
+ continue
229
+
230
+ if not os.path.isfile(full) or not name.endswith(extensions):
231
+ continue
232
+ if name.endswith(".d.ts"):
233
+ continue
234
+
235
+ scanned += 1
236
+
237
+ try:
238
+ if os.path.getsize(full) > MAX_READ:
239
+ continue
240
+ with open(full, "r", encoding="utf-8", errors="replace", newline="") as handle:
241
+ text = handle.read()
242
+ except OSError:
243
+ continue
244
+
245
+ found = client_import_in(text, language)
246
+ if not found:
247
+ continue
248
+
249
+ matches.append(dict(found, file=os.path.relpath(full, cwd), path=full))
250
+ if len(matches) >= 5:
251
+ return matches
252
+
253
+ return matches or None
254
+
255
+
256
+ # -- the engine ----------------------------------------------------------
257
+
258
+
259
+ def request_id(prefix):
260
+ return prefix + uuid.uuid4().hex
261
+
262
+
263
+ def evaluate_body(check_id):
264
+ return {
265
+ "customer_id": INIT_CUSTOMER_ID,
266
+ "request_id": check_id,
267
+ "provider": CHECK_PROVIDER,
268
+ "requested_model": CHECK_MODEL,
269
+ "timestamp": datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
270
+ "customer_name": "Tragac init check",
271
+ }
272
+
273
+
274
+ def post_json(path, body, timeout, api_key, base=DEFAULT_API_BASE):
275
+ """POST JSON to Tragac. Raises OSError when the network produced no answer."""
276
+ payload = json.dumps(body, separators=(",", ":")).encode("utf-8")
277
+ request = urllib.request.Request(
278
+ base.rstrip("/") + path,
279
+ data=payload,
280
+ method="POST",
281
+ headers={
282
+ "Content-Type": "application/json",
283
+ "Accept": "application/json",
284
+ "Authorization": "Bearer " + api_key,
285
+ "User-Agent": USER_AGENT,
286
+ },
287
+ )
288
+
289
+ try:
290
+ with urllib.request.urlopen(request, timeout=timeout) as response:
291
+ status = response.status
292
+ raw = response.read()
293
+ except urllib.error.HTTPError as error:
294
+ status = error.code
295
+ raw = error.read()
296
+ except Exception as error: # noqa: BLE001 - every network failure is the same here
297
+ raise OSError("Tragac is unreachable") from error
298
+
299
+ try:
300
+ answer = json.loads(raw.decode("utf-8") or "{}")
301
+ except ValueError:
302
+ answer = None
303
+
304
+ return status, answer
305
+
306
+
307
+ def run_integration_checks(api_key, post=None, base=DEFAULT_API_BASE, clock=None):
308
+ """The Connect page's six checks, run with the project's own key.
309
+
310
+ The page can read the panel's rows directly; a command line only has the key,
311
+ so credits and visibility are read from the evaluate answer instead: an ALLOW
312
+ decision means the customer's credits allowed the call, and the echoed request
313
+ id means the decision was stored.
314
+ """
315
+ post = post or post_json
316
+ clock = clock or (lambda: 0.0)
317
+ send = lambda path, body, timeout: post(path, body, timeout, api_key, base) # noqa: E731
318
+
319
+ results = [
320
+ {"id": check_id, "label": label, "passed": False, "reason": reason}
321
+ for check_id, label, reason in CHECKS
322
+ ]
323
+ by_id = {result["id"]: result for result in results}
324
+
325
+ check_id = request_id("init_")
326
+ status = 0
327
+ answer = None
328
+ replied = False
329
+
330
+ started = clock()
331
+ try:
332
+ status, answer = send(EVALUATE_PATH, evaluate_body(check_id), WAIT_SECONDS)
333
+ replied = True
334
+ except OSError:
335
+ replied = False
336
+ elapsed = clock() - started
337
+
338
+ authenticated = replied and status != 401
339
+ by_id["key"]["passed"] = authenticated
340
+ by_id["connection"]["passed"] = replied and elapsed <= WAIT_SECONDS
341
+ by_id["customer"]["passed"] = bool(
342
+ authenticated and isinstance(answer, dict) and answer.get("customer_id") == INIT_CUSTOMER_ID
343
+ )
344
+
345
+ allowed = bool(
346
+ isinstance(answer, dict) and answer.get("decision") == "ALLOW" and answer.get("decision_id")
347
+ )
348
+
349
+ if replied and authenticated and allowed and isinstance(answer.get("effective_model"), str):
350
+ try:
351
+ usage_status, usage_answer = send(
352
+ USAGE_PATH,
353
+ {
354
+ "request_id": check_id,
355
+ "status": "success",
356
+ "provider": CHECK_PROVIDER,
357
+ "actual_model": answer["effective_model"],
358
+ "input_tokens": 12,
359
+ "output_tokens": 8,
360
+ "attempt": 1,
361
+ },
362
+ USAGE_TIMEOUT,
363
+ )
364
+ passed = usage_status == 200 and isinstance(usage_answer, dict) and usage_answer.get("accepted") is True
365
+ by_id["usage"]["passed"] = passed
366
+
367
+ if not passed and isinstance(usage_answer, dict) and usage_answer.get("error") == "PRICING_UNAVAILABLE":
368
+ by_id["usage"]["reason"] = "Tragac stored the usage but has no price for that model yet."
369
+ except OSError:
370
+ by_id["usage"]["passed"] = False
371
+
372
+ by_id["credits"]["passed"] = allowed
373
+ if not allowed:
374
+ by_id["usage"]["reason"] = "There was no allowed decision to report usage for."
375
+ if replied and authenticated and isinstance(answer, dict) and answer.get("reason"):
376
+ by_id["credits"]["reason"] = "The test request was blocked: %s." % answer["reason"]
377
+
378
+ by_id["visibility"]["passed"] = bool(
379
+ authenticated
380
+ and isinstance(answer, dict)
381
+ and isinstance(answer.get("request_id"), str)
382
+ and answer["request_id"] == check_id
383
+ )
384
+
385
+ return results
386
+
387
+
388
+ # -- the command ---------------------------------------------------------
389
+
390
+
391
+ def plain_check_reason(status):
392
+ if status == 401:
393
+ return "Your key was not accepted."
394
+ if status == 400:
395
+ return "Tragac rejected the check request as invalid."
396
+ return "Tragac answered with an error (%s)." % status
397
+
398
+
399
+ def _ask(prompt):
400
+ return input(prompt).strip()
401
+
402
+
403
+ def _confirm(prompt):
404
+ return input(prompt).strip().lower() in ("y", "yes")
405
+
406
+
407
+ def _secret(prompt):
408
+ try:
409
+ return getpass.getpass(prompt).strip()
410
+ except Exception: # noqa: BLE001 - a terminal without hidden input still works
411
+ return input(prompt).strip()
412
+
413
+
414
+ def init(env=None, ask=None, confirm=None, secret=None, post=None, cwd=None, clock=None, out=None):
415
+ """Run the guided setup and return the exit code."""
416
+ env = os.environ if env is None else env
417
+ ask = ask or _ask
418
+ confirm = confirm or _confirm
419
+ secret = secret or _secret
420
+ cwd = cwd or os.getcwd()
421
+ out = out or (lambda line: print(line))
422
+
423
+ def send(path, body, timeout):
424
+ return (post or post_json)(path, body, timeout, key, base)
425
+
426
+ try:
427
+ # 1. The key, from the environment or typed. Only the first eight
428
+ # characters and a fixed mask are ever shown.
429
+ key = normalise_key(env.get("TRAGAC_KEY"))
430
+ if key:
431
+ out("Using TRAGAC_KEY from your environment: " + mask_key(key))
432
+ else:
433
+ out("Tragac needs your project key. Use your test key first.")
434
+ key = normalise_key(secret("Project key: "))
435
+ if not key:
436
+ out("No key was given. Nothing was changed.")
437
+ return 1
438
+ out("Using project key " + mask_key(key) + ".")
439
+
440
+ # A test key is the default. A live key, or a key that does not say it
441
+ # is a test key, is only used after the user types the word live.
442
+ if key_kind(key) != "test":
443
+ if ask("This is a live key. Type live to confirm: ").strip().lower() != "live":
444
+ out("A live key needs the word live to confirm. Nothing was changed.")
445
+ return 1
446
+
447
+ base = (env.get("TRAGAC_API_BASE") or DEFAULT_API_BASE).strip().rstrip("/")
448
+
449
+ # 2. One evaluate request checks the key. It happens before any file is
450
+ # written, so an unreachable engine leaves the folder untouched.
451
+ try:
452
+ status, answer = send(EVALUATE_PATH, evaluate_body(request_id("init_")), WAIT_SECONDS)
453
+ except OSError:
454
+ out("Tragac is unreachable. Nothing was changed.")
455
+ return 1
456
+
457
+ if status != 200 or not isinstance(answer, dict):
458
+ out(plain_check_reason(status))
459
+ out("Nothing was changed.")
460
+ return 1
461
+
462
+ out("Key works.")
463
+
464
+ # 3. The language comes from the files in this folder.
465
+ detected = detect_language(cwd)
466
+ language = None
467
+
468
+ if detected["node"] and detected["python"]:
469
+ choice = ask("This folder looks like Node and Python. Which do you use? Type node or python: ").strip().lower()
470
+ if choice not in ("node", "python"):
471
+ out("I could not tell the language. Nothing was changed.")
472
+ return 1
473
+ language = choice
474
+ elif detected["node"]:
475
+ language = "node"
476
+ elif detected["python"]:
477
+ language = "python"
478
+ else:
479
+ out("This folder has no package.json, requirements.txt or pyproject.toml, so I cannot tell the language.")
480
+ out("Nothing was changed.")
481
+ return 1
482
+
483
+ out("Setting up for " + ("Node" if language == "node" else "Python") + ".")
484
+
485
+ # 4. The key goes into .env, and nowhere else. The change is shown first.
486
+ env_file = os.path.join(cwd, ".env")
487
+ next_env = with_key(read_if_present(env_file), key)
488
+
489
+ if next_env is None:
490
+ out(".env already has this TRAGAC_KEY.")
491
+ else:
492
+ out("")
493
+ out("In .env:")
494
+ out(" TRAGAC_KEY=" + mask_key(key))
495
+
496
+ if not confirm("Write this to .env? [y/N] "):
497
+ out(".env was left unchanged. Nothing else was written.")
498
+ return 1
499
+
500
+ with open(env_file, "w", encoding="utf-8", newline="") as handle:
501
+ handle.write(next_env)
502
+ out(".env is set.")
503
+
504
+ # 5. .env must never be committed.
505
+ ignore_file = os.path.join(cwd, ".gitignore")
506
+ next_ignore = with_env_ignored(read_if_present(ignore_file))
507
+
508
+ if next_ignore is None:
509
+ out(".env is already ignored by .gitignore.")
510
+ else:
511
+ out("")
512
+ out("In .gitignore:")
513
+ out(" .env")
514
+
515
+ if confirm("Write this to .gitignore? [y/N] "):
516
+ with open(ignore_file, "w", encoding="utf-8", newline="") as handle:
517
+ handle.write(next_ignore)
518
+ out(".gitignore ignores .env.")
519
+ else:
520
+ out("Your key is in .env, which is not ignored. Add .env to .gitignore before committing.")
521
+
522
+ # 6. One line beside the AI client the project already uses. The line is
523
+ # shown first and the file is only edited after a yes.
524
+ wrapper = wrapper_line(language)
525
+ matches = find_client_import(cwd, language)
526
+
527
+ out("")
528
+
529
+ if not matches:
530
+ out("No AI client was found, so no file was changed.")
531
+ out("Add this line below your AI client's import:")
532
+ out(" " + wrapper)
533
+ out("Then wrap the client where you create it:")
534
+ out(" " + wrap_call(language))
535
+ else:
536
+ client = matches[0]
537
+
538
+ out("Found an AI client import:")
539
+ out(" %s:%s" % (client["file"], client["line"]))
540
+ out(" " + client["text"])
541
+
542
+ if client["already_imported"]:
543
+ out("Tragac is already imported in that file.")
544
+ else:
545
+ out("Add below that import:")
546
+ out(" " + wrapper)
547
+
548
+ if confirm("Edit %s? [y/N] " % client["file"]):
549
+ text = read_if_present(client["path"]) or ""
550
+ eol = "\r\n" if "\r\n" in text else "\n"
551
+ lines = text.split(eol)
552
+ lines.insert(client["line"], wrapper)
553
+ with open(client["path"], "w", encoding="utf-8", newline="") as handle:
554
+ handle.write(eol.join(lines))
555
+ out("%s imports Tragac." % client["file"])
556
+ else:
557
+ out("%s was left unchanged." % client["file"])
558
+
559
+ if len(matches) > 1:
560
+ out(
561
+ "There %s %d more AI client import%s in this folder."
562
+ % ("is" if len(matches) == 2 else "are", len(matches) - 1, "" if len(matches) == 2 else "s")
563
+ )
564
+
565
+ out("Then wrap the client where you create it:")
566
+ out(" " + wrap_call(language))
567
+
568
+ # 7. The same six checks the Connect page runs.
569
+ out("")
570
+ out("Running the integration test:")
571
+
572
+ results = run_integration_checks(key, post=post, base=base, clock=clock)
573
+ for result in results:
574
+ out(" %s %s" % ("\u2713" if result["passed"] else "\u2717", result["label"]))
575
+
576
+ failed = next((result for result in results if not result["passed"]), None)
577
+ out("")
578
+
579
+ if failed:
580
+ out(failed["reason"])
581
+ return 1
582
+
583
+ out("Setup complete")
584
+ return 0
585
+ finally:
586
+ close = getattr(out, "close", None)
587
+ if callable(close):
588
+ close()
589
+
590
+
591
+ def main(argv=None):
592
+ argv = sys.argv[1:] if argv is None else argv
593
+ command = argv[0] if argv else ""
594
+
595
+ if command == "init":
596
+ return init()
597
+ if command in ("", "help", "--help", "-h"):
598
+ sys.stdout.write(USAGE_TEXT)
599
+ return 0
600
+
601
+ sys.stderr.write("Unknown command: %s\n\n%s" % (command, USAGE_TEXT))
602
+ return 1
603
+
604
+
605
+ if __name__ == "__main__":
606
+ sys.exit(main())