Knarr.pm

filter: Statementstmt 84.5% 235 / 278 Branchbran 71.6% 43 / 60 Conditioncond 61.3% 27 / 44 MC/DCmcdc 32.0% 8 / 25 Subroutinesub 80.7% 46 / 57 Podpod 100% 3 / 3 totaltotal 77.5% 362 / 467 CC 56 SCAR 14.1
CC
56
Cov
80%
__ANON__
12.0
_check_auth
10.0
_handle_raw_passthrough
6.6
CRAP 4.1
« Knarr/Protocol/AGUI.pm ↑ Summary Knarr/Protocol/ACP.pm »
1 package Langertha::Knarr;
2 # ABSTRACT: Universal LLM hub — proxy, server, and translator across OpenAI/Anthropic/Ollama/A2A/ACP/AG-UI
3 11 our $VERSION = '1.100';
4 11 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 11 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 11 ▶use IO::Async::Loop;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 11 ▶use Net::Async::HTTP::Server;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 11 ▶use HTTP::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 11 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 11 ▶use Data::UUID;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 11 ▶use Module::Runtime qw( use_module );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 11 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
13 11 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 11 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 11 ▶use Langertha::Knarr::Session;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17  
18  
19 11 has handler => (
20 is => 'ro',
21 required => 1,
22 );
23  
24 11 has host => (
25 is => 'ro',
26 isa => 'Str',
27 default => '127.0.0.1',
28 );
29  
30 11 has port => (
31 is => 'ro',
32 isa => 'Int',
33 default => 8088,
34 );
35  
36 # Listen on one or more addresses. Each entry is either "host:port" or
37 # { host => ..., port => ... }. Defaults to a single entry composed from
38 # the host/port attributes above.
39 11 has listen => (
40 is => 'ro',
41 isa => 'ArrayRef',
42 lazy => 1,
43 builder => '_build_listen',
44 );
45  
46 sub _build_listen {
47 13 ▶ my ($self) = @_;
Subroutine _build_listen: called CC=1 SCAR=0.0
48 13 return [ { host => $self->host, port => $self->port + 0 } ];
49 }
50  
51 11 has loop => (
52 is => 'ro',
53 lazy => 1,
54 builder => '_build_loop',
55 );
56 0 ▶sub _build_loop { IO::Async::Loop->new }
Subroutine _build_loop: not called CC=1 SCAR=6.9
57  
58 has protocols => (
59 is => 'ro',
60 isa => 'ArrayRef[Str]',
61 18 ▶ default => sub { [qw( OpenAI Anthropic Ollama A2A ACP AGUI )] },
Subroutine __ANON__: called CC=1 SCAR=0.0
62 11 );
63  
64 # Optional shared secret. When set, every incoming request must present it
65 # either as 'Authorization: Bearer <key>' or 'x-api-key: <key>'. The agent
66 # card and well-known discovery routes are exempt because they need to be
67 # anonymously fetchable.
68 has router => (
69 is => 'ro',
70 isa => 'Maybe[Object]',
71 16 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
72 11 );
73  
74 has raw_passthrough => (
75 is => 'ro',
76 isa => 'Maybe[Object]',
77 16 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
78 11 );
79  
80 has tracing => (
81 is => 'ro',
82 isa => 'Maybe[Object]',
83 17 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
84 11 );
85  
86 has auth_token => (
87 is => 'ro',
88 isa => 'Maybe[Str]',
89 17 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
90 11 );
91  
92 11 has _protocol_objects => (
93 is => 'ro',
94 lazy => 1,
95 builder => '_build_protocol_objects',
96 );
97  
98 11 has _routes => (
99 is => 'ro',
100 lazy => 1,
101 builder => '_build_routes',
102 );
103  
104 has _sessions => (
105 is => 'ro',
106 18 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
107 11 );
108  
109 has _uuid => (
110 is => 'ro',
111 18 ▶ default => sub { Data::UUID->new },
Subroutine __ANON__: called CC=1 SCAR=0.0
112 11 );
113  
114 has _json => (
115 is => 'ro',
116 18 ▶ default => sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1 ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
117 11 );
118  
119 11 has _server => (
120 is => 'rw',
121 );
122  
123 has _servers => (
124 is => 'rw',
125 18 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
126 11 );
127  
128 sub _build_protocol_objects {
129 15 ▶ my ($self) = @_;
Subroutine _build_protocol_objects: called CC=3 SCAR=11.0
130 15 my @objs;
131 15 for my $name ( @{ $self->protocols } ) {
132 90 ▶ my $class = $name =~ /::/ ? $name : "Langertha::Knarr::Protocol::$name";
Branch: 1 branch
BranchTrueFalseTotal
$name =~ /::/ ? : 0 90 90
133 90 use_module($class);
134 90 push @objs, $class->new;
135 }
136 15 return \@objs;
137 }
138  
139 sub _build_routes {
140 14 ▶ my ($self) = @_;
Subroutine _build_routes: called CC=3 SCAR=11.0
141 14 my @routes;
142 14 for my $proto ( @{ $self->_protocol_objects } ) {
143 84 for my $r ( @{ $proto->protocol_routes } ) {
144 168 push @routes, { %$r, protocol => $proto };
145 }
146 }
147 14 return \@routes;
148 }
149  
150 sub session {
151 40 ▶ my ($self, $id) = @_;
Subroutine session: called CC=3 SCAR=11.6
Pod documented
152 40 ▶ $id //= $self->_uuid->create_str;
Condition66%2/3
$id //= $self->_uuid->create_str
l!l&&r!l&&!r
3370
MC/DC0%0/2
$id //= $self->_uuid->create_str
$id $self->_uuid->create_str
Truth table66%2/3
A //= B
A= $idB= $self->_uuid->create_str
ABresult
1X1
011
000
153 40 ▶ $self->_sessions->{$id} //= Langertha::Knarr::Session->new( id => $id );
Condition33%1/3
$self->_sessions->{$id} //= "Langertha::Knarr::Session"->new("id", $id)
l!l&&r!l&&!r
0400
MC/DC0%0/2
$self->_sessions->{$id} //= "Langertha::Knarr::Session"->new("id", $id)
$self->_sessions->{$id} "Langertha::Knarr::Session"->new("id", $id)
Truth table33%1/3
A //= B
A= $self->_sessions->{$id}B= "Langertha::Knarr::Session"->new("id", $id)
ABresult
1X1
011
000
154 40 $self->_sessions->{$id}->touch;
155 40 return $self->_sessions->{$id};
156 }
157  
158 sub _listen_addrs {
159 15 ▶ my ($self) = @_;
Subroutine _listen_addrs: called CC=6 SCAR=18.2
160 15 my @out;
161 15 for my $entry ( @{ $self->listen } ) {
162 17 ▶ if ( ref $entry eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $entry eq 'HASH') { } 15 2 17
163 15 ▶ push @out, { host => $entry->{host} // '127.0.0.1', port => $entry->{port} + 0 };
Condition50%1/2
$entry->{"host"} // "127.0.0.1"
l!l
150
MC/DC0%0/1
$entry->{"host"} // "127.0.0.1"
$entry->{"host"}
Truth table50%1/2
A
A= $entry->{"host"}
Aresult
11
00
164 } else {
165 2 my ($h, $p) = split /:/, $entry, 2;
166 2 ▶ $h ||= '127.0.0.1';
Condition50%1/2
$h ||= "127.0.0.1"
l!l
20
MC/DC0%0/1
$h ||= "127.0.0.1"
$h
Truth table50%1/2
A
A= $h
Aresult
11
00
167 2 ▶ push @out, { host => $h, port => ($p // 8088) + 0 };
Condition50%1/2
$p // 8088
l!l
20
MC/DC0%0/1
$p // 8088
$p
Truth table50%1/2
A
A= $p
Aresult
11
00
168 }
169 }
170 15 return @out;
171 }
172  
173 sub start {
174 13 ▶ my ($self) = @_;
Subroutine start: called CC=2 SCAR=6.9
Pod documented
175 13 my @servers;
176 13 for my $a ( $self->_listen_addrs ) {
177 my $server = Net::Async::HTTP::Server->new(
178 on_request => sub {
179 37 ▶ my ($srv, $req) = @_;
Subroutine __ANON__: called CC=1 SCAR=0.0
180 37 $self->_dispatch($req);
181 },
182 14 );
183 14 $self->loop->add($server);
184 $server->listen(
185 addr => {
186 family => 'inet',
187 socktype => 'stream',
188 port => $a->{port},
189 ip => $a->{host},
190 },
191 14 )->get;
192 14 push @servers, $server;
193 }
194 13 $self->_servers(\@servers);
195 13 $self->_server( $servers[0] );
196 13 return $self;
197 }
198  
199 sub run {
200 0 ▶ my ($self) = @_;
Subroutine run: not called CC=2 SCAR=17.9
Pod documented
201 0 ▶ $self->start unless $self->_server;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_server 0 0 0
202 0 $self->loop->run;
203 }
204  
205 sub _match_route {
206 41 ▶ my ($self, $method, $path) = @_;
Subroutine _match_route: called CC=4 SCAR=13.9
207 41 for my $r ( @{ $self->_routes } ) {
208 124 ▶ next unless $r->{method} eq $method;
Branch: 1 branch
BranchTrueFalseTotal
unless $r->{"method"} eq $method 39 85 124
209 85 ▶ return $r if $r->{path} eq $path;
Branch: 1 branch
BranchTrueFalseTotal
if $r->{"path"} eq $path 41 44 85
210 }
211 0 return undef;
212 }
213  
214 sub _check_auth {
215 37 ▶ my ($self, $req, $action) = @_;
Subroutine _check_auth: called CC=10 SCAR=23.1
216 37 ▶ return 1 unless defined $self->auth_token && length $self->auth_token;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->auth_token and length $self->auth_token 32 5 37
Condition66%2/3
defined $self->auth_token and length $self->auth_token
!ll&&!rl&&r
3205
MC/DC50%1/2
defined $self->auth_token and length $self->auth_token
defined $self->auth_token length $self->auth_token
Truth table66%2/3
A and B
A= defined $self->auth_tokenB= length $self->auth_token
ABresult
0X0
100
111
217 # Discovery endpoints stay anonymous so clients can introspect.
218 5 ▶ return 1 if $action eq 'a2a_card';
Branch: 1 branch
BranchTrueFalseTotal
if $action eq "a2a_card" 1 4 5
219 4 my $expected = $self->auth_token;
220 4 ▶ my $auth = scalar( $req->header('Authorization') ) // '';
Condition100%2/2
scalar $req->header("Authorization") // ""
l!l
22
MC/DC100%1/1
scalar $req->header("Authorization") // ""
scalar $req->header("Authorization")
Truth table100%2/2
A
A= scalar $req->header("Authorization")
Aresult
11
00
221 4 ▶ if ( $auth =~ /^Bearer\s+(.+)$/i && $1 eq $expected ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($auth =~ /^Bearer\s+(.+)$/i and $1 eq $expected) 1 3 4
Condition100%3/3
$auth =~ /^Bearer\s+(.+)$/i and $1 eq $expected
!ll&&!rl&&r
211
MC/DC100%2/2
$auth =~ /^Bearer\s+(.+)$/i and $1 eq $expected
$auth =~ /^Bearer\s+(.+)$/i $1 eq $expected
Truth table100%3/3
A and B
A= $auth =~ /^Bearer\s+(.+)$/iB= $1 eq $expected
ABresult
0X0
100
111
222 1 return 1;
223 }
224 3 ▶ my $api_key = scalar( $req->header('x-api-key') ) // '';
Condition100%2/2
scalar $req->header("x-api-key") // ""
l!l
12
MC/DC100%1/1
scalar $req->header("x-api-key") // ""
scalar $req->header("x-api-key")
Truth table100%2/2
A
A= scalar $req->header("x-api-key")
Aresult
11
00
225 3 ▶ return 1 if $api_key eq $expected && length $api_key;
Branch: 1 branch
BranchTrueFalseTotal
if $api_key eq $expected and length $api_key 1 2 3
Condition66%2/3
$api_key eq $expected and length $api_key
!ll&&!rl&&r
201
MC/DC50%1/2
$api_key eq $expected and length $api_key
$api_key eq $expected length $api_key
Truth table66%2/3
A and B
A= $api_key eq $expectedB= length $api_key
ABresult
0X0
100
111
226 2 return 0;
227 }
228  
229 sub _dispatch {
230 37 ▶ my ($self, $req) = @_;
Subroutine _dispatch: called CC=4 SCAR=14.8
231 37 my $method = $req->method;
232 37 my $path = $req->path;
233 37 my $route = $self->_match_route( $method, $path );
234 37 ▶ unless ( $route ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($route) 0 37 37
235 0 return $self->_send_simple( $req, 404, 'application/json',
236 $self->_json->encode({ error => { message => "no route for $method $path" } }) );
237 }
238 37 my $action = $route->{action};
239 37 ▶ unless ( $self->_check_auth( $req, $action ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_check_auth($req, $action)) 2 35 37
240 2 return $self->_send_simple( $req, 401, 'application/json',
241 $self->_json->encode({ error => { message => 'unauthorized' } }) );
242 }
243 35 my $proto = $route->{protocol};
244 35 my $code = $self->can("_action_$action");
245 35 ▶ unless ( $code ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($code) 0 35 35
246 0 return $self->_send_simple( $req, 500, 'application/json',
247 $self->_json->encode({ error => { message => "unknown action $action" } }) );
248 }
249 try {
250 35 ▶ $self->$code( $proto, $req );
Subroutine __ANON__: called CC=1 SCAR=0.0
251 } catch {
252 0 ▶ my $err = $_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
253 0 $log->errorf("Request error (%s): %s", $action, $err);
254 0 $self->_send_simple( $req, 500, 'application/json',
255 $self->_json->encode({ error => { message => "$err" } }) );
256 35 };
257 }
258  
259 sub _action_chat {
260 34 ▶ my ($self, $proto, $req) = @_;
Subroutine _action_chat: called CC=5 SCAR=16.9
261 34 my $body = $req->body;
262 34 my $sb_req = $proto->parse_chat_request( $req, \$body );
263  
264 # Raw passthrough: pipe bytes 1:1 to upstream, skip handler chain
265 34 ▶ if ($self->raw_passthrough && $self->router
Branch: 1 branch
BranchTrueFalseTotal
if ($self->raw_passthrough and $self->router and $self->router->is_passthrough_model($sb_req->model)) 4 30 34
Condition66%4/6
$self->raw_passthrough and $self->router and $self->router->is_passthrough_model($sb_req->model)
!ll&&!rl&&r
3004
$self->raw_passthrough and $self->router
!ll&&!rl&&r
3004
MC/DC33%1/3
$self->raw_passthrough and $self->router and $self->router->is_passthrough_model($sb_req->model)
$self->raw_passthrough $self->router $self->router->is_passthrough_model($sb_req->model)
Truth table50%2/4
A and B and C
A= $self->raw_passthroughB= $self->routerC= $self->router->is_passthrough_model($sb_req->model)
ABCresult
0XX0
10X0
1100
1111
266 && $self->router->is_passthrough_model($sb_req->model)) {
267 4 return $self->_handle_raw_passthrough( $proto, $req, $sb_req );
268 }
269  
270 30 my $session = $self->session( $sb_req->session_id );
271 30 my $handler = $self->handler;
272  
273 30 ▶ if ( $sb_req->stream ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sb_req->stream) 11 19 30
274 11 return $self->_handle_stream( $proto, $req, $sb_req, $session, $handler );
275 }
276  
277 19 my $f = $handler->handle_chat_f( $session, $sb_req );
278 $f->on_done( sub {
279 19 ▶ my ($response) = @_;
Subroutine __ANON__: called CC=1 SCAR=0.8
280 try {
281 19 ▶ my ($status, $headers, $body) = $proto->format_chat_response( $response, $sb_req );
Subroutine __ANON__: called CC=2 SCAR=7.2
282 19 ▶ $self->_send_simple( $req, $status, $headers->{'Content-Type'} // 'application/json', $body );
Condition50%1/2
$headers->{"Content-Type"} // "application/json"
l!l
190
MC/DC0%0/1
$headers->{"Content-Type"} // "application/json"
$headers->{"Content-Type"}
Truth table50%1/2
A
A= $headers->{"Content-Type"}
Aresult
11
00
283 } catch {
284 0 ▶ my $err = $_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
285 0 $log->errorf("Chat response error: %s", $err);
286 0 $self->_send_simple( $req, 500, 'application/json',
287 $self->_json->encode({ error => { message => "$err" } }) );
288 19 };
289 19 });
290 $f->on_fail( sub {
291 0 ▶ my ($err) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
292 0 $log->errorf("Chat handler error: %s", $err);
293 0 $self->_send_simple( $req, 500, 'application/json',
294 $self->_json->encode({ error => { message => "$err" } }) );
295 19 });
296 19 $f->retain;
297 }
298  
299 sub _handle_stream {
300 11 ▶ my ($self, $proto, $req, $sb_req, $session, $handler) = @_;
Subroutine _handle_stream: called CC=1 SCAR=0.3
301  
302 11 my $header = HTTP::Response->new( 200 );
303 11 $header->protocol('HTTP/1.1');
304 11 $header->header( 'Content-Type' => $proto->stream_content_type );
305 11 $header->header( 'Cache-Control' => 'no-cache' );
306 11 $req->respond_chunk_header( $header );
307  
308 my $write = sub {
309 71 ▶ my ($bytes) = @_;
Subroutine __ANON__: called CC=4 SCAR=14.1
310 71 ▶ return unless defined $bytes && length $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes and length $bytes 18 53 71
Condition66%2/3
defined $bytes and length $bytes
!ll&&!rl&&r
01853
MC/DC50%1/2
defined $bytes and length $bytes
defined $bytes length $bytes
Truth table66%2/3
A and B
A= defined $bytesB= length $bytes
ABresult
0X0
100
111
311 53 ▶ return if $req->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $req->is_closed 0 53 53
312 53 $req->write_chunk( $bytes );
313 11 };
314  
315 11 my $f = $handler->handle_stream_f( $session, $sb_req );
316 $f->on_done( sub {
317 11 ▶ my ($stream) = @_;
Subroutine __ANON__: called CC=1 SCAR=0.5
318 11 $write->( $proto->format_stream_open($sb_req) );
319 11 my $pump; $pump = sub {
320 49 ▶ if ( $req->is_closed ) { undef $pump; return }
Subroutine __ANON__: called CC=2 SCAR=8.5
Branch: 1 branch
BranchTrueFalseTotal
if ($req->is_closed) 0 49 49
321 $stream->next_chunk_f->on_done( sub {
322 49 ▶ my ($delta) = @_;
Subroutine __ANON__: called CC=3 SCAR=11.2
323 49 ▶ if ( $req->is_closed ) { undef $pump; return }
Branch: 1 branch
BranchTrueFalseTotal
if ($req->is_closed) 0 49 49
324 49 ▶ if ( defined $delta ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $delta) { } 38 11 49
325 38 $write->( $proto->format_stream_chunk( $delta, $sb_req ) );
326 38 $pump->();
327 }
328 else {
329 11 $write->( $proto->format_stream_close($sb_req) );
330 11 $write->( $proto->format_stream_done($sb_req) );
331 11 $req->write_chunk_eof;
332 11 undef $pump;
333 }
334 })->on_fail( sub {
335 0 ▶ my ($err) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
336 0 $log->errorf("Stream chunk error: %s", $err);
337 0 $write->( $proto->format_stream_chunk( "[error: $err]", $sb_req ) );
338 0 $write->( $proto->format_stream_close($sb_req) );
339 0 $req->write_chunk_eof;
340 0 undef $pump;
341 49 });
342 11 };
343 11 $pump->();
344 11 });
345 $f->on_fail( sub {
346 0 ▶ my ($err) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
347 0 $log->errorf("Stream handler error: %s", $err);
348 0 $write->( $proto->format_stream_chunk( "[error: $err]", $sb_req ) );
349 0 $req->write_chunk_eof;
350 11 });
351 11 $f->retain;
352 }
353  
354 sub _handle_raw_passthrough {
355 4 ▶ my ($self, $proto, $req, $sb_req) = @_;
Subroutine _handle_raw_passthrough: called CC=6 SCAR=18.9
356 4 my $pt = $self->raw_passthrough;
357 4 ▶ my $model = $sb_req->model // 'unknown';
Condition50%1/2
$sb_req->model // "unknown"
l!l
40
MC/DC0%0/1
$sb_req->model // "unknown"
$sb_req->model
Truth table50%1/2
A
A= $sb_req->model
Aresult
11
00
358 4 my $protocol = $sb_req->protocol;
359  
360 # Build upstream URL from passthrough config
361 4 my $url = $pt->_upstream_url($protocol);
362 4 my $http_req = HTTP::Request->new(POST => $url);
363  
364 # Forward all client headers except hop-by-hop / connection-specific
365 4 my %skip = map { lc($_) => 1 } qw( host content-length connection transfer-encoding );
366 4 for my $pair ($req->headers) {
367 22 my ($name, $value) = @$pair;
368 22 ▶ next if $skip{lc($name)};
Branch: 1 branch
BranchTrueFalseTotal
if $skip{lc $name} 12 10 22
369 10 $http_req->header($name => $value);
370 }
371 4 $http_req->content($req->body);
372  
373 4 $log->infof("Passthrough %s [%s] -> %s", $model, $protocol, $url);
374  
375 # Lightweight tracing for passthrough requests
376 4 ▶ my $trace = $self->tracing ? $self->tracing->start_trace(
Branch: 1 branch
BranchTrueFalseTotal
$self->tracing ? : 3 1 4
377 model => $model,
378 engine => 'passthrough',
379 format => $protocol,
380 messages => $sb_req->messages,
381 ) : undef;
382  
383 4 ▶ if ($sb_req->stream) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sb_req->stream) { } 1 3 4
384 my $f = $pt->_http->do_request(
385 request => $http_req,
386 on_header => sub {
387 1 ▶ my ($response) = @_;
Subroutine __ANON__: called CC=1 SCAR=0.0
388 1 my $header = HTTP::Response->new($response->code);
389 1 $header->protocol('HTTP/1.1');
390 1 $header->header('Content-Type' => scalar $response->header('Content-Type'));
391 1 $header->header('Cache-Control' => 'no-cache');
392 1 $req->respond_chunk_header($header);
393  
394 return sub {
395 4 ▶ my ($data) = @_;
Subroutine __ANON__: called CC=5 SCAR=16.6
396 4 ▶ if (!defined $data) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 1 3 4
397 1 ▶ $req->write_chunk_eof unless $req->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
unless $req->is_closed 1 0 1
398 1 ▶ $self->tracing->end_trace($trace, output => '[stream]') if $trace;
Branch: 1 branch
BranchTrueFalseTotal
if $trace 1 0 1
399 1 return;
400 }
401 3 ▶ $req->write_chunk($data) unless $req->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
unless $req->is_closed 3 0 3
402 1 };
403 },
404 1 );
405 $f->on_fail(sub {
406 0 ▶ my ($err) = @_;
Subroutine __ANON__: not called CC=3 SCAR=24.8
407 0 $log->errorf("Passthrough stream error [%s]: %s", $model, $err);
408 0 ▶ $self->tracing->end_trace($trace, error => "$err") if $trace;
Branch: 1 branch
BranchTrueFalseTotal
if $trace 0 0 0
409 0 ▶ $req->write_chunk_eof unless $req->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
unless $req->is_closed 0 0 0
410 1 });
411 1 $f->retain;
412 } else {
413 3 my $f = $pt->_http->do_request(request => $http_req);
414 $f->on_done(sub {
415 3 ▶ my ($resp) = @_;
Subroutine __ANON__: called CC=3 SCAR=11.1
416 3 ▶ $self->_send_simple($req, $resp->code,
Condition50%1/2
scalar $resp->header("Content-Type") // "application/json"
l!l
30
MC/DC0%0/1
scalar $resp->header("Content-Type") // "application/json"
scalar $resp->header("Content-Type")
Truth table50%1/2
A
A= scalar $resp->header("Content-Type")
Aresult
11
00
417 scalar $resp->header('Content-Type') // 'application/json',
418 $resp->decoded_content);
419 3 ▶ $self->tracing->end_trace($trace, output => '[passthrough]') if $trace;
Branch: 1 branch
BranchTrueFalseTotal
if $trace 2 1 3
420 3 });
421 $f->on_fail(sub {
422 0 ▶ my ($err) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
423 0 $log->errorf("Passthrough error [%s]: %s", $model, $err);
424 0 ▶ $self->tracing->end_trace($trace, error => "$err") if $trace;
Branch: 1 branch
BranchTrueFalseTotal
if $trace 0 0 0
425 0 $self->_send_simple($req, 502, 'application/json',
426 $self->_json->encode({ error => { message => "passthrough failed: $err" } }));
427 3 });
428 3 $f->retain;
429 }
430 }
431  
432 0 ▶sub _action_acp_agents { goto &_action_models }
Subroutine _action_acp_agents: not called CC=1 SCAR=6.9
433 sub _action_a2a_card {
434 1 ▶ my ($self, $proto, $req) = @_;
Subroutine _action_a2a_card: called CC=2 SCAR=7.1
435 1 my ($status, $headers, $body) = $proto->format_agent_card;
436 1 ▶ $self->_send_simple( $req, $status, $headers->{'Content-Type'} // 'application/json', $body );
Condition50%1/2
$headers->{"Content-Type"} // "application/json"
l!l
10
MC/DC0%0/1
$headers->{"Content-Type"} // "application/json"
$headers->{"Content-Type"}
Truth table50%1/2
A
A= $headers->{"Content-Type"}
Aresult
11
00
437 }
438  
439 sub _action_models {
440 0 ▶ my ($self, $proto, $req) = @_;
Subroutine _action_models: not called CC=2 SCAR=17.9
441 0 my $models = $self->handler->list_models;
442 0 my ($status, $headers, $body) = $proto->format_models_response( $models );
443 0 ▶ $self->_send_simple( $req, $status, $headers->{'Content-Type'} // 'application/json', $body );
Condition0%0/2
$headers->{"Content-Type"} // "application/json"
l!l
00
MC/DC0%0/1
$headers->{"Content-Type"} // "application/json"
$headers->{"Content-Type"}
Truth table0%0/2
A
A= $headers->{"Content-Type"}
Aresult
11
00
444 }
445  
446 sub _send_simple {
447 25 ▶ my ($self, $req, $status, $ctype, $body) = @_;
Subroutine _send_simple: called CC=1 SCAR=0.0
448 25 my $resp = HTTP::Response->new( $status );
449 25 $resp->protocol('HTTP/1.1');
450 25 $resp->header( 'Content-Type' => $ctype );
451 25 $resp->header( 'Content-Length' => length($body) );
452 25 $resp->content($body);
453 25 $req->respond($resp);
454 }
455  
456 11 __PACKAGE__->meta->make_immutable;
457 11 1;
458  
459 __END__
460  
461 =pod
462  
463 =encoding UTF-8
464  
465 =head1 NAME
466  
467 Langertha::Knarr - Universal LLM hub — proxy, server, and translator across OpenAI/Anthropic/Ollama/A2A/ACP/AG-UI
468  
469 =head1 VERSION
470  
471 version 1.100
472  
473 =head1 SYNOPSIS
474  
475 The fastest way to use Knarr is the Docker image:
476  
477 docker run -e ANTHROPIC_API_KEY -p 8080:8080 raudssus/langertha-knarr
478 ANTHROPIC_BASE_URL=http://localhost:8080 claude
479  
480 The Perl API behind it:
481  
482 use IO::Async::Loop;
483 use Langertha::Knarr;
484 use Langertha::Knarr::Config;
485 use Langertha::Knarr::Router;
486 use Langertha::Knarr::Handler::Router;
487  
488 my $loop = IO::Async::Loop->new;
489 my $config = Langertha::Knarr::Config->new(file => 'knarr.yaml');
490 my $router = Langertha::Knarr::Router->new(config => $config);
491  
492 my $knarr = Langertha::Knarr->new(
493 handler => Langertha::Knarr::Handler::Router->new(router => $router),
494 loop => $loop,
495 listen => $config->listen,
496 );
497 $knarr->run; # blocks; OpenWebUI etc. can now connect
498  
499 =head1 DESCRIPTION
500  
501 Langertha::Knarr is a universal LLM hub that exposes any backend — a
502 L<Langertha::Raider>, a raw L<Langertha::Engine>, a remote A2A or ACP
503 agent, or any custom L<Langertha::Knarr::Handler> — over the standard
504 LLM HTTP wire protocols spoken by OpenWebUI, the OpenAI / Anthropic /
505 Ollama SDKs, and the agent ecosystems around A2A, ACP, and AG-UI.
506  
507 By default a single running Knarr answers OpenAI
508 C</v1/chat/completions>, Anthropic C</v1/messages>, Ollama
509 C</api/chat>, A2A's C</.well-known/agent.json> plus JSON-RPC C</>,
510 ACP's C</runs>, and AG-UI's C</awp> simultaneously on every listening
511 port. The same handler implementation drives all of them.
512  
513 Knarr 1.000 is built on L<IO::Async> and L<Net::Async::HTTP::Server>
514 with native L<Future::AsyncAwait> integration into Langertha engines,
515 so streaming works end-to-end token-by-token without any thread or
516 event-loop bridges.
517  
518 =head1 ARCHITECTURE
519  
520 Three pluggable layers:
521  
522 =over
523  
524 =item B<Protocols>
525  
526 Wire formats live in C<Langertha::Knarr::Protocol::*>. Each consumes
527 L<Langertha::Knarr::Protocol> and is loaded by default. See
528 L<Langertha::Knarr::Protocol::OpenAI>,
529 L<Langertha::Knarr::Protocol::Anthropic>,
530 L<Langertha::Knarr::Protocol::Ollama>,
531 L<Langertha::Knarr::Protocol::A2A>,
532 L<Langertha::Knarr::Protocol::ACP>,
533 L<Langertha::Knarr::Protocol::AGUI>.
534  
535 =item B<Handlers>
536  
537 Backend logic — what answers the request. Knarr ships with
538 L<Langertha::Knarr::Handler::Router> (the default, model→engine via
539 L<Langertha::Knarr::Router>), L<Langertha::Knarr::Handler::Engine>
540 (single engine), L<Langertha::Knarr::Handler::Raider> (per-session
541 agent), L<Langertha::Knarr::Handler::Passthrough> (raw HTTP forward),
542 L<Langertha::Knarr::Handler::A2AClient> /
543 L<Langertha::Knarr::Handler::ACPClient> (consume remote agents), and
544 L<Langertha::Knarr::Handler::Code> (coderef-backed for tests). Implement
545 L<Langertha::Knarr::Handler> to write your own. Decorators
546 (L<Langertha::Knarr::Handler::Tracing>,
547 L<Langertha::Knarr::Handler::RequestLog>) wrap any inner handler and
548 add behavior on top — they themselves consume the Handler role and
549 compose freely.
550  
551 =item B<Transport>
552  
553 Default is L<Net::Async::HTTP::Server> with chunked SSE / NDJSON
554 streaming on one or more listen sockets. For Plack deployments,
555 L<Langertha::Knarr::PSGI> wraps the same Knarr instance into a PSGI
556 app (buffered — see its docs for the streaming caveat).
557  
558 =back
559  
560 =head2 handler
561  
562 Required. An object consuming L<Langertha::Knarr::Handler>.
563  
564 =head2 listen
565  
566 ArrayRef of C<host:port> strings or C<< { host => ..., port => ... } >>
567 hashes. Defaults to a single entry composed from L</host> and L</port>.
568  
569 =head2 host
570  
571 Default C<127.0.0.1>. Used when L</listen> is not given.
572  
573 =head2 port
574  
575 Default C<8088>. Used when L</listen> is not given.
576  
577 =head2 loop
578  
579 Optional L<IO::Async::Loop> instance. Defaults to a fresh one.
580  
581 =head2 protocols
582  
583 ArrayRef of protocol class basenames to load. Defaults to all six
584 shipped protocols.
585  
586 =head2 auth_token
587  
588 Optional shared secret. When set, every incoming request must present
589 it as C<Authorization: Bearer> or C<x-api-key>. Discovery routes
590 (C</.well-known/agent.json>) stay anonymous.
591  
592 =head2 start
593  
594 $knarr->start;
595  
596 Binds all listen sockets and registers the dispatcher. Returns
597 C<$self>. Does not enter the event loop.
598  
599 =head2 run
600  
601 $knarr->run; # blocks
602  
603 Calls L</start> if needed, then enters the L</loop> and blocks.
604  
605 =head2 session
606  
607 my $session = $knarr->session($id);
608  
609 Returns the L<Langertha::Knarr::Session> for the given id, creating
610 one on demand. Used internally by the dispatcher.
611  
612 =head1 SUPPORT
613  
614 =head2 Issues
615  
616 Please report bugs and feature requests on GitHub at
617 L<https://github.com/Getty/langertha-knarr/issues>.
618  
619 =head2 IRC
620  
621 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
622  
623 =head1 CONTRIBUTING
624  
625 Contributions are welcome! Please fork the repository and submit a pull request.
626  
627 =head1 AUTHOR
628  
629 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
630  
631 =head1 COPYRIGHT AND LICENSE
632  
633 This software is copyright (c) 2026 by Torsten Raudssus.
634  
635 This is free software; you can redistribute it and/or modify it under
636 the same terms as the Perl 5 programming language system itself.
637  
638 =cut
« Knarr/Protocol/AGUI.pm ↑ Summary Knarr/Protocol/ACP.pm »