truthlock-io 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.
- truthlock_io/__init__.py +36 -0
- truthlock_io/cli.py +194 -0
- truthlock_io/client.py +249 -0
- truthlock_io/errors.py +47 -0
- truthlock_io/models.py +126 -0
- truthlock_io/py.typed +0 -0
- truthlock_io/webhooks.py +103 -0
- truthlock_io-0.1.0.dist-info/METADATA +140 -0
- truthlock_io-0.1.0.dist-info/RECORD +13 -0
- truthlock_io-0.1.0.dist-info/WHEEL +4 -0
- truthlock_io-0.1.0.dist-info/entry_points.txt +2 -0
- truthlock_io-0.1.0.dist-info/licenses/LICENSE +202 -0
- truthlock_io-0.1.0.dist-info/licenses/NOTICE +2 -0
truthlock_io/__init__.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""TruthLock: standing verification for AI responses."""
|
|
2
|
+
|
|
3
|
+
from truthlock_io.client import TruthLock
|
|
4
|
+
from truthlock_io.errors import (
|
|
5
|
+
ApiError,
|
|
6
|
+
AuthenticationError,
|
|
7
|
+
NotFound,
|
|
8
|
+
PaymentRequired,
|
|
9
|
+
RateLimited,
|
|
10
|
+
TruthLockError,
|
|
11
|
+
VerificationTimeout,
|
|
12
|
+
WebhookSignatureError,
|
|
13
|
+
)
|
|
14
|
+
from truthlock_io.models import Accepted, Answer, Decision, Record
|
|
15
|
+
from truthlock_io.webhooks import WebhookEvent, parse_webhook, verify_signature
|
|
16
|
+
|
|
17
|
+
__version__ = "0.1.0"
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"Accepted",
|
|
21
|
+
"Answer",
|
|
22
|
+
"ApiError",
|
|
23
|
+
"AuthenticationError",
|
|
24
|
+
"Decision",
|
|
25
|
+
"NotFound",
|
|
26
|
+
"PaymentRequired",
|
|
27
|
+
"RateLimited",
|
|
28
|
+
"Record",
|
|
29
|
+
"TruthLock",
|
|
30
|
+
"TruthLockError",
|
|
31
|
+
"VerificationTimeout",
|
|
32
|
+
"WebhookEvent",
|
|
33
|
+
"WebhookSignatureError",
|
|
34
|
+
"parse_webhook",
|
|
35
|
+
"verify_signature",
|
|
36
|
+
]
|
truthlock_io/cli.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""The ``truthlock`` command: the SDK from a shell, with ``--json`` for piping.
|
|
2
|
+
|
|
3
|
+
truthlock verify --org field-service --file answer.txt --json | jq .overall.grade
|
|
4
|
+
truthlock may 3f2a... publish # exit 0 only when the decision is allow
|
|
5
|
+
truthlock attest 3f2a... --export bundle.zip
|
|
6
|
+
|
|
7
|
+
The key comes from TRUTHLOCK_API_KEY, the organization from --org or
|
|
8
|
+
TRUTHLOCK_ORGANIZATION, and the address from --url or TRUTHLOCK_URL.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import json
|
|
15
|
+
import sys
|
|
16
|
+
from collections.abc import Sequence
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from truthlock_io import __version__
|
|
21
|
+
from truthlock_io.client import TruthLock
|
|
22
|
+
from truthlock_io.errors import ApiError, TruthLockError, WebhookSignatureError
|
|
23
|
+
from truthlock_io.models import Record
|
|
24
|
+
from truthlock_io.webhooks import parse_webhook
|
|
25
|
+
|
|
26
|
+
EXIT_OK, EXIT_NO, EXIT_ERROR = 0, 1, 2
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _parser() -> argparse.ArgumentParser:
|
|
30
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
31
|
+
common.add_argument("--org", help="organization slug (or TRUTHLOCK_ORGANIZATION)")
|
|
32
|
+
common.add_argument("--url", help="API address (or TRUTHLOCK_URL)")
|
|
33
|
+
common.add_argument("--json", action="store_true", help="print the full JSON")
|
|
34
|
+
|
|
35
|
+
p = argparse.ArgumentParser(prog="truthlock", description="TruthLock from the shell.")
|
|
36
|
+
p.add_argument("--version", action="version", version=f"truthlock {__version__}")
|
|
37
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
38
|
+
|
|
39
|
+
v = sub.add_parser("verify", parents=[common], help="verify an AI response")
|
|
40
|
+
source = v.add_mutually_exclusive_group(required=True)
|
|
41
|
+
source.add_argument("--file", help="file holding the response; - reads standard input")
|
|
42
|
+
source.add_argument("--text", help="the response itself")
|
|
43
|
+
v.add_argument("--question", help="what was asked")
|
|
44
|
+
v.add_argument("--external-id", help="your own id for this response")
|
|
45
|
+
v.add_argument("--operation", help="decide reliance for this operation as part of the run")
|
|
46
|
+
v.add_argument("--webhook-url", help="where to send the signed completion event")
|
|
47
|
+
v.add_argument("--no-wait", action="store_true", help="print the id and return at once")
|
|
48
|
+
v.add_argument("--timeout", type=float, default=300.0, help="seconds to wait (default 300)")
|
|
49
|
+
|
|
50
|
+
g = sub.add_parser("get", parents=[common], help="fetch a verification")
|
|
51
|
+
g.add_argument("id")
|
|
52
|
+
|
|
53
|
+
w = sub.add_parser("wait", parents=[common], help="wait for a verification to finish")
|
|
54
|
+
w.add_argument("id")
|
|
55
|
+
w.add_argument("--timeout", type=float, default=300.0)
|
|
56
|
+
|
|
57
|
+
m = sub.add_parser(
|
|
58
|
+
"may", parents=[common], help="may this record be relied on? exit 0 only for allow"
|
|
59
|
+
)
|
|
60
|
+
m.add_argument("id")
|
|
61
|
+
m.add_argument("operation")
|
|
62
|
+
|
|
63
|
+
a = sub.add_parser("attest", parents=[common], help="the record's attestations, or its bundle")
|
|
64
|
+
a.add_argument("id")
|
|
65
|
+
a.add_argument("--export", metavar="ZIP", help="save record, evidence, proof and signature")
|
|
66
|
+
|
|
67
|
+
r = sub.add_parser("respond", parents=[common], help="ask the organization's responder")
|
|
68
|
+
r.add_argument("question")
|
|
69
|
+
r.add_argument("--grounded", action="store_true", help="answer from published sources")
|
|
70
|
+
|
|
71
|
+
d = sub.add_parser("deliveries", parents=[common], help="webhook deliveries for a record")
|
|
72
|
+
d.add_argument("id")
|
|
73
|
+
|
|
74
|
+
wh = sub.add_parser("webhook-verify", help="check a captured webhook body and signature")
|
|
75
|
+
wh.add_argument("--body", required=True, help="file holding the raw body; - for stdin")
|
|
76
|
+
wh.add_argument("--signature", required=True, help="the TruthLock-Signature header")
|
|
77
|
+
wh.add_argument("--secret", required=True, help="the key's webhook secret (whsec_...)")
|
|
78
|
+
wh.add_argument("--tolerance", type=int, default=300, help="max age in seconds; 0 = any")
|
|
79
|
+
wh.add_argument("--json", action="store_true")
|
|
80
|
+
return p
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _read(path: str) -> str:
|
|
84
|
+
if path == "-":
|
|
85
|
+
return sys.stdin.read()
|
|
86
|
+
with open(path, encoding="utf-8") as handle:
|
|
87
|
+
return handle.read()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _emit(value: Any) -> None:
|
|
91
|
+
print(json.dumps(value, indent=2, default=str))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _summary(record: Record) -> str:
|
|
95
|
+
if record.status == "failed":
|
|
96
|
+
return f"{record.id} failed: {record.error or 'unknown error'}"
|
|
97
|
+
if not record.finished:
|
|
98
|
+
return f"{record.id} {record.status}"
|
|
99
|
+
lines = [f"{record.id} {record.grade or 'NO_CLAIMS'} ({len(record.claims)} claims)"]
|
|
100
|
+
lines += [f" - {c}" for c in record.caveats()]
|
|
101
|
+
return "\n".join(lines)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _client(args: argparse.Namespace) -> TruthLock:
|
|
105
|
+
return TruthLock(organization=args.org, base_url=args.url)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _run(args: argparse.Namespace) -> int:
|
|
109
|
+
if args.command == "webhook-verify":
|
|
110
|
+
# Bytes, not text: the signature is over exactly what was sent.
|
|
111
|
+
body = sys.stdin.buffer.read() if args.body == "-" else Path(args.body).read_bytes()
|
|
112
|
+
event = parse_webhook(body, args.signature, args.secret, tolerance=args.tolerance)
|
|
113
|
+
_emit(event.raw) if args.json else print(f"valid: {event.type} {event.verification_id}")
|
|
114
|
+
return EXIT_OK
|
|
115
|
+
|
|
116
|
+
with _client(args) as tl:
|
|
117
|
+
if args.command == "verify":
|
|
118
|
+
text = args.text if args.text is not None else _read(args.file)
|
|
119
|
+
accepted = tl.verify(
|
|
120
|
+
text,
|
|
121
|
+
question=args.question,
|
|
122
|
+
external_id=args.external_id,
|
|
123
|
+
operation=args.operation,
|
|
124
|
+
webhook_url=args.webhook_url,
|
|
125
|
+
)
|
|
126
|
+
if args.no_wait:
|
|
127
|
+
_emit(accepted.__dict__) if args.json else print(accepted.id)
|
|
128
|
+
return EXIT_OK
|
|
129
|
+
record = tl.wait(accepted.id, timeout=args.timeout)
|
|
130
|
+
elif args.command == "get":
|
|
131
|
+
record = tl.get(args.id)
|
|
132
|
+
elif args.command == "wait":
|
|
133
|
+
record = tl.wait(args.id, timeout=args.timeout)
|
|
134
|
+
elif args.command == "may":
|
|
135
|
+
decision = tl.check(args.id, args.operation, store=False)
|
|
136
|
+
if args.json:
|
|
137
|
+
_emit(decision.raw)
|
|
138
|
+
else:
|
|
139
|
+
flagged = [str(c["claim_id"]) for c in decision.claims if c["decision"] != "allow"]
|
|
140
|
+
print(decision.decision + (f" claims {','.join(flagged)}" if flagged else ""))
|
|
141
|
+
return EXIT_OK if decision.allowed else EXIT_NO
|
|
142
|
+
elif args.command == "attest":
|
|
143
|
+
if args.export:
|
|
144
|
+
print(tl.export(args.id, args.export))
|
|
145
|
+
return EXIT_OK
|
|
146
|
+
status = tl.attestations(args.id)
|
|
147
|
+
if args.json:
|
|
148
|
+
_emit(status)
|
|
149
|
+
return EXIT_OK
|
|
150
|
+
if not status.get("attested"):
|
|
151
|
+
print("not attested")
|
|
152
|
+
return EXIT_NO
|
|
153
|
+
print("stands" if status.get("stands") else "withdrawn")
|
|
154
|
+
for item in status.get("chain") or []:
|
|
155
|
+
print(
|
|
156
|
+
f" {item.get('code', '')} {item.get('kind', '')} {item.get('created_at', '')}"
|
|
157
|
+
)
|
|
158
|
+
return EXIT_OK if status.get("stands") else EXIT_NO
|
|
159
|
+
elif args.command == "respond":
|
|
160
|
+
answer = tl.respond(args.question, grounded=args.grounded)
|
|
161
|
+
_emit(answer.raw) if args.json else print(answer.response)
|
|
162
|
+
return EXIT_OK
|
|
163
|
+
elif args.command == "deliveries":
|
|
164
|
+
rows = tl.webhook_deliveries(args.id)
|
|
165
|
+
if args.json:
|
|
166
|
+
_emit(rows)
|
|
167
|
+
else:
|
|
168
|
+
for row in rows:
|
|
169
|
+
print(f"{row['status']} x{row['attempts']} {row['url']} {row['last_error']}")
|
|
170
|
+
return EXIT_OK
|
|
171
|
+
else: # pragma: no cover - argparse refuses unknown commands first
|
|
172
|
+
return EXIT_ERROR
|
|
173
|
+
|
|
174
|
+
_emit(record.raw) if args.json else print(_summary(record))
|
|
175
|
+
return EXIT_OK if record.ok else EXIT_NO
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
179
|
+
args = _parser().parse_args(argv)
|
|
180
|
+
try:
|
|
181
|
+
return _run(args)
|
|
182
|
+
except WebhookSignatureError as exc:
|
|
183
|
+
print(f"invalid: {exc}", file=sys.stderr)
|
|
184
|
+
return EXIT_NO
|
|
185
|
+
except ApiError as exc:
|
|
186
|
+
print(f"truthlock: {exc.detail} (HTTP {exc.status})", file=sys.stderr)
|
|
187
|
+
return EXIT_ERROR
|
|
188
|
+
except (TruthLockError, OSError) as exc:
|
|
189
|
+
print(f"truthlock: {exc}", file=sys.stderr)
|
|
190
|
+
return EXIT_ERROR
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
if __name__ == "__main__":
|
|
194
|
+
raise SystemExit(main())
|
truthlock_io/client.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"""The TruthLock client.
|
|
2
|
+
|
|
3
|
+
from truthlock_io import TruthLock
|
|
4
|
+
|
|
5
|
+
tl = TruthLock(api_key="tl_...", organization="field-service")
|
|
6
|
+
record = tl.verify_and_wait(question=question, response=answer_text)
|
|
7
|
+
if tl.may(record, "display"):
|
|
8
|
+
show(answer_text)
|
|
9
|
+
|
|
10
|
+
Verification is asynchronous: it takes seconds to a minute or two. ``verify`` returns at
|
|
11
|
+
once with an id; ``wait`` polls until the record is finished; a webhook (see
|
|
12
|
+
``truthlock.webhooks``) saves you the polling.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
import time
|
|
19
|
+
from collections.abc import Callable
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
import httpx
|
|
24
|
+
|
|
25
|
+
from truthlock_io.errors import (
|
|
26
|
+
ApiError,
|
|
27
|
+
AuthenticationError,
|
|
28
|
+
NotFound,
|
|
29
|
+
PaymentRequired,
|
|
30
|
+
RateLimited,
|
|
31
|
+
TruthLockError,
|
|
32
|
+
VerificationTimeout,
|
|
33
|
+
)
|
|
34
|
+
from truthlock_io.models import Accepted, Answer, Decision, Record
|
|
35
|
+
|
|
36
|
+
DEFAULT_URL = "https://app.truthlock.io"
|
|
37
|
+
USER_AGENT = "truthlock-python/0.1.0"
|
|
38
|
+
|
|
39
|
+
_ERRORS: dict[int, type[ApiError]] = {
|
|
40
|
+
401: AuthenticationError,
|
|
41
|
+
403: AuthenticationError,
|
|
42
|
+
402: PaymentRequired,
|
|
43
|
+
404: NotFound,
|
|
44
|
+
429: RateLimited,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class TruthLock:
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
api_key: str | None = None,
|
|
52
|
+
organization: str | None = None,
|
|
53
|
+
*,
|
|
54
|
+
base_url: str | None = None,
|
|
55
|
+
timeout: float = 30.0,
|
|
56
|
+
transport: httpx.BaseTransport | None = None,
|
|
57
|
+
) -> None:
|
|
58
|
+
key = api_key or os.environ.get("TRUTHLOCK_API_KEY")
|
|
59
|
+
if not key:
|
|
60
|
+
raise TruthLockError("no API key: pass api_key= or set TRUTHLOCK_API_KEY")
|
|
61
|
+
self.organization = organization or os.environ.get("TRUTHLOCK_ORGANIZATION")
|
|
62
|
+
url = (base_url or os.environ.get("TRUTHLOCK_URL") or DEFAULT_URL).rstrip("/")
|
|
63
|
+
self._http = httpx.Client(
|
|
64
|
+
base_url=url,
|
|
65
|
+
timeout=timeout,
|
|
66
|
+
transport=transport,
|
|
67
|
+
headers={"X-API-Key": key, "User-Agent": USER_AGENT, "Accept": "application/json"},
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
# --- plumbing ------------------------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
def close(self) -> None:
|
|
73
|
+
self._http.close()
|
|
74
|
+
|
|
75
|
+
def __enter__(self) -> TruthLock:
|
|
76
|
+
return self
|
|
77
|
+
|
|
78
|
+
def __exit__(self, *_exc: object) -> None:
|
|
79
|
+
self.close()
|
|
80
|
+
|
|
81
|
+
def _org(self, organization: str | None) -> str:
|
|
82
|
+
slug = organization or self.organization
|
|
83
|
+
if not slug:
|
|
84
|
+
raise TruthLockError(
|
|
85
|
+
"no organization: pass organization= or set TRUTHLOCK_ORGANIZATION"
|
|
86
|
+
)
|
|
87
|
+
return f"/v1/organizations/{slug}"
|
|
88
|
+
|
|
89
|
+
def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
|
|
90
|
+
try:
|
|
91
|
+
response = self._http.request(method, path, **kwargs)
|
|
92
|
+
except httpx.HTTPError as exc:
|
|
93
|
+
raise TruthLockError(f"could not reach TruthLock: {exc}") from exc
|
|
94
|
+
if response.is_success:
|
|
95
|
+
return response
|
|
96
|
+
try:
|
|
97
|
+
detail = response.json().get("detail", response.text)
|
|
98
|
+
except ValueError:
|
|
99
|
+
detail = response.text
|
|
100
|
+
retry = response.headers.get("Retry-After")
|
|
101
|
+
raise _ERRORS.get(response.status_code, ApiError)(
|
|
102
|
+
response.status_code, detail, int(retry) if retry and retry.isdigit() else None
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# --- verify ----------------------------------------------------------------------------------
|
|
106
|
+
|
|
107
|
+
def verify(
|
|
108
|
+
self,
|
|
109
|
+
response: str,
|
|
110
|
+
*,
|
|
111
|
+
question: str | None = None,
|
|
112
|
+
cited_sources: list[dict[str, Any]] | None = None,
|
|
113
|
+
external_id: str | None = None,
|
|
114
|
+
operation: str | None = None,
|
|
115
|
+
meta: dict[str, Any] | None = None,
|
|
116
|
+
webhook_url: str | None = None,
|
|
117
|
+
organization: str | None = None,
|
|
118
|
+
) -> Accepted:
|
|
119
|
+
"""Submit an AI response. Returns at once; the work happens in the background."""
|
|
120
|
+
body: dict[str, Any] = {"response": response}
|
|
121
|
+
for name, value in (
|
|
122
|
+
("question", question),
|
|
123
|
+
("cited_sources", cited_sources),
|
|
124
|
+
("external_id", external_id),
|
|
125
|
+
("operation", operation),
|
|
126
|
+
("meta", meta),
|
|
127
|
+
("webhook_url", webhook_url),
|
|
128
|
+
):
|
|
129
|
+
if value is not None:
|
|
130
|
+
body[name] = value
|
|
131
|
+
raw = self._request("POST", f"{self._org(organization)}/verify", json=body).json()
|
|
132
|
+
return Accepted(str(raw["id"]), str(raw["status"]), str(raw.get("status_url", "")))
|
|
133
|
+
|
|
134
|
+
def get(self, verification_id: str, *, organization: str | None = None) -> Record:
|
|
135
|
+
path = f"{self._org(organization)}/verifications/{verification_id}"
|
|
136
|
+
return Record.from_json(self._request("GET", path).json())
|
|
137
|
+
|
|
138
|
+
def recent(self, limit: int = 20, *, organization: str | None = None) -> list[dict[str, Any]]:
|
|
139
|
+
path = f"{self._org(organization)}/verifications"
|
|
140
|
+
return list(self._request("GET", path, params={"limit": limit}).json())
|
|
141
|
+
|
|
142
|
+
def wait(
|
|
143
|
+
self,
|
|
144
|
+
verification_id: str,
|
|
145
|
+
*,
|
|
146
|
+
timeout: float = 300.0,
|
|
147
|
+
interval: float = 2.0,
|
|
148
|
+
organization: str | None = None,
|
|
149
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
150
|
+
) -> Record:
|
|
151
|
+
"""Poll until the record is done or failed. Raises VerificationTimeout otherwise;
|
|
152
|
+
the verification carries on, and ``get`` will find it later."""
|
|
153
|
+
deadline = time.monotonic() + timeout
|
|
154
|
+
delay = interval
|
|
155
|
+
while True:
|
|
156
|
+
record = self.get(verification_id, organization=organization)
|
|
157
|
+
if record.finished:
|
|
158
|
+
return record
|
|
159
|
+
if time.monotonic() + delay > deadline:
|
|
160
|
+
raise VerificationTimeout(verification_id, timeout)
|
|
161
|
+
sleep(delay)
|
|
162
|
+
delay = min(delay * 1.5, 10.0)
|
|
163
|
+
|
|
164
|
+
def verify_and_wait(
|
|
165
|
+
self, response: str, *, timeout: float = 300.0, interval: float = 2.0, **kwargs: Any
|
|
166
|
+
) -> Record:
|
|
167
|
+
accepted = self.verify(response, **kwargs)
|
|
168
|
+
return self.wait(
|
|
169
|
+
accepted.id,
|
|
170
|
+
timeout=timeout,
|
|
171
|
+
interval=interval,
|
|
172
|
+
organization=kwargs.get("organization"),
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
# --- reliance --------------------------------------------------------------------------------
|
|
176
|
+
|
|
177
|
+
def check(
|
|
178
|
+
self,
|
|
179
|
+
record: Record | str,
|
|
180
|
+
operation: str,
|
|
181
|
+
*,
|
|
182
|
+
store: bool = True,
|
|
183
|
+
apply: str = "none",
|
|
184
|
+
organization: str | None = None,
|
|
185
|
+
) -> Decision:
|
|
186
|
+
"""Decide whether the record may be relied on for ``operation``."""
|
|
187
|
+
verification_id = record.id if isinstance(record, Record) else record
|
|
188
|
+
raw = self._request(
|
|
189
|
+
"POST",
|
|
190
|
+
f"{self._org(organization)}/reliance/check",
|
|
191
|
+
json={
|
|
192
|
+
"verification_id": verification_id,
|
|
193
|
+
"operation": operation,
|
|
194
|
+
"store": store,
|
|
195
|
+
"apply": apply,
|
|
196
|
+
},
|
|
197
|
+
).json()
|
|
198
|
+
return Decision.from_json(raw, verification_id)
|
|
199
|
+
|
|
200
|
+
def may(self, record: Record | str, operation: str, *, organization: str | None = None) -> bool:
|
|
201
|
+
"""True only when the decision is ``allow``. A record that already carries a
|
|
202
|
+
decision for this operation is not asked about again."""
|
|
203
|
+
if isinstance(record, Record):
|
|
204
|
+
stored = record.decision(operation)
|
|
205
|
+
if stored is not None:
|
|
206
|
+
return stored.allowed
|
|
207
|
+
return self.check(record, operation, store=False, organization=organization).allowed
|
|
208
|
+
|
|
209
|
+
# --- the rest --------------------------------------------------------------------------------
|
|
210
|
+
|
|
211
|
+
def respond(
|
|
212
|
+
self, question: str, *, grounded: bool = False, organization: str | None = None
|
|
213
|
+
) -> Answer:
|
|
214
|
+
raw = self._request(
|
|
215
|
+
"POST",
|
|
216
|
+
f"{self._org(organization)}/respond",
|
|
217
|
+
json={"question": question, "grounded": grounded},
|
|
218
|
+
timeout=120.0,
|
|
219
|
+
).json()
|
|
220
|
+
return Answer(
|
|
221
|
+
response=str(raw.get("response", "")),
|
|
222
|
+
cited_sources=list(raw.get("cited_sources") or []),
|
|
223
|
+
warnings=list(raw.get("warnings") or []),
|
|
224
|
+
origin=dict(raw.get("origin") or {}),
|
|
225
|
+
raw=raw,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
def attestations(
|
|
229
|
+
self, verification_id: str, *, organization: str | None = None
|
|
230
|
+
) -> dict[str, Any]:
|
|
231
|
+
"""Whether the record is attested and still stands, the current attestation, and
|
|
232
|
+
the ``chain`` of every attestation issued for it, oldest first."""
|
|
233
|
+
path = f"{self._org(organization)}/verifications/{verification_id}/attestations"
|
|
234
|
+
return dict(self._request("GET", path).json())
|
|
235
|
+
|
|
236
|
+
def export(
|
|
237
|
+
self, verification_id: str, path: str | Path, *, organization: str | None = None
|
|
238
|
+
) -> Path:
|
|
239
|
+
"""Save the record, its evidence, the proof and the signature as one zip."""
|
|
240
|
+
url = f"{self._org(organization)}/verifications/{verification_id}/export"
|
|
241
|
+
target = Path(path)
|
|
242
|
+
target.write_bytes(self._request("GET", url, timeout=120.0).content)
|
|
243
|
+
return target
|
|
244
|
+
|
|
245
|
+
def webhook_deliveries(
|
|
246
|
+
self, verification_id: str, *, organization: str | None = None
|
|
247
|
+
) -> list[dict[str, Any]]:
|
|
248
|
+
path = f"{self._org(organization)}/verifications/{verification_id}/webhook-deliveries"
|
|
249
|
+
return list(self._request("GET", path).json())
|
truthlock_io/errors.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""What can go wrong, as types a caller can catch."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TruthLockError(Exception):
|
|
9
|
+
"""Base class for every error this library raises."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ApiError(TruthLockError):
|
|
13
|
+
"""The API answered with an error status."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, status: int, detail: Any, retry_after: int | None = None) -> None:
|
|
16
|
+
self.status = status
|
|
17
|
+
self.detail = detail
|
|
18
|
+
self.retry_after = retry_after
|
|
19
|
+
super().__init__(f"{status}: {detail}")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AuthenticationError(ApiError):
|
|
23
|
+
"""401 or 403: the key is missing, wrong, paused, or not allowed to do this."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PaymentRequired(ApiError):
|
|
27
|
+
"""402: the plan's allowance is spent, or an invoice is past its grace period."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class RateLimited(ApiError):
|
|
31
|
+
"""429: too many calls this minute. ``retry_after`` says how long to wait."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class NotFound(ApiError):
|
|
35
|
+
"""404."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class VerificationTimeout(TruthLockError):
|
|
39
|
+
"""``wait`` gave up before the verification finished. It may still finish."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, verification_id: str, seconds: float) -> None:
|
|
42
|
+
self.verification_id = verification_id
|
|
43
|
+
super().__init__(f"verification {verification_id} was not finished after {seconds:g}s")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class WebhookSignatureError(TruthLockError):
|
|
47
|
+
"""The webhook was not signed by this secret, was altered, or is a replay."""
|
truthlock_io/models.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Thin views over the API's JSON. The raw dict is always there as ``.raw``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
# Grades that mean "do not present this claim as established".
|
|
9
|
+
WEAK_GRADES = ("CONTRADICTED", "UNCONFIRMED", "REFUSED")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Accepted:
|
|
14
|
+
id: str
|
|
15
|
+
status: str
|
|
16
|
+
status_url: str
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Decision:
|
|
21
|
+
"""May this record be relied on for one operation: ``allow``, ``review`` or ``deny``."""
|
|
22
|
+
|
|
23
|
+
verification_id: str
|
|
24
|
+
operation: str
|
|
25
|
+
decision: str
|
|
26
|
+
counts: dict[str, int]
|
|
27
|
+
claims: list[dict[str, Any]]
|
|
28
|
+
applied_text: str | None
|
|
29
|
+
raw: dict[str, Any] = field(repr=False)
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def allowed(self) -> bool:
|
|
33
|
+
return self.decision == "allow"
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def from_json(cls, raw: dict[str, Any], verification_id: str = "") -> Decision:
|
|
37
|
+
return cls(
|
|
38
|
+
verification_id=str(raw.get("verification_id") or verification_id),
|
|
39
|
+
operation=str(raw.get("operation", "")),
|
|
40
|
+
decision=str(raw.get("decision", "deny")),
|
|
41
|
+
counts=dict(raw.get("counts") or {}),
|
|
42
|
+
claims=list(raw.get("claims") or []),
|
|
43
|
+
applied_text=raw.get("applied_text"),
|
|
44
|
+
raw=raw,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class Record:
|
|
50
|
+
"""A verification: what each claim rests on, and what may be done with it."""
|
|
51
|
+
|
|
52
|
+
id: str
|
|
53
|
+
status: str
|
|
54
|
+
raw: dict[str, Any] = field(repr=False)
|
|
55
|
+
|
|
56
|
+
@classmethod
|
|
57
|
+
def from_json(cls, raw: dict[str, Any]) -> Record:
|
|
58
|
+
return cls(id=str(raw["id"]), status=str(raw.get("status", "")), raw=raw)
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def finished(self) -> bool:
|
|
62
|
+
return self.status in ("done", "failed")
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def ok(self) -> bool:
|
|
66
|
+
return self.status == "done"
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def error(self) -> str | None:
|
|
70
|
+
return self.raw.get("error")
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def overall(self) -> dict[str, Any]:
|
|
74
|
+
return dict(self.raw.get("overall") or {})
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def grade(self) -> str | None:
|
|
78
|
+
"""The worst grade among the claims: VERIFIED, SUPPORTED, UNCONFIRMED,
|
|
79
|
+
CONTRADICTED or REFUSED."""
|
|
80
|
+
grade = self.overall.get("grade")
|
|
81
|
+
return str(grade) if grade else None
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def claims(self) -> list[dict[str, Any]]:
|
|
85
|
+
return list(self.raw.get("claims") or [])
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def external_id(self) -> str | None:
|
|
89
|
+
return self.raw.get("external_id")
|
|
90
|
+
|
|
91
|
+
def decision(self, operation: str) -> Decision | None:
|
|
92
|
+
"""The decision already written on the record for this operation, if any."""
|
|
93
|
+
stored = (self.raw.get("reliance") or {}).get(operation)
|
|
94
|
+
return Decision.from_json(stored, self.id) if isinstance(stored, dict) else None
|
|
95
|
+
|
|
96
|
+
def caveats(self) -> list[str]:
|
|
97
|
+
"""One line per claim that should not be presented as established."""
|
|
98
|
+
out: list[str] = []
|
|
99
|
+
for c in self.claims:
|
|
100
|
+
grade = str(c.get("grade") or "")
|
|
101
|
+
if grade not in WEAK_GRADES:
|
|
102
|
+
continue
|
|
103
|
+
text = c.get("claim") or c.get("text_snippet") or f"claim {c.get('claim_id')}"
|
|
104
|
+
why = c.get("explanation") or c.get("reason_code") or ""
|
|
105
|
+
out.append(f"{text} [{grade}{': ' + why if why else ''}]")
|
|
106
|
+
return out
|
|
107
|
+
|
|
108
|
+
def review_ids(self) -> list[int]:
|
|
109
|
+
"""The claims a person should look at: weak grades and anything flagged."""
|
|
110
|
+
return [
|
|
111
|
+
int(c["claim_id"])
|
|
112
|
+
for c in self.claims
|
|
113
|
+
if "claim_id" in c
|
|
114
|
+
and (str(c.get("grade") or "") in WEAK_GRADES or c.get("needs_review"))
|
|
115
|
+
]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass(frozen=True)
|
|
119
|
+
class Answer:
|
|
120
|
+
"""An answer from the organization's responder agent, ready to verify."""
|
|
121
|
+
|
|
122
|
+
response: str
|
|
123
|
+
cited_sources: list[dict[str, Any]]
|
|
124
|
+
warnings: list[str]
|
|
125
|
+
origin: dict[str, Any]
|
|
126
|
+
raw: dict[str, Any] = field(repr=False)
|
truthlock_io/py.typed
ADDED
|
File without changes
|
truthlock_io/webhooks.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Receiving a TruthLock webhook: prove it is ours, then read it.
|
|
2
|
+
|
|
3
|
+
Every event carries ``TruthLock-Signature: t=<unix>,v1=<hex>``, where ``v1`` is the
|
|
4
|
+
HMAC-SHA256 of ``"<t>.<raw body>"`` under the API key's webhook secret. The timestamp is
|
|
5
|
+
inside the signed text, so an old capture cannot be replayed with a fresh one.
|
|
6
|
+
|
|
7
|
+
Verify against the raw bytes you received, before any JSON parsing: re-serialising the
|
|
8
|
+
body changes it, and the signature is over what was sent.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import hmac
|
|
15
|
+
import json
|
|
16
|
+
import time
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from truthlock_io.errors import WebhookSignatureError
|
|
21
|
+
|
|
22
|
+
SIGNATURE_HEADER = "TruthLock-Signature"
|
|
23
|
+
DEFAULT_TOLERANCE_SECONDS = 300
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class WebhookEvent:
|
|
28
|
+
id: str
|
|
29
|
+
type: str
|
|
30
|
+
created: int
|
|
31
|
+
data: dict[str, Any]
|
|
32
|
+
raw: dict[str, Any]
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def verification_id(self) -> str:
|
|
36
|
+
return str(self.data.get("id", ""))
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def completed(self) -> bool:
|
|
40
|
+
return self.type == "verification.completed"
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def grade(self) -> str | None:
|
|
44
|
+
overall = self.data.get("overall") or {}
|
|
45
|
+
grade = overall.get("grade")
|
|
46
|
+
return str(grade) if grade else None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def sign(payload: bytes, secret: str, timestamp: int | None = None) -> str:
|
|
50
|
+
"""Build the header TruthLock would send. For tests of your own receiver."""
|
|
51
|
+
ts = int(time.time()) if timestamp is None else timestamp
|
|
52
|
+
mac = hmac.new(secret.encode(), f"{ts}.".encode() + payload, hashlib.sha256).hexdigest()
|
|
53
|
+
return f"t={ts},v1={mac}"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def verify_signature(
|
|
57
|
+
payload: bytes | str,
|
|
58
|
+
header: str | None,
|
|
59
|
+
secret: str,
|
|
60
|
+
*,
|
|
61
|
+
tolerance: int = DEFAULT_TOLERANCE_SECONDS,
|
|
62
|
+
now: float | None = None,
|
|
63
|
+
) -> None:
|
|
64
|
+
"""Raise WebhookSignatureError unless ``payload`` was signed by ``secret`` recently."""
|
|
65
|
+
body = payload.encode() if isinstance(payload, str) else payload
|
|
66
|
+
if not header:
|
|
67
|
+
raise WebhookSignatureError(f"no {SIGNATURE_HEADER} header")
|
|
68
|
+
parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
|
|
69
|
+
try:
|
|
70
|
+
ts = int(parts["t"])
|
|
71
|
+
sent = parts["v1"]
|
|
72
|
+
except (KeyError, ValueError):
|
|
73
|
+
raise WebhookSignatureError(f"malformed {SIGNATURE_HEADER} header") from None
|
|
74
|
+
expected = sign(body, secret, ts).split("v1=", 1)[1]
|
|
75
|
+
if not hmac.compare_digest(expected, sent):
|
|
76
|
+
raise WebhookSignatureError("the signature does not match this body and secret")
|
|
77
|
+
current = time.time() if now is None else now
|
|
78
|
+
if tolerance > 0 and abs(current - ts) > tolerance:
|
|
79
|
+
raise WebhookSignatureError(
|
|
80
|
+
f"the signature is {abs(current - ts):.0f}s old; refusing a possible replay"
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def parse_webhook(
|
|
85
|
+
payload: bytes | str,
|
|
86
|
+
header: str | None,
|
|
87
|
+
secret: str,
|
|
88
|
+
*,
|
|
89
|
+
tolerance: int = DEFAULT_TOLERANCE_SECONDS,
|
|
90
|
+
) -> WebhookEvent:
|
|
91
|
+
"""Verify, then parse. The only safe order."""
|
|
92
|
+
verify_signature(payload, header, secret, tolerance=tolerance)
|
|
93
|
+
try:
|
|
94
|
+
raw = json.loads(payload)
|
|
95
|
+
except ValueError:
|
|
96
|
+
raise WebhookSignatureError("the body is signed but is not JSON") from None
|
|
97
|
+
return WebhookEvent(
|
|
98
|
+
id=str(raw.get("id", "")),
|
|
99
|
+
type=str(raw.get("type", "")),
|
|
100
|
+
created=int(raw.get("created") or 0),
|
|
101
|
+
data=dict(raw.get("data") or {}),
|
|
102
|
+
raw=raw,
|
|
103
|
+
)
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: truthlock-io
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Client for the TruthLock verification API: submit, wait, decide, and verify signed webhooks.
|
|
5
|
+
Project-URL: Homepage, https://truthlock.io
|
|
6
|
+
Project-URL: Documentation, https://truthlock.io/developers
|
|
7
|
+
Author-email: Iron Rod Systems LLC <contact@truthlock.io>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
License-File: NOTICE
|
|
11
|
+
Keywords: attestation,llm,truthlock,verification
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Requires-Dist: httpx>=0.27
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# truthlock-io
|
|
21
|
+
|
|
22
|
+
Python client and command line tool for [TruthLock](https://truthlock.io): standing
|
|
23
|
+
verification for AI responses.
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
pip install truthlock-io
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
The package is `truthlock-io` and the module is `truthlock_io`. The similarly named
|
|
30
|
+
`truthlock` on PyPI belongs to a different company and does not talk to this service.
|
|
31
|
+
|
|
32
|
+
## Verify a response
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from truthlock_io import TruthLock
|
|
36
|
+
|
|
37
|
+
tl = TruthLock(api_key="tl_...", organization="field-service")
|
|
38
|
+
|
|
39
|
+
record = tl.verify_and_wait(
|
|
40
|
+
question="How do I clear fault E-41 on the press?",
|
|
41
|
+
response=answer_text,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
if tl.may(record, "display"):
|
|
45
|
+
show(answer_text)
|
|
46
|
+
elif tl.may(record, "display_with_caveat"):
|
|
47
|
+
show(answer_text, caveats=record.caveats())
|
|
48
|
+
else:
|
|
49
|
+
hold(record.review_ids())
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The key and organization may also come from `TRUTHLOCK_API_KEY` and
|
|
53
|
+
`TRUTHLOCK_ORGANIZATION`. `TRUTHLOCK_URL` points the client at a dedicated stack;
|
|
54
|
+
the default is `https://app.truthlock.io`.
|
|
55
|
+
|
|
56
|
+
Verification takes seconds to a minute or two, so it is asynchronous. `verify` returns an
|
|
57
|
+
id at once. `wait` polls with a growing interval and raises `VerificationTimeout` if it
|
|
58
|
+
gives up; the verification carries on, and `get` finds it later.
|
|
59
|
+
|
|
60
|
+
| Call | What it does |
|
|
61
|
+
|---|---|
|
|
62
|
+
| `verify(response, question=, external_id=, operation=, webhook_url=, meta=)` | Submit. Returns `Accepted(id, status, status_url)`. |
|
|
63
|
+
| `get(id)` / `wait(id)` / `verify_and_wait(...)` / `recent(limit)` | The `Record`: `.grade`, `.claims`, `.caveats()`, `.review_ids()`, `.raw`. |
|
|
64
|
+
| `check(record, operation)` | The reliance `Decision`: `allow`, `review` or `deny`, per claim and overall. |
|
|
65
|
+
| `may(record, operation)` | `True` only for `allow`. |
|
|
66
|
+
| `respond(question, grounded=False)` | An answer from the organization's responder agent. |
|
|
67
|
+
| `attestations(id)` / `export(id, path)` | Whether the record is attested and stands, with its signed `chain`; or the whole bundle as a zip. |
|
|
68
|
+
| `webhook_deliveries(id)` | What was sent for the record, and what your receiver answered. |
|
|
69
|
+
|
|
70
|
+
Errors are typed: `AuthenticationError` (401, 403), `PaymentRequired` (402: the plan's
|
|
71
|
+
allowance is spent, or an invoice is past due), `RateLimited` (429, with `.retry_after`),
|
|
72
|
+
`NotFound`, and `ApiError` for the rest.
|
|
73
|
+
|
|
74
|
+
## Webhooks
|
|
75
|
+
|
|
76
|
+
Give an API key a webhook under **Advanced → API keys → Webhook**, or:
|
|
77
|
+
|
|
78
|
+
```
|
|
79
|
+
curl -X PUT https://app.truthlock.io/v1/api-keys/$KEY_ID/webhook \
|
|
80
|
+
-H "X-API-Key: $ADMIN_KEY" -H "Content-Type: application/json" \
|
|
81
|
+
-d '{"url": "https://example.com/hooks/truthlock"}'
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The response carries the signing secret, `whsec_...`, once. When a verification submitted
|
|
85
|
+
with that key finishes, TruthLock posts a `verification.completed` or
|
|
86
|
+
`verification.failed` event, signed:
|
|
87
|
+
|
|
88
|
+
```
|
|
89
|
+
TruthLock-Signature: t=1700000000,v1=<hex HMAC-SHA256 of "<t>.<raw body>">
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Verify against the raw bytes, before parsing them:
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from truthlock_io import parse_webhook, WebhookSignatureError
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@app.post("/hooks/truthlock")
|
|
99
|
+
async def hook(request):
|
|
100
|
+
try:
|
|
101
|
+
event = parse_webhook(
|
|
102
|
+
await request.body(),
|
|
103
|
+
request.headers.get("TruthLock-Signature"),
|
|
104
|
+
WEBHOOK_SECRET,
|
|
105
|
+
)
|
|
106
|
+
except WebhookSignatureError:
|
|
107
|
+
return Response(status_code=400)
|
|
108
|
+
if event.completed:
|
|
109
|
+
record = tl.get(event.verification_id)
|
|
110
|
+
return Response(status_code=204)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`parse_webhook` rejects an altered body, another key's secret, and anything older than five
|
|
114
|
+
minutes, which is what stops a captured delivery being replayed. Answer with any 2xx
|
|
115
|
+
quickly and do the work afterwards: anything else is retried, eight times over about a day.
|
|
116
|
+
A delivery may arrive more than once; `event.id` is the same each time.
|
|
117
|
+
|
|
118
|
+
## Command line
|
|
119
|
+
|
|
120
|
+
```
|
|
121
|
+
$ export TRUTHLOCK_API_KEY=tl_...
|
|
122
|
+
$ truthlock verify --org field-service --file answer.txt --json | jq .overall.grade
|
|
123
|
+
"CONTRADICTED"
|
|
124
|
+
$ truthlock may 3f2a9b1c-... publish
|
|
125
|
+
review claims 1
|
|
126
|
+
$ truthlock attest 3f2a9b1c-... --export bundle.zip
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
| Command | |
|
|
130
|
+
|---|---|
|
|
131
|
+
| `verify --file F \| --text T [--question Q] [--no-wait] [--webhook-url U]` | Submit and wait. `-` reads standard input. |
|
|
132
|
+
| `get ID`, `wait ID` | Fetch, or wait for, a record. |
|
|
133
|
+
| `may ID OPERATION` | Prints the decision. Exit 0 only for `allow`. |
|
|
134
|
+
| `attest ID [--export ZIP]` | The attestation chain, or the bundle. |
|
|
135
|
+
| `respond QUESTION [--grounded]` | Ask the responder agent. |
|
|
136
|
+
| `deliveries ID` | Webhook deliveries for a record. |
|
|
137
|
+
| `webhook-verify --body F --signature H --secret S` | Check a captured delivery. |
|
|
138
|
+
|
|
139
|
+
Every command takes `--json`. Exit codes: 0 done or allowed, 1 a finding that says no
|
|
140
|
+
(failed run, decision other than allow, bad signature), 2 an error.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
truthlock_io/__init__.py,sha256=XR-SlBPSAdJQk_6OQcfKwUjNfcIDluODPzuywUJqQ_Y,805
|
|
2
|
+
truthlock_io/cli.py,sha256=0Qp1aEoBq6XPkckG9zYc54o6QZ7tMBuTuLTkDyy5F_4,8257
|
|
3
|
+
truthlock_io/client.py,sha256=vXs0HiDWlD4FhpYJVcjFXMJG6BtdtWZcaMdODvs0bEM,9222
|
|
4
|
+
truthlock_io/errors.py,sha256=kW_-oURDMRhNWMwy4FKLSW9lKzxdhAGd8jxQzyJBOV8,1396
|
|
5
|
+
truthlock_io/models.py,sha256=_ZIvhNygZ_O4PH6jG5iJlYX9Wm25fA4C8sDdoVJ_nPM,3916
|
|
6
|
+
truthlock_io/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
truthlock_io/webhooks.py,sha256=TnvvP1xMdeCdZLUeHNpRUs8Up1yQlNNxZ9db_z0YedQ,3375
|
|
8
|
+
truthlock_io-0.1.0.dist-info/METADATA,sha256=x0rPe8rdHKedWtC3e0CEExOqzOUe6xkf_b4acH7C_yc,5350
|
|
9
|
+
truthlock_io-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
10
|
+
truthlock_io-0.1.0.dist-info/entry_points.txt,sha256=cz1tEU5oeTUp9ObsJZTSRCxd5hbt6TimafsshVXXGLg,52
|
|
11
|
+
truthlock_io-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
12
|
+
truthlock_io-0.1.0.dist-info/licenses/NOTICE,sha256=YJbbHW_jtH2T-q6HMAgIyENp7BIOX-5Xi9gcZkZKhGA,50
|
|
13
|
+
truthlock_io-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|