-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlemmacomputer_policy_callback.py
More file actions
1596 lines (1462 loc) · 67.3 KB
/
Copy pathlemmacomputer_policy_callback.py
File metadata and controls
1596 lines (1462 loc) · 67.3 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
"""Fail-closed LiteLLM MCP pre-call policy callback owned by LemmaComputer."""
import asyncio
import base64
import contextvars
import hashlib
import hmac
import json
import logging
import os
import re
import threading
import time
from datetime import datetime, timedelta, timezone
import urllib.error
import urllib.request
from fastapi import HTTPException
import litellm
from litellm.integrations.custom_logger import CustomLogger
LOGGER = logging.getLogger(__name__)
POLICY_URL = os.environ.get(
"LEMMACOMPUTER_MCP_POLICY_URL",
"http://control-api:4100/internal/v1/mcp/authorize",
)
POLICY_TOKEN = os.environ.get("LEMMACOMPUTER_MCP_POLICY_TOKEN", "")
WORKSPACE_ACCESS_URL = os.environ.get(
"LEMMACOMPUTER_WORKSPACE_ACCESS_URL",
"http://control-api:4100/internal/v1/workspace-access/authorize",
)
WORKSPACE_ACCESS_TOKEN = os.environ.get("LEMMACOMPUTER_WORKSPACE_ACCESS_TOKEN", "")
POLICY_TIMEOUT_SECONDS = 15
POLICY_ATTEMPTS = 2
USAGE_URL = os.environ.get(
"LEMMACOMPUTER_AI_USAGE_URL",
"http://control-api:4100/internal/v1/ai-usage",
).rstrip("/")
USAGE_TOKEN = os.environ.get("LEMMACOMPUTER_AI_USAGE_TOKEN", "")
ROUTING_STATE_KEY = "lemmacomputer_routing_state"
USAGE_STATE_KEY = "lemmacomputer_usage_state"
USAGE_CHAIN_KEY = "lemmacomputer_usage_chain"
USAGE_STATE_TTL_SECONDS = 15 * 60
ROUTING_HEALTH_TTL_SECONDS = 60
_ROUTING_HEALTH_LOCK = threading.Lock()
_ROUTING_UNAVAILABLE_UNTIL = {}
_USAGE_STATE_LOCK = threading.Lock()
_USAGE_STATES_BY_CALL = {}
_INTERNAL_ADMISSION_CONTEXT = contextvars.ContextVar(
"lemmacomputer_internal_admission_context", default=None
)
PROVIDER_ROUTE_TEST_EXEMPTION = "provider-route-test-v1"
USAGE_CHAIN_SECRET = hmac.new(
USAGE_TOKEN.encode("utf-8"),
b"lemmacomputer-usage-chain-secret/v1",
hashlib.sha256,
).digest()
MS365_SERVER_NAME = "lemmacomputer_ms365"
MS365_SERVER_ID = hashlib.sha256(
b"lemmacomputer_ms365|http://ms365-mcp:3000/mcp|http|oauth2|"
).hexdigest()[:32]
MS365_ACCOUNT_LOOKUP_TOOL = "get-current-user"
MS365_ACCOUNT_LOOKUP_ARGUMENTS = {
"$select": "displayName,mail,userPrincipalName",
}
AUDIT_ONLY_ARGUMENTS = {"lemmacomputerAudit"}
_PROVIDER_INTERNAL_FIELDS = (
"user_api_key_dict",
"user_api_key_metadata",
)
def _metadata(auth):
value = getattr(auth, "metadata", None)
if isinstance(value, str):
try:
value = json.loads(value)
except json.JSONDecodeError:
value = None
return value if isinstance(value, dict) else {}
def _optional_string(metadata, name):
value = metadata.get(name)
return value if isinstance(value, str) and value else None
def _server_binding(metadata, data, permitted_servers):
bindings = metadata.get("lemmacomputer_mcp_server_bindings")
if not isinstance(bindings, dict):
bindings = {}
server_names = metadata.get("lemmacomputer_mcp_servers")
if isinstance(server_names, list) and len(server_names) == len(permitted_servers):
bindings = {
**dict(zip(permitted_servers, server_names)),
**bindings,
}
server_id = data.get("server_id")
if not isinstance(server_id, str) or not server_id:
server_id = permitted_servers[0] if len(permitted_servers) == 1 else None
if not isinstance(server_id, str) or server_id not in permitted_servers:
return None, None
server_name = bindings.get(server_id)
if server_id == MS365_SERVER_ID and not isinstance(server_name, str):
server_name = MS365_SERVER_NAME
if not isinstance(server_name, str) or not server_name:
return None, None
return server_id, server_name
def _is_connection_account_lookup(metadata, payload):
return (
metadata.get("lemmacomputer_connection_credential") is True
and metadata.get("lemmacomputer_connection_account_lookup") is True
and metadata.get("lemmacomputer_connection_server") == MS365_SERVER_NAME
and payload.get("tenantId") is not None
and payload.get("subjectId") is not None
and payload.get("serverName") == MS365_SERVER_NAME
and payload.get("toolName") == MS365_ACCOUNT_LOOKUP_TOOL
and payload.get("arguments") == MS365_ACCOUNT_LOOKUP_ARGUMENTS
)
def _contains_image_input(value):
if isinstance(value, str):
return value.startswith("data:image/")
if isinstance(value, list):
return any(_contains_image_input(child) for child in value)
if not isinstance(value, dict):
return False
content_type = value.get("type")
if content_type in {"image", "image_url", "input_image"}:
return True
source = value.get("source")
if isinstance(source, dict) and (
source.get("type") == "base64"
and isinstance(source.get("media_type"), str)
and source["media_type"].startswith("image/")
):
return True
return any(_contains_image_input(child) for child in value.values())
def _supports_vision(kwargs):
params = kwargs.get("litellm_params")
candidates = [
params.get("model_info") if isinstance(params, dict) else None,
kwargs.get("litellm_model_info"),
kwargs.get("model_info"),
kwargs.get("metadata", {}).get("model_info")
if isinstance(kwargs.get("metadata"), dict)
else None,
]
for candidate in candidates:
if isinstance(candidate, dict) and isinstance(candidate.get("supports_vision"), bool):
return candidate["supports_vision"]
model = kwargs.get("model")
if not isinstance(model, str) or not model:
return False
try:
return litellm.get_model_info(model).get("supports_vision") is True
except Exception:
return False
def _request_decision(payload):
if len(POLICY_TOKEN) < 24:
raise RuntimeError("MCP policy callback token is not configured")
encoded = json.dumps(payload, separators=(",", ":")).encode("utf-8")
result = None
for attempt in range(POLICY_ATTEMPTS):
request = urllib.request.Request(
POLICY_URL,
data=encoded,
method="POST",
headers={
"content-type": "application/json",
"x-lemmacomputer-mcp-policy-token": POLICY_TOKEN,
},
)
try:
with urllib.request.urlopen(request, timeout=POLICY_TIMEOUT_SECONDS) as response:
if response.status != 200:
raise RuntimeError("MCP policy authority returned a non-success status")
result = json.load(response)
break
except urllib.error.HTTPError:
raise
except (OSError, urllib.error.URLError):
# Authorization is idempotent for an exact tool call. If Control
# committed the operation but the response was lost, one immediate
# retry recovers the same operation ID instead of making the model
# retry the original write with newly generated arguments.
if attempt + 1 >= POLICY_ATTEMPTS:
raise
required = {
"schemaVersion",
"decision",
"code",
"capabilityId",
"schemaId",
"schemaHash",
"operationId",
}
if (
not isinstance(result, dict)
or set(result) not in (required, required | {"problem"})
or result.get("schemaVersion") != 1
):
raise RuntimeError("MCP policy authority returned a malformed decision")
if result.get("decision") not in ("allow", "deny", "approval_required"):
raise RuntimeError("MCP policy authority returned an unknown decision")
problem = result.get("problem")
if problem is not None and (
not isinstance(problem, dict)
or set(problem) != {"category", "field", "message", "retryable"}
or problem.get("category") not in {
"invalid_argument", "unsupported_option", "authentication_failure", "policy_denial",
"provider_rejection", "timeout", "unknown_failure",
}
or not isinstance(problem.get("message"), str)
or not isinstance(problem.get("retryable"), bool)
or (problem.get("field") is not None and not isinstance(problem.get("field"), str))
):
raise RuntimeError("MCP policy authority returned an invalid problem detail")
return result
def _agent_instance_id(data):
candidates = [data.get("request_headers"), data.get("headers")]
proxy_request = data.get("proxy_server_request")
if isinstance(proxy_request, dict):
candidates.append(proxy_request.get("headers"))
for headers in candidates:
if not isinstance(headers, dict):
continue
for name, value in headers.items():
if isinstance(name, str) and name.lower() == "x-lemmacomputer-agent-instance-id" and isinstance(value, str):
return value
return None
def _source_invocation_id(data):
candidates = [data.get("request_headers"), data.get("headers")]
proxy_request = data.get("proxy_server_request")
if isinstance(proxy_request, dict):
candidates.append(proxy_request.get("headers"))
for headers in candidates:
if not isinstance(headers, dict):
continue
for name, value in headers.items():
if isinstance(name, str) and name.lower() == "x-lemmacomputer-tool-invocation-id" and isinstance(value, str):
return value
return None
def _authorize_workspace_access(metadata):
workspace_id = metadata.get("lemmacomputer_workspace_id")
if not isinstance(workspace_id, str) or not workspace_id:
return
generation = metadata.get("lemmacomputer_access_generation")
payload = {
"tenantId": metadata.get("lemmacomputer_tenant_id"),
"subjectId": metadata.get("lemmacomputer_subject_id"),
"workspaceId": workspace_id,
"accessGeneration": generation,
}
if (
len(WORKSPACE_ACCESS_TOKEN) < 24
or not isinstance(payload["tenantId"], str)
or not isinstance(payload["subjectId"], str)
or not isinstance(generation, int)
or generation < 1
):
raise RuntimeError("Workspace access metadata is incomplete")
request = urllib.request.Request(
WORKSPACE_ACCESS_URL,
data=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
method="POST",
headers={
"content-type": "application/json",
"x-lemmacomputer-mcp-policy-token": WORKSPACE_ACCESS_TOKEN,
},
)
with urllib.request.urlopen(request, timeout=0.9) as response:
result = json.load(response)
if response.status != 200 or result != {"allowed": True}:
raise RuntimeError("Workspace access is no longer active")
def _as_dict(value):
if isinstance(value, dict):
return value
if hasattr(value, "model_dump"):
dumped = value.model_dump()
return dumped if isinstance(dumped, dict) else {}
if hasattr(value, "dict"):
dumped = value.dict()
return dumped if isinstance(dumped, dict) else {}
return {}
def _metadata_dicts(kwargs):
values = []
direct = kwargs.get("metadata")
if isinstance(direct, dict):
values.append(direct)
params = kwargs.get("litellm_params")
if isinstance(params, dict) and isinstance(params.get("metadata"), dict):
values.append(params["metadata"])
return values
def _litellm_call_id(kwargs):
candidates = [kwargs.get("litellm_call_id")]
params = kwargs.get("litellm_params")
if isinstance(params, dict):
candidates.append(params.get("litellm_call_id"))
for metadata in _metadata_dicts(kwargs):
candidates.append(metadata.get("litellm_call_id"))
for candidate in candidates:
if isinstance(candidate, str) and candidate.strip():
return candidate.strip()
return None
def _usage_provider_deployment_id(kwargs):
candidates = []
params = kwargs.get("litellm_params")
if isinstance(params, dict):
candidates.append(params.get("model_info"))
candidates.extend([kwargs.get("litellm_model_info"), kwargs.get("model_info")])
for metadata in _metadata_dicts(kwargs):
candidates.append(metadata.get("model_info"))
for candidate in candidates:
if isinstance(candidate, dict):
deployment_id = candidate.get("lemmacomputer_deployment_id")
if isinstance(deployment_id, str) and deployment_id:
return deployment_id
return None
def _prune_usage_states(now):
for call_id in list(_USAGE_STATES_BY_CALL):
live = [
entry for entry in _USAGE_STATES_BY_CALL[call_id]
if entry["expiresAt"] > now
]
if live:
_USAGE_STATES_BY_CALL[call_id] = live
else:
_USAGE_STATES_BY_CALL.pop(call_id, None)
while len(_USAGE_STATES_BY_CALL) > 4096:
oldest = min(
_USAGE_STATES_BY_CALL,
key=lambda call_id: _USAGE_STATES_BY_CALL[call_id][-1]["recordedAt"],
)
_USAGE_STATES_BY_CALL.pop(oldest, None)
def _remember_usage_state(kwargs, state):
call_id = _litellm_call_id(kwargs)
admission_id = state.get("admissionId") if isinstance(state, dict) else None
if call_id is None or not isinstance(admission_id, str):
return
now = time.monotonic()
entry = {
"state": state,
"providerDeploymentId": _usage_provider_deployment_id(kwargs),
"recordedAt": now,
"expiresAt": now + USAGE_STATE_TTL_SECONDS,
}
with _USAGE_STATE_LOCK:
_prune_usage_states(now)
current = [
candidate for candidate in _USAGE_STATES_BY_CALL.get(call_id, [])
if candidate["state"].get("admissionId") != admission_id
]
_USAGE_STATES_BY_CALL[call_id] = (current + [entry])[-8:]
_prune_usage_states(now)
def _registered_usage_state(kwargs):
call_id = _litellm_call_id(kwargs)
if call_id is None:
return None
now = time.monotonic()
deployment_id = _usage_provider_deployment_id(kwargs)
with _USAGE_STATE_LOCK:
_prune_usage_states(now)
entries = _USAGE_STATES_BY_CALL.get(call_id, [])
if deployment_id is not None:
matches = [
entry for entry in entries
if entry["providerDeploymentId"] == deployment_id
]
if matches:
return matches[-1]["state"]
return entries[-1]["state"] if entries else None
def _forget_usage_state(state):
admission_id = state.get("admissionId") if isinstance(state, dict) else None
if not isinstance(admission_id, str):
return
with _USAGE_STATE_LOCK:
for call_id in list(_USAGE_STATES_BY_CALL):
remaining = [
entry for entry in _USAGE_STATES_BY_CALL[call_id]
if entry["state"].get("admissionId") != admission_id
]
if remaining:
_USAGE_STATES_BY_CALL[call_id] = remaining
else:
_USAGE_STATES_BY_CALL.pop(call_id, None)
def _trusted_key_metadata(kwargs):
"""Read identity only from LiteLLM's authenticated key projection."""
auth = kwargs.get("user_api_key_dict")
return _metadata(auth) if auth is not None else {}
def _provider_request(kwargs):
"""Return provider-bound kwargs without LiteLLM authentication internals."""
request = {
name: value
for name, value in kwargs.items()
if not (isinstance(name, str) and name.startswith("lemmacomputer_"))
}
for name in _PROVIDER_INTERNAL_FIELDS:
request.pop(name, None)
metadata = request.get("metadata")
if isinstance(metadata, dict):
request["metadata"] = {
name: value
for name, value in metadata.items()
if not (isinstance(name, str) and name.startswith("lemmacomputer_"))
}
params = request.get("litellm_params")
if isinstance(params, dict):
params = {
name: value
for name, value in params.items()
if not (isinstance(name, str) and name.startswith("lemmacomputer_"))
}
nested_metadata = params.get("metadata")
if isinstance(nested_metadata, dict):
params["metadata"] = {
name: value
for name, value in nested_metadata.items()
if not (isinstance(name, str) and name.startswith("lemmacomputer_"))
}
request["litellm_params"] = params
return request
def _signed_usage_chain(value):
encoded = base64.urlsafe_b64encode(
json.dumps(value, separators=(",", ":"), sort_keys=True).encode("utf-8")
).decode("ascii").rstrip("=")
signature = hmac.new(
USAGE_CHAIN_SECRET,
b"lemmacomputer-usage-chain/v1\0" + encoded.encode("ascii"),
hashlib.sha256,
).hexdigest()
return f"{encoded}.{signature}"
def _verified_usage_chain(value):
if not isinstance(value, str):
return None
try:
encoded, signature = value.split(".", 1)
expected = hmac.new(
USAGE_CHAIN_SECRET,
b"lemmacomputer-usage-chain/v1\0" + encoded.encode("ascii"),
hashlib.sha256,
).hexdigest()
if not hmac.compare_digest(signature, expected):
return None
padding = "=" * (-len(encoded) % 4)
decoded = json.loads(base64.urlsafe_b64decode(encoded + padding))
return decoded if isinstance(decoded, dict) else None
except (ValueError, UnicodeError, json.JSONDecodeError):
return None
def _request_usage_context_and_strip_reserved(kwargs, source_attempt_id=None):
"""Recover only callback-signed lineage or the proxy-owned initial binding."""
task_binding = None
parent_attempt_id = None
lineage_found = False
for metadata in _metadata_dicts(kwargs):
chain = _verified_usage_chain(metadata.get(USAGE_CHAIN_KEY))
if chain is not None:
candidate = chain.get("taskBinding")
if task_binding is None and isinstance(candidate, str):
task_binding = candidate
prior_admission_id = chain.get("admissionId")
prior_source_attempt_id = chain.get("sourceAttemptId")
original_parent_attempt_id = chain.get("originalParentAttemptId")
original_parent_is_valid = (
original_parent_attempt_id is None
or isinstance(original_parent_attempt_id, str)
)
if not lineage_found and isinstance(prior_admission_id, str):
if (
isinstance(source_attempt_id, str)
and prior_source_attempt_id == source_attempt_id
and "originalParentAttemptId" in chain
and original_parent_is_valid
):
# LiteLLM may enter the deployment hook again for the same
# concrete invocation. Preserve the parent admitted the
# first time instead of making the attempt its own parent.
parent_attempt_id = original_parent_attempt_id
else:
# A different concrete retry/fallback descends from the
# prior admitted invocation.
parent_attempt_id = prior_admission_id
lineage_found = True
requester = metadata.get("requester_metadata")
if isinstance(requester, dict):
candidate = requester.get("lemmacomputer_task_binding")
if task_binding is None and isinstance(candidate, str):
task_binding = candidate
for name in list(requester):
if isinstance(name, str) and name.startswith("lemmacomputer_"):
requester.pop(name, None)
candidate = metadata.get("lemmacomputer_task_binding")
if task_binding is None and isinstance(candidate, str):
task_binding = candidate
for name in list(metadata):
if isinstance(name, str) and name.startswith("lemmacomputer_"):
metadata.pop(name, None)
return task_binding, parent_attempt_id
def _is_internal_responses_conversion(kwargs, call_type):
call_type_value = str(getattr(call_type, "value", call_type) or "").lower()
return "response" in call_type_value or _nested_parameter(kwargs, "aresponses") is True
def _verified_usage_reentry(kwargs, source_attempt_id, route, call_type):
"""Accept a signed same attempt or LiteLLM's internal Responses conversion."""
if not isinstance(source_attempt_id, str) or not source_attempt_id:
return False
route_provider = route.get("lemmacomputer_provider") if isinstance(route, dict) else None
internal_responses_conversion = _is_internal_responses_conversion(kwargs, call_type)
for metadata in _metadata_dicts(kwargs):
chain = _verified_usage_chain(metadata.get(USAGE_CHAIN_KEY))
state = metadata.get(USAGE_STATE_KEY)
if (
isinstance(chain, dict)
and isinstance(state, dict)
and (
chain.get("sourceAttemptId") == source_attempt_id
or internal_responses_conversion
)
and isinstance(chain.get("admissionId"), str)
and chain.get("admissionId") == state.get("admissionId")
and isinstance(state.get("tenantId"), str)
and bool(state.get("tenantId"))
and isinstance(state.get("provider"), str)
and bool(state.get("provider"))
and state.get("provider") == route_provider
):
_remember_usage_state(kwargs, state)
return True
context = _INTERNAL_ADMISSION_CONTEXT.get()
if internal_responses_conversion and isinstance(context, dict):
state = context.get("state")
signed_chain = context.get("signedChain")
chain = _verified_usage_chain(signed_chain)
if (
isinstance(state, dict)
and isinstance(signed_chain, str)
and isinstance(chain, dict)
and chain.get("admissionId") == state.get("admissionId")
and context.get("provider") == route_provider
and context.get("deploymentId") == route.get("lemmacomputer_deployment_id")
):
kwargs[USAGE_STATE_KEY] = state
metadata = kwargs.get("metadata")
if not isinstance(metadata, dict):
metadata = {}
kwargs["metadata"] = metadata
metadata[USAGE_STATE_KEY] = state
metadata[USAGE_CHAIN_KEY] = signed_chain
_remember_usage_state(kwargs, state)
return True
return False
def _verified_provider_probe(kwargs, route, call_type):
"""Accept only a Control-issued probe on its provider-native entry point."""
trusted = _trusted_key_metadata(kwargs)
if trusted.get("lemmacomputer_non_billable_exemption") != PROVIDER_ROUTE_TEST_EXEMPTION:
return False
trusted_provider = trusted.get("lemmacomputer_provider")
trusted_deployment_id = trusted.get("lemmacomputer_deployment_id")
if not all(
isinstance(value, str) and bool(value)
for value in (trusted_provider, trusted_deployment_id)
):
raise RuntimeError("Provider route test key binding is incomplete")
if trusted_provider == "openai" and not _is_internal_responses_conversion(kwargs, call_type):
raise RuntimeError("OpenAI provider route tests must use the Responses API")
route_provider = route.get("lemmacomputer_provider") if isinstance(route, dict) else None
route_deployment_id = (
route.get("lemmacomputer_deployment_id") if isinstance(route, dict) else None
)
if (
isinstance(route_provider, str)
and route_provider != trusted_provider
) or (
isinstance(route_deployment_id, str)
and route_deployment_id != trusted_deployment_id
):
raise RuntimeError("Provider route test binding does not match the concrete route")
return True
def _model_info(kwargs):
candidates = []
params = kwargs.get("litellm_params")
if isinstance(params, dict):
candidates.append(params.get("model_info"))
candidates.extend([kwargs.get("litellm_model_info"), kwargs.get("model_info")])
for metadata in _metadata_dicts(kwargs):
candidates.append(metadata.get("model_info"))
for candidate in candidates:
if isinstance(candidate, dict) and candidate.get("lemmacomputer_deployment_id"):
return candidate
return {}
def _iso(value=None):
current = value if isinstance(value, datetime) else datetime.now(timezone.utc)
if current.tzinfo is None:
current = current.replace(tzinfo=timezone.utc)
return current.astimezone(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
def _usage_request(path, payload):
if len(USAGE_TOKEN) < 32:
raise RuntimeError("AI usage callback token is not configured")
encoded = json.dumps(payload, separators=(",", ":")).encode("utf-8")
result = None
for attempt in range(2):
request = urllib.request.Request(
f"{USAGE_URL}/{path}",
data=encoded,
method="POST",
headers={
"content-type": "application/json",
"x-lemmacomputer-ai-usage-token": USAGE_TOKEN,
},
)
try:
with urllib.request.urlopen(request, timeout=2) as response:
if response.status not in (200, 201):
raise RuntimeError("AI usage authority returned a non-success status")
result = json.load(response)
break
except urllib.error.HTTPError:
raise
except (OSError, urllib.error.URLError):
if attempt == 1:
raise
if not isinstance(result, dict) or result.get("schemaVersion") != 1:
raise RuntimeError("AI usage authority returned a malformed response")
return result
def _routing_state(kwargs):
value = kwargs.get(ROUTING_STATE_KEY)
if isinstance(value, dict):
return value
for metadata in _metadata_dicts(kwargs):
value = metadata.get(ROUTING_STATE_KEY)
if isinstance(value, dict):
return value
return None
def _set_routing_state(kwargs, state):
kwargs[ROUTING_STATE_KEY] = state
metadata = kwargs.get("metadata")
if not isinstance(metadata, dict):
metadata = {}
kwargs["metadata"] = metadata
metadata[ROUTING_STATE_KEY] = state
def _record_execution_health(tenant_id, deployment_id, outcome):
if not isinstance(tenant_id, str) or not isinstance(deployment_id, str):
return
key = (tenant_id, deployment_id)
with _ROUTING_HEALTH_LOCK:
if outcome == "unavailable":
_ROUTING_UNAVAILABLE_UNTIL[key] = time.monotonic() + ROUTING_HEALTH_TTL_SECONDS
elif outcome == "healthy":
_ROUTING_UNAVAILABLE_UNTIL.pop(key, None)
def _unavailable_deployment_ids(tenant_id):
now = time.monotonic()
with _ROUTING_HEALTH_LOCK:
expired = [key for key, expires_at in _ROUTING_UNAVAILABLE_UNTIL.items() if expires_at <= now]
for key in expired:
_ROUTING_UNAVAILABLE_UNTIL.pop(key, None)
return sorted(
deployment_id
for (candidate_tenant, deployment_id), expires_at in _ROUTING_UNAVAILABLE_UNTIL.items()
if candidate_tenant == tenant_id and expires_at > now
)[:100]
def _request_routing_metadata(kwargs):
values = {}
for metadata in _metadata_dicts(kwargs):
requester = metadata.get("requester_metadata")
if isinstance(requester, dict):
values.update(requester)
values.update(metadata)
return values
def _bounded_request_text(value, remaining=8192):
if remaining <= 0:
return ""
if isinstance(value, str):
return value[:remaining]
if isinstance(value, list):
return " ".join(_bounded_request_text(item, remaining) for item in value)[:remaining]
if isinstance(value, dict):
return " ".join(_bounded_request_text(item, remaining) for item in value.values())[:remaining]
return ""
def _routing_signals(kwargs, estimated):
text = _bounded_request_text(kwargs.get("messages") or kwargs.get("input")).lower()
signals = []
if estimated < 20:
signals.append("short_request")
if "```" in text or re.search(r"\b(function|class|import|const|def|sql|typescript|python)\b", text):
signals.append("code_request")
if re.search(r"\b(api|database|debug|latency|schema|deployment|network|architecture)\b", text):
signals.append("technical_request")
if re.search(r"\b(reason|reasoning|prove|trade-?offs?|root cause|step by step|compare and justify)\b", text):
signals.append("reasoning_request")
if (isinstance(kwargs.get("messages"), list) and len(kwargs["messages"]) > 4) or re.search(r"(?:^|\n)\s*[1-3][.)]", text):
signals.append("multi_step_request")
if estimated > 16000:
signals.extend(["long_request", "long_context_required"])
return list(dict.fromkeys(signals)) or ["low_confidence_default"]
def _routing_payload(kwargs):
trusted = _trusted_key_metadata(kwargs)
if trusted.get("lemmacomputer_policy_model_alias") != "lemmacomputer-auto":
return None
if kwargs.get("model") != "lemmacomputer-auto":
raise RuntimeError("Governed routing accepts only the synthetic Auto transport alias")
tenant_id = trusted.get("lemmacomputer_tenant_id")
subject_id = trusted.get("lemmacomputer_subject_id")
if not isinstance(tenant_id, str) or not tenant_id or not isinstance(subject_id, str) or not subject_id:
raise RuntimeError("Governed routing authenticated identity is incomplete")
call_id = kwargs.get("litellm_call_id")
if not isinstance(call_id, str) or not call_id:
params = kwargs.get("litellm_params")
call_id = params.get("litellm_call_id") if isinstance(params, dict) else None
if not isinstance(call_id, str) or not call_id:
raise RuntimeError("Governed routing invocation ID is missing")
messages = kwargs.get("messages")
estimated = _estimated_input_tokens(kwargs)
signals = _routing_signals(kwargs, estimated)
vision = _contains_image_input(messages) or _contains_image_input(kwargs.get("input"))
tools = bool(_nested_parameter(kwargs, "tools"))
if vision:
signals.append("vision_required")
if tools:
signals.append("tools_required")
signals = list(dict.fromkeys(signals))
maximum_output = _maximum_output_tokens(kwargs, {})
request_metadata = _request_routing_metadata(kwargs)
task_binding = request_metadata.get("lemmacomputer_task_binding")
if not isinstance(task_binding, str) or len(task_binding) < 32:
raise RuntimeError("Governed routing requires a signed AI task binding")
requested_class = request_metadata.get("lemmacomputer_requested_service_class", "auto")
if requested_class not in ("auto", "lite", "balanced", "pro"):
raise RuntimeError("Governed routing service class is invalid")
requested_reasoning_effort = request_metadata.get("lemmacomputer_requested_reasoning_effort")
if requested_reasoning_effort is not None and requested_reasoning_effort not in ("auto", "low", "medium", "high"):
raise RuntimeError("Governed routing reasoning effort is invalid")
workspace_id = trusted.get("lemmacomputer_workspace_id")
agent_id = trusted.get("lemmacomputer_agent_id")
if not isinstance(workspace_id, str) or not workspace_id or not isinstance(agent_id, str) or not agent_id:
raise RuntimeError("Governed routing workspace identity is incomplete")
payload = {
"schemaVersion": 1,
"tenantId": tenant_id,
"subjectId": subject_id,
"workspaceId": workspace_id,
"agentId": agent_id,
"taskBinding": task_binding,
"requestId": call_id,
"requestedServiceClass": requested_class,
"boundedSignals": signals,
"estimatedInputTokens": estimated,
"requiredCapabilities": {
"vision": vision,
"tools": tools,
"streaming": bool(kwargs.get("stream")),
"contextTokens": estimated,
"outputTokens": maximum_output,
},
"expectedUsage": [
{"unit": "input_uncached_token", "quantity": str(estimated)},
{"unit": "output_token", "quantity": str(maximum_output)},
],
}
if requested_reasoning_effort is not None:
payload["requestedReasoningEffort"] = requested_reasoning_effort
unavailable = _unavailable_deployment_ids(tenant_id)
if unavailable:
payload["unavailableDeploymentIds"] = unavailable
return payload
def _tracking_metadata(kwargs):
candidates = [kwargs.get("litellm_metadata"), kwargs.get("metadata")]
params = kwargs.get("litellm_params")
if isinstance(params, dict):
candidates.extend([params.get("litellm_metadata"), params.get("metadata")])
return [candidate for candidate in candidates if isinstance(candidate, dict)]
def _previous_models(kwargs):
previous = kwargs.get("previous_models")
for candidate in _tracking_metadata(kwargs):
if not isinstance(previous, list):
previous = candidate.get("previous_models")
params = kwargs.get("litellm_params")
if not isinstance(previous, list) and isinstance(params, dict):
previous = params.get("previous_models")
return previous if isinstance(previous, list) else []
def _attempt_ordinal(kwargs):
# LiteLLM v1.93 initializes this to zero before the first router call and
# sets current_attempt + 1 immediately before each concrete retry.
for candidate in _tracking_metadata(kwargs):
value = candidate.get("attempted_retries")
if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
return value
# Non-router calls have no retry metadata. The previous-model list is the
# v1.93 compatibility signal for retries created before tracking starts.
return len(_previous_models(kwargs))
def _fallback_depth(kwargs):
value = kwargs.get("fallback_depth")
return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else 0
def _attempt_kind(kwargs, call_type):
value = str(getattr(call_type, "value", call_type) or "")
if "embedding" in value:
return "embedding"
if _fallback_depth(kwargs) > 0:
return "fallback"
if _attempt_ordinal(kwargs) > 0 or _previous_models(kwargs):
return "retry"
return "inference"
def _source_attempt_id(kwargs, route):
# In pinned LiteLLM v1.93 the proxy installs `litellm_call_id` from
# x-litellm-call-id (or a generated UUID), provider wrappers preserve it,
# and this hook runs after deployment selection. Never substitute fresh
# randomness here: replaying the same concrete hook must be idempotent.
call_id = kwargs.get("litellm_call_id")
if not isinstance(call_id, str) or not call_id.strip():
params = kwargs.get("litellm_params")
call_id = params.get("litellm_call_id") if isinstance(params, dict) else None
if not isinstance(call_id, str) or not call_id.strip():
raise RuntimeError("LiteLLM concrete invocation ID is missing")
identity = {
"schemaVersion": 1,
"litellmCallId": call_id.strip(),
"retryOrdinal": _attempt_ordinal(kwargs),
"fallbackDepth": _fallback_depth(kwargs),
"deploymentId": route["lemmacomputer_deployment_id"],
}
encoded = json.dumps(identity, separators=(",", ":"), sort_keys=True).encode("utf-8")
digest = hashlib.sha256(b"lemmacomputer-litellm-attempt/v1\0" + encoded).hexdigest()
return f"litellm-attempt-{digest}"
def _set_usage_state(
kwargs, state, task_binding, source_attempt_id, original_parent_attempt_id
):
owned_state = {**state, "sourceAttemptId": source_attempt_id}
kwargs[USAGE_STATE_KEY] = owned_state
metadata = kwargs.get("metadata")
if not isinstance(metadata, dict):
metadata = {}
kwargs["metadata"] = metadata
metadata[USAGE_STATE_KEY] = owned_state
metadata[USAGE_CHAIN_KEY] = _signed_usage_chain({
"admissionId": owned_state["admissionId"],
"taskBinding": task_binding,
"sourceAttemptId": source_attempt_id,
"originalParentAttemptId": original_parent_attempt_id,
})
_remember_usage_state(kwargs, owned_state)
def _usage_state(kwargs):
direct = kwargs.get(USAGE_STATE_KEY)
if isinstance(direct, dict):
return direct
for metadata in _metadata_dicts(kwargs):
value = metadata.get(USAGE_STATE_KEY)
if isinstance(value, dict):
return value
registered = _registered_usage_state(kwargs)
if isinstance(registered, dict):
return registered
# LiteLLM's Anthropic Messages -> Responses conversion builds fresh hook
# kwargs and removes callback-owned metadata before the completion hook.
# Context variables follow the request task, so recover only the state
# paired with the callback-signed chain created at admission.
context = _INTERNAL_ADMISSION_CONTEXT.get()
if isinstance(context, dict):
value = context.get("state")
chain = _verified_usage_chain(context.get("signedChain"))
if (
isinstance(value, dict)
and isinstance(chain, dict)
and isinstance(value.get("admissionId"), str)
and chain.get("admissionId") == value.get("admissionId")
and isinstance(value.get("tenantId"), str)
and bool(value.get("tenantId"))
and isinstance(value.get("provider"), str)
and bool(value.get("provider"))
):
return value
return None
def _nonnegative_integer(value, fallback=0, maximum=100):
if isinstance(value, (int, float)) and value >= 0:
return min(maximum, int(value))
return fallback
def _nested_parameter(kwargs, name):
value = kwargs.get(name)
if value is not None:
return value
params = kwargs.get("litellm_params")
return params.get(name) if isinstance(params, dict) else None
def _text_bytes(value):
if isinstance(value, str):
return len(value.encode("utf-8"))
if isinstance(value, list):
return sum(_text_bytes(item) for item in value)
if isinstance(value, dict):
return sum(_text_bytes(item) for item in value.values())
return 0
def _estimated_input_tokens(kwargs):
messages = kwargs.get("messages")
model = kwargs.get("model")
try:
count = litellm.token_counter(model=model, messages=messages)
if isinstance(count, int) and count >= 0:
return count
except Exception:
pass
source = messages if messages is not None else kwargs.get("input")
return max(1, _text_bytes(source))
def _maximum_output_tokens(kwargs, route):
requested = _nested_parameter(kwargs, "max_tokens") or _nested_parameter(kwargs, "max_output_tokens")
if isinstance(requested, (int, float)) and requested >= 0:
return int(requested)
declared = route.get("max_output_tokens")