entitybind 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.
@@ -0,0 +1,900 @@
1
+ """Entity Bind - Core API commands: resolve, quote, discover, jobs, usage,
2
+ billing, keys and decisions.
3
+
4
+ With --json each command prints the server's JSON body unchanged (a few wrap
5
+ it, as documented in docs/AGENT-CLI.md). Without --json it prints a short
6
+ summary for a person.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import csv
12
+ import io
13
+ import json
14
+ import re
15
+ from collections.abc import Iterable
16
+ from datetime import datetime, timezone
17
+ from pathlib import Path
18
+ from typing import Any
19
+ from urllib.parse import quote
20
+
21
+ from entitybind.context import Context
22
+ from entitybind.errors import (
23
+ EXIT_CONFLICT,
24
+ EXIT_NOT_FOUND,
25
+ EXIT_OK,
26
+ EXIT_RATE_LIMITED,
27
+ EXIT_SERVER,
28
+ ApiError,
29
+ CliError,
30
+ NetworkError,
31
+ PendingError,
32
+ UsageError,
33
+ )
34
+ from entitybind.files import atomic_write
35
+ from entitybind.http import ApiClient, ApiResponse, new_idempotency_key, retry_after_seconds
36
+ from entitybind.products import ADMIN_KEY_ENV, CORE, is_safe_browser_url
37
+ from entitybind.records import (
38
+ LoadedRecords,
39
+ chunked,
40
+ load_csv,
41
+ load_json_records,
42
+ not_utf8,
43
+ read_text,
44
+ unreadable,
45
+ )
46
+ from entitybind.submissions import SubmissionStore, submission_digest
47
+
48
+ # The synchronous resolve runs under a 300-second server deadline.
49
+ SYNC_RESOLVE_TIMEOUT = 330.0
50
+ TERMINAL_STATES = frozenset(
51
+ {"succeeded", "failed", "cancelled", "reconciliation_required", "erased"}
52
+ )
53
+ STATE_EXIT_CODES = {
54
+ "succeeded": EXIT_OK,
55
+ "failed": EXIT_SERVER,
56
+ "reconciliation_required": EXIT_SERVER,
57
+ "cancelled": EXIT_CONFLICT,
58
+ "erased": EXIT_NOT_FOUND,
59
+ }
60
+ RECORD_FLAGS = (
61
+ "name",
62
+ "country",
63
+ "domain",
64
+ "website",
65
+ "registration_number",
66
+ "jurisdiction",
67
+ "lei",
68
+ "vat_number",
69
+ "duns",
70
+ "ticker",
71
+ "exchange",
72
+ "context",
73
+ "email",
74
+ "phone",
75
+ "client_ref",
76
+ "postcode",
77
+ )
78
+ CSV_COLUMNS = (
79
+ "client_ref",
80
+ "record_id",
81
+ "decision",
82
+ "stage",
83
+ "match_confidence",
84
+ "entity_id",
85
+ "decision_id",
86
+ "review_id",
87
+ "entity_created",
88
+ "more_input_needed",
89
+ )
90
+ _DURATION = re.compile(r"^\s*(\d+)\s*([smhdw]?)\s*$")
91
+ _DURATION_SECONDS = {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
92
+ # The lifetimes `POST /v1/admin/keys` accepts as `expires_in_seconds` (core-keys).
93
+ MIN_KEY_LIFETIME = 3_600
94
+ MAX_KEY_LIFETIME = 31_536_000
95
+
96
+
97
+ def segment(value: str) -> str:
98
+ """One URL path segment, so an identifier can never change the route."""
99
+ cleaned = (value or "").strip()
100
+ if not cleaned:
101
+ raise UsageError("an identifier is required")
102
+ if set(cleaned) == {"."}:
103
+ # quote() leaves dots alone, and "." or ".." would be removed as a path step.
104
+ raise UsageError(f"{cleaned!r} is not an identifier")
105
+ return quote(cleaned, safe="")
106
+
107
+
108
+ def _load_json(path: str, ctx: Context) -> Any:
109
+ text = read_text(path, ctx.runtime.stdin)
110
+ try:
111
+ return json.loads(text)
112
+ except ValueError:
113
+ raise UsageError(f"{path} is not valid JSON") from None
114
+
115
+
116
+ def _load_object(path: str, ctx: Context) -> dict[str, Any]:
117
+ value = _load_json(path, ctx)
118
+ if not isinstance(value, dict):
119
+ raise UsageError(f"{path} must hold a JSON object")
120
+ return value
121
+
122
+
123
+ def record_from_args(ctx: Context, *, require: bool = True) -> dict[str, Any]:
124
+ args = ctx.args
125
+ record: dict[str, Any] = _load_object(args.input, ctx) if args.input else {}
126
+ for name in RECORD_FLAGS:
127
+ value = getattr(args, name, None)
128
+ if value is not None:
129
+ record[name] = value
130
+ if getattr(args, "city", None):
131
+ address = dict(record.get("address") or {})
132
+ address["city"] = args.city
133
+ record["address"] = address
134
+ if getattr(args, "depth", None):
135
+ record["depth"] = args.depth
136
+ if getattr(args, "no_enrich", False):
137
+ record["enrich"] = False
138
+ if getattr(args, "fields", None):
139
+ record["fields"] = [item.strip() for item in args.fields.split(",") if item.strip()]
140
+ if getattr(args, "field_pack", None):
141
+ record["field_packs"] = list(args.field_pack)
142
+ if require:
143
+ missing = [key for key in ("name", "country") if not str(record.get(key) or "").strip()]
144
+ if missing:
145
+ raise UsageError(
146
+ f"a record needs {' and '.join(missing)}: pass --name and --country, "
147
+ "or --input with a JSON record"
148
+ )
149
+ return record
150
+
151
+
152
+ def _print_outcome(ctx: Context, body: Any) -> None:
153
+ if not isinstance(body, dict):
154
+ ctx.output.data(body)
155
+ return
156
+ entity = body.get("entity") if isinstance(body.get("entity"), dict) else {}
157
+ usage = body.get("usage") if isinstance(body.get("usage"), dict) else {}
158
+ values = {
159
+ "decision": body.get("decision"),
160
+ "stage": body.get("stage"),
161
+ "match_confidence": body.get("match_confidence"),
162
+ "entity_id": entity.get("entity_id") if entity else None,
163
+ "decision_id": body.get("decision_id"),
164
+ "review_id": body.get("review_id"),
165
+ "client_ref": body.get("client_ref"),
166
+ "candidates_considered": body.get("candidates_considered"),
167
+ "more_input_needed": body.get("more_input_needed") or None,
168
+ "credits_charged": usage.get("credits_charged") if usage else None,
169
+ "credits_remaining": usage.get("credits_remaining") if usage else None,
170
+ }
171
+ ctx.output.fields(values)
172
+ ctx.output.info("(use --json for the full response)")
173
+
174
+
175
+ def _print_job(ctx: Context, view: Any) -> None:
176
+ if not isinstance(view, dict):
177
+ ctx.output.data(view)
178
+ return
179
+ ctx.output.fields(
180
+ view, ["job_id", "state", "total_records", "created_at", "finished_at", "error_code"]
181
+ )
182
+
183
+
184
+ def job_paths(job_id: str) -> tuple[str, str, str]:
185
+ """Status, result and cancel paths. Resolve jobs (rjob…) live under /v1/resolve-jobs."""
186
+ seg = segment(job_id)
187
+ if job_id.strip().startswith("rjob"):
188
+ base = f"/v1/resolve-jobs/{seg}"
189
+ return base, f"{base}/results", f"{base}/cancel"
190
+ base = f"/v1/batch-jobs/{seg}"
191
+ return base, f"{base}/result", f"{base}/cancel"
192
+
193
+
194
+ def _transient(error: CliError) -> bool:
195
+ """A failed status read that says nothing about the job: polling carries on."""
196
+ if isinstance(error, NetworkError):
197
+ return True
198
+ if isinstance(error, ApiError):
199
+ return error.status >= 500 or (error.status == 429 and error.exit_code == EXIT_RATE_LIMITED)
200
+ return False
201
+
202
+
203
+ def wait_for_job(
204
+ ctx: Context, client: ApiClient, job_id: str, *, deadline: float, interval: float
205
+ ) -> dict[str, Any]:
206
+ """Poll until the job is terminal or `deadline` passes (then exit 9).
207
+
208
+ A 5xx, a rate limit or a network failure while polling is not the job's
209
+ outcome (the job keeps running through a release or a dropped connection),
210
+ so it is retried with the same backoff until the deadline.
211
+ """
212
+ status_path = job_paths(job_id)[0]
213
+ now = ctx.runtime.now
214
+ delay = max(0.5, interval)
215
+ view: dict[str, Any] = {}
216
+ last_error: CliError | None = None
217
+ while True:
218
+ advised: float | None = None
219
+ try:
220
+ response = client.get(status_path)
221
+ except CliError as error:
222
+ if not _transient(error):
223
+ raise
224
+ last_error = error
225
+ else:
226
+ last_error = None
227
+ view = response.body if isinstance(response.body, dict) else {}
228
+ if view.get("state") in TERMINAL_STATES:
229
+ return view
230
+ advised = retry_after_seconds(response.headers, now)
231
+ remaining = deadline - now()
232
+ if remaining <= 0:
233
+ data: dict[str, Any] = {"job": view}
234
+ message = f"job {job_id} is still {view.get('state') or 'pending'}"
235
+ if last_error is not None:
236
+ data["last_error"] = {"code": last_error.code, "message": last_error.message}
237
+ message += f" (the last status request failed: {last_error.code})"
238
+ raise PendingError(
239
+ message,
240
+ code="job_pending",
241
+ hint=f"run `entitybind jobs wait {job_id}` to keep waiting",
242
+ data=data,
243
+ )
244
+ ctx.runtime.sleep(min(max(advised if advised is not None else delay, 0.5), remaining))
245
+ delay = min(delay * 1.5, 15.0)
246
+
247
+
248
+ def _add_hint(error: CliError, advice: str) -> None:
249
+ error.hint = f"{error.hint}; {advice}" if error.hint else advice
250
+
251
+
252
+ def _retry_safely(error: CliError) -> None:
253
+ """After a timeout or 5xx the work may have run: say how to retry without repeating it."""
254
+ key = error.data.get("idempotency_key")
255
+ uncertain = isinstance(error, NetworkError) or (
256
+ isinstance(error, ApiError) and error.status >= 500
257
+ )
258
+ if uncertain and isinstance(key, str):
259
+ _add_hint(error, f"to retry without repeating the work, rerun with --idempotency-key {key}")
260
+
261
+
262
+ def _finish_wait(ctx: Context, view: dict[str, Any]) -> int:
263
+ if ctx.output.json_mode:
264
+ ctx.output.data(view)
265
+ else:
266
+ _print_job(ctx, view)
267
+ return STATE_EXIT_CODES.get(str(view.get("state")), EXIT_SERVER)
268
+
269
+
270
+ # --- resolve, quote, discover ---------------------------------------------
271
+
272
+
273
+ def cmd_resolve(ctx: Context) -> int:
274
+ args = ctx.args
275
+ record = record_from_args(ctx)
276
+ if args.wait and not args.async_:
277
+ raise UsageError("--wait applies to --async resolves")
278
+ timeout = None if args.async_ else ctx.http_timeout(SYNC_RESOLVE_TIMEOUT)
279
+ client, _, _ = ctx.authenticated(CORE, timeout=timeout)
280
+ with client:
281
+ path = "/v1/resolve-jobs" if args.async_ else "/v1/resolve"
282
+ try:
283
+ submitted = client.post(path, json_body=record, idempotency_key=args.idempotency_key)
284
+ except CliError as error:
285
+ _retry_safely(error)
286
+ raise
287
+ if not args.async_:
288
+ if ctx.output.json_mode:
289
+ ctx.output.data(submitted.body)
290
+ else:
291
+ _print_outcome(ctx, submitted.body)
292
+ return EXIT_OK
293
+ job = submitted.body if isinstance(submitted.body, dict) else {}
294
+ job_id = job.get("job_id")
295
+ if not args.wait or not isinstance(job_id, str):
296
+ if ctx.output.json_mode:
297
+ ctx.output.data({**job, "idempotency_key": submitted.idempotency_key})
298
+ else:
299
+ _print_job(ctx, job)
300
+ ctx.output.info(f"idempotency key: {submitted.idempotency_key}")
301
+ return EXIT_OK
302
+ deadline = ctx.runtime.now() + args.timeout
303
+ view = wait_for_job(ctx, client, job_id, deadline=deadline, interval=args.interval)
304
+ if view.get("state") != "succeeded":
305
+ return _finish_wait(ctx, view)
306
+ result = client.get(job_paths(job_id)[1])
307
+ if ctx.output.json_mode:
308
+ ctx.output.data(result.body)
309
+ else:
310
+ _print_outcome(ctx, result.body)
311
+ return EXIT_OK
312
+
313
+
314
+ def _check_skipped(ctx: Context, loaded: LoadedRecords, *, action: str) -> None:
315
+ """Rows that cannot be sent are refused unless --skip-invalid."""
316
+ if loaded.skipped and not ctx.args.skip_invalid:
317
+ first = "; ".join(f"line {item['line']}: {item['reason']}" for item in loaded.skipped[:5])
318
+ raise UsageError(
319
+ f"{len(loaded.skipped)} row(s) cannot be sent ({first})",
320
+ hint="fix the rows, add --default-country, or pass --skip-invalid",
321
+ )
322
+ if not loaded.records:
323
+ raise UsageError(f"no records to {action}")
324
+
325
+
326
+ def _quote_body(ctx: Context) -> Any:
327
+ args = ctx.args
328
+ has_flags = any(getattr(args, name, None) is not None for name in RECORD_FLAGS)
329
+ if args.csv:
330
+ loaded = _load_csv_records(ctx)
331
+ _check_skipped(ctx, loaded, action="quote")
332
+ if loaded.skipped:
333
+ ctx.output.info(f"Skipped {len(loaded.skipped)} row(s) without a name or country.")
334
+ return {"records": loaded.records}
335
+ if args.input and not has_flags:
336
+ value = _load_json(args.input, ctx)
337
+ if isinstance(value, list):
338
+ return {"records": value}
339
+ if isinstance(value, dict):
340
+ if args.depth and isinstance(value.get("records"), list):
341
+ for item in value["records"]:
342
+ if isinstance(item, dict):
343
+ item.setdefault("depth", args.depth)
344
+ return value
345
+ raise UsageError(f"{args.input} must hold a JSON object or list")
346
+ return {"records": [record_from_args(ctx)]}
347
+
348
+
349
+ def cmd_quote(ctx: Context) -> int:
350
+ body = _quote_body(ctx)
351
+ client, _, _ = ctx.authenticated(CORE)
352
+ with client:
353
+ response = client.post(
354
+ "/v1/quotes", json_body=body, idempotency_key=ctx.args.idempotency_key
355
+ )
356
+ if ctx.output.json_mode or not isinstance(response.body, dict):
357
+ ctx.output.data(response.body)
358
+ else:
359
+ ctx.output.fields(response.body)
360
+ ctx.output.info("(use --json for the full quote)")
361
+ return EXIT_OK
362
+
363
+
364
+ def cmd_discover(ctx: Context) -> int:
365
+ args = ctx.args
366
+ body: dict[str, Any] = _load_object(args.input, ctx) if args.input else {}
367
+ for name in ("name", "country", "website"):
368
+ value = getattr(args, name, None)
369
+ if value is not None:
370
+ body[name] = value
371
+ missing = [key for key in ("name", "country") if not str(body.get(key) or "").strip()]
372
+ if missing:
373
+ raise UsageError(f"discover needs {' and '.join(missing)}: pass --name and --country")
374
+ client, _, _ = ctx.authenticated(CORE)
375
+ with client:
376
+ response = client.post(
377
+ "/v1/company-discovery", json_body=body, idempotency_key=args.idempotency_key
378
+ )
379
+ if ctx.output.json_mode or not isinstance(response.body, dict):
380
+ ctx.output.data(response.body)
381
+ return EXIT_OK
382
+ candidates = next(
383
+ (
384
+ response.body[key]
385
+ for key in ("candidates", "results", "companies")
386
+ if isinstance(response.body.get(key), list)
387
+ ),
388
+ None,
389
+ )
390
+ if candidates is None:
391
+ ctx.output.data(response.body)
392
+ return EXIT_OK
393
+ ctx.output.line(f"{len(candidates)} candidate(s)")
394
+ for item in candidates:
395
+ if not isinstance(item, dict):
396
+ continue
397
+ name = item.get("name") or item.get("legal_name") or "?"
398
+ ident = item.get("registration_number") or item.get("company_number") or item.get("id")
399
+ status = item.get("status") or item.get("legal_status")
400
+ parts = [str(name)]
401
+ if ident:
402
+ parts.append(str(ident))
403
+ if status:
404
+ parts.append(str(status))
405
+ ctx.output.line(" - " + " | ".join(parts))
406
+ return EXIT_OK
407
+
408
+
409
+ # --- jobs ------------------------------------------------------------------
410
+
411
+
412
+ def _load_csv_records(ctx: Context) -> LoadedRecords:
413
+ args = ctx.args
414
+ path = Path(args.csv)
415
+ if not path.is_file():
416
+ raise UsageError(f"file not found: {args.csv}")
417
+ try:
418
+ with path.open(encoding="utf-8-sig", newline="") as stream:
419
+ return load_csv(
420
+ stream,
421
+ maps=args.map or [],
422
+ default_country=args.default_country,
423
+ key_column=getattr(args, "key_column", None),
424
+ depth=args.depth,
425
+ )
426
+ except UnicodeDecodeError:
427
+ raise not_utf8(args.csv) from None
428
+ except OSError as error:
429
+ raise unreadable(args.csv, error) from None
430
+
431
+
432
+ def _announce_submission(ctx: Context, base_key: str, chunks: int, *, resumed: bool) -> None:
433
+ """Name the idempotency key before the first chunk is sent, in case the run is killed."""
434
+ if ctx.output.json_mode:
435
+ ctx.output.event(
436
+ {
437
+ "event": "jobs_submit",
438
+ "idempotency_key": base_key,
439
+ "chunks": chunks,
440
+ "resumed": resumed,
441
+ }
442
+ )
443
+ return
444
+ note = "; resuming an unfinished submission of this input" if resumed else ""
445
+ ctx.output.info(f"Submitting {chunks} job(s) with idempotency key {base_key}{note}.")
446
+
447
+
448
+ def _interrupted(
449
+ error: CliError,
450
+ base_key: str,
451
+ jobs: list[dict[str, Any]],
452
+ chunks: int,
453
+ *,
454
+ explicit: bool,
455
+ ) -> None:
456
+ """Carry what was accepted, and how to resume, on an error that stops `jobs submit`."""
457
+ accepted = [str(job["job_id"]) for job in jobs if isinstance(job.get("job_id"), str)]
458
+ error.data = {
459
+ **error.data,
460
+ "idempotency_key": base_key,
461
+ "jobs": jobs,
462
+ "chunks": chunks,
463
+ "chunks_accepted": len(jobs),
464
+ }
465
+ if len(jobs) == chunks:
466
+ _add_hint(
467
+ error,
468
+ f"all {chunks} job(s) were accepted and keep running ({', '.join(accepted)}); "
469
+ "run `entitybind jobs wait <job_id>`, or rerun the same command to wait again",
470
+ )
471
+ return
472
+ error.data["failed_chunk"] = len(jobs) + 1
473
+ rerun = (
474
+ f"rerun with the same --idempotency-key {base_key}"
475
+ if explicit
476
+ else f"rerun the same command within 24 hours (or pass --idempotency-key {base_key})"
477
+ )
478
+ _add_hint(
479
+ error,
480
+ f"{len(jobs)} of {chunks} job(s) were accepted ({', '.join(accepted) or 'none'}); "
481
+ f"{rerun} to recover them instead of queueing them again",
482
+ )
483
+
484
+
485
+ def cmd_jobs_submit(ctx: Context) -> int:
486
+ args = ctx.args
487
+ if bool(args.csv) == bool(args.records):
488
+ raise UsageError("pass exactly one of --csv FILE or --records FILE")
489
+ if args.csv:
490
+ loaded = _load_csv_records(ctx)
491
+ else:
492
+ loaded = load_json_records(
493
+ read_text(args.records, ctx.runtime.stdin), args.records, depth=args.depth
494
+ )
495
+ _check_skipped(ctx, loaded, action="submit")
496
+ batches = chunked(loaded.records, args.chunk_size)
497
+ client, _, base_url = ctx.authenticated(CORE)
498
+ # Without --idempotency-key, the key is remembered until the run finishes, so a
499
+ # plain rerun after a failure recovers the accepted jobs instead of duplicating them.
500
+ resumes = None if args.idempotency_key else SubmissionStore(ctx.env, ctx.runtime.now)
501
+ digest = submission_digest(base_url, args.chunk_size, loaded.records)
502
+ resumed = resumes.get(digest) if resumes is not None else None
503
+ base_key = args.idempotency_key or resumed or new_idempotency_key()
504
+ if resumes is not None:
505
+ resumes.put(digest, base_key)
506
+ _announce_submission(ctx, base_key, len(batches), resumed=resumed is not None)
507
+ jobs: list[dict[str, Any]] = []
508
+ with client:
509
+ try:
510
+ for index, batch in enumerate(batches, start=1):
511
+ key = base_key if len(batches) == 1 else f"{base_key}-{index}"
512
+ response = client.post(
513
+ "/v1/batch-jobs", json_body={"records": batch}, idempotency_key=key
514
+ )
515
+ view = response.body if isinstance(response.body, dict) else {}
516
+ jobs.append({**view, "idempotency_key": key})
517
+ except CliError as error:
518
+ _interrupted(error, base_key, jobs, len(batches), explicit=resumes is None)
519
+ raise
520
+ exit_code = EXIT_OK
521
+ if args.wait:
522
+ deadline = ctx.runtime.now() + args.timeout
523
+ finished: list[dict[str, Any]] = []
524
+ try:
525
+ for job in jobs:
526
+ job_id = job.get("job_id")
527
+ if not isinstance(job_id, str):
528
+ finished.append(job)
529
+ continue
530
+ view = wait_for_job(
531
+ ctx, client, job_id, deadline=deadline, interval=args.interval
532
+ )
533
+ finished.append({**view, "idempotency_key": job["idempotency_key"]})
534
+ code = STATE_EXIT_CODES.get(str(view.get("state")), EXIT_SERVER)
535
+ exit_code = exit_code or code
536
+ except CliError as error:
537
+ known = finished + jobs[len(finished) :]
538
+ _interrupted(error, base_key, known, len(batches), explicit=resumes is None)
539
+ raise
540
+ jobs = finished
541
+ if resumes is not None:
542
+ resumes.delete(digest)
543
+ summary = {
544
+ "jobs": jobs,
545
+ "submitted_records": len(loaded.records),
546
+ "skipped": loaded.skipped,
547
+ "idempotency_key": base_key,
548
+ }
549
+ if ctx.output.json_mode:
550
+ ctx.output.data(summary)
551
+ return exit_code
552
+ for job in jobs:
553
+ _print_job(ctx, job)
554
+ ctx.output.line("")
555
+ ctx.output.info(
556
+ f"Submitted {len(loaded.records)} record(s) in {len(jobs)} job(s); "
557
+ f"skipped {len(loaded.skipped)}. Idempotency key: {base_key}"
558
+ )
559
+ return exit_code
560
+
561
+
562
+ def cmd_jobs_list(ctx: Context) -> int:
563
+ args = ctx.args
564
+ client, _, _ = ctx.authenticated(CORE)
565
+ with client:
566
+ response = client.get(
567
+ "/v1/batch-jobs",
568
+ params={"limit": args.limit, "cursor": args.cursor, "state": args.state},
569
+ )
570
+ body = response.body
571
+ if ctx.output.json_mode:
572
+ ctx.output.data(body)
573
+ return EXIT_OK
574
+ items = body.get("jobs") if isinstance(body, dict) else body
575
+ if not isinstance(items, list):
576
+ ctx.output.data(body)
577
+ return EXIT_OK
578
+ for job in items:
579
+ if isinstance(job, dict):
580
+ ctx.output.line(
581
+ f"{job.get('job_id')} {job.get('state')} "
582
+ f"{job.get('total_records')} record(s) {job.get('created_at')}"
583
+ )
584
+ cursor = body.get("next_cursor") if isinstance(body, dict) else None
585
+ if cursor:
586
+ ctx.output.info(f"more: entitybind jobs list --cursor {cursor}")
587
+ return EXIT_OK
588
+
589
+
590
+ def cmd_jobs_get(ctx: Context) -> int:
591
+ client, _, _ = ctx.authenticated(CORE)
592
+ with client:
593
+ response = client.get(job_paths(ctx.args.job_id)[0])
594
+ if ctx.output.json_mode:
595
+ ctx.output.data(response.body)
596
+ else:
597
+ _print_job(ctx, response.body)
598
+ return EXIT_OK
599
+
600
+
601
+ def cmd_jobs_wait(ctx: Context) -> int:
602
+ args = ctx.args
603
+ client, _, _ = ctx.authenticated(CORE)
604
+ deadline = ctx.runtime.now() + args.timeout
605
+ with client:
606
+ view = wait_for_job(ctx, client, args.job_id, deadline=deadline, interval=args.interval)
607
+ return _finish_wait(ctx, view)
608
+
609
+
610
+ def _neutralize(value: Any) -> str:
611
+ if value is None:
612
+ return ""
613
+ if isinstance(value, bool):
614
+ return "true" if value else "false"
615
+ if isinstance(value, str):
616
+ # A cell starting with these is run as a formula by spreadsheet apps.
617
+ return f"'{value}" if value[:1] in ("=", "+", "-", "@", "\t", "\r") else value
618
+ return str(value)
619
+
620
+
621
+ def outcomes_csv(body: Any) -> str:
622
+ if isinstance(body, dict) and isinstance(body.get("outcomes"), list):
623
+ outcomes: Iterable[Any] = body["outcomes"]
624
+ elif isinstance(body, dict):
625
+ outcomes = [body]
626
+ else:
627
+ raise UsageError("the result is not a resolve or batch response, so it has no CSV form")
628
+ buffer = io.StringIO()
629
+ writer = csv.writer(buffer, lineterminator="\n")
630
+ writer.writerow(CSV_COLUMNS)
631
+ for outcome in outcomes:
632
+ if not isinstance(outcome, dict):
633
+ continue
634
+ entity = outcome.get("entity") if isinstance(outcome.get("entity"), dict) else {}
635
+ row = {**outcome, "entity_id": entity.get("entity_id") if entity else None}
636
+ writer.writerow([_neutralize(row.get(column)) for column in CSV_COLUMNS])
637
+ return buffer.getvalue()
638
+
639
+
640
+ def cmd_jobs_results(ctx: Context) -> int:
641
+ args = ctx.args
642
+ client, _, _ = ctx.authenticated(CORE)
643
+ with client:
644
+ if args.wait:
645
+ deadline = ctx.runtime.now() + args.timeout
646
+ view = wait_for_job(ctx, client, args.job_id, deadline=deadline, interval=args.interval)
647
+ if view.get("state") != "succeeded":
648
+ return _finish_wait(ctx, view)
649
+ response: ApiResponse = client.get(job_paths(args.job_id)[1])
650
+ if response.status == 202:
651
+ raise PendingError(
652
+ f"job {args.job_id} has not finished",
653
+ code="job_pending",
654
+ hint=f"run `entitybind jobs results {args.job_id} --wait`",
655
+ data={"job": response.body},
656
+ )
657
+ text = (
658
+ outcomes_csv(response.body)
659
+ if args.format == "csv"
660
+ else json.dumps(response.body, indent=2, ensure_ascii=False) + "\n"
661
+ )
662
+ if args.output:
663
+ target = atomic_write(Path(args.output).expanduser(), text, mode=0o600)
664
+ if ctx.output.json_mode:
665
+ ctx.output.data({"path": str(target), "format": args.format})
666
+ else:
667
+ ctx.output.info(f"Wrote {args.format.upper()} results to {target}")
668
+ return EXIT_OK
669
+ ctx.runtime.stdout.write(text)
670
+ ctx.runtime.stdout.flush()
671
+ return EXIT_OK
672
+
673
+
674
+ def cmd_jobs_cancel(ctx: Context) -> int:
675
+ client, _, _ = ctx.authenticated(CORE)
676
+ with client:
677
+ response = client.post(job_paths(ctx.args.job_id)[2], json_body={})
678
+ if ctx.output.json_mode:
679
+ ctx.output.data(response.body)
680
+ else:
681
+ _print_job(ctx, response.body)
682
+ return EXIT_OK
683
+
684
+
685
+ # --- usage, billing, decisions -------------------------------------------
686
+
687
+
688
+ def cmd_usage(ctx: Context) -> int:
689
+ args = ctx.args
690
+ client, _, _ = ctx.authenticated(CORE)
691
+ with client:
692
+ response = client.get("/v1/usage", params={"since": args.since, "until": args.until})
693
+ body = response.body
694
+ if ctx.output.json_mode or not isinstance(body, dict):
695
+ ctx.output.data(body)
696
+ return EXIT_OK
697
+ period = body.get("period") if isinstance(body.get("period"), dict) else {}
698
+ credits = body.get("credits") if isinstance(body.get("credits"), dict) else {}
699
+ if period:
700
+ ctx.output.line(f"period: {period.get('since')} to {period.get('until')}")
701
+ ctx.output.fields({"calls": body.get("calls")})
702
+ if credits:
703
+ ctx.output.fields({f"credits.{key}": value for key, value in credits.items()})
704
+ ctx.output.info("(use --json for rates, intervals and the stage breakdown)")
705
+ return EXIT_OK
706
+
707
+
708
+ def cmd_billing_status(ctx: Context) -> int:
709
+ client, _, _ = ctx.authenticated(CORE)
710
+ with client:
711
+ response = client.get("/v1/billing")
712
+ if ctx.output.json_mode or not isinstance(response.body, dict):
713
+ ctx.output.data(response.body)
714
+ else:
715
+ ctx.output.fields(response.body)
716
+ return EXIT_OK
717
+
718
+
719
+ def cmd_billing_checkout(ctx: Context) -> int:
720
+ args = ctx.args
721
+ client, _, _ = ctx.authenticated(CORE)
722
+ with client:
723
+ response = client.post(
724
+ "/v1/billing/checkout-sessions",
725
+ json_body={"plan": args.plan},
726
+ idempotency_key=args.idempotency_key,
727
+ )
728
+ body = response.body if isinstance(response.body, dict) else {}
729
+ url = body.get("url") or body.get("checkout_url")
730
+ if ctx.output.json_mode:
731
+ ctx.output.data(response.body)
732
+ elif isinstance(url, str):
733
+ ctx.output.info("Open this link to pay (payment is a step for a person):")
734
+ ctx.output.line(url)
735
+ else:
736
+ ctx.output.data(response.body)
737
+ if args.open and isinstance(url, str) and is_safe_browser_url(url):
738
+ ctx.runtime.open_browser(url)
739
+ return EXIT_OK
740
+
741
+
742
+ def cmd_decisions_get(ctx: Context) -> int:
743
+ client, _, _ = ctx.authenticated(CORE)
744
+ with client:
745
+ response = client.get(f"/v1/decisions/{segment(ctx.args.decision_id)}")
746
+ body = response.body
747
+ if ctx.output.json_mode or not isinstance(body, dict):
748
+ ctx.output.data(body)
749
+ return EXIT_OK
750
+ nested_decision = body.get("decision")
751
+ decision = nested_decision if isinstance(nested_decision, dict) else body
752
+ ctx.output.fields(
753
+ decision,
754
+ ["decision_id", "decision", "stage", "match_confidence", "entity_id", "created_at"],
755
+ )
756
+ ctx.output.info("(use --json for the full receipt)")
757
+ return EXIT_OK
758
+
759
+
760
+ # --- keys ------------------------------------------------------------------
761
+
762
+
763
+ def parse_expiry(expires_in: str | None, expires_at: str | None, now: float) -> int | None:
764
+ """A key lifetime in seconds, as `POST /v1/admin/keys` takes it (`expires_in_seconds`)."""
765
+ if expires_in and expires_at:
766
+ raise UsageError("pass --expires-in or --expires-at, not both")
767
+ if expires_in:
768
+ match = _DURATION.match(expires_in)
769
+ if not match or int(match.group(1)) <= 0:
770
+ raise UsageError("--expires-in takes a positive duration such as 3600, 90m, 12h or 30d")
771
+ seconds = int(match.group(1)) * _DURATION_SECONDS[match.group(2)]
772
+ elif expires_at:
773
+ try:
774
+ moment = datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
775
+ except ValueError:
776
+ raise UsageError(
777
+ "--expires-at must be an ISO 8601 time, e.g. 2027-01-31T00:00:00Z"
778
+ ) from None
779
+ if moment.tzinfo is None:
780
+ moment = moment.replace(tzinfo=timezone.utc)
781
+ seconds = round(moment.timestamp() - now)
782
+ else:
783
+ return None
784
+ if not MIN_KEY_LIFETIME <= seconds <= MAX_KEY_LIFETIME:
785
+ raise UsageError(
786
+ "a key's lifetime must be between one hour and one year "
787
+ f"({MIN_KEY_LIFETIME} to {MAX_KEY_LIFETIME} seconds from now)"
788
+ )
789
+ return seconds
790
+
791
+
792
+ def _tenant_id(ctx: Context, client: ApiClient) -> str:
793
+ if ctx.args.tenant_id:
794
+ return str(ctx.args.tenant_id)
795
+ try:
796
+ body = client.get("/v1/credential").body
797
+ except ApiError as error:
798
+ raise UsageError(
799
+ f"pass --tenant-id (could not read it from GET /v1/credential: {error.code})"
800
+ ) from None
801
+ if isinstance(body, dict) and isinstance(body.get("credential"), dict):
802
+ body = body["credential"]
803
+ tenant = body.get("tenant_id") if isinstance(body, dict) else None
804
+ if not isinstance(tenant, str) or not tenant:
805
+ raise UsageError("pass --tenant-id (GET /v1/credential did not include tenant_id)")
806
+ return tenant
807
+
808
+
809
+ def _admin_client(ctx: Context) -> ApiClient:
810
+ client, _, _ = ctx.authenticated(CORE, override_env=ADMIN_KEY_ENV)
811
+ return client
812
+
813
+
814
+ def cmd_keys_list(ctx: Context) -> int:
815
+ with _admin_client(ctx) as client:
816
+ tenant = _tenant_id(ctx, client)
817
+ response = client.get("/v1/admin/keys", params={"tenant_id": tenant})
818
+ body = response.body
819
+ if ctx.output.json_mode:
820
+ ctx.output.data(body)
821
+ return EXIT_OK
822
+ keys = body.get("keys") if isinstance(body, dict) else None
823
+ if not isinstance(keys, list):
824
+ ctx.output.data(body)
825
+ return EXIT_OK
826
+ for key in keys:
827
+ if isinstance(key, dict):
828
+ state = "active" if key.get("active") else "inactive"
829
+ expires = f" expires {key.get('expires_at')}" if key.get("expires_at") else ""
830
+ ctx.output.line(
831
+ f"{key.get('key_id')} {key.get('name')} {key.get('scope')} "
832
+ f"{key.get('plan')} {state}{expires}"
833
+ )
834
+ return EXIT_OK
835
+
836
+
837
+ def _print_issued(ctx: Context, body: Any, verb: str) -> None:
838
+ if ctx.output.json_mode or not isinstance(body, dict):
839
+ ctx.output.data(body)
840
+ return
841
+ nested_key = body.get("key")
842
+ key = nested_key if isinstance(nested_key, dict) else {}
843
+ ctx.output.info(
844
+ f"{verb} key {key.get('key_id')} ({key.get('name')}, scope {key.get('scope')}). "
845
+ "The key is shown once; store it now:"
846
+ )
847
+ secret = body.get("api_key")
848
+ if isinstance(secret, str):
849
+ ctx.output.line(secret)
850
+ superseded = body.get("superseded")
851
+ if isinstance(superseded, dict) and superseded.get("expires_at"):
852
+ ctx.output.info(f"The old key stops working at {superseded.get('expires_at')}.")
853
+
854
+
855
+ def cmd_keys_create(ctx: Context) -> int:
856
+ args = ctx.args
857
+ lifetime = parse_expiry(args.expires_in, args.expires_at, ctx.runtime.now())
858
+ if args.credit_limit is not None and args.credit_limit < 0:
859
+ raise UsageError("--credit-limit must be zero or more")
860
+ with _admin_client(ctx) as client:
861
+ body: dict[str, Any] = {
862
+ "tenant_id": _tenant_id(ctx, client),
863
+ "name": args.name,
864
+ "scope": args.scope,
865
+ }
866
+ if args.plan:
867
+ body["plan"] = args.plan
868
+ if lifetime is not None:
869
+ body["expires_in_seconds"] = lifetime
870
+ if args.credit_limit is not None:
871
+ body["credit_limit"] = args.credit_limit
872
+ if args.max_depth:
873
+ body["max_depth"] = args.max_depth
874
+ response = client.post("/v1/admin/keys", json_body=body)
875
+ _print_issued(ctx, response.body, "Created")
876
+ return EXIT_OK
877
+
878
+
879
+ def cmd_keys_rotate(ctx: Context) -> int:
880
+ args = ctx.args
881
+ payload: dict[str, Any] = {}
882
+ if args.grace_seconds is not None:
883
+ if args.grace_seconds < 0:
884
+ raise UsageError("--grace-seconds must be zero or more")
885
+ payload["grace_seconds"] = args.grace_seconds
886
+ with _admin_client(ctx) as client:
887
+ response = client.post(f"/v1/admin/keys/{segment(args.key_id)}/rotate", json_body=payload)
888
+ _print_issued(ctx, response.body, "Rotated; new")
889
+ return EXIT_OK
890
+
891
+
892
+ def cmd_keys_revoke(ctx: Context) -> int:
893
+ with _admin_client(ctx) as client:
894
+ response = client.delete(f"/v1/admin/keys/{segment(ctx.args.key_id)}")
895
+ body = response.body
896
+ if ctx.output.json_mode or not isinstance(body, dict):
897
+ ctx.output.data(body)
898
+ else:
899
+ ctx.output.fields(body, ["key_id", "name", "scope", "active", "revoked"])
900
+ return EXIT_OK