agentplane-control-plane 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.
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.5
2
+ Name: agentplane-control-plane
3
+ Version: 0.1.0
4
+ Summary: Shared AgentPlane control plane: Chronicle envelopes + TokenOps governance over HTTP.
5
+ Project-URL: Homepage, https://github.com/theagentplane/control-plane
6
+ Project-URL: Repository, https://github.com/theagentplane/control-plane
7
+ Project-URL: Issues, https://github.com/theagentplane/control-plane/issues
8
+ Project-URL: Changelog, https://github.com/theagentplane/control-plane/blob/main/CHANGELOG.md
9
+ Author: Susheem Koul, Tisha Chawla
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,chronicle,control-plane,governance,llm,observability,tokenops
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Topic :: System :: Systems Administration
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: fastapi>=0.115
23
+ Requires-Dist: httpx>=0.27
24
+ Requires-Dist: jinja2>=3.1
25
+ Requires-Dist: pydantic>=2
26
+ Requires-Dist: pyyaml>=6
27
+ Requires-Dist: uvicorn[standard]>=0.32
28
+ Provides-Extra: dev
29
+ Requires-Dist: build>=1.2; extra == 'dev'
30
+ Requires-Dist: httpx>=0.27; extra == 'dev'
31
+ Requires-Dist: pytest>=8; extra == 'dev'
32
+ Requires-Dist: ruff==0.15.22; extra == 'dev'
33
+ Requires-Dist: twine>=6; extra == 'dev'
34
+ Provides-Extra: ui
35
+ Requires-Dist: pandas>=2; extra == 'ui'
36
+ Requires-Dist: streamlit>=1.32; extra == 'ui'
37
+ Description-Content-Type: text/markdown
38
+
39
+ # AgentPlane Control Plane
40
+
41
+ Shared HTTP control plane for **Chronicle** and **TokenOps**. SQLite lives
42
+ **only** in this process. Agents never open the database file.
43
+
44
+ Design: [`docs/DESIGN.md`](docs/DESIGN.md) · Issue: [#2](https://github.com/theagentplane/control-plane/issues/2)
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ pip install agentplane-control-plane
50
+ control-plane serve --port 8800 --db control_plane.db
51
+ ```
52
+
53
+ From a clone:
54
+
55
+ ```bash
56
+ python -m venv .venv && source .venv/bin/activate
57
+ pip install -e ".[dev]"
58
+ control-plane serve --port 8800 --db control_plane.db
59
+ ```
60
+
61
+ Open http://127.0.0.1:8800/ — Admin, Chronicle, TokenOps tabs. No login.
62
+
63
+ Sidecars:
64
+
65
+ ```bash
66
+ export CONTROL_PLANE_URL=http://127.0.0.1:8800
67
+ # Chronicle
68
+ chronicle.record("run", store=RemoteStore(os.environ["CONTROL_PLANE_URL"], batch_size=1))
69
+ # TokenOps
70
+ export TOKENOPS_URL=http://127.0.0.1:8800
71
+ # TOKENOPS_EMBEDDED must be unset
72
+ ```
73
+
74
+ ## API callers
75
+
76
+ | Route | Caller |
77
+ |---|---|
78
+ | `POST /v1/envelopes:batch` | Chronicle sidecar (only ingest API; `batch_size=1` = immediate flush) |
79
+ | `GET /v1/traces/{id}/envelopes` | Chronicle sidecar (fixture replay) and Chronicle UI waterfall |
80
+ | `GET /v1/traces` | Chronicle UI search |
81
+ | `POST /v1/runs`, ledger, governance, run-records | TokenOps sidecar |
82
+ | segments / budgets / policies, admin keys | UI |
83
+
84
+ Auth off when no keys exist (local). Create keys in Admin, or:
85
+
86
+ ```bash
87
+ export CONTROL_PLANE_API_KEYS='chron:local:ingest+read,tops:local:ingest+read,admin:local:read+admin'
88
+ export CONTROL_PLANE_API_KEY=chron # sidecar
89
+ ```
90
+
91
+ ## Local SQLite
92
+
93
+ Default is a file next to the server (`CONTROL_PLANE_DB`). Do not point TokenOps
94
+ or Chronicle at that file. Unit tests in those repos keep their own sqlite/jsonl
95
+ when `TOKENOPS_EMBEDDED=1` / local Chronicle stores.
@@ -0,0 +1,25 @@
1
+ control_plane/__init__.py,sha256=gdDb8ftZzH5_D-AD-zP9xT26yNbfYvYqwBRYLSKecHE,110
2
+ control_plane/app.py,sha256=dOc2yDzw98xc1WxSzfp15IulltBwflgQmxN0cqThl8c,18522
3
+ control_plane/auth.py,sha256=Bu6yHYzGduFcO8TQop_C2MQ4R3CCI6gR86y_G7D7eok,3400
4
+ control_plane/cli.py,sha256=BK1sD7qnW4IXqdj_hcNp5c2_JmjTjxjhPyY695ycP9c,1302
5
+ control_plane/envelope_store.py,sha256=pA0q3u63T-9t9yIv9G4pb1DS_iUaXGx-Aj-j2Ili_s4,8879
6
+ control_plane/governance_loader.py,sha256=P6EQmu4Ep-nLiEat4jErE_cz5V2H6QAwbD27B61mqlQ,1014
7
+ control_plane/models.py,sha256=90XaV1gH2dUdNhtEq4BFK9Ypw3E3ENVutbeaaSy_62w,2621
8
+ control_plane/remote_store.py,sha256=GGD2Ojl43tan0JlF1gn5lNi4YD3CmLGp9tnTJxNnWzI,8606
9
+ control_plane/serde.py,sha256=fFNLnfGfMOlbs1YqCOOyRogu7IJvurmlv7HrRfdRmss,3852
10
+ control_plane/settings.py,sha256=W4vkfDQaG8Bu4kR3P_8p0lMMr75r9Cs91H2RyboUmoM,1064
11
+ control_plane/store.py,sha256=anXpNeOuHYx3bY4rEuGS4IpBmk2y6GrYFKhxHHoqYR4,23035
12
+ control_plane/store_factory.py,sha256=uC7u0Svp5dQySitZ20aaOSk5v_a7U7M56o7IQnfQ2jg,1367
13
+ control_plane/store_protocol.py,sha256=uS5qHF6q79h81U99fzrNVz-DON-5jiDXmBL0wE7M4bw,2839
14
+ control_plane/templates.py,sha256=i6TZl6RzQZgJ4KeWKu_EQCqhYMI7t4hG-a8R1Qqta7Y,509
15
+ control_plane/web.py,sha256=vflUkTPATIei5xI07r4YJ2qYQZvOWa2QS3xFtP-MZiw,963
16
+ control_plane/web/static/logo-mark.png,sha256=Yw4JD68b_pbiUMYudJa0dHnh412t4Alh2bwWC1fafNs,124432
17
+ control_plane/web/static/plane.css,sha256=nXs0z5G3gwZJT6nN8JpBop8yNCYA9lAU1bmKZwg7tvA,11573
18
+ control_plane/web/static/plane.js,sha256=lzHdSjDOfSFANFALUQh-1N3ZYfakiHLHFA6kWB_7dYQ,16680
19
+ control_plane/web/templates/index.html,sha256=5ROEzNoX6wCNVENY-8dT57Swfay_cHuEn1TcZ4hVU4E,2488
20
+ control_plane/default.yaml,sha256=DbLQeb1OxwVU89OM8Xxfq7WLh1qmSQV2zhaW651yV1Y,956
21
+ agentplane_control_plane-0.1.0.dist-info/METADATA,sha256=zdHztJMbvr6Ri-5JC-bfTdWQTpBsQOqyvb7sLbImfLw,3390
22
+ agentplane_control_plane-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
23
+ agentplane_control_plane-0.1.0.dist-info/entry_points.txt,sha256=6MKOgQlt9WFZKjBC0GadaaMyRGYy70ZBWZ7pH1a0DAo,57
24
+ agentplane_control_plane-0.1.0.dist-info/licenses/LICENSE,sha256=zdDVko5zpKFraUulwcFM4q38cz8uFYnYMAMOumrccC4,1067
25
+ agentplane_control_plane-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ control-plane = control_plane.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 agentplane
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ """AgentPlane shared control plane — governance (TokenOps) + Chronicle envelopes."""
2
+
3
+ __version__ = "0.1.0"
control_plane/app.py ADDED
@@ -0,0 +1,494 @@
1
+ """AgentPlane control-plane HTTP API.
2
+
3
+ Hosts:
4
+ * TokenOps governance / runs / ledger (from tokenops-cp-split)
5
+ * Chronicle envelope ingest + query (RFC control-plane-api)
6
+ * Bearer auth with tenant + scopes when CONTROL_PLANE_API_KEYS is set
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ from fastapi import Depends, FastAPI, HTTPException, Request
14
+ from fastapi.responses import JSONResponse
15
+
16
+ from control_plane.auth import Principal, env_key_views, parse_api_keys, require_scopes
17
+ from control_plane.envelope_store import EnvelopeStore
18
+ from control_plane.models import RunAlreadyRegisteredError, parse_governance_mode
19
+ from control_plane.serde import (
20
+ budget_from_dict,
21
+ budget_to_dict,
22
+ policy_from_dict,
23
+ policy_to_dict,
24
+ registration_from_dict,
25
+ registration_to_dict,
26
+ run_from_dict,
27
+ run_to_dict,
28
+ segment_from_dict,
29
+ segment_to_dict,
30
+ )
31
+ from control_plane.settings import Settings, load_settings
32
+ from control_plane.store import SqliteStore, new_id
33
+
34
+
35
+ def create_app(
36
+ store: SqliteStore | None = None,
37
+ envelopes: EnvelopeStore | None = None,
38
+ settings: Settings | None = None,
39
+ ) -> FastAPI:
40
+ cfg = settings or load_settings()
41
+ gov = store or SqliteStore(cfg.db_path)
42
+ env_store = envelopes or EnvelopeStore(cfg.db_path)
43
+ owns = store is None
44
+
45
+ app = FastAPI(
46
+ title="agentplane-control-plane",
47
+ version=cfg.version,
48
+ description="SQLite-backed AgentPlane control plane. Callers: agent-chronicle, "
49
+ "agent-tokenops, ui. See docs/DESIGN.md.",
50
+ )
51
+ app.state.settings = cfg
52
+ app.state.api_keys = parse_api_keys(cfg.api_keys)
53
+ app.state.store = gov
54
+ app.state.envelopes = env_store
55
+
56
+ from control_plane.web import mount_web
57
+
58
+ mount_web(app)
59
+
60
+ @app.get("/health")
61
+ async def health() -> dict[str, str]:
62
+ return {"status": "ok", "service": "control-plane", "version": cfg.version}
63
+
64
+ @app.get("/ready")
65
+ async def ready() -> dict[str, str]:
66
+ # Cheap DB ping
67
+ gov.list_budgets()
68
+ return {"status": "ready"}
69
+
70
+ @app.on_event("shutdown")
71
+ async def _shutdown() -> None:
72
+ if owns:
73
+ gov.close()
74
+ env_store.close()
75
+
76
+ def _durability(request: Request) -> str:
77
+ header = (request.headers.get("Durability") or cfg.default_durability).strip().lower()
78
+ if header not in {"sync", "queued"}:
79
+ raise HTTPException(status_code=400, detail="Durability must be sync|queued")
80
+ # queued: v1 acks after SQLite commit (same as sync) — placeholder for real queue
81
+ return header
82
+
83
+ # ---- Chronicle envelopes (agent ingest = batch only) ------------------ #
84
+
85
+ @app.post("/v1/envelopes:batch", tags=["agent-chronicle"])
86
+ async def ingest_batch(
87
+ request: Request,
88
+ principal: Principal = Depends(require_scopes("ingest")),
89
+ ) -> JSONResponse:
90
+ """Caller: Chronicle sidecar. Only ingest API. batch_size=1 is immediate flush."""
91
+ if int(request.headers.get("content-length") or 0) > cfg.max_body_bytes:
92
+ raise HTTPException(status_code=413, detail="payload too large")
93
+ payload = await request.json()
94
+ items = payload.get("envelopes") if isinstance(payload, dict) else None
95
+ if not isinstance(items, list):
96
+ raise HTTPException(status_code=400, detail="expected {envelopes: [...]}")
97
+ if len(items) > cfg.max_batch:
98
+ raise HTTPException(status_code=400, detail=f"batch max {cfg.max_batch}")
99
+ durability = _durability(request)
100
+ try:
101
+ result = env_store.append_many(principal.tenant_id, items)
102
+ except ValueError as exc:
103
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
104
+ return JSONResponse(
105
+ {
106
+ "status": "stored",
107
+ "accepted": result["accepted"],
108
+ "deduped": result["deduped"],
109
+ "envelope_ids": result["envelope_ids"],
110
+ "durability": durability,
111
+ },
112
+ status_code=201,
113
+ )
114
+
115
+ @app.get("/v1/traces/{trace_id}", tags=["agent-chronicle", "ui"])
116
+ async def get_trace(
117
+ trace_id: str,
118
+ principal: Principal = Depends(require_scopes("read")),
119
+ ) -> dict[str, Any]:
120
+ """Caller: Chronicle sidecar (replay) or Chronicle UI."""
121
+ tr = env_store.get_trace(principal.tenant_id, trace_id)
122
+ if tr is None:
123
+ raise HTTPException(status_code=404, detail="not found")
124
+ return tr
125
+
126
+ @app.get("/v1/traces/{trace_id}/envelopes", tags=["agent-chronicle", "ui"])
127
+ async def list_trace_envelopes(
128
+ trace_id: str,
129
+ principal: Principal = Depends(require_scopes("read")),
130
+ ) -> dict[str, Any]:
131
+ """Caller: Chronicle sidecar (full fixture for mocks) or Chronicle UI waterfall."""
132
+ return {"envelopes": env_store.list_trace_envelopes(principal.tenant_id, trace_id)}
133
+
134
+ @app.get("/v1/traces", tags=["ui"])
135
+ async def find_traces(
136
+ q: str | None = None,
137
+ session_id: str | None = None,
138
+ message_id: str | None = None,
139
+ user_id: str | None = None,
140
+ limit: int = 200,
141
+ offset: int = 0,
142
+ principal: Principal = Depends(require_scopes("read")),
143
+ ) -> dict[str, Any]:
144
+ """Caller: Chronicle UI — search / filter traces. Not used by the agent sidecar."""
145
+ traces = env_store.search_traces(
146
+ principal.tenant_id,
147
+ q=q,
148
+ session_id=session_id,
149
+ message_id=message_id,
150
+ user_id=user_id,
151
+ limit=min(limit, 500),
152
+ offset=max(offset, 0),
153
+ )
154
+ return {"traces": traces}
155
+
156
+ # ---- TokenOps registration -------------------------------------------- #
157
+
158
+ @app.post("/v1/runs")
159
+ async def register_run(
160
+ request: Request,
161
+ principal: Principal = Depends(require_scopes("ingest")),
162
+ ) -> JSONResponse:
163
+ payload = await request.json()
164
+ run_id = str(payload.get("run_id") or "").strip() or new_id("run")
165
+ try:
166
+ mode = parse_governance_mode(payload.get("mode") or payload.get("governance_mode"))
167
+ except ValueError as exc:
168
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
169
+ reg = registration_from_dict(
170
+ {
171
+ "run_id": run_id,
172
+ "intent": payload.get("intent", ""),
173
+ "user_dims": payload.get("user_dims") or {},
174
+ "mode": mode.value,
175
+ }
176
+ )
177
+ try:
178
+ saved = gov.register_run(reg)
179
+ except RunAlreadyRegisteredError as exc:
180
+ return JSONResponse({"error": str(exc)}, status_code=409)
181
+ # Chronicle session coupling intentionally omitted — agents own their traces.
182
+ return JSONResponse(
183
+ {
184
+ "run_id": saved.run_id,
185
+ "status": "registered",
186
+ "mode": saved.mode.value,
187
+ "intent": saved.intent,
188
+ "user_dims": dict(saved.user_dims),
189
+ },
190
+ status_code=201,
191
+ )
192
+
193
+ @app.get("/v1/runs/{run_id}/registration")
194
+ async def get_registration(
195
+ run_id: str,
196
+ principal: Principal = Depends(require_scopes("read")),
197
+ ) -> JSONResponse:
198
+ reg = gov.get_run_registration(run_id)
199
+ if reg is None:
200
+ return JSONResponse({"error": f"run {run_id!r} is not registered"}, status_code=404)
201
+ return JSONResponse(registration_to_dict(reg))
202
+
203
+ # ---- governance ------------------------------------------------------- #
204
+
205
+ @app.get("/v1/governance/{agent}")
206
+ async def governance_for_agent(
207
+ agent: str,
208
+ principal: Principal = Depends(require_scopes("read")),
209
+ ) -> dict[str, Any]:
210
+ return gov.governance_config_for(agent)
211
+
212
+ @app.get("/v1/segments")
213
+ async def list_segments(principal: Principal = Depends(require_scopes("read"))) -> list[dict[str, Any]]:
214
+ return [segment_to_dict(s) for s in gov.list_segments()]
215
+
216
+ @app.put("/v1/segments")
217
+ async def upsert_segment(
218
+ request: Request,
219
+ principal: Principal = Depends(require_scopes("admin")),
220
+ ) -> dict[str, Any]:
221
+ seg = segment_from_dict(await request.json())
222
+ return segment_to_dict(gov.upsert_segment(seg))
223
+
224
+ @app.get("/v1/segments/{sid}")
225
+ async def get_segment(
226
+ sid: str,
227
+ principal: Principal = Depends(require_scopes("read")),
228
+ ) -> JSONResponse:
229
+ seg = gov.get_segment(sid)
230
+ if seg is None:
231
+ return JSONResponse({"error": "not found"}, status_code=404)
232
+ return JSONResponse(segment_to_dict(seg))
233
+
234
+ @app.delete("/v1/segments/{sid}")
235
+ async def delete_segment(
236
+ sid: str,
237
+ principal: Principal = Depends(require_scopes("admin")),
238
+ ) -> dict[str, str]:
239
+ gov.delete_segment(sid)
240
+ return {"status": "deleted"}
241
+
242
+ @app.get("/v1/budgets")
243
+ async def list_budgets(principal: Principal = Depends(require_scopes("read"))) -> list[dict[str, Any]]:
244
+ return [budget_to_dict(b) for b in gov.list_budgets()]
245
+
246
+ @app.put("/v1/budgets")
247
+ async def upsert_budget(
248
+ request: Request,
249
+ principal: Principal = Depends(require_scopes("admin")),
250
+ ) -> dict[str, Any]:
251
+ spec = budget_from_dict(await request.json())
252
+ return budget_to_dict(gov.upsert_budget(spec))
253
+
254
+ @app.get("/v1/budgets/{bid}")
255
+ async def get_budget(
256
+ bid: str,
257
+ principal: Principal = Depends(require_scopes("read")),
258
+ ) -> JSONResponse:
259
+ spec = gov.get_budget(bid)
260
+ if spec is None:
261
+ return JSONResponse({"error": "not found"}, status_code=404)
262
+ return JSONResponse(budget_to_dict(spec))
263
+
264
+ @app.delete("/v1/budgets/{bid}")
265
+ async def delete_budget(
266
+ bid: str,
267
+ principal: Principal = Depends(require_scopes("admin")),
268
+ ) -> dict[str, str]:
269
+ gov.delete_budget(bid)
270
+ return {"status": "deleted"}
271
+
272
+ @app.get("/v1/policies")
273
+ async def list_policies(principal: Principal = Depends(require_scopes("read"))) -> list[dict[str, Any]]:
274
+ return [policy_to_dict(p) for p in gov.list_policy_instances()]
275
+
276
+ @app.put("/v1/policies")
277
+ async def upsert_policy(
278
+ request: Request,
279
+ principal: Principal = Depends(require_scopes("admin")),
280
+ ) -> dict[str, Any]:
281
+ pi = policy_from_dict(await request.json())
282
+ try:
283
+ saved = gov.upsert_policy_instance(pi)
284
+ except ValueError as exc:
285
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
286
+ return policy_to_dict(saved)
287
+
288
+ @app.get("/v1/policies/{pid}")
289
+ async def get_policy(
290
+ pid: str,
291
+ principal: Principal = Depends(require_scopes("read")),
292
+ ) -> JSONResponse:
293
+ pi = gov.get_policy_instance(pid)
294
+ if pi is None:
295
+ return JSONResponse({"error": "not found"}, status_code=404)
296
+ return JSONResponse(policy_to_dict(pi))
297
+
298
+ @app.delete("/v1/policies/{pid}")
299
+ async def delete_policy(
300
+ pid: str,
301
+ principal: Principal = Depends(require_scopes("admin")),
302
+ ) -> dict[str, str]:
303
+ gov.delete_policy_instance(pid)
304
+ return {"status": "deleted"}
305
+
306
+ # ---- run history ------------------------------------------------------ #
307
+
308
+ @app.put("/v1/run-records")
309
+ async def create_run_record(
310
+ request: Request,
311
+ principal: Principal = Depends(require_scopes("ingest")),
312
+ ) -> dict[str, Any]:
313
+ rec = run_from_dict(await request.json())
314
+ return run_to_dict(gov.create_run(rec))
315
+
316
+ @app.patch("/v1/run-records/{run_id}")
317
+ async def update_run_record(
318
+ run_id: str,
319
+ request: Request,
320
+ principal: Principal = Depends(require_scopes("ingest")),
321
+ ) -> dict[str, str]:
322
+ fields = await request.json()
323
+ gov.update_run(run_id, **fields)
324
+ return {"status": "updated"}
325
+
326
+ @app.get("/v1/run-records/{run_id}")
327
+ async def get_run_record(
328
+ run_id: str,
329
+ principal: Principal = Depends(require_scopes("read")),
330
+ ) -> JSONResponse:
331
+ rec = gov.get_run(run_id)
332
+ if rec is None:
333
+ return JSONResponse({"error": "not found"}, status_code=404)
334
+ return JSONResponse(run_to_dict(rec))
335
+
336
+ @app.get("/v1/run-records")
337
+ async def list_run_records(
338
+ problematic_only: bool = False,
339
+ limit: int = 200,
340
+ principal: Principal = Depends(require_scopes("read")),
341
+ ) -> list[dict[str, Any]]:
342
+ return [run_to_dict(r) for r in gov.list_runs(problematic_only=problematic_only, limit=limit)]
343
+
344
+ @app.get("/v1/run-records/tag-keys")
345
+ async def run_tag_keys(
346
+ limit: int = 500,
347
+ principal: Principal = Depends(require_scopes("read")),
348
+ ) -> list[str]:
349
+ return gov.run_tag_keys(limit=limit)
350
+
351
+ # ---- ledger ----------------------------------------------------------- #
352
+
353
+ @app.post("/v1/ledger/spent/add")
354
+ async def ledger_add_spent(
355
+ request: Request,
356
+ principal: Principal = Depends(require_scopes("ingest")),
357
+ ) -> dict[str, int]:
358
+ body = await request.json()
359
+ spent = gov.ledger_add_spent(
360
+ body["budget_id"], body["segment_key"], body.get("period", "lifetime"), int(body["delta"]),
361
+ )
362
+ return {"spent_micros": spent}
363
+
364
+ @app.get("/v1/ledger/spent")
365
+ async def ledger_get_spent(
366
+ budget_id: str,
367
+ segment_key: str,
368
+ period: str = "lifetime",
369
+ principal: Principal = Depends(require_scopes("read")),
370
+ ) -> dict[str, int]:
371
+ return {"spent_micros": gov.ledger_get_spent(budget_id, segment_key, period)}
372
+
373
+ @app.post("/v1/ledger/inflight/admit")
374
+ async def ledger_admit(
375
+ request: Request,
376
+ principal: Principal = Depends(require_scopes("ingest")),
377
+ ) -> dict[str, int]:
378
+ body = await request.json()
379
+ return {"count": gov.ledger_admit(body["segment_key"])}
380
+
381
+ @app.post("/v1/ledger/inflight/complete")
382
+ async def ledger_complete(
383
+ request: Request,
384
+ principal: Principal = Depends(require_scopes("ingest")),
385
+ ) -> dict[str, int]:
386
+ body = await request.json()
387
+ return {"count": gov.ledger_complete(body["segment_key"])}
388
+
389
+ @app.get("/v1/ledger/inflight")
390
+ async def ledger_inflight(
391
+ segment_key: str,
392
+ principal: Principal = Depends(require_scopes("read")),
393
+ ) -> dict[str, int]:
394
+ return {"count": gov.ledger_inflight(segment_key)}
395
+
396
+ @app.post("/v1/ledger/halt/mark")
397
+ async def ledger_mark_halted(
398
+ request: Request,
399
+ principal: Principal = Depends(require_scopes("ingest")),
400
+ ) -> dict[str, str]:
401
+ body = await request.json()
402
+ gov.ledger_mark_halted(body["run_id"], body.get("reason", ""))
403
+ return {"status": "halted"}
404
+
405
+ @app.get("/v1/ledger/halt/{run_id}")
406
+ async def ledger_halt_status(
407
+ run_id: str,
408
+ principal: Principal = Depends(require_scopes("read")),
409
+ ) -> dict[str, Any]:
410
+ return {
411
+ "halted": gov.ledger_is_halted(run_id),
412
+ "halt_reason": gov.ledger_halt_reason(run_id),
413
+ }
414
+
415
+ @app.post("/v1/ledger/halt/clear")
416
+ async def ledger_clear_halt(
417
+ request: Request,
418
+ principal: Principal = Depends(require_scopes("admin")),
419
+ ) -> dict[str, str]:
420
+ body = await request.json()
421
+ gov.ledger_clear_halt(body["run_id"])
422
+ return {"status": "cleared"}
423
+
424
+ # ---- admin ------------------------------------------------------------ #
425
+
426
+ @app.post("/v1/admin/seed-if-empty")
427
+ async def seed_if_empty(
428
+ request: Request,
429
+ principal: Principal = Depends(require_scopes("admin")),
430
+ ) -> dict[str, bool]:
431
+ body = await request.json()
432
+ seeded = gov.seed_default_governance_if_empty(body.get("governance"))
433
+ return {"seeded": seeded}
434
+
435
+ @app.post("/v1/admin/clear-all")
436
+ async def clear_all(principal: Principal = Depends(require_scopes("admin"))) -> dict[str, str]:
437
+ gov.clear_all()
438
+ return {"status": "cleared"}
439
+
440
+ @app.post("/v1/admin/clear-governance")
441
+ async def clear_governance(principal: Principal = Depends(require_scopes("admin"))) -> dict[str, str]:
442
+ gov.clear_governance()
443
+ return {"status": "cleared"}
444
+
445
+ @app.post("/v1/admin/reseed-governance")
446
+ async def reseed_governance(
447
+ request: Request,
448
+ principal: Principal = Depends(require_scopes("admin")),
449
+ ) -> dict[str, bool]:
450
+ body = await request.json()
451
+ seeded = gov.reseed_governance(body.get("governance"))
452
+ return {"seeded": seeded}
453
+
454
+ # ---- API keys (Admin UI) ---------------------------------------------- #
455
+
456
+ @app.get("/v1/admin/keys", tags=["ui"])
457
+ async def list_keys(principal: Principal = Depends(require_scopes("admin"))) -> dict[str, Any]:
458
+ """Caller: Admin UI. Env keys include the secret (already on the host). DB keys show prefix only."""
459
+ db_keys = [k.__dict__ for k in gov.list_api_keys()]
460
+ env_keys = [k.__dict__ for k in env_key_views(cfg.api_keys)]
461
+ return {"keys": env_keys + db_keys, "auth_disabled": not cfg.api_keys and not gov.list_api_keys()}
462
+
463
+ @app.post("/v1/admin/keys", tags=["ui"])
464
+ async def create_key(
465
+ request: Request,
466
+ principal: Principal = Depends(require_scopes("admin")),
467
+ ) -> dict[str, Any]:
468
+ """Caller: Admin UI. Secret is returned once."""
469
+ body = await request.json()
470
+ name = str(body.get("name") or "").strip()
471
+ tenant = str(body.get("tenant_id") or "local").strip()
472
+ scopes = body.get("scopes") or ["ingest", "read"]
473
+ if isinstance(scopes, str):
474
+ scopes = [s for s in scopes.replace("+", ",").split(",") if s.strip()]
475
+ if not name:
476
+ raise HTTPException(status_code=400, detail="name is required")
477
+ created = gov.create_api_key(name=name, tenant_id=tenant, scopes=scopes)
478
+ return created.__dict__
479
+
480
+ @app.delete("/v1/admin/keys/{kid}", tags=["ui"])
481
+ async def delete_key(
482
+ kid: str,
483
+ principal: Principal = Depends(require_scopes("admin")),
484
+ ) -> dict[str, str]:
485
+ """Caller: Admin UI. Env keys cannot be deleted here."""
486
+ if kid.startswith("env:"):
487
+ raise HTTPException(status_code=400, detail="env keys are removed by unsetting CONTROL_PLANE_API_KEYS")
488
+ gov.delete_api_key(kid)
489
+ return {"status": "deleted"}
490
+
491
+ return app
492
+
493
+
494
+ # ASGI entry: uvicorn control_plane.app:create_app --factory