Class: Myrr::Rack::Middleware
- Inherits:
-
Object
- Object
- Myrr::Rack::Middleware
- Defined in:
- lib/myrr/rack/middleware.rb
Overview
Rack middleware that detects X-Myrr-Agent headers on incoming requests,
performs challenge-response verification against the protocol server
(or uses a configured identity_adapter), and sets
request.env["myrr.current_agent"].
After the inner app runs, if the response is text/markdown, it counts
the tokens and adds env["myrr.token_count"] and the
X-Myrr-Tokens response header.
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, myrr_module = nil) ⇒ Middleware
constructor
A new instance of Middleware.
Constructor Details
#initialize(app, myrr_module = nil) ⇒ Middleware
Returns a new instance of Middleware.
14 15 16 17 |
# File 'lib/myrr/rack/middleware.rb', line 14 def initialize(app, myrr_module = nil) @app = app @myrr = myrr_module || Myrr end |
Instance Method Details
#call(env) ⇒ Object
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 |
# File 'lib/myrr/rack/middleware.rb', line 20 def call(env) agent_did = env["HTTP_X_MYRR_AGENT"] if agent_did && !agent_did.empty? begin agent_info = @myrr.verify_agent(agent_did) if agent_info env["myrr.current_agent"] = agent_info override_format_to_markdown(env) if should_override_format?(env) end rescue => e if @myrr.config&.fail_open warn "[myrr] Agent verification failed (fail_open=true): #{e.}" else return fail_response(env, e.) end end end status, headers, body = @app.call(env) # Token counting for markdown responses if env["myrr.current_agent"] && content_type_is_markdown?(headers) body_text = extract_body(body) token_count = @myrr::Tokenizer.count(body_text) env["myrr.token_count"] = token_count headers["X-Myrr-Tokens"] = token_count.to_s end [status, headers, body] end |