plotroom 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.
Files changed (150) hide show
  1. plotroom/__init__.py +0 -0
  2. plotroom/__main__.py +8 -0
  3. plotroom/_secret_file.py +8 -0
  4. plotroom/adapters/__init__.py +0 -0
  5. plotroom/adapters/claude_desktop.py +219 -0
  6. plotroom/adapters/embedding_http.py +175 -0
  7. plotroom/adapters/github/__init__.py +337 -0
  8. plotroom/adapters/github/app_credential.py +209 -0
  9. plotroom/adapters/github/ci.py +738 -0
  10. plotroom/adapters/github/commit_statuses.py +63 -0
  11. plotroom/adapters/github/deployments.py +213 -0
  12. plotroom/adapters/github/details.py +867 -0
  13. plotroom/adapters/github/issue_details.py +368 -0
  14. plotroom/adapters/github/junit.py +210 -0
  15. plotroom/adapters/github/junit_xml.py +162 -0
  16. plotroom/adapters/github/kodus_review.py +347 -0
  17. plotroom/adapters/github/pr_details.py +192 -0
  18. plotroom/adapters/github/pull_comparison.py +108 -0
  19. plotroom/adapters/github/read.py +530 -0
  20. plotroom/adapters/github/ticket_tree.py +336 -0
  21. plotroom/adapters/mcp/__init__.py +5 -0
  22. plotroom/adapters/mcp/proxy.py +722 -0
  23. plotroom/adapters/mcp/server.py +931 -0
  24. plotroom/adapters/openrouter.py +151 -0
  25. plotroom/adapters/store_sqlite/__init__.py +6 -0
  26. plotroom/adapters/store_sqlite/actions_sql.py +148 -0
  27. plotroom/adapters/store_sqlite/asks_sql.py +153 -0
  28. plotroom/adapters/store_sqlite/backfill_sql.py +138 -0
  29. plotroom/adapters/store_sqlite/budgets_sql.py +102 -0
  30. plotroom/adapters/store_sqlite/checklists_sql.py +77 -0
  31. plotroom/adapters/store_sqlite/claims_sql.py +54 -0
  32. plotroom/adapters/store_sqlite/embedding_sql.py +275 -0
  33. plotroom/adapters/store_sqlite/github_sql.py +331 -0
  34. plotroom/adapters/store_sqlite/goals_sql.py +57 -0
  35. plotroom/adapters/store_sqlite/human_queue_sql.py +60 -0
  36. plotroom/adapters/store_sqlite/items_sql.py +129 -0
  37. plotroom/adapters/store_sqlite/lanes_sql.py +85 -0
  38. plotroom/adapters/store_sqlite/ledger_sql.py +506 -0
  39. plotroom/adapters/store_sqlite/migrate.py +194 -0
  40. plotroom/adapters/store_sqlite/migrations/env.py +36 -0
  41. plotroom/adapters/store_sqlite/migrations/script.py.mako +19 -0
  42. plotroom/adapters/store_sqlite/migrations/versions/0001_project_meta.py +23 -0
  43. plotroom/adapters/store_sqlite/migrations/versions/0002_event_log.py +40 -0
  44. plotroom/adapters/store_sqlite/migrations/versions/0003_next_items.py +49 -0
  45. plotroom/adapters/store_sqlite/migrations/versions/0004_actions.py +28 -0
  46. plotroom/adapters/store_sqlite/migrations/versions/0005_lanes.py +36 -0
  47. plotroom/adapters/store_sqlite/migrations/versions/0006_work_items.py +22 -0
  48. plotroom/adapters/store_sqlite/migrations/versions/0007_item_changes.py +33 -0
  49. plotroom/adapters/store_sqlite/migrations/versions/0008_claude_turn_aliases.py +30 -0
  50. plotroom/adapters/store_sqlite/migrations/versions/0009_github_projection.py +38 -0
  51. plotroom/adapters/store_sqlite/migrations/versions/0010_github_pull_freshness.py +37 -0
  52. plotroom/adapters/store_sqlite/migrations/versions/0011_github_resources.py +27 -0
  53. plotroom/adapters/store_sqlite/migrations/versions/0012_local_triggers_outbox.py +80 -0
  54. plotroom/adapters/store_sqlite/migrations/versions/0013_lane_claims.py +22 -0
  55. plotroom/adapters/store_sqlite/migrations/versions/0015_recurring_triggers.py +45 -0
  56. plotroom/adapters/store_sqlite/migrations/versions/0016_merge_controller.py +28 -0
  57. plotroom/adapters/store_sqlite/migrations/versions/0017_lane_checklists.py +36 -0
  58. plotroom/adapters/store_sqlite/migrations/versions/0018_guardrails.py +33 -0
  59. plotroom/adapters/store_sqlite/migrations/versions/0019_clerk_import_metadata.py +16 -0
  60. plotroom/adapters/store_sqlite/migrations/versions/0020_search.py +30 -0
  61. plotroom/adapters/store_sqlite/migrations/versions/0021_human_queue.py +46 -0
  62. plotroom/adapters/store_sqlite/migrations/versions/0022_search_records.py +77 -0
  63. plotroom/adapters/store_sqlite/migrations/versions/0023_operator_goals.py +25 -0
  64. plotroom/adapters/store_sqlite/migrations/versions/0024_embedding_rejections.py +36 -0
  65. plotroom/adapters/store_sqlite/outbox_sql.py +78 -0
  66. plotroom/adapters/store_sqlite/routes_sql.py +26 -0
  67. plotroom/adapters/store_sqlite/search_sql.py +116 -0
  68. plotroom/adapters/store_sqlite/store.py +623 -0
  69. plotroom/adapters/store_sqlite/triggers_sql.py +111 -0
  70. plotroom/adapters/store_sqlite/work_items_sql.py +36 -0
  71. plotroom/adapters/switchboard.py +152 -0
  72. plotroom/adapters/usage_fixture.py +11 -0
  73. plotroom/adapters/work_items_bmad.py +256 -0
  74. plotroom/adapters/work_items_github_issues.py +323 -0
  75. plotroom/app/__init__.py +0 -0
  76. plotroom/app/bridge.py +162 -0
  77. plotroom/app/clerk_import.py +349 -0
  78. plotroom/app/cli.py +290 -0
  79. plotroom/app/clock.py +12 -0
  80. plotroom/app/config.py +984 -0
  81. plotroom/app/daemon_start.py +453 -0
  82. plotroom/app/lock.py +77 -0
  83. plotroom/app/logging.py +93 -0
  84. plotroom/app/portfile.py +218 -0
  85. plotroom/app/runtime.py +518 -0
  86. plotroom/app/serve.py +671 -0
  87. plotroom/app/session_intake.py +51 -0
  88. plotroom/app/sqlite_floor.py +35 -0
  89. plotroom/app/tokens.py +265 -0
  90. plotroom/core/__init__.py +0 -0
  91. plotroom/core/actions.py +67 -0
  92. plotroom/core/ask_checks.py +124 -0
  93. plotroom/core/asks.py +123 -0
  94. plotroom/core/branch_updates.py +207 -0
  95. plotroom/core/bridge.py +112 -0
  96. plotroom/core/briefs.py +83 -0
  97. plotroom/core/budgets.py +182 -0
  98. plotroom/core/catalog.py +464 -0
  99. plotroom/core/checklists.py +151 -0
  100. plotroom/core/claims.py +296 -0
  101. plotroom/core/clerk_import.py +379 -0
  102. plotroom/core/commands.py +85 -0
  103. plotroom/core/deploy_window.py +21 -0
  104. plotroom/core/envelope.py +20 -0
  105. plotroom/core/events.py +227 -0
  106. plotroom/core/github.py +306 -0
  107. plotroom/core/github_projection.py +310 -0
  108. plotroom/core/goal_language.py +374 -0
  109. plotroom/core/goal_projection.py +146 -0
  110. plotroom/core/human_queue.py +119 -0
  111. plotroom/core/intake.py +106 -0
  112. plotroom/core/kodus_review.py +53 -0
  113. plotroom/core/lanes.py +281 -0
  114. plotroom/core/ledger.py +808 -0
  115. plotroom/core/merge_controller.py +344 -0
  116. plotroom/core/merge_flakes.py +422 -0
  117. plotroom/core/merge_gate.py +724 -0
  118. plotroom/core/merge_lane.py +70 -0
  119. plotroom/core/merge_overlap.py +76 -0
  120. plotroom/core/next_items.py +60 -0
  121. plotroom/core/operator_goals.py +103 -0
  122. plotroom/core/outbox.py +70 -0
  123. plotroom/core/pull_overlaps.py +152 -0
  124. plotroom/core/reports.py +62 -0
  125. plotroom/core/roles.py +100 -0
  126. plotroom/core/routing.py +55 -0
  127. plotroom/core/run_reports.py +53 -0
  128. plotroom/core/search.py +266 -0
  129. plotroom/core/search_sources.py +94 -0
  130. plotroom/core/snapshot.py +204 -0
  131. plotroom/core/trigger_actions.py +89 -0
  132. plotroom/core/triggers.py +550 -0
  133. plotroom/core/unit_of_work.py +541 -0
  134. plotroom/core/watchers.py +35 -0
  135. plotroom/core/work_items.py +23 -0
  136. plotroom/core/writer.py +164 -0
  137. plotroom/ports/__init__.py +6 -0
  138. plotroom/ports/clock.py +12 -0
  139. plotroom/ports/github_write.py +72 -0
  140. plotroom/ports/search.py +197 -0
  141. plotroom/ports/session_reader.py +23 -0
  142. plotroom/ports/store.py +323 -0
  143. plotroom/ports/usage_meter.py +35 -0
  144. plotroom/ports/work_items.py +22 -0
  145. plotroom/py.typed +0 -0
  146. plotroom-0.1.0.dist-info/METADATA +230 -0
  147. plotroom-0.1.0.dist-info/RECORD +150 -0
  148. plotroom-0.1.0.dist-info/WHEEL +4 -0
  149. plotroom-0.1.0.dist-info/entry_points.txt +2 -0
  150. plotroom-0.1.0.dist-info/licenses/LICENSE +21 -0
