context-engineering-core 0.12.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.
Files changed (84) hide show
  1. context_engine/__init__.py +15 -0
  2. context_engine/__main__.py +3 -0
  3. context_engine/_sqlite.py +19 -0
  4. context_engine/_windows_security.py +125 -0
  5. context_engine/_windows_storage.py +110 -0
  6. context_engine/adapters.py +148 -0
  7. context_engine/answers.py +90 -0
  8. context_engine/budget.py +93 -0
  9. context_engine/cli.py +222 -0
  10. context_engine/config.py +193 -0
  11. context_engine/context.py +116 -0
  12. context_engine/demo.py +98 -0
  13. context_engine/errors.py +91 -0
  14. context_engine/evaluation/__init__.py +1 -0
  15. context_engine/evaluation/commands.py +90 -0
  16. context_engine/evaluation/corpus.py +247 -0
  17. context_engine/evaluation/data/freeze.json +26 -0
  18. context_engine/evaluation/data/ground_truth.json +287 -0
  19. context_engine/evaluation/data/pin_retention.json +8 -0
  20. context_engine/evaluation/data/protocol.json +122 -0
  21. context_engine/evaluation/data/scenario.json +1226 -0
  22. context_engine/evaluation/data/summary_fixture.json +7 -0
  23. context_engine/evaluation/execution.py +538 -0
  24. context_engine/evaluation/fixtures.py +32 -0
  25. context_engine/evaluation/grading.py +62 -0
  26. context_engine/evaluation/harness.py +165 -0
  27. context_engine/evaluation/heldout/__init__.py +260 -0
  28. context_engine/evaluation/heldout/__main__.py +40 -0
  29. context_engine/evaluation/heldout/data/ground_truth.json +18 -0
  30. context_engine/evaluation/heldout/data/manifest.json +9 -0
  31. context_engine/evaluation/heldout/data/protocol.json +14 -0
  32. context_engine/evaluation/heldout/data/scenarios.json +18 -0
  33. context_engine/evaluation/heldout/data/scoring_manifest.json +4 -0
  34. context_engine/evaluation/heldout/data/scoring_protocol.json +12 -0
  35. context_engine/evaluation/heldout/scoring.py +176 -0
  36. context_engine/evaluation/protocol.py +264 -0
  37. context_engine/evaluation/reporting.py +294 -0
  38. context_engine/evaluation/results.py +331 -0
  39. context_engine/evaluation/run_commands.py +146 -0
  40. context_engine/evaluation/strategies.py +261 -0
  41. context_engine/inspection.py +266 -0
  42. context_engine/layers/__init__.py +18 -0
  43. context_engine/layers/cap.py +99 -0
  44. context_engine/layers/common.py +162 -0
  45. context_engine/layers/pin.py +68 -0
  46. context_engine/layers/retrieve.py +233 -0
  47. context_engine/layers/summarize.py +202 -0
  48. context_engine/layers/window.py +29 -0
  49. context_engine/mcp_server.py +267 -0
  50. context_engine/memory/__init__.py +5 -0
  51. context_engine/memory/codec.py +91 -0
  52. context_engine/memory/demo.py +90 -0
  53. context_engine/memory/store.py +770 -0
  54. context_engine/models.py +384 -0
  55. context_engine/pipeline.py +383 -0
  56. context_engine/providers/__init__.py +1 -0
  57. context_engine/providers/client.py +301 -0
  58. context_engine/providers/commands.py +138 -0
  59. context_engine/providers/contracts.py +324 -0
  60. context_engine/providers/credentials.py +66 -0
  61. context_engine/providers/memory.py +112 -0
  62. context_engine/providers/store.py +408 -0
  63. context_engine/providers/transport.py +195 -0
  64. context_engine/providers/windows_credentials.py +23 -0
  65. context_engine/py.typed +0 -0
  66. context_engine/service/__init__.py +1 -0
  67. context_engine/service/__main__.py +68 -0
  68. context_engine/service/app.py +404 -0
  69. context_engine/service/auth.py +132 -0
  70. context_engine/service/client.py +52 -0
  71. context_engine/service/control.py +134 -0
  72. context_engine/service/demo.py +151 -0
  73. context_engine/service/integrations.py +28 -0
  74. context_engine/service/schemas.py +59 -0
  75. context_engine/service/worker.py +59 -0
  76. context_engine/service/workers.py +156 -0
  77. context_engine/summaries.py +196 -0
  78. context_engine/tokens.py +171 -0
  79. context_engine/work.py +46 -0
  80. context_engineering_core-0.12.0.dist-info/METADATA +203 -0
  81. context_engineering_core-0.12.0.dist-info/RECORD +84 -0
  82. context_engineering_core-0.12.0.dist-info/WHEEL +4 -0
  83. context_engineering_core-0.12.0.dist-info/entry_points.txt +3 -0
  84. context_engineering_core-0.12.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,408 @@
