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
@@ -0,0 +1,323 @@
1
+ """Read ready BMad tickets from the project's GitHub Issues projection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import re
7
+ import tomllib
8
+ from collections.abc import Awaitable, Callable
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import Any, cast
12
+
13
+ import yaml
14
+
15
+ from plotroom.ports.work_items import MAX_WORK_ITEM_BODY_BYTES, WorkItem
16
+
17
+ _LEAF_TYPES = ("story", "spike", "bug")
18
+ _STATES = ("backlog", "in-progress", "review", "done", "dropped")
19
+ _CONFIG_LIMIT = 128 * 1024
20
+ _BODY_LIMIT = 128 * 1024
21
+ _METADATA_LIMIT = 8 * 1024
22
+ _METADATA_START = re.compile(r"\A```yaml[ \t]*\r?\n")
23
+ _METADATA_END = re.compile(r"^```[ \t]*\r?(?:\n|\Z)", re.M)
24
+ _UNKNOWN = re.compile(r"^[ \t]*(?:[-*][ \t]+)?Unknown:[ \t]*\S", re.M)
25
+
26
+ type IssueSnapshot = Callable[[], Awaitable[tuple[dict[str, Any], ...]]]
27
+
28
+
29
+ class GitHubIssuesError(ValueError):
30
+ """The projection or ticket-store configuration cannot supply ready issues."""
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class _Issue:
35
+ number: int
36
+ title: str
37
+ kind: str | None
38
+ status: str | None
39
+ body: str
40
+ milestone: int | None
41
+ children: tuple[int, ...]
42
+ blockers: tuple[int | str, ...]
43
+
44
+ @property
45
+ def can_start(self) -> bool:
46
+ return (
47
+ self.status == "backlog"
48
+ and self.kind in _LEAF_TYPES
49
+ and _body_allows_start(self.kind, self.body)
50
+ )
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class _IssueTree:
55
+ issues: dict[int, _Issue]
56
+ parents: dict[int, tuple[_Issue, int]]
57
+ milestones: dict[int, str]
58
+
59
+ def scoped(
60
+ self, issue: _Issue, milestone_filter: int | None
61
+ ) -> tuple[tuple[_Issue, int] | None, int | None] | None:
62
+ if issue.kind not in _LEAF_TYPES:
63
+ return None
64
+ parent = self.parents.get(issue.number)
65
+ milestone = issue.milestone or (parent[0].milestone if parent else None)
66
+ if milestone_filter is not None and milestone != milestone_filter:
67
+ return None
68
+ if milestone is not None and self.milestones.get(milestone) != "open":
69
+ return None
70
+ return parent, milestone
71
+
72
+
73
+ def _settings(path: Path) -> dict[str, Any]:
74
+ try:
75
+ with path.open("rb") as file:
76
+ raw = file.read(_CONFIG_LIMIT + 1)
77
+ if len(raw) > _CONFIG_LIMIT:
78
+ raise ValueError("ticket-store configuration is too large")
79
+ value = tomllib.loads(raw.decode("utf-8-sig"))["tickets"]
80
+ if not isinstance(value, dict):
81
+ raise ValueError("expected a GitHub ticket store")
82
+ table = cast("dict[str, Any]", value)
83
+ if table.get("store") != "github":
84
+ raise ValueError("expected a GitHub ticket store")
85
+ return table
86
+ except KeyError, OSError, ValueError:
87
+ raise GitHubIssuesError("cannot read the BMad GitHub ticket-store configuration") from None
88
+
89
+
90
+ def _mapping(base: dict[str, Any], overrides: dict[str, Any], key: str) -> dict[str, str]:
91
+ default, custom = base.get(key), overrides.get(key, {})
92
+ if not isinstance(default, dict) or not isinstance(custom, dict):
93
+ raise GitHubIssuesError(f"BMad tickets.{key} must be a table")
94
+ values = cast("dict[str, Any]", default) | cast("dict[str, Any]", custom)
95
+ normalized: dict[str, str] = {}
96
+ for name, value in values.items():
97
+ if not isinstance(value, str):
98
+ raise GitHubIssuesError(f"BMad tickets.{key} values must be strings")
99
+ normalized[name] = value.strip().casefold()
100
+ return normalized
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class _StoreMapping:
105
+ types: dict[str, str]
106
+ statuses: dict[str, str]
107
+
108
+ @classmethod
109
+ def load(cls, starter: Path, project: Path, repository: str) -> _StoreMapping:
110
+ base, overrides = _settings(starter), _settings(project)
111
+ repo = overrides.get("repo", base.get("repo", ""))
112
+ if not isinstance(repo, str) or (repo and repo.casefold() != repository.casefold()):
113
+ raise GitHubIssuesError("BMad repository must match the configured GitHub repository")
114
+ types = _mapping(base, overrides, "types")
115
+ statuses = _mapping(base, overrides, "status")
116
+ previous = ""
117
+ for state in _STATES:
118
+ # A blank tracker status inherits the preceding state. On a read with no
119
+ # recorded BMad state, the earliest match wins.
120
+ previous = statuses[state] = statuses.get(state) or previous
121
+ if not statuses["backlog"]:
122
+ raise GitHubIssuesError("BMad tickets.status requires a backlog label")
123
+ return cls(types, statuses)
124
+
125
+ def kind(self, labels: frozenset[str]) -> str | None:
126
+ matches = [kind for kind in ("epic", *_LEAF_TYPES) if self.types.get(kind) in labels]
127
+ return matches[0] if len(matches) == 1 else None
128
+
129
+ def status(self, state: str, reason: str | None, labels: frozenset[str]) -> str | None:
130
+ if state == "closed":
131
+ closed_as = f"closed: {(reason or '').casefold().replace('_', ' ')}"
132
+ for value in (closed_as, "closed"):
133
+ for status in ("done", "dropped"):
134
+ if self.statuses[status] == value:
135
+ return status
136
+ return None
137
+ matches = [(key, self.statuses[key]) for key in _STATES[:3] if self.statuses[key] in labels]
138
+ return matches[0][0] if len({label for _, label in matches}) == 1 else None
139
+
140
+
141
+ def _number(value: Any) -> int:
142
+ if type(value) is not int or not 0 < value <= 2**63 - 1:
143
+ raise GitHubIssuesError("the GitHub issue snapshot has an invalid number")
144
+ return value
145
+
146
+
147
+ def _list(value: Any) -> list[Any]:
148
+ if not isinstance(value, list):
149
+ raise GitHubIssuesError("the GitHub issue snapshot is missing a list")
150
+ return cast("list[Any]", value)
151
+
152
+
153
+ def _without_comments(body: str) -> str:
154
+ parts: list[str] = []
155
+ position = 0
156
+ while (start := body.find("<!--", position)) != -1:
157
+ end = body.find("-->", start + 4)
158
+ if end == -1:
159
+ break
160
+ parts.append(body[position:start])
161
+ position = end + 3
162
+ parts.append(body[position:])
163
+ return "".join(parts)
164
+
165
+
166
+ def _body_allows_start(kind: str, body: str) -> bool:
167
+ if len(body) > _BODY_LIMIT:
168
+ return False
169
+ refined: bool | None = None
170
+ if start := _METADATA_START.match(body):
171
+ limit = start.end() + _METADATA_LIMIT
172
+ end = _METADATA_END.search(body, start.end(), limit)
173
+ if end is None or (end.end() == limit < len(body) and not end.group().endswith("\n")):
174
+ return False
175
+ try:
176
+ # Compose syntax nodes without constructing YAML values or expanding aliases.
177
+ metadata = cast(
178
+ "yaml.Node | None",
179
+ yaml.compose( # pyright: ignore[reportUnknownMemberType]
180
+ body[start.end() : end.start()], Loader=yaml.SafeLoader
181
+ ),
182
+ )
183
+ except yaml.YAMLError, RecursionError:
184
+ return False
185
+ if not isinstance(metadata, yaml.MappingNode):
186
+ return False
187
+ for key, value in metadata.value:
188
+ if isinstance(key, yaml.ScalarNode) and key.value == "refined":
189
+ if refined is not None or not isinstance(value, yaml.ScalarNode):
190
+ return False
191
+ flag = value.value.casefold()
192
+ if flag not in ("true", "false"):
193
+ return False
194
+ refined = flag == "true"
195
+ body = body[end.end() :]
196
+ return (refined if refined is not None else kind != "bug") and not _UNKNOWN.search(
197
+ _without_comments(body)
198
+ )
199
+
200
+
201
+ def _issue(row: dict[str, Any], mapping: _StoreMapping) -> _Issue:
202
+ title, state, reason = row.get("title"), row.get("state"), row.get("state_reason")
203
+ body = row.get("body")
204
+ labels = _list(row.get("labels"))
205
+ if (
206
+ not isinstance(title, str)
207
+ or state not in ("open", "closed")
208
+ or (reason is not None and not isinstance(reason, str))
209
+ or (body is not None and not isinstance(body, str))
210
+ or not all(isinstance(label, str) and label for label in labels)
211
+ ):
212
+ raise GitHubIssuesError("the GitHub issue snapshot has an invalid issue")
213
+ normalized = frozenset(label.casefold() for label in cast("list[str]", labels))
214
+ milestone = row.get("milestone")
215
+ kind = mapping.kind(normalized)
216
+ status = mapping.status(cast("str", state), reason, normalized)
217
+ return _Issue(
218
+ _number(row.get("number")),
219
+ title,
220
+ kind,
221
+ status,
222
+ body or "",
223
+ _number(milestone) if milestone is not None else None,
224
+ tuple(_number(child) for child in _list(row.get("sub_issues"))),
225
+ tuple(
226
+ blocker if isinstance(blocker, str) and blocker else _number(blocker)
227
+ for blocker in _list(row.get("blocked_by"))
228
+ ),
229
+ )
230
+
231
+
232
+ class GitHubIssuesWorkItems:
233
+ """Classify tickets from a complete, committed issue and milestone snapshot."""
234
+
235
+ def __init__(
236
+ self,
237
+ read: IssueSnapshot,
238
+ starter: Path,
239
+ project_config: Path,
240
+ repository: str,
241
+ milestone: int | None = None,
242
+ ) -> None:
243
+ self._read = read
244
+ self._starter = starter
245
+ self._project_config = project_config
246
+ self._repository = repository
247
+ self._milestone = milestone
248
+
249
+ async def ready_items(self) -> tuple[WorkItem, ...]:
250
+ rows = await self._read()
251
+ return await asyncio.to_thread(self._classify, rows)
252
+
253
+ async def body(self, ref: str) -> str | None:
254
+ if re.fullmatch(r"[1-9][0-9]{0,18}", ref) is None:
255
+ return None
256
+ tree = await asyncio.to_thread(self._snapshot, await self._read())
257
+ issue = tree.issues.get(int(ref))
258
+ if issue is None or tree.scoped(issue, self._milestone) is None:
259
+ return None
260
+ if len(issue.body.encode("utf-8")) > MAX_WORK_ITEM_BODY_BYTES:
261
+ raise GitHubIssuesError("the GitHub issue snapshot has an invalid body")
262
+ return issue.body
263
+
264
+ def _snapshot(self, rows: tuple[dict[str, Any], ...]) -> _IssueTree:
265
+ mapping = _StoreMapping.load(self._starter, self._project_config, self._repository)
266
+ milestones: dict[int, str] = {}
267
+ issues: dict[int, _Issue] = {}
268
+ for row in rows:
269
+ if row.get("resource") == "milestone":
270
+ number, state = _number(row.get("number")), row.get("state")
271
+ if state not in ("open", "closed") or number in milestones:
272
+ raise GitHubIssuesError("the GitHub issue snapshot has an invalid milestone")
273
+ milestones[number] = cast("str", state)
274
+ elif row.get("resource") == "issue":
275
+ issue = _issue(row, mapping)
276
+ if issue.number in issues:
277
+ raise GitHubIssuesError("the GitHub issue snapshot has duplicate issues")
278
+ issues[issue.number] = issue
279
+
280
+ if self._milestone is not None and self._milestone not in milestones:
281
+ raise GitHubIssuesError("the configured GitHub milestone is unavailable")
282
+
283
+ parents: dict[int, tuple[_Issue, int]] = {}
284
+ for epic in issues.values():
285
+ if epic.kind == "epic":
286
+ for position, child in enumerate(epic.children):
287
+ if child in parents:
288
+ raise GitHubIssuesError("a GitHub sub-issue occurs more than once")
289
+ parents[child] = (epic, position)
290
+ return _IssueTree(issues, parents, milestones)
291
+
292
+ def _classify(self, rows: tuple[dict[str, Any], ...]) -> tuple[WorkItem, ...]:
293
+ tree = self._snapshot(rows)
294
+ done = {
295
+ issue.number
296
+ for issue in tree.issues.values()
297
+ if issue.status == "done" and issue.kind is not None
298
+ }
299
+ met = done | {
300
+ issue.number
301
+ for issue in tree.issues.values()
302
+ if issue.status == "review" and issue.kind in _LEAF_TYPES
303
+ }
304
+ ready: list[tuple[tuple[int, bool, int, int], WorkItem]] = []
305
+ for issue in tree.issues.values():
306
+ scope = tree.scoped(issue, self._milestone)
307
+ if scope is None or not issue.can_start:
308
+ continue
309
+ parent, milestone = scope
310
+ epic = parent[0] if parent else None
311
+ if not met.issuperset(issue.blockers):
312
+ continue
313
+ # An epic's own children can block its acceptance without gating its work.
314
+ if epic and not done.issuperset(set(epic.blockers).difference(epic.children)):
315
+ continue
316
+ order = (
317
+ milestone or 0,
318
+ epic is None,
319
+ epic.number if epic else issue.number,
320
+ parent[1] if parent else 0,
321
+ )
322
+ ready.append((order, WorkItem(str(issue.number), issue.title)))
323
+ return tuple(item for _, item in sorted(ready, key=lambda entry: entry[0]))
File without changes
plotroom/app/bridge.py ADDED
@@ -0,0 +1,162 @@
1
+ """Connect one explicit local Switchboard board to a scoped MCP server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import json
8
+ import logging
9
+ import os
10
+ from collections.abc import Sequence
11
+ from time import monotonic
12
+ from typing import Any, Literal, cast
13
+ from uuid import uuid4
14
+
15
+ import httpx2
16
+ from mcp import ClientSession
17
+ from mcp.client.client import Client
18
+ from mcp.client.stdio import StdioServerParameters, stdio_client
19
+ from mcp.client.streamable_http import streamable_http_client
20
+ from mcp.types import TextContent
21
+
22
+ from plotroom.adapters.mcp.proxy import EndpointError, check_endpoint
23
+ from plotroom.adapters.switchboard import NAME, WAIT_SECONDS, call_relay
24
+
25
+ log = logging.getLogger("plotroom.bridge")
26
+
27
+
28
+ async def _tool(client: Client, name: str, **arguments: Any) -> dict[str, Any]:
29
+ result = await client.call_tool(name, arguments)
30
+ if result.is_error or not result.content or not isinstance(result.content[0], TextContent):
31
+ raise ValueError("the server did not accept a bridge operation")
32
+ decoded: Any = json.loads(result.content[0].text)
33
+ envelope = cast("dict[str, Any]", decoded) if isinstance(decoded, dict) else {}
34
+ if envelope.get("ok") is not True:
35
+ raise ValueError("the server rejected a bridge operation")
36
+ data = envelope.get("data")
37
+ if not isinstance(data, dict):
38
+ raise ValueError("the server did not return bridge data")
39
+ return cast("dict[str, Any]", data)
40
+
41
+
42
+ async def _receive(relay: ClientSession, client: Client, board: str) -> None:
43
+ while True:
44
+ batch = await call_relay(relay, "wait", {"timeout_s": WAIT_SECONDS}, WAIT_SECONDS + 5)
45
+ messages = batch.get("messages")
46
+ if not isinstance(messages, list):
47
+ raise ValueError("the relay did not return a message list")
48
+ for raw in cast("list[Any]", messages):
49
+ if not isinstance(raw, dict):
50
+ raise ValueError("the relay returned an invalid claim")
51
+ message = cast("dict[str, Any]", raw)
52
+ message_id, sender, body, receipt = (
53
+ message.get(key) for key in ("id", "from", "body", "receipt")
54
+ )
55
+ if (
56
+ type(message_id) is not int
57
+ or not isinstance(sender, str)
58
+ or not isinstance(body, str)
59
+ or not isinstance(receipt, str)
60
+ or not receipt
61
+ ):
62
+ raise ValueError("the relay returned an invalid claim")
63
+ await _tool(
64
+ client,
65
+ "bridge_receive",
66
+ board=board,
67
+ message_id=message_id,
68
+ sender=sender,
69
+ body=body,
70
+ )
71
+ ack = await call_relay(relay, "ack", {"id": message_id, "receipt": receipt})
72
+ if ack.get("ok") is not True:
73
+ log.warning("bridge receipt expired before acknowledgment")
74
+
75
+
76
+ async def _send(relay: ClientSession, client: Client, consumer_id: str, board: str) -> None:
77
+ while True:
78
+ wake = await _tool(client, "wait", timeout=WAIT_SECONDS)
79
+ item = wake["item"]
80
+ if item is None or item["kind"] != "bridge_ready":
81
+ continue
82
+ requested_at = monotonic()
83
+ result = await _tool(
84
+ client, "bridge_lease", request_id=str(uuid4()), consumer_id=consumer_id, board=board
85
+ )
86
+ lease = result["lease"]
87
+ if lease is None:
88
+ continue
89
+ lease_deadline = requested_at + lease["lease_seconds"]
90
+ if monotonic() + 10 >= lease_deadline:
91
+ continue
92
+ key, address, body = (lease[name] for name in ("action_key", "to", "body"))
93
+ sent = await call_relay(
94
+ relay,
95
+ "send",
96
+ {
97
+ "to": address,
98
+ "body": json.dumps({"action_key": key, "body": body}, ensure_ascii=False),
99
+ "idempotency_key": key,
100
+ },
101
+ )
102
+ if type(sent.get("id")) is not int or sent.get("to") != address:
103
+ raise ValueError("the relay did not accept a bridge send")
104
+ await _tool(client, "bridge_done", act_id=lease["act_id"])
105
+
106
+
107
+ async def _bridge(
108
+ url: str, board: str, token: str, mode: Literal["auto", "legacy"], command: Sequence[str]
109
+ ) -> None:
110
+ params = StdioServerParameters(
111
+ command=command[0],
112
+ args=list(command[1:]),
113
+ env={"SWITCHBOARD_BOARD": board, "SWITCHBOARD_AUTO": "0"},
114
+ )
115
+ consumer = str(uuid4())
116
+ delay = 0.25
117
+ while True:
118
+ ready_at: float | None = None
119
+ try:
120
+ with open(os.devnull, "w", encoding="utf-8") as errlog: # noqa: ASYNC230
121
+ async with (
122
+ stdio_client(params, errlog=errlog) as (read, write),
123
+ ClientSession(read, write, read_timeout_seconds=10) as relay,
124
+ httpx2.AsyncClient(
125
+ headers={"Authorization": f"Bearer {token}"},
126
+ trust_env=False,
127
+ timeout=httpx2.Timeout(10, read=WAIT_SECONDS + 10),
128
+ ) as http,
129
+ Client(streamable_http_client(url, http_client=http), mode=mode) as client,
130
+ ):
131
+ await relay.initialize()
132
+ registration = await call_relay(relay, "register", {"name": NAME})
133
+ if registration.get("ok") is not True or registration.get("you") != NAME:
134
+ raise ValueError("the relay refused the protected bridge address")
135
+ ready_at = monotonic()
136
+ async with asyncio.TaskGroup() as directions:
137
+ directions.create_task(_receive(relay, client, board))
138
+ directions.create_task(_send(relay, client, consumer, board))
139
+ except Exception:
140
+ if ready_at is not None and monotonic() - ready_at >= WAIT_SECONDS:
141
+ delay = 0.25
142
+ log.warning("bridge connection unavailable, retrying", extra={"retry_seconds": delay})
143
+ await asyncio.sleep(delay)
144
+ delay = min(delay * 2, 30)
145
+
146
+
147
+ def run_bridge(
148
+ url: str, board: str, mode: Literal["auto", "legacy"], command: Sequence[str]
149
+ ) -> int:
150
+ token = os.environ.get("PLOTROOM_TOKEN")
151
+ try:
152
+ check_endpoint(url, credentialed=True)
153
+ if not command:
154
+ raise EndpointError("a relay command may not be empty")
155
+ if not token or not board:
156
+ raise EndpointError("a board and PLOTROOM_TOKEN are required")
157
+ except EndpointError as exc:
158
+ log.error("invalid bridge configuration", extra={"reason": str(exc)})
159
+ return 2
160
+ with contextlib.suppress(KeyboardInterrupt):
161
+ asyncio.run(_bridge(url, board, token, mode, command))
162
+ return 0