Repository navigation
Expand file tree
/
Copy pathshim.py
More file actions
1721 lines (1552 loc) · 80.5 KB
/
Copy pathshim.py
File metadata and controls
1721 lines (1552 loc) · 80.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
shim.py — OpenAI-compatible HTTP façade in front of router.lua.
Any client that speaks /v1/chat/completions can POST OpenAI-shaped requests.
The shim translates them to a router contract, runs `router.execute`, and
translates the router result back to an OpenAI response. Provider selection,
fallback, retries and provider auth all live on the router side; the client
sees a single endpoint.
Model field convention (explicit prefixes, no magic):
model = "" -> default_profile
model = "profile:cheap_explore" -> contract.profile
model = "family:deepseek-v3" -> contract.requirements.model_family
model = "pin:<provider>/<family>" -> contract.requirements.pin
model = anything else -> default_profile (logged)
Streaming is supported. With a `streaming_call` dispatcher, `stream: true`
streams token-by-token (with fallback before the first byte); without one — and
for flows, which have no token stream — the finished result is pseudo-streamed
as SSE. Either way the client gets a valid `text/event-stream`.
Concurrency note: lupa serializes Lua execution. FastAPI's threadpool will
queue concurrent /v1/chat/completions calls behind the single LuaRuntime.
Fine for one or a handful of concurrent clients; for hundreds-to-thousands
of concurrent callers, use a luerl-based host instead.
"""
from __future__ import annotations
import asyncio
import logging
import time
import uuid
from typing import Any
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, ConfigDict
import host_store
_log = logging.getLogger("unhardcoded.shim")
# Profile name used when nothing else can be inferred. Replaced via
# create_app(default_profile=...).
DEFAULT_PROFILE_FALLBACK = "default"
# max_tokens supplied when the client omits it. max_tokens is *optional* in
# the OpenAI spec, but some upstream providers / policy candidates reject
# requests that leave it out (the symptom is no_candidates/exhausted), so the
# shim fills in a sane ceiling instead of forwarding nothing. Override via
# create_app(default_max_tokens=...); pass None to keep the strict
# omit-when-absent behaviour.
DEFAULT_MAX_TOKENS_FALLBACK = 4096
class ChatRequest(BaseModel):
"""Permissive OpenAI /v1/chat/completions body.
Unknown fields are kept (`extra="allow"`) so future OpenAI fields don't
require shim edits; the shim only forwards the fields the router knows.
"""
model_config = ConfigDict(extra="allow")
model: str = ""
messages: list[dict] = []
stream: bool = False
tools: list[dict] | None = None
tool_choice: Any = None
response_format: dict | None = None
temperature: float | None = None
seed: int | None = None
max_tokens: int | None = None
# Optional upstream liveness guard. For OpenAI-compatible streaming-capable
# routes, fail/fallback if no content/tool delta arrives before this budget.
first_token_timeout_ms: int | None = None
# Σ_pol per-call policy: a TERM (plain JSON array, e.g.
# ["policy", ["ev_zero"], ["meets_req"], ...]). Data, never code: the
# core admits it (sorts/arity/depth/node bounds) and ∧-composes the
# host's config.policy_envelope so callers narrow, never widen.
# Admission failure -> 400 invalid_policy.
policy_ir: list | None = None
# Σ_flow per-call composition: a flow TERM (plain JSON, { "flow", nodes })
# where each node carries its own policy_ir + system prompt. Data, never
# code: the core admits the whole DAG (graph validity + every node's
# policy). When present it takes precedence over policy_ir/model. Admission
# failure -> 400 invalid_flow.
flow_ir: list | None = None
# Conversation/session id (optional). When present the host learns which peer
# served this session (route_cache) and, next turn, marks that peer's offer
# cache_hot so a cache-aware policy keeps the prompt-cache-hot peer sticky.
# Pure host state — never enters the algebra's signature; clients without a
# session simply get no affinity. Additive to OpenAI-compat.
session: str | None = None
# The authed consumer key behind this request, set by the ingress proxy via
# the x-llm-router-caller header (consumers cannot set it — the proxy strips
# and re-injects it). Never sent to the core; used only to bind sid->owner in
# the session meter so the consumer-facing session view stays per-consumer.
caller: str | None = None
class ResponsesRequest(BaseModel):
"""Permissive OpenAI /v1/responses body. Unknown fields are kept
(extra="allow") so Responses params the shim does not read (reasoning,
include, store, parallel_tool_calls, prompt_cache_key, text,
previous_response_id, …) never break the request."""
model_config = ConfigDict(extra="allow")
model: str = ""
input: Any = None # str | list[item]
instructions: str | None = None
tools: list[dict] | None = None
tool_choice: Any = None
stream: bool = False
max_output_tokens: int | None = None
temperature: float | None = None
first_token_timeout_ms: int | None = None
policy_ir: list | None = None
session: str | None = None
caller: str | None = None
class PolicyRankRequest(BaseModel):
"""Body of POST /x/rank — dry-run a per-call policy term."""
policy_ir: list
context: int = 32000
requirements: dict | None = None
class CompactRequest(BaseModel):
"""Body of POST /v1/compact — append-only context sealing.
A STATELESS transform: the caller sends the whole message array, the host
seals the aged middle into one summary (routed cheaply by `policy_ir`) and
returns the spliced array. The host holds NO conversation state — the agent
stays sovereign over its context (the cache_hot peer also stays hot because
the frozen prefix is never rewritten)."""
messages: list[dict]
keep_recent: int = 6 # verbatim tail kept after the seal
policy_ir: list | None = None # cheap routing for the summarizer
max_tokens: int | None = 512
class FlowNormalizeRequest(BaseModel):
"""Body of POST /x/flow/normalize — admit + identify a Σ_flow term."""
flow_ir: list
class PolicyBuildRequest(BaseModel):
"""Body of POST /x/policy/build — the declarative surface the dashboard
builder collects; lowered by the core's elaborate, never host-side."""
weights: dict | None = None
filter: list | dict | str | None = None
selector: str | None = None
selector_opts: dict | None = None
mutate: list | dict | str | None = None
retry_table: dict | None = None
def _rank_rows(ranked: list) -> list[dict]:
rows = []
for r in ranked:
c = r.get("candidate") or {}
rows.append({
"provider": c.get("provider_id"),
"model_family": c.get("model_family"),
"served_model_id": c.get("served_model_id"),
"tier": c.get("tier"),
"discovery": c.get("discovery"),
"price_in": c.get("price_in"),
"price_out": c.get("price_out"),
"quality": c.get("quality_hint"),
"score": r.get("score"),
})
return rows
# ---- context compaction (POST /v1/compact) --------------------------------
_SEAL_SYSTEM = (
"Summarize the conversation below, preserving decisions, open threads, file "
"paths, and key identifiers. Be dense and concrete.")
_SEAL_PREFIX = "[Earlier conversation, sealed summary]\n"
# Cheapest healthy route — a seal is auxiliary work, never the main model.
_DEFAULT_COMPACT_POLICY = [
"policy",
["and", ["meets_req"], ["not", ["is", "disabled"]]],
["neg", ["normalize", ["field", "price_in"]]],
["argmax"], ["id"], ["always", {"action": "next_candidate"}],
]
def _render_messages(msgs: list[dict]) -> str:
out = []
for m in msgs:
content = m.get("content")
if isinstance(content, list): # multimodal parts -> text only
content = " ".join(p.get("text", "") for p in content
if isinstance(p, dict))
out.append(f"{m.get('role', '?')}: {content}")
return "\n".join(out)
def _compact_suggested(resp: dict) -> bool:
"""Context-pressure hint: True once a call's INPUT crosses the operator
threshold (settings `compaction.at_tokens`). Surfaced on x_router so an agent
knows to POST /v1/compact — it owns the threshold decision, not the agent.
Measured on the real prompt_tokens the call reported, so it costs nothing."""
import settings as _settings
n = resp.get("tokens_in")
if not n:
return False
try:
return int(n) >= int(_settings.get("compaction.at_tokens"))
except (TypeError, ValueError):
return False
def create_app(host, default_profile: str = DEFAULT_PROFILE_FALLBACK,
streaming_call=None,
default_max_tokens: int | None = DEFAULT_MAX_TOKENS_FALLBACK,
codex_store=None,
) -> FastAPI:
"""Build a FastAPI app wired to a pre-initialized LLMRouterHost.
The host must already have `init()` called and `host.call_provider`
pointing at something that actually talks to providers (or a mock for
tests).
`streaming_call(request, emit)` is the streaming api_kind dispatcher
(streaming.make_streaming_dispatcher). Without it, `stream: true`
requests still work via the pseudo-stream path (complete result encoded
as SSE) — which is also what mocked backends produce.
"""
import asyncio
import streaming as _streaming
app = FastAPI(title="llm-router shim", docs_url=None, redoc_url=None)
# subscription backends (codex) are billed $0 per request — their ranking
# price is a scarcity shadow price, not a cost
subscription_providers = frozenset(
pid for pid, p in ((host.catalog() or {}).get("providers") or {}).items()
if isinstance(p, dict) and p.get("api_kind") == "openai_codex")
@app.post("/x/codex/reload")
def reload_codex_accounts():
"""Re-scan the Codex accounts dir on the PVC so accounts added/removed
from the dashboard go live without a router restart. Internal — /x/* is
hidden from consumers."""
if codex_store is None:
return JSONResponse(status_code=404, content={"error": {
"message": "codex multi-account store not configured",
"type": "not_found", "code": "codex_store_absent"}})
names = codex_store.reload()
return {"ok": True, "accounts": names}
@app.post("/x/config/reload")
def reload_config():
"""Re-read operator config overrides (dashboard Config tab) so tunable
knobs (antseed top-N, codex scarcity ramp, runway thresholds, price
multipliers) apply without a router restart. Sources read settings.get
live; marketplace discovery is invalidated so source-level filters that
affect offers refresh immediately instead of waiting for the discovery
TTL. Price multipliers are applied live at candidate assembly time.
Internal — /x/* is hidden from consumers."""
import settings as _settings
overrides = _settings.reload()
for provider in (host.catalog().get("providers") or {}).values():
if isinstance(provider, dict) and provider.get("discovery") == "marketplace":
did = provider.get("discovery_id")
if did:
host.invalidate_discovery(did)
return {"ok": True, "overrides": overrides}
@app.get("/x/session/{sid}")
def session_meter(sid: str, request: Request):
"""Accumulated usage for a session: calls, tokens_in/out, tokens_cached,
cost_usd — the running total the per-call x_router.session_acc reflects —
plus `warm`: the routes (family/provider/served_by) currently holding the
session's prompt-cache prefix. Internal (/x/* hidden from consumers).
Cross-consumer isolation: a session's economics + warm peers belong to the
consumer that first wrote the sid (bound in observe(owner=...)). When the
ingress proxy forwards a consumer's authed key as x-llm-router-caller (the
consumer-facing /v1/session/{sid} view), only that owner may read it —
anyone else gets 404 (NOT 403: confirming the sid exists would itself leak
that consumer A holds it). Operator callers (dashboard /x/*, no caller
header) are unscoped, as before. The in-process meter resets on restart,
so an unknown owner also means there is simply nothing to show — 404 is
consistent either way."""
caller = request.headers.get("x-llm-router-caller")
if caller:
owner = host_store.session_owner(sid)
if owner is None or owner != caller:
return JSONResponse(status_code=404, content={"error": {
"message": "session not found", "type": "not_found",
"code": "session_not_found"}})
acc = host_store.session_totals(sid)
return {**acc, "warm": host_store.session_warm(sid)}
@app.get("/x/sessions")
def session_meters():
"""All session meters (operator view of per-session spend/cache)."""
return {"sessions": host_store.all_session_totals()}
@app.get("/x/calls")
def recent_calls(limit: int = 100):
"""Recent rows from the host-store call ledger (operator view /
verification of the emerging source of truth). Read-only."""
import host_store
return {"calls": host_store.recent_calls(min(max(int(limit), 1), 1000)),
"total": host_store.count()}
# ---- AntSeed buyer hot-wallet control (dashboard self-service) -----------
# Proxy deposit/withdraw/refresh to the sidecar control server, then refresh
# SOURCE_STATE so /x/market reflects the new escrow at once. Internal — /x/*
# is hidden from consumers.
import os as _os
import re as _re
_AMOUNT_RE = _re.compile(r"^\d+(\.\d{1,6})?$")
def _wallet_control():
url = (_os.getenv("ANTSEED_CONTROL_URL") or "").rstrip("/")
token = _os.getenv("ANTSEED_CONTROL_TOKEN") or ""
return (url, token) if (url and token) else (None, None)
def _antseed_wallet_view():
import sources as _sources
for pid, bal in ((_sources.SOURCE_STATE.get("antseed") or {})
.get("balances") or {}).items():
det = bal.get("detail") or {}
return {"provider": pid, "address": det.get("wallet"),
"deposits_available": bal.get("value"),
"deposits_reserved": det.get("reserved"),
"wallet_usdc": det.get("wallet_usdc"),
"wallet_eth": det.get("wallet_eth"),
"connection": det.get("connection"),
"fetched_at": bal.get("fetched_at")}
return None
async def _refresh_antseed_wallet():
import sources as _sources
from sources.antseed import AntSeedSource
try:
await _sources.refresh_once(host, host.catalog(), AntSeedSource(host.catalog()))
except Exception: # noqa: BLE001 — refresh is best-effort
pass
return _antseed_wallet_view()
async def _wallet_mutate(op: str, body: dict):
url, token = _wallet_control()
if not url:
return JSONResponse(status_code=503, content={"error": {
"message": "antseed wallet control not configured",
"type": "wallet_error", "code": "wallet_control_unavailable"}})
amount = str((body or {}).get("amount", "")).strip()
if not _AMOUNT_RE.match(amount) or float(amount) <= 0:
return JSONResponse(status_code=400, content={"error": {
"message": "amount must be a positive USDC value (<=6 decimals)",
"type": "invalid_request", "code": "wallet_amount"}})
import httpx
try:
async with httpx.AsyncClient() as c:
r = await c.post(f"{url}/{op}", json={"amount": amount},
headers={"x-antseed-control-token": token}, timeout=130.0)
except httpx.HTTPError as e:
return JSONResponse(status_code=502, content={"error": {
"message": f"wallet control unreachable: {e}",
"type": "wallet_error", "code": "wallet_control_unreachable"}})
if r.status_code != 200:
try:
detail = (r.json() or {}).get("error")
except Exception: # noqa: BLE001
detail = (r.text or "")[:300]
return JSONResponse(status_code=502, content={"error": {
"message": str(detail), "type": "wallet_error", "code": "wallet_op_failed"}})
return {"ok": True, "action": op, "amount": amount,
"wallet": await _refresh_antseed_wallet()}
@app.get("/x/wallet")
async def wallet_view():
# Read-only balance snapshot for the dashboard wallet panel (no on-chain
# tx). Falls back to a live refresh if the source cache is empty.
w = _antseed_wallet_view()
if w is None:
w = await _refresh_antseed_wallet()
return {"ok": True, "wallet": w}
@app.post("/x/wallet/deposit")
async def wallet_deposit(body: dict):
return await _wallet_mutate("deposit", body)
@app.post("/x/wallet/withdraw")
async def wallet_withdraw(body: dict):
return await _wallet_mutate("withdraw", body)
@app.post("/x/wallet/refresh")
async def wallet_refresh():
url, token = _wallet_control()
if url:
import httpx
try:
async with httpx.AsyncClient() as c:
await c.post(f"{url}/status",
headers={"x-antseed-control-token": token}, timeout=35.0)
except httpx.HTTPError:
pass
return {"ok": True, "wallet": await _refresh_antseed_wallet()}
async def _wallet_reclaim(op: str, timeout: float, with_wallet: bool):
# Channel reclaim: recover USDC reserved in idle payment channels.
# scan read-only enumeration of on-chain reclaimable funds
# request-close start the ~15-min on-chain challenge (one tx/channel)
# withdraw pull funds from channels whose window has elapsed
url, token = _wallet_control()
if not url:
return JSONResponse(status_code=503, content={"error": {
"message": "antseed wallet control not configured",
"type": "wallet_error", "code": "wallet_control_unavailable"}})
import httpx
try:
async with httpx.AsyncClient() as c:
r = await c.post(f"{url}/reclaim/{op}",
headers={"x-antseed-control-token": token}, timeout=timeout)
except httpx.HTTPError as e:
return JSONResponse(status_code=502, content={"error": {
"message": f"wallet control unreachable: {e}",
"type": "wallet_error", "code": "wallet_control_unreachable"}})
try:
payload = r.json() or {}
except Exception: # noqa: BLE001
payload = {}
if r.status_code != 200:
detail = payload.get("error") or (r.text or "")[:300]
return JSONResponse(status_code=502, content={"error": {
"message": str(detail), "type": "wallet_error", "code": "reclaim_failed"}})
if with_wallet:
payload["wallet"] = await _refresh_antseed_wallet()
return payload
@app.post("/x/wallet/reclaim/scan")
async def wallet_reclaim_scan():
return await _wallet_reclaim("scan", 95.0, with_wallet=False)
@app.post("/x/wallet/reclaim/set-operator")
async def wallet_reclaim_set_operator():
# One-time: assign the buyer wallet as its own deposits operator so
# requestClose/withdraw stop reverting NotAuthorized(). Moves no funds.
return await _wallet_reclaim("set-operator", 250.0, with_wallet=False)
@app.post("/x/wallet/reclaim/request-close")
async def wallet_reclaim_request_close():
return await _wallet_reclaim("request-close", 250.0, with_wallet=False)
@app.post("/x/wallet/reclaim/withdraw")
async def wallet_reclaim_withdraw():
return await _wallet_reclaim("withdraw", 250.0, with_wallet=True)
@app.get("/healthz")
def healthz():
info = host.info()
return {"ok": True, "initialized": info.get("initialized", False)}
@app.get("/v1/models")
def list_models():
import sources as _sources
info = host.info()
ids = [f"profile:{p}" for p in (info.get("profile_names") or [])]
seen = set(info.get("models_loaded") or [])
ids += [f"family:{f}" for f in seen]
# discovered marketplace families (e.g. live OpenRouter models) are
# routable too, so list them alongside the curated families.
for sstate in _sources.SOURCE_STATE.values():
for r in (sstate.get("book") or {}).get("rows") or []:
fam = r.get("model_family")
if fam and fam not in seen:
seen.add(fam)
ids.append(f"family:{fam}")
return {"object": "list", "data": [{"id": i, "object": "model"} for i in ids]}
@app.get("/x/runtime")
def runtime_state():
"""Live router runtime for the operator dashboard: circuit breakers,
disabled providers, EMA metrics (incl. live prices), source freshness
and balances. Internal — the ingress proxy hides /x/* from consumer
callers and fetches this server-side."""
import sources as _sources
state = host.dump_state() or {}
balances: dict = {}
sources_view: dict = {}
for name, s in _sources.SOURCE_STATE.items():
balances.update(s.get("balances") or {})
sources_view[name] = {k: v for k, v in s.items()
if k not in ("balances", "book")}
return {
"ts": int(time.time()),
"circuit_breakers": state.get("circuit_breakers") or {},
"disabled_providers": state.get("disabled_providers") or {},
"ema_metrics": state.get("ema_metrics") or {},
"balances": balances,
"sources": sources_view,
}
@app.get("/x/market")
def market_view():
"""Full price book per curated family: every seller each source knows
about (marketplace sellers trimmed to the best few per family by the
source), with live performance from EMA metrics where the router has
actually called that provider|family. Internal — the dashboard
fetches this server-side; /x/* is hidden from consumers."""
import sources as _sources
import host_store
catalog = host.catalog() or {}
models = catalog.get("models") or {}
state = host.dump_state() or {}
ema = state.get("ema_metrics") or {} # still carries seeded price + credits
disabled = state.get("disabled_providers") or {}
marketplace_pids = {
pid for pid, p in (catalog.get("providers") or {}).items()
if isinstance(p, dict) and p.get("discovery") == "marketplace"}
# Live perf is host-owned now (#15): the engine folds no EMA, so build it
# from the host's per-route measurements — DERIVED on the fly from
# route_observations (#4a), aggregated across the peers/route ids that
# serve a given provider|family. None until the router has called it.
_stats = host_store.route_stats() # {route_key: {success_rate, latency_ms, count}}
def _perf(provider, family):
prefix = f"{provider}|{family}|"
rows = [v for k, v in _stats.items() if k.startswith(prefix)]
total = sum(r["count"] for r in rows)
if not total:
return None
sr_rows = [r for r in rows if r.get("success_rate") is not None]
lt_rows = [r for r in rows if r.get("latency_ms") is not None]
sr_calls = sum(r["count"] for r in sr_rows)
lt_calls = sum(r["count"] for r in lt_rows)
sr = sum(r["success_rate"] * r["count"] for r in sr_rows)
lt = sum(r["latency_ms"] * r["count"] for r in lt_rows)
return {"success_rate": (sr / sr_calls) if sr_calls else None,
"latency_ms": round(lt / lt_calls) if lt_calls else None,
"calls": total}
def _antseed_row(r, family, book):
via = (r.get("tradable_via") or [None])[0]
return {
"source": "antseed",
"seller": f"peer {str(r.get('seller') or '')[:8]}",
"wire_model_id": r.get("wire_model_id"),
"price_in": r.get("price_in"),
"price_out": r.get("price_out"),
"price_refreshed_at": book.get("fetched_at"),
"last_seen": r.get("last_seen"),
"pinned": bool(r.get("pinned_by")),
"tradable": bool(via),
"via": via,
"perf": _perf(via, family) if via else None,
}
# Registered model-level traits (OpenRouter benchmarks/modalities/caps),
# per curated family — same source the policy/builder gate on.
meta = host.model_meta() or {}
book = (_sources.SOURCE_STATE.get("antseed") or {}).get("book") or {}
book_rows: dict[str, list] = {}
for r in book.get("rows") or []:
book_rows.setdefault(r.get("model_family"), []).append(r)
# without a book (source down / first boot), fall back to the
# marketplace EMA rows so pinned offers stay visible
have_book = bool(book.get("rows"))
families = []
for family, model in models.items():
rows = []
for key, m in ema.items():
provider, _, fam = key.partition("|")
if fam != family:
continue
if have_book and provider in marketplace_pids:
continue
if m.get("price_in") is None and m.get("price_out") is None:
continue
rows.append({
"source": provider,
"seller": provider,
"wire_model_id": None,
"price_in": m.get("price_in"),
"price_out": m.get("price_out"),
"price_refreshed_at": m.get("price_refreshed_at"),
"pinned": None,
"tradable": provider not in disabled,
"via": provider,
"perf": _perf(provider, family),
})
for r in book_rows.get(family) or []:
rows.append(_antseed_row(r, family, book))
rows.sort(key=lambda r: (r.get("price_in") is None,
r.get("price_in") or 0,
r.get("price_out") or 0))
direct = len([r for r in rows if r["source"] != "antseed"])
market_total = ((book.get("families") or {}).get(family) or {}).get(
"sellers_total", len([r for r in rows if r["source"] == "antseed"]))
families.append({
"family": family,
"quality": model.get("static_quality_hint"),
"sellers_total": direct + market_total,
"meta": meta.get(family) or {},
"rows": rows,
})
# uncurated marketplace services: routable but absent from the curated
# catalog (no benchmark). Surface them too so the dashboard shows the
# WHOLE market, flagged uncurated and sorted after the curated families.
for family, brows in book_rows.items():
if family in models:
continue
rows = sorted((_antseed_row(r, family, book) for r in brows),
key=lambda r: (r.get("price_in") is None,
r.get("price_in") or 0,
r.get("price_out") or 0))
market_total = ((book.get("families") or {}).get(family) or {}).get(
"sellers_total", len(rows))
families.append({
"family": family,
"quality": None,
"uncurated": True,
"sellers_total": market_total,
"meta": {},
"rows": rows,
})
# Other marketplace sources that expose a book (e.g. live OpenRouter
# discovery). Their rows are already source-tagged; surface the uncurated
# families the same way antseed's are, so the Catalog shows the whole
# OpenRouter catalog without hand curation.
for sname, sstate in _sources.SOURCE_STATE.items():
if sname == "antseed":
continue
sbook = sstate.get("book") or {}
srows: dict[str, list] = {}
for r in sbook.get("rows") or []:
srows.setdefault(r.get("model_family"), []).append(r)
for family, brows in srows.items():
if family in models:
continue # curated families already shown above
rows = sorted(({
"source": r.get("source") or sname,
"seller": r.get("seller") or sname,
"wire_model_id": r.get("wire_model_id"),
"price_in": r.get("price_in"),
"price_out": r.get("price_out"),
"price_refreshed_at": sbook.get("fetched_at"),
"pinned": None,
"tradable": bool(r.get("tradable", True)),
"via": r.get("via"),
"perf": _perf(r.get("via"), family) if r.get("via") else None,
} for r in brows), key=lambda r: (r.get("price_in") is None,
r.get("price_in") or 0,
r.get("price_out") or 0))
fam_info = (sbook.get("families") or {}).get(family) or {}
market_total = fam_info.get("sellers_total", len(rows))
families.append({
# discovered, but first-class: full live benchmarks/modalities
# in `meta`, same shape the curated families expose.
"family": family, "quality": None, "discovered": True,
"sellers_total": market_total, "meta": fam_info.get("meta") or {},
"rows": rows,
})
def _family_sort_key(f):
# curated first, then discovered/uncurated; within a group sort by
# quality hint or, for discovered families, their live benchmark.
grp = 1 if (f.get("uncurated") or f.get("discovered")) else 0
q = f["quality"] if f["quality"] is not None \
else (f.get("meta") or {}).get("bench_intelligence")
return (grp, -(q if q is not None else -1), f["family"])
families.sort(key=_family_sort_key)
# AntSeed buyer hot-wallet: address (where to top up), deposits and
# connection, read live from the source's balances() — so the address
# always reflects the CURRENT identity (if the data volume regenerates
# it, the new address shows here automatically). One buyer -> one wallet.
wallet = None
for pid, bal in ((_sources.SOURCE_STATE.get("antseed") or {})
.get("balances") or {}).items():
det = bal.get("detail") or {}
wallet = {
"provider": pid,
"address": det.get("wallet"),
"deposits_available": bal.get("value"),
"deposits_reserved": det.get("reserved"),
"wallet_usdc": det.get("wallet_usdc"),
"wallet_eth": det.get("wallet_eth"),
"connection": det.get("connection"),
"fetched_at": bal.get("fetched_at"),
}
break
return {"families": families, "wallet": wallet, "ts": int(time.time())}
@app.post("/x/providers")
def add_provider(body: dict):
"""Hot-add an operator-defined provider (openai_compatible + env key
only). Validates against the live catalog, injects the key into the
process env, merges the provider into the Lua config and re-inits the
core with breakers/EMA state preserved. Persistence is the ingress's
job (the provider_overlays store + .env.secrets); this endpoint only
makes it live. Internal — /x/* is hidden from consumers."""
import os
from provider_overlay import apply_to_host, validate_entry
pid = str(body.get("id") or "").strip()
entry = {
"base_url": body.get("base_url"),
"api_kind": body.get("api_kind") or "openai_compatible",
"tier": body.get("tier") or "partner",
"auth_env": body.get("auth_env"),
"served_models": body.get("served_models") or [],
}
errors = validate_entry(pid, entry, host.catalog())
if any("already exists" in e for e in errors):
return JSONResponse(status_code=409, content={"error": {
"message": f"provider {pid!r} already exists",
"type": "conflict", "code": "provider_exists"}})
if errors:
return JSONResponse(status_code=400, content={"error": {
"message": "; ".join(errors), "type": "invalid_request",
"code": "provider_invalid"}})
key = body.get("key")
if key:
os.environ[str(entry["auth_env"])] = str(key)
host.set_env(str(entry["auth_env"]), str(key))
snapshot = host.dump_state()
applied = apply_to_host(host, {"providers": {pid: entry}})
host.init()
host.restore_state(snapshot)
return {"ok": True, "provider": pid, "applied": applied,
"key_installed": bool(key)}
@app.post("/x/provider-key")
def set_provider_key(body: dict):
"""Update the API key of an EXISTING provider — no catalog change, so
no 'already exists' rejection and no re-init. Injects the key into the
process env and host._env; the core reads host._env live, so the next
call uses the new key. Persistence (.env.secrets) is the ingress's job.
Internal — /x/* is hidden from consumers."""
import os
pid = str(body.get("provider") or body.get("id") or "").strip()
key = body.get("key")
if not key:
return JSONResponse(status_code=400, content={"error": {
"message": "key is required", "type": "invalid_request",
"code": "provider_key"}})
provider = (host.catalog().get("providers") or {}).get(pid)
if not isinstance(provider, dict):
return JSONResponse(status_code=404, content={"error": {
"message": f"provider {pid!r} not found",
"type": "not_found", "code": "provider_not_found"}})
auth_env = str(provider.get("auth_env") or "").strip()
if not auth_env:
return JSONResponse(status_code=400, content={"error": {
"message": f"provider {pid!r} has no auth_env (e.g. oauth/codex); "
"key update not applicable",
"type": "invalid_request", "code": "provider_no_auth_env"}})
os.environ[auth_env] = str(key)
host.set_env(auth_env, str(key))
return {"ok": True, "provider": pid, "auth_env": auth_env,
"key_installed": True}
@app.get("/x/rank")
def rank_profile(profile: str, context: int = 32000):
"""Live ranking for one profile — live prices, breakers, marketplace
offers included. Internal: the dashboard renders THIS instead of
rebuilding a seed-priced copy of the router."""
try:
ranked, rejected = host.rank({"profile": profile,
"requirements": {"context": context}})
except Exception as exc:
return JSONResponse(status_code=400, content={"error": {
"message": str(exc), "type": "router_error", "code": "rank"}})
return {"profile": profile, "rank_source": "router",
"ranked": _rank_rows(ranked), "rejected": rejected,
"ts": int(time.time())}
@app.post("/x/policy/build")
def policy_build(body: PolicyBuildRequest):
"""Lower a declarative spec (weights + filter gates + selector) to a
Σ_pol term via the core's elaborate — the policy builder's compose
step. Returns {policy_ir, fingerprint, version}. The term is NOT
admitted here: admission happens with the live schema and the host
envelope where the term is used (POST /x/rank, execution)."""
try:
return host.build_policy(body.model_dump(exclude_none=True))
except Exception as exc:
msg = str(exc)
idx = msg.find("elaborate: ")
if idx == -1 and "lua" not in type(exc).__module__:
raise
return JSONResponse(status_code=400, content={"error": {
"message": msg[idx + 11:] if idx != -1 else msg,
"type": "invalid_request_error", "code": "invalid_policy_spec"}})
@app.get("/x/fields")
def list_fields():
"""The observable fields (core vocabulary + config.fields extensions)
with sort and builder group — drives the data-driven builder."""
return {"fields": host.field_schema()}
@app.post("/x/policy/normalize")
def policy_normalize(body: PolicyRankRequest):
"""Normalize a raw Σ_pol term and return {policy_ir, fingerprint,
version} — the builder's download/identify step when the frontend
composes the IR directly. Admission still happens at use (POST /x/rank,
execution)."""
try:
return host.normalize_policy(body.policy_ir)
except Exception as exc:
admission = _policy_admission_error(exc)
if admission is not None:
return _invalid_policy_response(admission)
return JSONResponse(status_code=400, content={"error": {
"message": str(exc), "type": "invalid_request_error",
"code": "invalid_policy"}})
@app.post("/x/flow/normalize")
def flow_normalize(body: FlowNormalizeRequest):
"""Admit + normalize a Σ_flow term and return {flow_ir, fingerprint,
version} — the Flow Builder's review/identify step. Admission (graph
validity + every node's policy) is the core's job, like policy_ir."""
try:
return host.flow_admit(body.flow_ir)
except Exception as exc:
admission = _flow_admission_error(exc)
if admission is not None:
return _invalid_flow_response(admission)
return JSONResponse(status_code=400, content={"error": {
"message": str(exc), "type": "invalid_request_error",
"code": "invalid_flow"}})
@app.post("/x/rank")
def rank_policy_ir(body: PolicyRankRequest):
"""Dry-run ranking for a per-call Σ_pol policy term — the policy
builder's preview. Same admission path as execution: the core checks
the term and ∧-applies the host envelope; nothing is called."""
contract: dict = {"policy_ir": body.policy_ir,
"requirements": body.requirements
or {"context": body.context}}
try:
ranked, rejected = host.rank(contract)
except Exception as exc:
admission = _policy_admission_error(exc)
if admission is None:
raise
return _invalid_policy_response(admission)
return {"rank_source": "router", "ranked": _rank_rows(ranked),
"rejected": rejected, "ts": int(time.time())}
@app.post("/v1/compact")
async def compact(req: CompactRequest):
"""Append-only context sealing (stateless). Seal the aged middle of the
message array into one cheaply-routed summary and splice it back so the
frozen prefix and the recent tail are byte-identical — keeping everything
upstream cache-hot. Returns {messages, compacted}. The agent owns its
context; the host stores nothing.
Cost accounting (additive wire contract): the seal is a real billable
LLM leg, so every response that FOLLOWS host.execute_async — the sealed
success AND the compacted:false seal-failure — also carries "usage"
(OpenAI token shape, the summarizer call's tokens) and "x_router" (the
same block _build_x_router puts on chat responses), so a metering proxy
in front can record the seal's spend instead of a $0 row. Early returns
that precede execution made no call and carry neither key."""
msgs = req.messages or []
keep = max(1, req.keep_recent)
# frozen prefix = a leading system message (the skill/tools/rules), if any
frozen = msgs[:1] if (msgs and msgs[0].get("role") == "system") else []
head = len(frozen)
if len(msgs) - head <= keep: # nothing worth sealing
return {"messages": msgs, "compacted": False}
recent = msgs[len(msgs) - keep:]
aged = msgs[head:len(msgs) - keep]
# Anti-orphan (the API-400 trap): a leading `tool` message in `recent`
# answers an assistant tool_call that lives in `aged` and is about to be
# dropped. Drop those orphaned tool turns at the seam.
while recent and recent[0].get("role") == "tool":
recent = recent[1:]
if not aged:
return {"messages": msgs, "compacted": False}
contract = {
"messages": [{"role": "system", "content": _SEAL_SYSTEM},
{"role": "user", "content": _render_messages(aged)}],
"policy_ir": req.policy_ir or _DEFAULT_COMPACT_POLICY,
"max_tokens": req.max_tokens or 512,
}
try:
res = await host.execute_async(contract)
except Exception as exc:
admission = _policy_admission_error(exc)
if admission is not None:
return _invalid_policy_response(admission)
raise
def _costed(body: dict) -> dict:
usage = _openai_usage(res.get("response") or {})
if usage:
body["usage"] = usage
body["x_router"] = _build_x_router(res, subscription_providers)
return body
summary = ((res.get("response") or {}).get("text") or "").strip()
if not summary: # seal failed -> never lose content
return _costed({"messages": msgs, "compacted": False})
sealed = {"role": "system", "content": _SEAL_PREFIX + summary}
return _costed({"messages": frozen + [sealed] + recent, "compacted": True})
@app.post("/v1/chat/completions")
async def chat_completions(req: ChatRequest, request: Request):
_session_from_header(req, request)
return await _handle_chat(req)
@app.post("/{profile_name}/v1/chat/completions")
async def chat_completions_profiled(profile_name: str, req: ChatRequest, request: Request):
"""Path-addressed policy endpoint.
POST /edge/v1/chat/completions always runs the `edge` profile, ignoring
the client's model string. This lets each intelligence tier be its own
base_url (…/edge, …/medium, …/dummy) so a client picks a policy by URL
instead of a `profile:` model prefix.
"""
_session_from_header(req, request)
return await _handle_chat(req, profile_name=profile_name)
def _session_from_header(req: ChatRequest, request: Request) -> None:
"""Fallback the conversation id from the X-Unhardcoded-Session header when
the body carries none. Clients (e.g. the opencode plugin) that can set
request headers but not extra body fields use this to get cache affinity +
per-session metering. An explicit body `session` always wins.
Also capture the authed consumer key the ingress proxy injects as
x-llm-router-caller, so the per-session meter can bind sid->owner (a body
field can't be trusted for this; only the proxy sets this header)."""
if not req.session:
hdr = request.headers.get("x-unhardcoded-session")
if hdr:
req.session = hdr
caller = request.headers.get("x-llm-router-caller")
if caller:
req.caller = caller
# ---- OpenAI Responses API surface (POST /v1/responses) ----------------
# The inbound mirror of codex_backend.py: translate a Responses request to
# the SAME chat contract the chat path builds, run the SAME engine, and
# translate the result back to a Responses object / SSE. Lets Responses-only
# clients (the Codex CLI) drive the router with all routing/policy/metering.
@app.post("/v1/responses")
async def responses(req: ResponsesRequest, request: Request):
_session_from_header(req, request)
return await _handle_responses(req)
@app.post("/{profile_name}/v1/responses")
async def responses_profiled(profile_name: str, req: ResponsesRequest,
request: Request):
_session_from_header(req, request)
return await _handle_responses(req, profile_name=profile_name)
def _responses_object_with_router(result: dict, req: ResponsesRequest,
response_id: str | None = None) -> dict:
import responses_api as _rapi
obj = _rapi.result_to_responses_object(result, req.model or "",
response_id=response_id)
obj["x_router"] = _build_x_router(result, subscription_providers,
req.session, req.caller)
return obj
async def _handle_responses(req: ResponsesRequest, profile_name: str | None = None):
if profile_name is None and (msg := _policy_model_without_ir(req)):
return _bad_policy_selector_response(msg)
import responses_api as _rapi
dropped = _rapi.dropped_tool_types(req.tools)
if dropped:
_log.warning("responses: dropped non-function tool types %s "
"(chat providers accept only function tools)", dropped)
chatreq = ChatRequest(
model=req.model or "",
messages=_rapi.input_to_messages(req.input, req.instructions),
tools=_rapi.tools_to_chat(req.tools),
tool_choice=_rapi.tool_choice_to_chat(req.tool_choice),
temperature=req.temperature,
max_tokens=req.max_output_tokens,
first_token_timeout_ms=req.first_token_timeout_ms,
policy_ir=req.policy_ir,
session=req.session,
)
contract = _request_to_contract(chatreq, default_profile, default_max_tokens)
if profile_name is not None:
contract["profile"] = profile_name
if not req.stream:
try: