-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathshim.py
More file actions
2091 lines (1903 loc) · 99.7 KB
/
Copy pathshim.py
File metadata and controls
2091 lines (1903 loc) · 99.7 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, Field
import control_plane_client
from env_coerce import env_int
import host_store
from policy_templates import (
PolicyTemplateError,
build_policy_template,
template_catalog,
)
_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
# Hard ceiling for one router execution, including retries and fallbacks. This
# deliberately stays below the production ALB's 60 s idle timeout so unary
# requests finish with a structured router error instead of being cut off as an
# opaque gateway 503. Override with ROUTER_REQUEST_DEADLINE_MS.
DEFAULT_REQUEST_DEADLINE_MS = 50_000
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
reasoning: dict | None = None
reasoning_effort: str | 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
# Hard timeout for each provider attempt. This is separate from the
# server-side request deadline, which caps the complete fallback chain.
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
flow_input: dict | list | str | None = None # typed data for a generic flow
# 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 DecisionsRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
model: str = ""
state: Any
questions: dict
policy_ir: list | None = None
timeout_ms: int | None = None
first_token_timeout_ms: int | None = None
session: 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 (
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
reasoning: dict | None = None
reasoning_effort: str | None = None
temperature: float | None = None
first_token_timeout_ms: int | None = None
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
protocol: str = "chat"
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
decision_policy_ir: list | None = None # opt-in fragment triage
target_ratio: float = Field(default=0.1, gt=0, le=1)
pinned_indices: list[int] | None = None # default: every user message
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,
request_deadline_ms: int | None = 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.
`request_deadline_ms` caps the complete router execution (all retries and
fallbacks). When omitted, ROUTER_REQUEST_DEADLINE_MS is read once at app
startup, defaulting to 50 seconds.
"""
import asyncio
import streaming as _streaming
if request_deadline_ms is None:
request_deadline_ms = env_int(
"ROUTER_REQUEST_DEADLINE_MS", DEFAULT_REQUEST_DEADLINE_MS)
if request_deadline_ms <= 0:
raise ValueError("request_deadline_ms must be greater than zero")
request_deadline_s = request_deadline_ms / 1000.0
async def _execute_with_deadline(awaitable):
"""Await one complete router run and cancel it at the outer deadline.
asyncio.timeout propagates cancellation into the active provider call,
so an expired request does not leave an orphan fallback chain running
after the HTTP response has finished.
"""
deadline = asyncio.timeout(request_deadline_s)
try:
async with deadline:
return await awaitable
except TimeoutError:
# Do not relabel a TimeoutError raised by the host itself: only the
# timeout context's own expiry is the outer request deadline.
if not deadline.expired():
raise
_log.warning(
"router request deadline exceeded after %d ms",
request_deadline_ms,
)
return {
"ok": False,
"error": "timeout",
"trace": {
"decision_path": [],
"request_deadline_exceeded": True,
"request_deadline_ms": request_deadline_ms,
"total_latency_ms": request_deadline_ms,
**automatic_trace(),
},
}
from saas_routes import ScopedHost, automatic_trace, install as install_saas
host = ScopedHost(host)
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()
def _antseed_pid() -> str:
"""The buyer proxy these dashboard ops act on — the ledger key. Matches
the sidecar's ANTSEED_BUYER_PID default when the catalog has none."""
import wallet_keeper as _wk
pids = _wk.antseed_provider_ids(host.catalog())
return pids[0] if pids else "antseed"
async def _wallet_mutate(op: str, body: dict):
"""A HUMAN-initiated deposit/withdraw from the dashboard.
Ledgered, for the same reason the keeper's are: this endpoint reaches the
same buyer CLI and the same hot wallet, and a dashboard deposit whose
HTTP call timed out while the CLI was still executing used to leave NO
record anywhere — real USDC moved, `wallet_ops` said nothing, and the
operator saw only "wallet control unreachable". Recorded under
`topup_manual`/`withdraw_manual` rather than the keeper's own `topup`, so
the audit trail is complete without a human top-up silently consuming the
keeper's daily cap (two actors, two budgets, one wallet)."""
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 wallet_keeper as _wk
pid = _antseed_pid()
op_id = host_store.wallet_op_begin(
pid, f"{op}_manual", amount_usdc=float(amount),
reason=f"dashboard-initiated {op}")
import httpx
try:
async with httpx.AsyncClient() as c:
# The client budget must strictly EXCEED the sidecar's own worst
# case for this endpoint, or the timeout is a lie: the control
# server goes on executing a request this side has written off.
r = await c.post(f"{url}/{op}", json={"amount": amount},
headers={"x-antseed-control-token": token},
timeout=_wk.DEPOSIT_TIMEOUT_S)
except (httpx.InvalidURL, httpx.UnsupportedProtocol) as e:
if op_id is not None:
host_store.wallet_op_finish(op_id, "failed", detail=str(e)[:2000])
return JSONResponse(status_code=502, content={"error": {
"message": f"wallet control misconfigured: {e}",
"type": "wallet_error", "code": "wallet_control_unreachable"}})
except Exception as e: # noqa: BLE001 — timeout, reset, DNS, TLS, ...
# The request reached the wire, so the CLI may have broadcast a Base
# mainnet transaction. `unknown`, never `failed`.
if op_id is not None:
host_store.wallet_op_finish(
op_id, "unknown",
detail=f"{type(e).__name__}: {e} (the transaction may have landed)")
return JSONResponse(status_code=502, content={"error": {
"message": f"wallet control unreachable: {e} — the {op} may still "
"have executed; check the wallet ops ledger before retrying",
"type": "wallet_error", "code": "wallet_control_unreachable"}})
if r.status_code != 200:
try:
payload = r.json() or {}
except Exception: # noqa: BLE001
payload = {}
detail = payload.get("error") or (r.text or "")[:300]
attempted = payload.get("attempted")
if not isinstance(attempted, bool):
attempted = r.status_code not in _wk.NOT_ATTEMPTED_STATUSES
if op_id is not None:
host_store.wallet_op_finish(
op_id, "unknown" if attempted else "failed",
detail=str(detail)[:2000])
return JSONResponse(status_code=502, content={"error": {
"message": str(detail), "type": "wallet_error", "code": "wallet_op_failed"}})
if op_id is not None:
host_store.wallet_op_finish(op_id, "ok", detail=str(
(r.json() or {}).get("stdout") if r.headers.get("content-type", "")
.startswith("application/json") else "")[:2000])
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
# Budgets are the keeper's, which are derived from the sidecar's OWN
# published worst case (antseed/control.js /budgets). A shorter one here
# would be a lie in the same way the keeper's used to be: the control server
# keeps working on a request this side has already given up on.
@app.post("/x/wallet/reclaim/scan")
async def wallet_reclaim_scan():
import wallet_keeper as _wk
return await _wallet_reclaim("scan", _wk.RECLAIM_SCAN_TIMEOUT_S,
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.
import wallet_keeper as _wk
return await _wallet_reclaim("set-operator", _wk.RECLAIM_TX_TIMEOUT_S,
with_wallet=False)
@app.post("/x/wallet/reclaim/request-close")
async def wallet_reclaim_request_close():
import wallet_keeper as _wk
return await _wallet_reclaim("request-close", _wk.RECLAIM_TX_TIMEOUT_S,
with_wallet=False)
@app.post("/x/wallet/reclaim/withdraw")
async def wallet_reclaim_withdraw():
import wallet_keeper as _wk
return await _wallet_reclaim("withdraw", _wk.RECLAIM_TX_TIMEOUT_S,
with_wallet=True)
# ---- keeper hard halts: the operator's way back ----------------------
# Both breakers are sticky and deliberately not self-clearing, and the docs
# say "until an operator clears the flag" — but nothing outside the tests
# ever called `wallet_clear_halt`, so the only recovery was psql. A breaker
# with no reset is not a breaker, it is a trap.
@app.get("/x/wallet/halts")
async def wallet_halts():
pid = _antseed_pid()
return {"ok": True, "provider": pid, "halts": {
kind: {
"halted": host_store.wallet_halted(pid, kind),
"rows": [r for r in host_store.wallet_ops_recent(pid, limit=100)
if r["op"] == f"halt:{kind}"],
} for kind in ("topup", "reclaim")}}
@app.post("/x/wallet/clear-halt")
async def wallet_clear_halt(body: dict):
kind = str((body or {}).get("kind", "")).strip()
if kind not in ("topup", "reclaim"):
return JSONResponse(status_code=400, content={"error": {
"message": "kind must be 'topup' or 'reclaim'",
"type": "invalid_request", "code": "wallet_halt_kind"}})
pid = _antseed_pid()
if not host_store.wallet_clear_halt(pid, kind):
return JSONResponse(status_code=502, content={"error": {
"message": "could not clear the halt (store unavailable)",
"type": "wallet_error", "code": "wallet_halt_clear_failed"}})
_log.warning("wallet keeper: %s halt CLEARED for %s by an operator",
kind, pid)
return {"ok": True, "provider": pid, "kind": kind,
"halted": host_store.wallet_halted(pid, kind)}
@app.get("/healthz")
def healthz():
info = host.info()
return {"ok": True, "initialized": info.get("initialized", False)}
@app.get("/v1/models")
def list_models(type: str | None = None):
import sources as _sources
from decision_protocol import known_decision_model
if type not in (None, 'all', 'text', 'decision', 'decisions'):
return _openai_error('Unknown model category', 'invalid_request_error', 400)
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}")
decision_families = {f for f, m in (host.catalog().get('models') or {}).items()
if m.get('protocol') == 'decisions'}
for sstate in _sources.SOURCE_STATE.values():
for row in (sstate.get('book') or {}).get('rows', []):
if row.get('category') == 'decision':
decision_families.add(row['model_family'])
data = []
for model_id in ids:
family = model_id.removeprefix('family:')
category = 'decision' if family in decision_families or known_decision_model(family) else 'text'
if type in ('decision', 'decisions') and category != 'decision' or type == 'text' and category != 'text':
continue
data.append({'id': model_id, 'object': 'model', 'type': category,
'category': 'Decision models' if category == 'decision' else 'Text models'})
return {"object": "list", "data": data}
@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 host_store as _host_store
import sources as _sources
import wallet_keeper as _wallet_keeper
state = host.dump_state() or {}
balances: dict = {}
sources_view: dict = {}
for name, s in _sources.SOURCE_STATE.items():
balances.update(s.get("balances") or {})
# `stats` rides along here (offers kept/suppressed, wallet_health);
# only the bulky per-row views are stripped.
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,
# The autonomous funding loop's last decision per buyer proxy, plus
# its recent wallet ops — the audit trail for money the router moved
# on its own. Read-only.
"keeper": dict(_wallet_keeper.KEEPER_STATE),
"wallet_ops": _host_store.wallet_ops_recent(limit=20),
}
@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)
from decision_protocol import known_decision_model
decision_families = {f for f, m in models.items() if m.get('protocol') == 'decisions'}
for sstate in _sources.SOURCE_STATE.values():
for row in (sstate.get('book') or {}).get('rows', []):
if row.get('category') == 'decision':
decision_families.add(row['model_family'])
for family in families:
is_decision = family['family'] in decision_families or known_decision_model(family['family'])
family['type'] = 'decision' if is_decision else 'text'
family['category'] = 'Decision models' if is_decision else 'Text models'
# 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")