itself 0.2.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.
itself/__init__.py ADDED
@@ -0,0 +1,282 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ # Copyright (C) 2026 Greater Expanse LLC
3
+
4
+ """Itself SDK: evidence infrastructure for AI systems."""
5
+
6
+ from ._version import __version__
7
+ from .bundle import (
8
+ BundleIntegrityError,
9
+ BundleSnapshot,
10
+ BundleValidator,
11
+ IntegrityCode,
12
+ IntegrityIssue,
13
+ )
14
+ from .decision_model import (
15
+ COUNTERBALANCED_ORDERS,
16
+ DECISION_MODEL_ADAPTER_ID,
17
+ DECISION_MODEL_ADAPTER_VERSION,
18
+ ChoiceQuestion,
19
+ DecisionModelAdapter,
20
+ DecisionModelAnswer,
21
+ DecisionModelAttempt,
22
+ DecisionModelClient,
23
+ DecisionModelEndpoint,
24
+ DecisionModelError,
25
+ DecisionModelEstimate,
26
+ DecisionModelResult,
27
+ DecisionQuestion,
28
+ DecisionQuestionType,
29
+ NoulQuestion,
30
+ OptionOrder,
31
+ ScoreQuestion,
32
+ build_decision_payload,
33
+ )
34
+ from .evidence_bundle import (
35
+ BUNDLE_MANIFEST_NAME,
36
+ DEFAULT_EVIDENCE_BUNDLE_LIMITATIONS,
37
+ DEFAULT_EVIDENCE_BUNDLE_LIMITS,
38
+ EVIDENCE_BUNDLE_LEDGER_PATH,
39
+ EVIDENCE_BUNDLE_RECEIPT_PATH,
40
+ EVIDENCE_BUNDLE_VERSION,
41
+ EvidenceBundleBuilder,
42
+ EvidenceBundleBuildError,
43
+ EvidenceBundleFile,
44
+ EvidenceBundleFileRole,
45
+ EvidenceBundleLimits,
46
+ EvidenceBundleValidationError,
47
+ EvidenceBundleValidator,
48
+ VerifiedEvidenceBundle,
49
+ canonical_bundle_json,
50
+ evidence_bundle_id,
51
+ parse_bundle_path,
52
+ )
53
+ from .inference import (
54
+ ADAPTER_ID,
55
+ ADAPTER_VERSION,
56
+ ArtifactReference,
57
+ ArtifactSink,
58
+ DirectoryArtifactSink,
59
+ EnvironmentCredential,
60
+ HttpRequest,
61
+ HttpResponse,
62
+ HttpTransport,
63
+ InferenceError,
64
+ InferenceFailure,
65
+ InferenceIdentity,
66
+ InferenceUsage,
67
+ OpenAICompatibleEndpoint,
68
+ StructuredInferenceAdapter,
69
+ StructuredInferenceClient,
70
+ StructuredInferenceResult,
71
+ StructuredOutputMode,
72
+ StructuredOutputProfile,
73
+ UrllibHttpTransport,
74
+ build_chat_completions_payload,
75
+ )
76
+ from .ledger import JsonlLedgerStore, Ledger, LedgerFormatError
77
+ from .receipts import (
78
+ LEDGER_CANONICALIZATION,
79
+ RECEIPT_VERSION,
80
+ JsonReceiptStore,
81
+ ReasoningReceiptFormatError,
82
+ ReasoningReceiptValidationError,
83
+ ReasoningReceiptValidator,
84
+ build_reasoning_receipt,
85
+ canonical_ledger_bytes,
86
+ ledger_sha256,
87
+ )
88
+ from .records import (
89
+ PROTOCOL_VERSION,
90
+ Actor,
91
+ Authority,
92
+ AuthorityType,
93
+ ClaimType,
94
+ DecisionDisposition,
95
+ Digest,
96
+ DigestAlgorithm,
97
+ EvidenceRelation,
98
+ EvidenceRelationType,
99
+ EvidenceType,
100
+ Oracle,
101
+ PredictionCondition,
102
+ RecordConstructionError,
103
+ RecordHeader,
104
+ Scope,
105
+ TestCost,
106
+ TestDesign,
107
+ TestStatus,
108
+ VerdictOutcome,
109
+ artifact_reference_record,
110
+ claim_record,
111
+ decision_record,
112
+ evidence_record,
113
+ hypothesis_record,
114
+ prediction_record,
115
+ protocol_test_record,
116
+ status_transition_record,
117
+ verdict_record,
118
+ )
119
+ from .reporting import (
120
+ LedgerSummary,
121
+ SubjectKind,
122
+ SubjectReplay,
123
+ replay_subjects,
124
+ summarize_ledger,
125
+ )
126
+ from .schema_export import (
127
+ SCHEMA_CATALOG_VERSION,
128
+ SCHEMA_LINE,
129
+ SCHEMA_LINES,
130
+ SCHEMA_NAMES,
131
+ SCHEMA_ORIGIN,
132
+ SCHEMA_PUBLIC_ROOT,
133
+ PublishedSchema,
134
+ SchemaExport,
135
+ SchemaExportError,
136
+ export_schemas,
137
+ )
138
+ from .state import (
139
+ EVIDENCE_BACKED_STATUSES,
140
+ ActorRole,
141
+ ActorType,
142
+ ClaimStatus,
143
+ TransitionError,
144
+ TransitionRequest,
145
+ validate_transition,
146
+ )
147
+ from .types import JsonObject, JsonScalar, JsonValue, StrPath
148
+ from .validation import ProtocolValidationError, ProtocolValidator
149
+
150
+ __all__ = [
151
+ "__version__",
152
+ "ADAPTER_ID",
153
+ "ADAPTER_VERSION",
154
+ "Actor",
155
+ "ActorRole",
156
+ "ActorType",
157
+ "ArtifactReference",
158
+ "ArtifactSink",
159
+ "Authority",
160
+ "AuthorityType",
161
+ "BUNDLE_MANIFEST_NAME",
162
+ "BundleIntegrityError",
163
+ "BundleSnapshot",
164
+ "BundleValidator",
165
+ "ChoiceQuestion",
166
+ "ClaimStatus",
167
+ "ClaimType",
168
+ "COUNTERBALANCED_ORDERS",
169
+ "DECISION_MODEL_ADAPTER_ID",
170
+ "DECISION_MODEL_ADAPTER_VERSION",
171
+ "DEFAULT_EVIDENCE_BUNDLE_LIMITATIONS",
172
+ "DEFAULT_EVIDENCE_BUNDLE_LIMITS",
173
+ "DecisionDisposition",
174
+ "DecisionModelAdapter",
175
+ "DecisionModelAnswer",
176
+ "DecisionModelAttempt",
177
+ "DecisionModelClient",
178
+ "DecisionModelEndpoint",
179
+ "DecisionModelError",
180
+ "DecisionModelEstimate",
181
+ "DecisionModelResult",
182
+ "DecisionQuestion",
183
+ "DecisionQuestionType",
184
+ "Digest",
185
+ "DigestAlgorithm",
186
+ "DirectoryArtifactSink",
187
+ "EVIDENCE_BACKED_STATUSES",
188
+ "EVIDENCE_BUNDLE_LEDGER_PATH",
189
+ "EVIDENCE_BUNDLE_RECEIPT_PATH",
190
+ "EVIDENCE_BUNDLE_VERSION",
191
+ "EvidenceBundleBuildError",
192
+ "EvidenceBundleBuilder",
193
+ "EvidenceBundleFile",
194
+ "EvidenceBundleFileRole",
195
+ "EvidenceBundleLimits",
196
+ "EvidenceBundleValidationError",
197
+ "EvidenceBundleValidator",
198
+ "EvidenceRelation",
199
+ "EvidenceRelationType",
200
+ "EvidenceType",
201
+ "EnvironmentCredential",
202
+ "HttpRequest",
203
+ "HttpResponse",
204
+ "HttpTransport",
205
+ "InferenceError",
206
+ "InferenceFailure",
207
+ "InferenceIdentity",
208
+ "InferenceUsage",
209
+ "IntegrityCode",
210
+ "IntegrityIssue",
211
+ "JsonObject",
212
+ "JsonReceiptStore",
213
+ "JsonScalar",
214
+ "JsonValue",
215
+ "JsonlLedgerStore",
216
+ "Ledger",
217
+ "LedgerFormatError",
218
+ "LedgerSummary",
219
+ "LEDGER_CANONICALIZATION",
220
+ "NoulQuestion",
221
+ "OpenAICompatibleEndpoint",
222
+ "OptionOrder",
223
+ "Oracle",
224
+ "PROTOCOL_VERSION",
225
+ "PredictionCondition",
226
+ "ProtocolValidationError",
227
+ "ProtocolValidator",
228
+ "PublishedSchema",
229
+ "RECEIPT_VERSION",
230
+ "ReasoningReceiptFormatError",
231
+ "ReasoningReceiptValidationError",
232
+ "ReasoningReceiptValidator",
233
+ "RecordConstructionError",
234
+ "RecordHeader",
235
+ "SCHEMA_CATALOG_VERSION",
236
+ "SCHEMA_LINE",
237
+ "SCHEMA_LINES",
238
+ "SCHEMA_NAMES",
239
+ "SCHEMA_ORIGIN",
240
+ "SCHEMA_PUBLIC_ROOT",
241
+ "Scope",
242
+ "ScoreQuestion",
243
+ "SchemaExport",
244
+ "SchemaExportError",
245
+ "StrPath",
246
+ "SubjectKind",
247
+ "SubjectReplay",
248
+ "StructuredInferenceAdapter",
249
+ "StructuredInferenceClient",
250
+ "StructuredInferenceResult",
251
+ "StructuredOutputMode",
252
+ "StructuredOutputProfile",
253
+ "TestCost",
254
+ "TestDesign",
255
+ "TestStatus",
256
+ "TransitionError",
257
+ "TransitionRequest",
258
+ "UrllibHttpTransport",
259
+ "VerifiedEvidenceBundle",
260
+ "VerdictOutcome",
261
+ "artifact_reference_record",
262
+ "build_chat_completions_payload",
263
+ "build_decision_payload",
264
+ "build_reasoning_receipt",
265
+ "canonical_bundle_json",
266
+ "canonical_ledger_bytes",
267
+ "claim_record",
268
+ "decision_record",
269
+ "evidence_bundle_id",
270
+ "evidence_record",
271
+ "export_schemas",
272
+ "hypothesis_record",
273
+ "ledger_sha256",
274
+ "parse_bundle_path",
275
+ "prediction_record",
276
+ "protocol_test_record",
277
+ "replay_subjects",
278
+ "status_transition_record",
279
+ "summarize_ledger",
280
+ "validate_transition",
281
+ "verdict_record",
282
+ ]
itself/_endpoints.py ADDED
@@ -0,0 +1,255 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ # Copyright (C) 2026 Greater Expanse LLC
3
+
4
+ """Endpoint configuration checks and response helpers shared by model adapters."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import ipaddress
9
+ import json
10
+ import math
11
+ import re
12
+ import threading
13
+ from collections.abc import Iterator, Mapping, Set
14
+ from copy import deepcopy
15
+ from types import MappingProxyType
16
+ from typing import Final
17
+ from urllib.parse import urlencode, urlsplit
18
+
19
+ from .types import JsonObject, JsonValue
20
+
21
+ IDENTIFIER_PATTERN: Final = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$")
22
+ HEADER_NAME_PATTERN: Final = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")
23
+ _HEADER_VALUE_PATTERN: Final = re.compile(r"[\t\x20-\x7e]*")
24
+ _URL_TEXT_PATTERN: Final = re.compile(r"[\x21-\x7e]*")
25
+ # The transport owns message framing and the target host, and the adapter owns
26
+ # content negotiation and its identity.
27
+ RESERVED_HEADERS: Final = frozenset(
28
+ {
29
+ "accept",
30
+ "content-length",
31
+ "content-type",
32
+ "host",
33
+ "transfer-encoding",
34
+ "user-agent",
35
+ }
36
+ )
37
+
38
+
39
+ class DefensiveJsonObject(Mapping[str, JsonValue]):
40
+ """Read-only mapping whose nested values are returned as defensive copies."""
41
+
42
+ def __init__(self, value: Mapping[str, JsonValue]) -> None:
43
+ self._value: JsonObject = deepcopy(dict(value))
44
+
45
+ def __getitem__(self, key: str) -> JsonValue:
46
+ return deepcopy(self._value[key])
47
+
48
+ def __iter__(self) -> Iterator[str]:
49
+ return iter(self._value)
50
+
51
+ def __len__(self) -> int:
52
+ return len(self._value)
53
+
54
+
55
+ def is_loopback_hostname(hostname: str | None) -> bool:
56
+ if hostname is None:
57
+ return False
58
+ if hostname == "localhost" or hostname.endswith(".localhost"):
59
+ return True
60
+ try:
61
+ return ipaddress.ip_address(hostname).is_loopback
62
+ except ValueError:
63
+ return False
64
+
65
+
66
+ def normalized_base_url(
67
+ base_url: str,
68
+ *,
69
+ credential_bearing: bool,
70
+ allow_insecure_http: object,
71
+ ) -> str:
72
+ """Return a validated base URL without a trailing slash."""
73
+
74
+ # urlsplit silently drops tabs and line breaks, so the raw text is checked
75
+ # before it is parsed; non-ASCII hosts and paths must arrive encoded.
76
+ if _URL_TEXT_PATTERN.fullmatch(base_url) is None:
77
+ raise ValueError(
78
+ "base_url must be printable ASCII without spaces or control characters"
79
+ )
80
+ normalized_url = base_url.rstrip("/")
81
+ parsed_url = urlsplit(normalized_url)
82
+ if parsed_url.scheme not in {"http", "https"} or not parsed_url.netloc:
83
+ raise ValueError("base_url must be an absolute HTTP or HTTPS URL")
84
+ if parsed_url.username is not None or parsed_url.password is not None:
85
+ raise ValueError("base_url must not contain credentials")
86
+ if parsed_url.query or parsed_url.fragment:
87
+ raise ValueError("base_url must not contain a query or fragment")
88
+ try:
89
+ port = parsed_url.port
90
+ except ValueError as error:
91
+ raise ValueError("base_url must have a valid port") from error
92
+ if port == 0:
93
+ raise ValueError("base_url must have a valid port")
94
+ if type(allow_insecure_http) is not bool:
95
+ raise ValueError("allow_insecure_http must be a boolean")
96
+ if parsed_url.scheme == "http":
97
+ if credential_bearing:
98
+ raise ValueError("credential-bearing endpoints must use HTTPS")
99
+ if not allow_insecure_http:
100
+ raise ValueError("HTTP endpoints require allow_insecure_http=True")
101
+ if not is_loopback_hostname(parsed_url.hostname):
102
+ raise ValueError("insecure HTTP endpoints are limited to loopback hosts")
103
+ return normalized_url
104
+
105
+
106
+ def normalized_resource_path(resource_path: str) -> str:
107
+ """Return a validated relative resource path without outer slashes."""
108
+
109
+ if _URL_TEXT_PATTERN.fullmatch(resource_path) is None:
110
+ raise ValueError(
111
+ "resource_path must be printable ASCII without spaces or control characters"
112
+ )
113
+ normalized_resource = resource_path.strip("/")
114
+ if normalized_resource and (
115
+ "\\" in normalized_resource
116
+ or any(part in {"", ".", ".."} for part in normalized_resource.split("/"))
117
+ ):
118
+ raise ValueError("resource_path must be a normalized relative URL path")
119
+ return normalized_resource
120
+
121
+
122
+ def _is_duration(value: float) -> bool:
123
+ # Socket timeouts and timer waits both overflow past threading.TIMEOUT_MAX.
124
+ return (
125
+ not isinstance(value, bool)
126
+ and math.isfinite(value)
127
+ and 0 < value <= threading.TIMEOUT_MAX
128
+ )
129
+
130
+
131
+ def validate_timeout(timeout_seconds: float) -> None:
132
+ if not _is_duration(timeout_seconds):
133
+ raise ValueError(
134
+ "timeout_seconds must be greater than zero and at most "
135
+ "threading.TIMEOUT_MAX"
136
+ )
137
+
138
+
139
+ def validate_deadline(deadline_seconds: float | None) -> None:
140
+ if deadline_seconds is not None and not _is_duration(deadline_seconds):
141
+ raise ValueError(
142
+ "deadline_seconds must be greater than zero and at most "
143
+ "threading.TIMEOUT_MAX, or None"
144
+ )
145
+
146
+
147
+ def frozen_query_parameters(
148
+ query_parameters: Mapping[str, str],
149
+ ) -> Mapping[str, str]:
150
+ """Return an immutable copy of non-secret, single-line query parameters."""
151
+
152
+ parameters = dict(query_parameters)
153
+ for name, value in parameters.items():
154
+ if (
155
+ not name
156
+ or name != name.strip()
157
+ or "\r" in name
158
+ or "\n" in name
159
+ or "\r" in value
160
+ or "\n" in value
161
+ ):
162
+ raise ValueError("query parameters must contain single-line values")
163
+ return MappingProxyType(parameters)
164
+
165
+
166
+ def frozen_extra_headers(
167
+ extra_headers: Mapping[str, str],
168
+ *,
169
+ credential_header: str | None,
170
+ ) -> Mapping[str, str]:
171
+ """Return an immutable copy of headers that cannot override owned fields."""
172
+
173
+ reserved_headers = set(RESERVED_HEADERS)
174
+ if credential_header is not None:
175
+ reserved_headers.add(credential_header.lower())
176
+ headers = dict(extra_headers)
177
+ for name, value in headers.items():
178
+ if name.lower() in reserved_headers:
179
+ raise ValueError(f"extra_headers cannot override {name!r}")
180
+ if HEADER_NAME_PATTERN.fullmatch(name) is None:
181
+ raise ValueError("extra header names must be valid HTTP field names")
182
+ if "\r" in value or "\n" in value:
183
+ raise ValueError("extra header values must be single lines")
184
+ if _HEADER_VALUE_PATTERN.fullmatch(value) is None:
185
+ raise ValueError("extra header values must be printable ASCII")
186
+ return MappingProxyType(headers)
187
+
188
+
189
+ def defensive_extra_body(
190
+ extra_body: Mapping[str, JsonValue],
191
+ *,
192
+ reserved: Set[str],
193
+ ) -> Mapping[str, JsonValue]:
194
+ """Return a defensive copy of finite JSON fields that avoid reserved names."""
195
+
196
+ body = deepcopy(dict(extra_body))
197
+ conflicts = sorted(set(reserved).intersection(body))
198
+ if conflicts:
199
+ raise ValueError(
200
+ "extra_body cannot override reserved fields: " + ", ".join(conflicts)
201
+ )
202
+ try:
203
+ json.dumps(body, allow_nan=False)
204
+ except (TypeError, ValueError) as error:
205
+ raise ValueError("extra_body must contain finite JSON values") from error
206
+ return DefensiveJsonObject(body)
207
+
208
+
209
+ def endpoint_url(
210
+ base_url: str,
211
+ resource_path: str,
212
+ query_parameters: Mapping[str, str],
213
+ ) -> str:
214
+ """Render a validated endpoint URL without credentials."""
215
+
216
+ target = base_url if not resource_path else f"{base_url}/{resource_path}"
217
+ if not query_parameters:
218
+ return target
219
+ return f"{target}?{urlencode(query_parameters)}"
220
+
221
+
222
+ def content_type(headers: Mapping[str, str]) -> str:
223
+ """Return the lower-case media type of a captured response."""
224
+
225
+ for name, value in headers.items():
226
+ if name.lower() == "content-type":
227
+ media_type = value.partition(";")[0].strip().lower()
228
+ return media_type or "application/octet-stream"
229
+ return "application/json"
230
+
231
+
232
+ def optional_non_negative_integer(value: JsonValue | None) -> int | None:
233
+ if value is None:
234
+ return None
235
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
236
+ raise TypeError("expected a non-negative JSON integer or null")
237
+ return value
238
+
239
+
240
+ def token_counts(
241
+ value: JsonValue,
242
+ ) -> tuple[int | None, int | None, int | None]:
243
+ """Read input, output, and total token counts from a usage object."""
244
+
245
+ if not isinstance(value, dict):
246
+ raise TypeError("expected a JSON object")
247
+ return (
248
+ optional_non_negative_integer(
249
+ value.get("prompt_tokens", value.get("input_tokens"))
250
+ ),
251
+ optional_non_negative_integer(
252
+ value.get("completion_tokens", value.get("output_tokens"))
253
+ ),
254
+ optional_non_negative_integer(value.get("total_tokens")),
255
+ )