2026-11-07 18:14:21 +00:00
from __future__ import annotations
import time
2026-11-07 19:59:47 +00:00
from .denying import request_status , request_words , requester_of
2026-11-07 18:14:21 +00:00
from .errors import Conflict , Missing , ToolError
from .fields import WAIT_CAP , bounded , decode , expect , field , seconds
from .records import iso_epoch
2026-11-13 18:14:17 +00:00
from .rules import EVERY_AGENT , rule_fields , rule_matches , signed_fields , subject_of
2026-11-07 18:14:21 +00:00
from .signed import signing
# Trip-wire: MCP carries no caller identity, so an agent may name itself anew for each request; AGENT_CAP only spreads the queue, TOTAL_CAP is the bound.
AGENT_CAP = 3
TOTAL_CAP = 20
WHY_LIMIT = 1000
RECENT_DAYS = 7
2026-11-27 19:05:38 +00:00
MATCH_WINDOW = 50
COUNT_ID = "0" * 16
2026-11-07 18:14:21 +00:00
RULE_FIELDS = ( "kind" , "tool" , "pattern" , "scope" , "expires" )
REQUEST_STATE = ( "id" , "status" , "rule" , "reason" , "decided" )
def request_state ( record : dict , now : float ) -> dict :
return { ** { key : record [ key ] for key in REQUEST_STATE }, "status" : request_status ( record , now )}
def created_of ( record : dict ) -> float :
return record [ "created_ts" ] if "created_ts" in record else iso_epoch ( record [ "created" ]) or 0.0
2026-11-14 21:29:42 +00:00
def matched ( record : dict , subjects : list [ dict ], now : float ) -> int :
"""Args:
record: id, kind, tool, pattern, scope and expires of a rule, with
agents when it applies to one agent or group only.
subjects: what recent_subjects() lists for the rule's kind.
now: the current time in epoch seconds.
Returns:
How many subjects the rule would have approved.
"""
kind_name = record [ "kind" ]
payload = signing . rule_payload ( record [ "id" ], [ kind_name ], record [ "tool" ], record [ "pattern" ], record [ "scope" ], int ( record [ "expires" ]))
if "agents" in record :
payload = signing . targeted ( payload , record [ "agents" ])
rule = { ** { key : record [ key ] for key in RULE_FIELDS }, "enabled" : True , "proof" : { "payload" : payload , "assertion" : None }}
return sum ( rule_matches ( rule , kind_name , subject , now ) for subject in subjects )
2026-11-27 19:05:38 +00:00
def counted_matches ( rule : dict , subjects : list [ dict ], now : float ) -> int :
"""Args:
rule: kind, tool, pattern and scope of a stored or draft rule, with
agents when it applies to one agent or group only.
subjects: what a rule of that kind is matched against.
now: the current time in epoch seconds.
Returns:
How many subjects matched() lets the rule approve, on or off,
expired or not.
"""
return matched ({ ** rule , "id" : COUNT_ID , "expires" : now + RECENT_DAYS * 86400 }, subjects , now )
def window_count ( rule : dict , subjects : list [ dict ], now : float ) -> dict :
"""Returns:
{"matched": counted_matches() of the rule, "of": how many subjects there
are}, at most MATCH_WINDOW for last_subjects().
"""
return { "matched" : counted_matches ( rule , subjects , now ), "of" : len ( subjects )}
2026-11-07 18:14:21 +00:00
class Requesting :
def open_requests ( self , now : float ) -> list [ dict ]:
return [ record for record in self . rule_requests . pending () if request_status ( record , now ) == "pending" ]
def rule_request ( self , arguments : dict ) -> dict :
expect ( arguments , ( * RULE_FIELDS , "agent" , "why" ))
now = time . time ()
2026-11-13 18:14:17 +00:00
fields = { name : value for name , value in rule_fields ( arguments , EVERY_AGENT , now ) . items () if name in RULE_FIELDS }
2026-11-07 18:14:21 +00:00
if fields [ "kind" ] == "decision" and fields [ "scope" ] != "*" :
raise ToolError ( "a decision rule takes scope *, as the rules form does" )
name = field ( arguments , "agent" ) . strip ()
why = bounded ( arguments , "why" , WHY_LIMIT ) . strip ()
if not why :
raise ToolError ( "why must name the purpose of the requested rule" )
def capped ( records : list [ dict ]) -> None :
pending = [ record for record in records if request_status ( record , now ) == "pending" ]
if len ( pending ) >= TOTAL_CAP :
raise ToolError ( f " { TOTAL_CAP } rule requests wait for the operator; ask again once some are answered" )
if sum ( 1 for record in pending if record [ "agent" ] == name ) >= AGENT_CAP :
raise ToolError ( f " { name } already has { AGENT_CAP } pending rule requests; wait for their answer with rule_request_wait" )
record = self . rule_requests . add_checked ({ ** fields , "agent" : name , "why" : why , "status" : "pending" , "rule" : None , "reason" : "" , "channel" : "" , "proof" : None , "decided" : None , "created_ts" : now }, capped )
2026-11-08 17:26:51 +00:00
self . log . add ({ "kind" : "rule" , "title" : f "Rule request from { name } : { request_words ( record ) } " , "text" : why , "ref" : { "request" : record [ "id" ]}})
2026-11-07 18:14:21 +00:00
return { "id" : record [ "id" ], "status" : record [ "status" ], "url" : self . url ()}
def rule_request_wait ( self , arguments : dict ) -> dict :
expect ( arguments , ( "id" , "timeout_seconds" ))
request_id = field ( arguments , "id" )
record = self . rule_requests . wait ( request_id , seconds ( arguments , "timeout_seconds" , WAIT_CAP ))
if record is None :
raise ToolError ( f "no rule request { request_id } " )
return request_state ( record , time . time ())
2026-11-27 19:05:38 +00:00
def kind_records ( self , kind_name : str ) -> list [ dict ]:
return { "ask" : self . asks , "review" : self . reviews , "decision" : self . decisions }[ kind_name ] . listed ()
def subjects_of ( self , kind_name : str , records : list [ dict ]) -> list [ dict ]:
return [ subject_of ( kind_name , entry , self . deciders ( kind_name , entry )) for entry in records ]
2026-11-14 21:29:42 +00:00
def recent_subjects ( self , kind_name : str , now : float ) -> list [ dict ]:
"""Returns:
The asks, reviews or decisions of the last RECENT_DAYS as a rule
of that kind is matched against them.
"""
since = now - RECENT_DAYS * 86400
2026-11-27 19:05:38 +00:00
return self . subjects_of ( kind_name , [ entry for entry in self . kind_records ( kind_name ) if created_of ( entry ) >= since ])
def last_subjects ( self , kind_name : str ) -> list [ dict ]:
"""Returns:
The newest MATCH_WINDOW asks, reviews or decisions as a rule of
that kind is matched against them.
"""
return self . subjects_of ( kind_name , sorted ( self . kind_records ( kind_name ), key = created_of )[ - MATCH_WINDOW :])
def rule_counts ( self , stored : list [ dict ], now : float ) -> dict [ str , dict ]:
"""Args:
stored: the stored rules.
now: the current time in epoch seconds.
Returns:
window_count() of each rule by id over the last MATCH_WINDOW
records of its kind.
"""
subjects = { kind_name : self . last_subjects ( kind_name ) for kind_name in { rule [ "kind" ] for rule in stored }}
return { rule [ "id" ]: window_count ( rule , subjects [ rule [ "kind" ]], now ) for rule in stored }
def match_rule ( self , body : bytes ) -> dict :
"""Args:
body: a draft rule as POST /api/rules/sign takes it.
Returns:
window_count() of the draft over the last MATCH_WINDOW records of
its kind; it reads only, stores nothing and grants nothing.
"""
fields = self . draft_fields ( body )
return window_count ( fields , self . last_subjects ( fields [ "kind" ]), time . time ())
2026-11-14 21:29:42 +00:00
2026-11-07 18:14:21 +00:00
def dry_run ( self , record : dict , now : float ) -> dict :
"""Returns:
How many of the asks, reviews or decisions of the last
RECENT_DAYS the requested rule would have approved, matched by
the same code that applies a stored rule.
"""
2026-11-14 21:29:42 +00:00
subjects = self . recent_subjects ( record [ "kind" ], now )
return { "matched" : matched ( record , subjects , now ), "total" : len ( subjects ), "days" : RECENT_DAYS }
2026-11-07 18:14:21 +00:00
2026-11-07 19:59:47 +00:00
def request_items ( self , base : dict , now : float , claims : list [ dict ]) -> list [ dict ]:
2026-11-07 18:14:21 +00:00
items = []
for record in self . open_requests ( now ):
rule = { key : record [ key ] for key in RULE_FIELDS }
2026-11-08 17:26:51 +00:00
fields = { "title" : f "Rule: { request_words ( record ) } " , "agent" : record [ "agent" ], "to" : requester_of ( claims , record [ "agent" ])[ 0 ], "detail" : record [ "why" ], "rule" : rule , "dry_run" : self . dry_run ( record , now ), "deniable" : True }
2026-11-07 18:14:21 +00:00
items . append ({ ** base , "kind" : "rule" , "id" : record [ "id" ], "ts" : record [ "created_ts" ], ** fields })
return items
def pending_request ( self , request_id : str ) -> dict :
record = self . rule_requests . get ( request_id )
if record is None :
raise Missing ( request_id )
state = request_state ( record , time . time ())
if state [ "status" ] != "pending" :
raise Conflict ( state )
if self . batches . holds ( "rule" , request_id ):
raise Conflict ({ "id" : request_id , "status" : "held" })
return record
def sign_request ( self , request_id : str ) -> dict :
record = self . pending_request ( request_id )
2026-11-13 18:14:17 +00:00
return { ** self . rule_offer ( rule_fields ( record , EVERY_AGENT , time . time ())), "sign" : True }
2026-11-07 18:14:21 +00:00
def accept_request ( self , request_id : str , body : bytes ) -> dict :
payload = decode ( body )
expect ( payload , ( "rule" , "assertion" ))
record = self . pending_request ( request_id )
now = time . time ()
rule = payload [ "rule" ]
fields = signed_fields ( rule , now )
if [ fields [ key ] for key in RULE_FIELDS ] != [ record [ key ] for key in RULE_FIELDS ]:
raise ToolError ( "the signed rule must be exactly the requested one" )
proof = self . proven_rule ( rule , payload [ "assertion" ])
2026-11-13 18:14:17 +00:00
self . offered ( rule , now )
2026-11-07 18:14:21 +00:00
decided , changed = self . rule_requests . decide ( request_id , { "status" : "accepted" , "rule" : rule [ "id" ]})
if not changed :
raise Conflict ( request_state ( decided , now ))
self . store_rule ( rule , fields , proof , True , now )
2026-11-08 17:26:51 +00:00
self . log . add ({ "kind" : "rule" , "title" : f "Rule request accepted: { request_words ( record ) } " , "text" : f "from { record [ 'agent' ] } " , "ref" : { "request" : request_id , "rule" : rule [ "id" ]}})
2026-11-07 18:14:21 +00:00
return request_state ( decided , now )