plotroom/__init__.py ADDED
File without changes
plotroom/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """``python -m plotroom`` runs the same command line as the ``plotroom`` script."""
2
+
3
+ import sys
4
+
5
+ from plotroom.app.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
@@ -0,0 +1,8 @@
1
+ """Read a mounted secret without blocking the event loop."""
2
+
3
+ import asyncio
4
+ from pathlib import Path
5
+
6
+
7
+ async def read_secret_file(path: Path) -> str:
8
+ return (await asyncio.to_thread(path.read_text, encoding="utf-8")).strip()
File without changes
@@ -0,0 +1,219 @@
1
+ """Read the local Claude Desktop formats observed in the session-state spike."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import os
8
+ import re
9
+ import stat
10
+ from collections.abc import Callable, Generator, Iterator
11
+ from contextlib import ExitStack, contextmanager
12
+ from dataclasses import dataclass, replace
13
+ from pathlib import Path
14
+ from typing import Any, BinaryIO, cast
15
+
16
+ from plotroom.core.intake import SESSION_MESSAGE, TURN_REPORT
17
+ from plotroom.ports.session_reader import SessionEvent
18
+
19
+ SESSION_ID = re.compile(r"[A-Za-z0-9_-]{1,128}")
20
+
21
+
22
+ def _object(value: Any) -> dict[str, Any]:
23
+ return cast("dict[str, Any]", value) if isinstance(value, dict) else {}
24
+
25
+
26
+ def _decode(text: bytes) -> dict[str, Any]:
27
+ try:
28
+ return _object(json.loads(text))
29
+ except ValueError:
30
+ return {}
31
+
32
+
33
+ @contextmanager
34
+ def _open_regular(root: Path, path: Path) -> Generator[BinaryIO]:
35
+ """Open a discovered file relative to the configured directory without following links."""
36
+ parts = path.relative_to(root).parts
37
+ if not parts or ".." in parts:
38
+ raise ValueError("file must be inside a configured session root")
39
+ directory_flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
40
+ with ExitStack() as stack:
41
+ directory = os.open(root, directory_flags)
42
+ stack.callback(os.close, directory)
43
+ for part in parts[:-1]:
44
+ directory = os.open(part, directory_flags, dir_fd=directory)
45
+ stack.callback(os.close, directory)
46
+ fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory)
47
+ stack.callback(os.close, fd)
48
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
49
+ raise ValueError("session data must be a regular file")
50
+ with open(fd, "rb", closefd=False) as stream:
51
+ yield stream
52
+
53
+
54
+ def _metadata(root: Path, pattern: str) -> Iterator[dict[str, Any]]:
55
+ for path in root.glob(pattern):
56
+ try:
57
+ with _open_regular(root, path) as stream:
58
+ entry = _decode(stream.read())
59
+ yield entry
60
+ except OSError, ValueError:
61
+ continue
62
+
63
+
64
+ @dataclass
65
+ class _Turn:
66
+ index: int
67
+ final_text: str = ""
68
+ recap: str = ""
69
+ reported: bool = False
70
+
71
+ def take_report(self, session: str) -> SessionEvent | None:
72
+ text = self.final_text or self.recap
73
+ if not text or self.reported:
74
+ return None
75
+ self.final_text = self.recap = ""
76
+ try:
77
+ text.encode("utf-8")
78
+ except UnicodeError:
79
+ return None
80
+ self.reported = True
81
+ return SessionEvent(TURN_REPORT, session, text, turn_index=self.index)
82
+
83
+ def observe(self, message: dict[str, Any]) -> None:
84
+ if self.reported or not isinstance(message.get("content"), list):
85
+ return
86
+ parts: list[str] = []
87
+ for item in message["content"]:
88
+ block = _object(item)
89
+ if block.get("type") == "text" and isinstance(block.get("text"), str):
90
+ parts.append(block["text"])
91
+ if block.get("type") == "tool_use" and str(block.get("name", "")).endswith("wrap_up"):
92
+ recap = _object(block.get("input")).get("recap")
93
+ if isinstance(recap, str):
94
+ self.recap = recap
95
+ if parts and message.get("stop_reason") == "end_turn":
96
+ self.final_text = "\n".join(parts)
97
+
98
+
99
+ @dataclass(frozen=True)
100
+ class _Position:
101
+ device: int
102
+ inode: int
103
+ offset: int
104
+ turn: _Turn | None
105
+
106
+
107
+ def _transcript(
108
+ stream: BinaryIO, session: str, previous: _Position | None, still_idle: Callable[[], bool]
109
+ ) -> tuple[tuple[SessionEvent, ...], _Position]:
110
+ info = os.fstat(stream.fileno())
111
+ offset = 0
112
+ turn: _Turn | None = None
113
+ if (
114
+ previous is not None
115
+ and (previous.device, previous.inode) == (info.st_dev, info.st_ino)
116
+ and previous.offset <= info.st_size
117
+ ):
118
+ offset = previous.offset
119
+ turn = replace(previous.turn) if previous.turn is not None else None
120
+ stream.seek(offset)
121
+ events: list[SessionEvent] = []
122
+ for line in stream:
123
+ if not line.endswith(b"\n"):
124
+ break # a concurrently appended row may still be incomplete
125
+ offset += len(line)
126
+ row = _decode(line)
127
+ if row.get("type") == "user":
128
+ index = _object(row.get("turnPosition")).get("turnIndex")
129
+ if type(index) is int and index > 0 and (turn is None or index != turn.index):
130
+ if turn is not None and (report := turn.take_report(session)) is not None:
131
+ events.append(report)
132
+ turn = _Turn(index)
133
+ origin = _object(row.get("origin"))
134
+ if origin.get("kind") == "peer" and isinstance(origin.get("body"), str):
135
+ key = row.get("uuid")
136
+ if not isinstance(key, str) or not key:
137
+ key = f"turn:{index}" if type(index) is int and index > 0 else None
138
+ if key is not None:
139
+ events.append(
140
+ SessionEvent(SESSION_MESSAGE, session, origin["body"], upstream_id=key)
141
+ )
142
+ elif turn is not None and row.get("type") == "assistant":
143
+ turn.observe(_object(row.get("message")))
144
+ if (
145
+ turn is not None
146
+ and not turn.reported
147
+ and still_idle()
148
+ and (report := turn.take_report(session)) is not None
149
+ ):
150
+ events.append(report)
151
+ return tuple(events), _Position(info.st_dev, info.st_ino, offset, turn)
152
+
153
+
154
+ class ClaudeDesktopReader:
155
+ def __init__(self, claude_home: Path, app_support: Path) -> None:
156
+ self._home = claude_home
157
+ self._support = app_support
158
+ self._accepted: dict[str, _Position] = {}
159
+ self._pending: dict[str, _Position] = {}
160
+
161
+ async def read(self, session_id: str) -> tuple[SessionEvent, ...]:
162
+ self._pending.pop(session_id, None)
163
+ result = await asyncio.to_thread(self._read, session_id, self._accepted.get(session_id))
164
+ if result is None:
165
+ return ()
166
+ events, position = result
167
+ self._pending[session_id] = position
168
+ return events
169
+
170
+ def accept(self, session_id: str) -> None:
171
+ if (position := self._pending.pop(session_id, None)) is not None:
172
+ self._accepted[session_id] = position
173
+
174
+ def _read(
175
+ self, session: str, previous: _Position | None
176
+ ) -> tuple[tuple[SessionEvent, ...], _Position] | None:
177
+ if not SESSION_ID.fullmatch(session):
178
+ return None
179
+ try:
180
+ states = _metadata(self._support, "claude-code-sessions/*/*/local_*.json")
181
+ if not any(state.get("cliSessionId") == session for state in states):
182
+ return None
183
+ before = self._status(session)
184
+ if before is None:
185
+ return None
186
+ paths = list(self._home.glob(f"projects/*/{session}.jsonl"))
187
+ if len(paths) == 1:
188
+ with _open_regular(self._home, paths[0]) as stream:
189
+ return _transcript(
190
+ stream,
191
+ session,
192
+ previous,
193
+ lambda: (
194
+ before[0] == "idle"
195
+ and before[1] > 0
196
+ and self._status(session) == before
197
+ ),
198
+ )
199
+ except OSError, ValueError:
200
+ pass # formats and files are local implementation details and can change during reads
201
+ return None
202
+
203
+ def _status(self, session: str) -> tuple[str, int] | None:
204
+ live = (
205
+ entry
206
+ for entry in _metadata(self._home, "sessions/*.json")
207
+ if entry.get("sessionId") == session
208
+ )
209
+ # A replaced process may leave a registry file briefly. Use the latest status.
210
+ latest = max(live, key=_status_time, default=None)
211
+ if latest is None:
212
+ return None
213
+ status = latest.get("status")
214
+ return (status, _status_time(latest)) if status in ("busy", "idle", "waiting") else None
215
+
216
+
217
+ def _status_time(entry: dict[str, Any]) -> int:
218
+ value = entry.get("statusUpdatedAt")
219
+ return value if type(value) is int else 0
@@ -0,0 +1,175 @@
1
+ """HTTP adapter for endpoints accepting the embeddings request and response format."""
2
+
3
+ import asyncio
4
+ import json
5
+ from http import HTTPStatus
6
+ from pathlib import Path
7
+ from typing import Any, Never, cast
8
+
9
+ import httpx
10
+
11
+ from plotroom._secret_file import read_secret_file
12
+ from plotroom.ports.search import (
13
+ EmbeddingError,
14
+ EmbeddingModel,
15
+ EmbeddingOutcome,
16
+ EmbeddingRejection,
17
+ )
18
+
19
+ MAX_RESPONSE_BYTES = 8 * 1024 * 1024
20
+ MAX_REJECTION_BYTES = 4 * 1024
21
+
22
+
23
+ class _BatchTooLarge(EmbeddingError):
24
+ """The request or its response exceeded a size limit."""
25
+
26
+
27
+ class HttpEmbedder:
28
+ """POST model, input and dimensions, then restore the response's input order."""
29
+
30
+ def __init__(
31
+ self,
32
+ client: httpx.AsyncClient,
33
+ url: str,
34
+ model: EmbeddingModel,
35
+ *,
36
+ key_file: Path | None = None,
37
+ ) -> None:
38
+ self._client = client
39
+ self._url = url
40
+ self._model = model
41
+ self._key_file = key_file
42
+
43
+ async def embed(self, texts: tuple[str, ...]) -> tuple[EmbeddingOutcome, ...]:
44
+ try:
45
+ return await self._embed_batch(texts)
46
+ except _BatchTooLarge:
47
+ if len(texts) <= 1:
48
+ raise
49
+ # Discard all outcomes if either half raises a batch-level failure.
50
+ middle = len(texts) // 2
51
+ first = await self.embed(texts[:middle])
52
+ return first + await self.embed(texts[middle:])
53
+
54
+ async def _embed_batch(self, texts: tuple[str, ...]) -> tuple[EmbeddingOutcome, ...]:
55
+ content = bytearray()
56
+ try:
57
+ async with asyncio.timeout(10):
58
+ headers = {"Accept-Encoding": "identity"}
59
+ if self._key_file is not None:
60
+ endpoint = httpx.URL(self._url)
61
+ if endpoint.scheme != "https" or not endpoint.host or endpoint.userinfo:
62
+ raise EmbeddingError("embedding key file requires an HTTPS endpoint")
63
+ key = await self._read_key(self._key_file)
64
+ headers["Authorization"] = f"Bearer {key}"
65
+ async with self._client.stream(
66
+ "POST",
67
+ self._url,
68
+ headers=headers,
69
+ follow_redirects=(
70
+ False if self._key_file is not None else httpx.USE_CLIENT_DEFAULT
71
+ ),
72
+ json={
73
+ "model": self._model.name,
74
+ "input": texts,
75
+ "dimensions": self._model.dimension,
76
+ },
77
+ ) as response:
78
+ if (
79
+ response.status_code == HTTPStatus.REQUEST_ENTITY_TOO_LARGE
80
+ and "Retry-After" not in response.headers
81
+ ):
82
+ if len(texts) != 1:
83
+ raise _BatchTooLarge("embedding endpoint request exceeded size limit")
84
+ if await _confirmed_input_rejection(response):
85
+ return (EmbeddingRejection.INPUT_TOO_LARGE,)
86
+ raise EmbeddingError("embedding endpoint returned an unconfirmed rejection")
87
+ response.raise_for_status()
88
+ # Refuse compression so one decoder call cannot inflate past the cap.
89
+ if response.headers.get("Content-Encoding", "identity").lower() != "identity":
90
+ raise EmbeddingError("embedding endpoint returned unsupported encoding")
91
+ async for chunk in response.aiter_raw(chunk_size=64 * 1024):
92
+ if len(content) + len(chunk) > MAX_RESPONSE_BYTES:
93
+ raise _BatchTooLarge("embedding endpoint response exceeded size limit")
94
+ content.extend(chunk)
95
+ except httpx.HTTPError, httpx.InvalidURL, TimeoutError:
96
+ raise EmbeddingError("embedding endpoint request failed") from None
97
+ return await asyncio.to_thread(self._decode_batch, content, len(texts))
98
+
99
+ @staticmethod
100
+ async def _read_key(path: Path) -> str:
101
+ try:
102
+ key = await read_secret_file(path)
103
+ except OSError, ValueError:
104
+ raise EmbeddingError("embedding key file could not be read") from None
105
+ if not key or not key.isascii() or not key.isprintable() or any(c.isspace() for c in key):
106
+ raise EmbeddingError("embedding key file is invalid")
107
+ return key
108
+
109
+ def _decode_batch(self, content: bytearray, size: int) -> tuple[tuple[float, ...], ...]:
110
+ try:
111
+ payload: Any = json.loads(content)
112
+ except (ValueError, RecursionError) as exc:
113
+ raise EmbeddingError("embedding endpoint returned invalid JSON") from exc
114
+ if not isinstance(payload, dict):
115
+ raise EmbeddingError("embedding endpoint returned an invalid response")
116
+ data = cast("dict[str, Any]", payload).get("data")
117
+ if not isinstance(data, list) or len(cast("list[Any]", data)) != size:
118
+ raise EmbeddingError("embedding endpoint returned an invalid vector count")
119
+
120
+ vectors: dict[int, tuple[float, ...]] = {}
121
+ for record in cast("list[Any]", data):
122
+ if not isinstance(record, dict):
123
+ raise EmbeddingError("embedding endpoint returned an invalid record")
124
+ item = cast("dict[str, Any]", record)
125
+ index, vector = item.get("index"), item.get("embedding")
126
+ if type(index) is not int or not 0 <= index < size or index in vectors:
127
+ raise EmbeddingError("embedding endpoint returned an invalid input index")
128
+ if not isinstance(vector, list):
129
+ raise EmbeddingError("embedding endpoint returned an invalid vector")
130
+ numbers = cast("list[Any]", vector)
131
+ if len(numbers) != self._model.dimension or any(
132
+ type(number) not in (float, int) for number in numbers
133
+ ):
134
+ raise EmbeddingError("embedding endpoint returned an invalid vector")
135
+ try:
136
+ vectors[index] = tuple(float(number) for number in numbers)
137
+ except OverflowError as exc:
138
+ raise EmbeddingError("embedding endpoint returned an out-of-range value") from exc
139
+ return tuple(vectors[index] for index in range(size))
140
+
141
+
142
+ async def _confirmed_input_rejection(response: httpx.Response) -> bool:
143
+ if response.headers.get("Content-Encoding", "identity").lower() != "identity":
144
+ return False
145
+ body = bytearray()
146
+ async for chunk in response.aiter_raw(chunk_size=MAX_REJECTION_BYTES + 1):
147
+ if len(body) + len(chunk) > MAX_REJECTION_BYTES:
148
+ return False
149
+ body.extend(chunk)
150
+ try:
151
+ payload: Any = json.loads(
152
+ body.decode("utf-8"),
153
+ parse_constant=_invalid_json_constant,
154
+ object_pairs_hook=_unique_json_object,
155
+ )
156
+ except ValueError, RecursionError:
157
+ return False
158
+ if not isinstance(payload, dict):
159
+ return False
160
+ error = cast("dict[str, Any]", payload).get("error")
161
+ return (
162
+ isinstance(error, dict)
163
+ and cast("dict[str, Any]", error).get("code") == EmbeddingRejection.INPUT_TOO_LARGE
164
+ )
165
+
166
+
167
+ def _invalid_json_constant(_value: str) -> Never:
168
+ raise ValueError("nonstandard JSON constant")
169
+
170
+
171
+ def _unique_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
172
+ result = dict(pairs)
173
+ if len(result) != len(pairs):
174
+ raise ValueError("duplicate JSON object key")
175
+ return result