1
+ """One local SQLite transaction boundary for quota admission, ledger and opt-in replay."""
2
+
3
+ import json
4
+ import math
5
+ import os
6
+ import sqlite3
7
+ import stat
8
+ import uuid
9
+ from contextlib import contextmanager
10
+ from dataclasses import asdict, dataclass
11
+ from pathlib import Path
12
+
13
+ from .._sqlite import connect
14
+ from ..errors import CacheError, ContractError, ProviderError, QuotaError, StorageError
15
+ from ..models import canonical_json, integer_value
16
+ from .contracts import (
17
+ Completion,
18
+ PriceCard,
19
+ QuotaPolicy,
20
+ ReplayPolicy,
21
+ Usage,
22
+ fingerprint,
23
+ identifier,
24
+ )
25
+
26
+ ACTIVE = {"reserved", "inflight", "uncertain"}
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Admission:
31
+ attempt_id: str | None = None
32
+ completion: Completion | None = None
33
+ source_attempt: str | None = None
34
+ original_cost: int | None = None
35
+
36
+
37
+ class RuntimeStore:
38
+ def __init__(self, path: Path):
39
+ try:
40
+ self.path = Path(path).absolute()
41
+ if self.path.is_symlink():
42
+ raise StorageError("Runtime database cannot be a symlink")
43
+ if os.name == "nt":
44
+ from .._windows_storage import private_file
45
+
46
+ private_file(self.path, create=True)
47
+ else:
48
+ self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
49
+ descriptor = os.open(
50
+ self.path, os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0), 0o600
51
+ )
52
+ try:
53
+ info = os.fstat(descriptor)
54
+ if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:
55
+ raise StorageError("Runtime database must be a private regular file")
56
+ finally:
57
+ os.close(descriptor)
58
+ with self.transaction() as db:
59
+ version = db.execute("PRAGMA user_version").fetchone()[0]
60
+ if version not in (0, 1):
61
+ raise StorageError("Unsupported runtime database version")
62
+ if version == 0:
63
+ if db.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchone():
64
+ raise StorageError("Refusing to adopt an unrelated database")
65
+ for sql in (
66
+ """CREATE TABLE accounts(account TEXT PRIMARY KEY, policy TEXT NOT NULL,
67
+ last_clock REAL NOT NULL)""",
68
+ """CREATE TABLE attempts(
69
+ id TEXT PRIMARY KEY, account TEXT NOT NULL, request_key TEXT NOT NULL,
70
+ model TEXT NOT NULL, created REAL NOT NULL, settled REAL,
71
+ state TEXT NOT NULL,
72
+ reserved_tokens INTEGER NOT NULL, reserved_cost INTEGER NOT NULL,
73
+ charged_tokens INTEGER, cost INTEGER, usage_json TEXT,
74
+ price_json TEXT NOT NULL, completion_hash TEXT, reason TEXT,
75
+ request_count INTEGER NOT NULL DEFAULT 1)""",
76
+ "CREATE INDEX account_attempts ON attempts(account,created)",
77
+ """CREATE UNIQUE INDEX one_active_request ON attempts(account,request_key)
78
+ WHERE state IN ('reserved','inflight','uncertain')""",
79
+ """CREATE TABLE replay(request_key TEXT PRIMARY KEY,
80
+ source_attempt TEXT NOT NULL,
81
+ created REAL NOT NULL, expires REAL NOT NULL,
82
+ payload TEXT NOT NULL, digest TEXT NOT NULL,
83
+ FOREIGN KEY(source_attempt) REFERENCES attempts(id))""",
84
+ """CREATE TABLE events(id TEXT PRIMARY KEY, account TEXT NOT NULL,
85
+ request_key TEXT NOT NULL, created REAL NOT NULL, kind TEXT NOT NULL,
86
+ source_attempt TEXT, evidence_ref TEXT,
87
+ new_cost INTEGER NOT NULL DEFAULT 0)""",
88
+ ):
89
+ db.execute(sql)
90
+ db.execute("PRAGMA user_version=1")
91
+ except (OSError, ValueError, TypeError):
92
+ raise StorageError("Cannot initialize private runtime database") from None
93
+
94
+ @contextmanager
95
+ def transaction(self):
96
+ db = None
97
+ try:
98
+ if os.name == "nt":
99
+ from .._windows_storage import private_file
100
+
101
+ private_file(self.path)
102
+ db = connect(self.path, timeout=0.2, isolation_level=None)
103
+ db.row_factory = sqlite3.Row
104
+ db.execute("PRAGMA foreign_keys=ON")
105
+ db.execute("BEGIN IMMEDIATE")
106
+ yield db
107
+ db.execute("COMMIT")
108
+ except sqlite3.Error:
109
+ if db is not None and db.in_transaction:
110
+ db.rollback()
111
+ raise StorageError("Runtime database unavailable or corrupt") from None
112
+ except BaseException:
113
+ if db is not None and db.in_transaction:
114
+ db.rollback()
115
+ raise
116
+ finally:
117
+ if db is not None:
118
+ db.close()
119
+
120
+ @staticmethod
121
+ def _clock(now):
122
+ if type(now) not in (int, float) or not math.isfinite(now) or now < 0:
123
+ raise StorageError("Invalid accounting clock")
124
+ return now
125
+
126
+ def _account(self, db, policy, now):
127
+ now = self._clock(now)
128
+ key, encoded = fingerprint(policy.account_id), canonical_json(asdict(policy))
129
+ row = db.execute("SELECT * FROM accounts WHERE account=?", (key,)).fetchone()
130
+ if row is None:
131
+ db.execute("INSERT INTO accounts VALUES(?,?,?)", (key, encoded, now))
132
+ else:
133
+ if row["policy"] != encoded:
134
+ raise QuotaError("Shared account policy changed; explicit migration is required")
135
+ if now + 5 < row["last_clock"]:
136
+ raise QuotaError("Accounting clock moved backwards")
137
+ now = max(now, row["last_clock"])
138
+ db.execute("UPDATE accounts SET last_clock=? WHERE account=?", (now, key))
139
+ return key, now
140
+
141
+ def admit(
142
+ self,
143
+ *,
144
+ policy: QuotaPolicy,
145
+ key: str,
146
+ model: str,
147
+ reserved_tokens: int,
148
+ reserved_cost: int,
149
+ prices: PriceCard,
150
+ replay: ReplayPolicy,
151
+ now: float,
152
+ send_allowed: bool = True,
153
+ ) -> Admission:
154
+ policy.validate_prices(prices)
155
+ if policy.billing_mode == "free_tier" and reserved_cost != 0:
156
+ raise ContractError("Free-tier mode cannot reserve paid spending")
157
+ for value in (reserved_tokens, reserved_cost):
158
+ integer_value("reservation", value)
159
+ if value > 10**12:
160
+ raise ContractError("Reservation exceeds accounting range")
161
+ with self.transaction() as db:
162
+ account, now = self._account(db, policy, now)
163
+ if replay.enabled:
164
+ cached = db.execute("SELECT * FROM replay WHERE request_key=?", (key,)).fetchone()
165
+ if cached and now < min(cached["expires"], cached["created"] + replay.ttl_seconds):
166
+ source = db.execute(
167
+ "SELECT * FROM attempts WHERE id=?", (cached["source_attempt"],)
168
+ ).fetchone()
169
+ try:
170
+ value = json.loads(cached["payload"])
171
+ completion = Completion.from_dict(value)
172
+ digest = fingerprint(value)
173
+ if (
174
+ digest != cached["digest"]
175
+ or not source
176
+ or source["account"] != account
177
+ or source["request_key"] != key
178
+ or source["state"] != "completed"
179
+ or digest != source["completion_hash"]
180
+ or completion.finish_reason != "stop"
181
+ or completion.model != model
182
+ ):
183
+ raise ValueError
184
+ except (ValueError, KeyError, TypeError, ContractError, RecursionError):
185
+ raise CacheError(
186
+ "Replay entry failed integrity checks; no request was sent"
187
+ ) from None
188
+ db.execute(
189
+ """INSERT INTO events(id,account,request_key,created,kind,source_attempt)
190
+ VALUES(?,?,?,?,?,?)""",
191
+ (uuid.uuid4().hex, account, key, now, "replay", source["id"]),
192
+ )
193
+ return Admission(
194
+ completion=completion,
195
+ source_attempt=source["id"],
196
+ original_cost=source["cost"],
197
+ )
198
+ if not send_allowed:
199
+ raise ProviderError("Credentials are required for a new provider request")
200
+ if db.execute(
201
+ """SELECT id FROM attempts WHERE account=? AND request_key=?
202
+ AND state IN ('reserved','inflight','uncertain')""",
203
+ (account, key),
204
+ ).fetchone():
205
+ raise QuotaError("An identical request is active or has uncertain billing")
206
+ if policy.daily_budget_microusd == 0 and policy.billing_mode != "free_tier":
207
+ raise QuotaError("Provider spending is disabled")
208
+ usage = {"rpm": 0, "tpm": 0, "rpd": 0, "tpd": 0, "cost": 0}
209
+ day = int(now // 86400) * 86400
210
+ for row in db.execute("SELECT * FROM attempts WHERE account=?", (account,)):
211
+ self._validate_row(row)
212
+ active = row["state"] in ACTIVE
213
+ anchor = row["settled"] if row["settled"] is not None else row["created"]
214
+ tokens = row["reserved_tokens"] if active else row["charged_tokens"] or 0
215
+ cost = row["reserved_cost"] if active else row["cost"] or 0
216
+ requests = 1 if active else row["request_count"]
217
+ if active or anchor > now - 60:
218
+ usage["rpm"] += requests
219
+ usage["tpm"] += tokens
220
+ if active or anchor >= day:
221
+ usage["rpd"] += requests
222
+ usage["tpd"] += tokens
223
+ usage["cost"] += cost
224
+ for field, extra in (
225
+ ("rpm", 1),
226
+ ("tpm", reserved_tokens),
227
+ ("rpd", 1),
228
+ ("tpd", reserved_tokens),
229
+ ("cost", reserved_cost),
230
+ ):
231
+ ceiling = (
232
+ policy.daily_budget_microusd if field == "cost" else getattr(policy, field)
233
+ )
234
+ if usage[field] + extra > ceiling:
235
+ raise QuotaError("Local account quota exhausted", dimension=field)
236
+ attempt = uuid.uuid4().hex
237
+ db.execute(
238
+ """INSERT INTO attempts(id,account,request_key,model,created,state,
239
+ reserved_tokens,reserved_cost,price_json)
240
+ VALUES(?,?,?,?,?,'reserved',?,?,?)""",
241
+ (
242
+ attempt,
243
+ account,
244
+ key,
245
+ model,
246
+ now,
247
+ reserved_tokens,
248
+ reserved_cost,
249
+ canonical_json(asdict(prices)),
250
+ ),
251
+ )
252
+ return Admission(attempt_id=attempt)
253
+
254
+ def mark_inflight(self, attempt: str):
255
+ with self.transaction() as db:
256
+ if (
257
+ db.execute(
258
+ "UPDATE attempts SET state='inflight' WHERE id=? AND state='reserved'",
259
+ (attempt,),
260
+ ).rowcount
261
+ != 1
262
+ ):
263
+ raise StorageError("Reservation is not ready for dispatch")
264
+
265
+ def settle(
266
+ self,
267
+ attempt: str,
268
+ *,
269
+ now: float,
270
+ completion: Completion | None = None,
271
+ usage: Usage | None = None,
272
+ uncertain=False,
273
+ reason=None,
274
+ sent=True,
275
+ replay: ReplayPolicy | None = None,
276
+ ) -> tuple[int | None, str | None]:
277
+ now = self._clock(now)
278
+ replay = replay or ReplayPolicy()
279
+ with self.transaction() as db:
280
+ row = db.execute("SELECT * FROM attempts WHERE id=?", (attempt,)).fetchone()
281
+ if not row or row["state"] not in ("reserved", "inflight"):
282
+ raise StorageError("Reservation already reconciled or missing")
283
+ usage = completion.usage if completion else usage
284
+ warning = None
285
+ if uncertain and usage is None:
286
+ db.execute(
287
+ "UPDATE attempts SET state='uncertain',reason=? WHERE id=?", (reason, attempt)
288
+ )
289
+ return None, "usage_unknown_reservation_held"
290
+ prices = PriceCard(**json.loads(row["price_json"]))
291
+ cost = prices.observed_cost(usage) if usage else 0
292
+ tokens = (
293
+ usage.total_tokens if usage else 0
294
+ ) # Conservatively count cached input in local limits.
295
+ if tokens > row["reserved_tokens"] or cost > row["reserved_cost"]:
296
+ warning = "provider_usage_exceeded_reservation"
297
+ elif usage and usage.cached_input_tokens is None:
298
+ warning = "cached_usage_unknown_cost_is_upper_estimate"
299
+ state = "completed" if completion and completion.finish_reason == "stop" else "rejected"
300
+ encoded = canonical_json(completion.to_dict()) if completion else None
301
+ digest = fingerprint(completion.to_dict()) if completion else None
302
+ db.execute(
303
+ """UPDATE attempts SET state=?,settled=?,charged_tokens=?,cost=?,usage_json=?,
304
+ completion_hash=?,reason=?,request_count=? WHERE id=?""",
305
+ (
306
+ state,
307
+ max(now, row["created"]),
308
+ tokens,
309
+ cost,
310
+ canonical_json(asdict(usage)) if usage else None,
311
+ digest,
312
+ reason or (completion.finish_reason if completion else None),
313
+ int(sent),
314
+ attempt,
315
+ ),
316
+ )
317
+ if state == "completed" and replay.enabled:
318
+ db.execute(
319
+ """INSERT INTO replay VALUES(?,?,?,?,?,?) ON CONFLICT(request_key) DO UPDATE SET
320
+ source_attempt=excluded.source_attempt,created=excluded.created,expires=excluded.expires,
321
+ payload=excluded.payload,digest=excluded.digest""",
322
+ (row["request_key"], attempt, now, now + replay.ttl_seconds, encoded, digest),
323
+ )
324
+ return cost, warning
325
+
326
+ def resolve_uncertain(
327
+ self,
328
+ attempt: str,
329
+ *,
330
+ evidence_ref: str,
331
+ now: float,
332
+ usage: Usage | None = None,
333
+ confirmed_not_processed: bool = False,
334
+ ):
335
+ identifier(evidence_ref)
336
+ self._clock(now)
337
+ if type(confirmed_not_processed) is not bool or (usage is None) == (
338
+ not confirmed_not_processed
339
+ ):
340
+ raise ContractError("Supply observed usage OR confirmed-not-processed evidence")
341
+ if usage is not None and not isinstance(usage, Usage):
342
+ raise ContractError("Reconciliation requires validated usage")
343
+ with self.transaction() as db:
344
+ row = db.execute("SELECT * FROM attempts WHERE id=?", (attempt,)).fetchone()
345
+ if not row or row["state"] not in ACTIVE:
346
+ raise StorageError("No unresolved reservation to reconcile")
347
+ prices = PriceCard(**json.loads(row["price_json"]))
348
+ cost = prices.observed_cost(usage) if usage else 0
349
+ db.execute(
350
+ """UPDATE attempts SET state='reconciled',settled=?,charged_tokens=?,cost=?,
351
+ usage_json=?,reason='external_reconciliation',request_count=? WHERE id=?""",
352
+ (
353
+ max(now, row["created"]),
354
+ usage.total_tokens if usage else 0,
355
+ cost,
356
+ canonical_json(asdict(usage)) if usage else None,
357
+ int(not confirmed_not_processed),
358
+ attempt,
359
+ ),
360
+ )
361
+ db.execute(
362
+ """INSERT INTO events(id,account,request_key,created,kind,
363
+ source_attempt,evidence_ref)
364
+ VALUES(?,?,?,?,?,?,?)""",
365
+ (
366
+ uuid.uuid4().hex,
367
+ row["account"],
368
+ row["request_key"],
369
+ now,
370
+ "reconciliation",
371
+ attempt,
372
+ evidence_ref,
373
+ ),
374
+ )
375
+
376
+ def snapshot(self, policy: QuotaPolicy) -> dict:
377
+ with self.transaction() as db:
378
+ rows = [
379
+ dict(row)
380
+ for row in db.execute(
381
+ "SELECT * FROM attempts WHERE account=?", (fingerprint(policy.account_id),)
382
+ )
383
+ ]
384
+ events = [
385
+ dict(row)
386
+ for row in db.execute(
387
+ "SELECT * FROM events WHERE account=?", (fingerprint(policy.account_id),)
388
+ )
389
+ ]
390
+ return {
391
+ "attempts": rows,
392
+ "events": events,
393
+ "known_cost_microusd": sum(row["cost"] or 0 for row in rows),
394
+ "held_cost_microusd": sum(
395
+ row["reserved_cost"] for row in rows if row["state"] in ACTIVE
396
+ ),
397
+ "unresolved_attempts": sum(row["state"] in ACTIVE for row in rows),
398
+ }
399
+
400
+ @staticmethod
401
+ def _validate_row(row):
402
+ if row["state"] not in ACTIVE | {"completed", "rejected", "reconciled"}:
403
+ raise StorageError("Invalid accounting state")
404
+ names = ["reserved_tokens", "reserved_cost", "request_count"]
405
+ if row["state"] not in ACTIVE:
406
+ names += ["charged_tokens", "cost"]
407
+ if any(type(row[name]) is not int or row[name] < 0 for name in names):
408
+ raise StorageError("Invalid accounting values")
@@ -0,0 +1,195 @@
1
+ """Chat-completions HTTPS transports (Groq, Inception) with bounded body reads, no
2
+ redirects and no automatic retries."""
3
+
4
+ import json
5
+ import math
6
+ from datetime import UTC, datetime
7
+ from email.utils import parsedate_to_datetime
8
+ from importlib import metadata
9
+
10
+ from ..errors import ContractError
11
+ from ..models import ToolCall
12
+ from .contracts import (
13
+ ADAPTER_VERSION,
14
+ ENDPOINT,
15
+ INCEPTION_ADAPTER_VERSION,
16
+ INCEPTION_ENDPOINT,
17
+ Completion,
18
+ TransportFailure,
19
+ Usage,
20
+ identifier,
21
+ )
22
+
23
+
24
+ def retry_after(value: str | None, now: float) -> float | None:
25
+ if value is None:
26
+ return None
27
+ try:
28
+ seconds = float(value)
29
+ except (ValueError, TypeError):
30
+ try:
31
+ date = parsedate_to_datetime(value)
32
+ if date.tzinfo is None:
33
+ date = date.replace(tzinfo=UTC)
34
+ seconds = date.timestamp() - now
35
+ except (ValueError, TypeError, OverflowError):
36
+ return None
37
+ return max(0.0, seconds) if math.isfinite(seconds) else None
38
+
39
+
40
+ def parse_completion(raw: bytes, expected_model: str) -> Completion:
41
+ usage = None
42
+
43
+ def unique(pairs):
44
+ result = {}
45
+ for key, value in pairs:
46
+ if key in result:
47
+ raise ValueError("duplicate key")
48
+ result[key] = value
49
+ return result
50
+
51
+ def reject(_):
52
+ raise ValueError("nonfinite")
53
+
54
+ try:
55
+ data = json.loads(raw.decode("utf-8"), object_pairs_hook=unique, parse_constant=reject)
56
+ if data["model"] != expected_model or data["object"] != "chat.completion":
57
+ raise ValueError("response identity mismatch")
58
+ response_id = identifier(data["id"])
59
+ raw_usage = data["usage"]
60
+ for name in ("prompt_tokens_details", "completion_tokens_details"):
61
+ if raw_usage.get(name) is not None and not isinstance(raw_usage[name], dict):
62
+ raise ValueError("invalid usage details")
63
+ usage = Usage(
64
+ raw_usage["prompt_tokens"],
65
+ raw_usage["completion_tokens"],
66
+ (raw_usage.get("prompt_tokens_details") or {}).get("cached_tokens"),
67
+ (raw_usage.get("completion_tokens_details") or {}).get("reasoning_tokens"),
68
+ )
69
+ if (
70
+ type(raw_usage["total_tokens"]) is not int
71
+ or raw_usage["total_tokens"] != usage.total_tokens
72
+ ):
73
+ usage = None
74
+ raise ValueError("inconsistent total")
75
+ if (
76
+ len(data["choices"]) != 1
77
+ or type(data["choices"][0]["index"]) is not int
78
+ or data["choices"][0]["index"] != 0
79
+ ):
80
+ raise ValueError("invalid choices")
81
+ choice = data["choices"][0]
82
+ message = choice["message"]
83
+ if message["role"] != "assistant":
84
+ raise ValueError("invalid response role")
85
+ calls = []
86
+ for call in message.get("tool_calls") or ():
87
+ if call["type"] != "function":
88
+ raise ValueError("unknown tool kind")
89
+ calls.append(
90
+ ToolCall(call["id"], call["function"]["name"], call["function"]["arguments"])
91
+ )
92
+ content = message.get("content")
93
+ if content is None and choice["finish_reason"] in (
94
+ "tool_calls",
95
+ "length",
96
+ "content_filter",
97
+ ):
98
+ content = ""
99
+ return Completion(
100
+ expected_model,
101
+ response_id,
102
+ content,
103
+ choice["finish_reason"],
104
+ usage,
105
+ tuple(calls),
106
+ data.get("system_fingerprint"),
107
+ )
108
+ except (
109
+ ValueError,
110
+ TypeError,
111
+ KeyError,
112
+ IndexError,
113
+ AttributeError,
114
+ RecursionError,
115
+ ContractError,
116
+ ):
117
+ raise TransportFailure("invalid_response", uncertain=True, usage=usage) from None
118
+
119
+
120
+ class GroqTransport:
121
+ """A custom HTTP transport is for offline testing, not an authorization boundary."""
122
+
123
+ endpoint = ENDPOINT
124
+ adapter = ADAPTER_VERSION
125
+ name = "groq"
126
+
127
+ def __init__(self, *, http_transport=None):
128
+ self.http_transport = http_transport
129
+ try:
130
+ version = metadata.version("httpx")
131
+ except metadata.PackageNotFoundError:
132
+ version = "unavailable"
133
+ mode = "live" if http_transport is None else "test-http"
134
+ self.namespace = f"{self.name}-{mode}-httpx-{version}-v1"
135
+
136
+ async def send(self, payload: dict, api_key: str, timeout: float) -> Completion:
137
+ try:
138
+ import httpx
139
+ except ImportError:
140
+ raise TransportFailure("provider_extra_missing", uncertain=False) from None
141
+ try:
142
+ async with httpx.AsyncClient(
143
+ transport=self.http_transport,
144
+ timeout=timeout,
145
+ follow_redirects=False,
146
+ trust_env=False,
147
+ ) as client:
148
+ async with client.stream(
149
+ "POST",
150
+ self.endpoint,
151
+ json=payload,
152
+ headers={
153
+ "Authorization": "Bearer " + api_key,
154
+ "Content-Type": "application/json",
155
+ },
156
+ ) as response:
157
+ if response.status_code == 429:
158
+ delay = retry_after(
159
+ response.headers.get("retry-after"), datetime.now(UTC).timestamp()
160
+ )
161
+ raise TransportFailure(
162
+ "rate_limit", uncertain=False, retryable=True, retry_after=delay
163
+ )
164
+ if 400 <= response.status_code < 500 and response.status_code != 408:
165
+ code = {
166
+ 401: "authentication",
167
+ 402: "billing_or_quota",
168
+ 403: "permission",
169
+ 404: "model_unavailable",
170
+ }.get(response.status_code, "provider_rejected")
171
+ raise TransportFailure(code, uncertain=False)
172
+ if response.status_code != 200:
173
+ raise TransportFailure("provider_error", uncertain=True)
174
+ body = bytearray()
175
+ async for part in response.aiter_bytes():
176
+ body.extend(part)
177
+ if len(body) > 2_000_000:
178
+ raise TransportFailure("response_too_large", uncertain=True)
179
+ return parse_completion(bytes(body), payload["model"])
180
+ except TransportFailure:
181
+ raise
182
+ except (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout):
183
+ raise TransportFailure("connection_not_sent", uncertain=False, retryable=True) from None
184
+ except httpx.TimeoutException:
185
+ raise TransportFailure("timeout", uncertain=True) from None
186
+ except httpx.HTTPError:
187
+ raise TransportFailure("transport", uncertain=True) from None
188
+
189
+
190
+ class InceptionTransport(GroqTransport):
191
+ """Inception Mercury chat completions; same bounded, non-retrying behavior."""
192
+
193
+ endpoint = INCEPTION_ENDPOINT
194
+ adapter = INCEPTION_ADAPTER_VERSION
195
+ name = "inception"
@@ -0,0 +1,23 @@
1
+ """Fail-closed Windows credential reads; never change an operator's ACL."""
2
+
3
+ from .._windows_security import WindowsReader, check_acl # noqa: F401
4
+ from ..errors import ContractError
5
+
6
+
7
+ def private_bytes(path, maximum):
8
+ """Bounded bytes from the same verified handle; all OS errors are redacted."""
9
+ try:
10
+ reader = WindowsReader()
11
+ handle = reader.open(path)
12
+ try:
13
+ reader.validate(handle)
14
+ raw = reader.read(handle, maximum + 1)
15
+ if len(raw) > maximum:
16
+ raise ContractError("Private configuration exceeds its size limit")
17
+ return raw
18
+ finally:
19
+ handle.Close()
20
+ except ContractError:
21
+ raise
22
+ except Exception:
23
+ raise ContractError("Cannot read private Windows configuration") from None
File without changes
@@ -0,0 +1 @@
1
+ """Optional authenticated service; the core never imports this package."""