blib/lib/Langertha/Knarr.pm

filter: Statementstmt 90.6% 603 / 665 Branchbran 74.3% 220 / 296 Conditioncond 68.2% 116 / 170 MC/DCmcdc 42.2% 41 / 97 Subroutinesub 92.5% 112 / 121 Podpod 100% 4 / 4 totaltotal 81.0% 1096 / 1353 CC 235 SCAR 23.7
CC
235
Cov
83%
__ANON__
74.8
_fork_worker
28.7
_simple_show
27.1
CRAP 10.7
« blib/lib/Langertha/Knarr/Request.pm ↑ Summary blib/lib/Langertha/Knarr/Image.pm »
1 package Langertha::Knarr;
2 # ABSTRACT: Universal LLM hub — proxy, server, and translator across OpenAI/Anthropic/Ollama/A2A/ACP/AG-UI
3 50 our $VERSION = '1.102';
4 50 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 50 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 50 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 50 ▶use IO::Async::Loop;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 50 ▶use IO::Async::Resolver;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 50 ▶use Net::Async::HTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 50 ▶use Net::Async::HTTP::Server;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 50 ▶use HTTP::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 50 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 50 ▶use Data::UUID;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 50 ▶use Module::Runtime qw( use_module );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 50 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
16 50 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
17 50 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 50 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
19 50 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
20 50 ▶use Socket ();
Subroutine BEGIN: called CC=1 SCAR=0.0
21 50 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
22 50 ▶use Langertha::Knarr::Session;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 50 ▶use Langertha::Knarr::Manifest;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 50 ▶use Langertha::Knarr::PassthroughUsage;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 50 ▶use Langertha::Knarr::Role::UpstreamHTTP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27  
28  
29 50 has handler => (
30 is => 'ro',
31 required => 1,
32 );
33  
34 50 has host => (
35 is => 'ro',
36 isa => 'Str',
37 default => '127.0.0.1',
38 );
39  
40 50 has port => (
41 is => 'ro',
42 isa => 'Int',
43 default => 8088,
44 );
45  
46 # Listen on one or more addresses. Each entry is either "host:port" or
47 # { host => ..., port => ... }. Defaults to a single entry composed from
48 # the host/port attributes above.
49 50 has listen => (
50 is => 'ro',
51 isa => 'ArrayRef',
52 lazy => 1,
53 builder => '_build_listen',
54 );
55  
56 31 ▶sub _build_listen {
Subroutine _build_listen: called CC=1 SCAR=0.0
57 31 my ($self) = @_;
58 31 return [ { host => $self->host, port => $self->port + 0 } ];
59 }
60  
61 50 has loop => (
62 is => 'ro',
63 lazy => 1,
64 builder => '_build_loop',
65 );
66 0 ▶sub _build_loop { IO::Async::Loop->new }
Subroutine _build_loop: not called CC=1 SCAR=6.9
67  
68 # Serving processes (k51): 1 is this one, more are forked by run().
69 has workers => (
70 is => 'ro',
71 isa => 'Int',
72 default => 1,
73 8 ▶ trigger => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
74 8 ▶ Carp::croak( "workers '$_[1]' must be 1 or more" ) unless $_[1] >= 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $_[1] >= 1 2 6 8
75 },
76 50 );
77  
78 has protocols => (
79 is => 'ro',
80 isa => 'ArrayRef[Str]',
81 115 ▶ default => sub { [qw( OpenAI Anthropic Ollama A2A ACP AGUI )] },
Subroutine __ANON__: called CC=1 SCAR=0.0
82 50 );
83  
84 has protocol_args => (
85 is => 'ro',
86 isa => 'HashRef[HashRef]',
87 107 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
88 50 );
89  
90 # Optional shared secret. When set, every incoming request must present it
91 # either as 'Authorization: Bearer <key>' or 'x-api-key: <key>'. The agent
92 # card and well-known discovery routes are exempt because they need to be
93 # anonymously fetchable.
94 has router => (
95 is => 'ro',
96 isa => 'Maybe[Object]',
97 58 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
98 50 );
99  
100 has raw_passthrough => (
101 is => 'ro',
102 isa => 'Maybe[Object]',
103 92 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
104 50 );
105  
106 has tracing => (
107 is => 'ro',
108 isa => 'Maybe[Object]',
109 107 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
110 50 );
111  
112 has auth_token => (
113 is => 'ro',
114 isa => 'Maybe[Str]',
115 100 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
116 50 );
117  
118 has public_url => (
119 is => 'ro',
120 isa => 'Maybe[Str]',
121 114 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
122 50 );
123  
124 # What GET /api/version answers (k27): the Ollama version the Ollama
125 # endpoints are compatible with, not Knarr's own. Current Ollama release
126 # (k28); it must stay >= 0.6.4 (Copilot BYOK floor) and digits-and-dots only
127 # (Open WebUI int()s each part).
128 has ollama_compat_version => (
129 is => 'ro',
130 isa => 'Str',
131 default => '0.34.4',
132 7 ▶ trigger => sub { _check_ollama_compat_version( $_[1] ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
133 50 );
134  
135 7 ▶sub _check_ollama_compat_version {
Subroutine _check_ollama_compat_version: called CC=2 SCAR=6.9
136 7 my ($version) = @_;
137 7 ▶ Carp::croak( "ollama_compat_version '$version' must be three dot-separated"
Branch: 1 branch
BranchTrueFalseTotal
unless $version =~ /\A\d+\.\d+\.\d+\z/ 6 1 7
138 . " numbers like 0.34.4 (Ollama clients parse each part as an integer)" )
139 unless $version =~ /\A\d+\.\d+\.\d+\z/;
140 1 return $version;
141 }
142  
143 has _manifest => (
144 is => 'ro',
145 lazy => 1,
146 9 ▶ default => sub { Langertha::Knarr::Manifest->new( knarr => $_[0] ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
147 50 );
148  
149 50 has _protocol_objects => (
150 is => 'ro',
151 lazy => 1,
152 builder => '_build_protocol_objects',
153 );
154  
155 50 has _routes => (
156 is => 'ro',
157 lazy => 1,
158 builder => '_build_routes',
159 );
160  
161 has _sessions => (
162 is => 'ro',
163 115 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
164 50 );
165  
166 has _uuid => (
167 is => 'ro',
168 115 ▶ default => sub { Data::UUID->new },
Subroutine __ANON__: called CC=1 SCAR=0.0
169 50 );
170  
171 has _json => (
172 is => 'ro',
173 115 ▶ default => sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1 ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
174 50 );
175  
176 50 has _server => (
177 is => 'rw',
178 );
179  
180 # The startup capability probe (k37), held until it is ready.
181 50 has _capability_probe => (
182 is => 'rw',
183 );
184  
185 has _servers => (
186 is => 'rw',
187 115 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
188 50 );
189  
190 92 ▶sub _build_protocol_objects {
Subroutine _build_protocol_objects: called CC=4 SCAR=13.9
191 92 my ($self) = @_;
192 92 my @objs;
193 92 for my $name ( @{ $self->protocols } ) {
194 552 ▶ my $class = $name =~ /::/ ? $name : "Langertha::Knarr::Protocol::$name";
Branch: 1 branch
BranchTrueFalseTotal
$name =~ /::/ ? : 0 552 552
195 552 use_module($class);
196 552 ▶ push @objs, $class->new( %{ $self->protocol_args->{$name} // {} } );
Condition100%2/2
$self->protocol_args->{$name} // {}
l!l
3549
MC/DC100%1/1
$self->protocol_args->{$name} // {}
$self->protocol_args->{$name}
Truth table100%2/2
A
A= $self->protocol_args->{$name}
Aresult
11
00
197 }
198 92 return \@objs;
199 }
200  
201 91 ▶sub _build_routes {
Subroutine _build_routes: called CC=3 SCAR=11.0
202 91 my ($self) = @_;
203 91 my @routes;
204 91 for my $proto ( @{ $self->_protocol_objects } ) {
205 546 for my $r ( @{ $proto->protocol_routes } ) {
206 1183 push @routes, { %$r, protocol => $proto };
207 }
208 }
209 # Knarr's own route, not a protocol's (k14).
210 91 push @routes, { method => 'GET', path => '/.well-known/langertha.json',
211 action => 'manifest', protocol => undef };
212 91 return \@routes;
213 }
214  
215 526 ▶sub session {
Subroutine session: called CC=3 SCAR=11.2
Pod documented
216 526 my ($self, $id) = @_;
217 526 ▶ $id //= $self->_uuid->create_str;
Condition66%2/3
$id //= $self->_uuid->create_str
l!l&&r!l&&!r
694570
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
218 526 ▶ $self->_sessions->{$id} //= Langertha::Knarr::Session->new( id => $id );
Condition66%2/3
$self->_sessions->{$id} //= "Langertha::Knarr::Session"->new("id", $id)
l!l&&r!l&&!r
604660
MC/DC0%0/2
$self->_sessions->{$id} //= "Langertha::Knarr::Session"->new("id", $id)
$self->_sessions->{$id} "Langertha::Knarr::Session"->new("id", $id)
Truth table66%2/3
A //= B
A= $self->_sessions->{$id}B= "Langertha::Knarr::Session"->new("id", $id)
ABresult
1X1
011
000
219 526 $self->_sessions->{$id}->touch;
220 526 return $self->_sessions->{$id};
221 }
222  
223 99 ▶sub _listen_addrs {
Subroutine _listen_addrs: called CC=6 SCAR=18.2
224 99 my ($self) = @_;
225 99 my @out;
226 99 for my $entry ( @{ $self->listen } ) {
227 102 ▶ if ( ref $entry eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $entry eq 'HASH') { } 33 69 102
228 33 ▶ push @out, { host => $entry->{host} // '127.0.0.1', port => $entry->{port} + 0 };
Condition50%1/2
$entry->{"host"} // "127.0.0.1"
l!l
330
MC/DC0%0/1
$entry->{"host"} // "127.0.0.1"
$entry->{"host"}
Truth table50%1/2
A
A= $entry->{"host"}
Aresult
11
00
229 } else {
230 69 my ($h, $p) = split /:/, $entry, 2;
231 69 ▶ $h ||= '127.0.0.1';
Condition50%1/2
$h ||= "127.0.0.1"
l!l
690
MC/DC0%0/1
$h ||= "127.0.0.1"
$h
Truth table50%1/2
A
A= $h
Aresult
11
00
232 69 ▶ push @out, { host => $h, port => ($p // 8088) + 0 };
Condition50%1/2
$p // 8088
l!l
690
MC/DC0%0/1
$p // 8088
$p
Truth table50%1/2
A
A= $p
Aresult
11
00
233 }
234 }
235 99 return @out;
236 }
237  
238 91 ▶sub start {
Subroutine start: called CC=1 SCAR=0.0
Pod documented
239 91 my ($self) = @_;
240 91 $self->_listen;
241 91 $self->_start_capability_probe;
242 91 return $self;
243 }
244  
245 97 ▶sub _listen {
Subroutine _listen: called CC=2 SCAR=6.9
246 97 my ($self) = @_;
247 97 my @servers;
248 97 for my $a ( $self->_listen_addrs ) {
249 my $server = Net::Async::HTTP::Server->new(
250 588 ▶ on_request => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
251 588 my ($srv, $req) = @_;
252 588 $self->_dispatch($req);
253 },
254 99 );
255 99 $self->loop->add($server);
256 $server->listen(
257 addr => {
258 family => 'inet',
259 socktype => 'stream',
260 port => $a->{port},
261 ip => $a->{host},
262 },
263 99 queuesize => $self->_listen_backlog,
264 )->get;
265 99 push @servers, $server;
266 }
267 97 $self->_servers(\@servers);
268 97 $self->_server( $servers[0] );
269 97 return;
270 }
271  
272 # Connections the kernel queues until a process accepts them (k51): the
273 # system maximum, not IO::Async's default of 3 -- with workers, connections
274 # wait here while the probe runs before the fork. The kernel caps it at
275 # net.core.somaxconn.
276 99 ▶sub _listen_backlog {
Subroutine _listen_backlog: called CC=3 SCAR=12.0
277 99 my ($self) = @_;
278 99 my $max = eval { Socket::SOMAXCONN() };
279 99 ▶ return $max && $max > 0 ? $max : 128;
Branch: 1 branch
BranchTrueFalseTotal
$max && $max > 0 ? : 99 0 99
Condition33%1/3
$max and $max > 0
!ll&&!rl&&r
0099
MC/DC0%0/2
$max and $max > 0
$max $max > 0
Truth table33%1/3
A and B
A= $maxB= $max > 0
ABresult
0X0
100
111
280 }
281  
282 # k37: once the server listens, ask each routed engine for its model's
283 # capabilities (Router->probe_capabilities_f). Deferred to the running loop
284 # so start() does not block on discovery; the Future is held here until it
285 # is ready. It never fails: probe errors are logged by the router.
286 97 ▶sub _start_capability_probe {
Subroutine _start_capability_probe: called CC=4 SCAR=14.1
287 97 my ($self) = @_;
288 97 my $router = $self->router;
289 97 ▶ return unless $router && $router->can('probe_capabilities_f');
Branch: 1 branch
BranchTrueFalseTotal
unless $router and $router->can("probe_capabilities_f") 55 42 97
Condition100%3/3
$router and $router->can("probe_capabilities_f")
!ll&&!rl&&r
431242
MC/DC100%2/2
$router and $router->can("probe_capabilities_f")
$router $router->can("probe_capabilities_f")
Truth table100%3/3
A and B
A= $routerB= $router->can("probe_capabilities_f")
ABresult
0X0
100
111
290 42 ▶ return if $self->_capability_probe;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_capability_probe 0 42 42
291 42 my $loop = $self->loop;
292 42 ▶ $self->_capability_probe( $loop->delay_future( after => 0 )->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
293 42 $router->probe_capabilities_f( loop => $loop );
294 0 ▶ })->else(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
295 0 $log->warnf( "Capability probe failed: %s", $_[0] );
296 0 Future->done(0);
297 42 }) );
298 42 return;
299 }
300  
301 5 ▶sub run {
Subroutine run: called CC=3 SCAR=16.5
Pod documented
302 5 my ($self) = @_;
303 5 ▶ return $self->_run_workers if $self->workers > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->workers > 1 5 0 5
304 0 ▶ $self->start unless $self->_server;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_server 0 0 0
305 0 $self->loop->run;
306 }
307  
308 # k51: prefork. This process binds, discovers and probes once, forks the
309 # workers -- which inherit all of it -- and supervises them until SIGTERM or
310 # SIGINT. It serves no request itself.
311 5 ▶sub _run_workers {
Subroutine _run_workers: called CC=1 SCAR=1.0
312 5 my ($self) = @_;
313 5 $self->_prepare_workers;
314  
315 5 my %workers; # pid => start time
316 5 my $stopping = 0;
317 5 ▶ my $stop = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
318 5 my ($signal) = @_;
319 5 ▶ $log->infof( "SIG%s: stopping %d worker(s)", $signal, scalar keys %workers )
Branch: 1 branch
BranchTrueFalseTotal
unless $stopping 5 0 5
320 unless $stopping;
321 5 $stopping = 1;
322 5 kill TERM => keys %workers;
323 5 };
324 5 local $SIG{TERM} = $stop;
325 5 local $SIG{INT} = $stop;
326  
327 11 ▶ my $spawn = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
328 11 my $pid = $self->_fork_worker;
329 11 $workers{$pid} = time;
330 11 ▶ kill TERM => $pid if $stopping; # the signal came in during the fork
Branch: 1 branch
BranchTrueFalseTotal
if $stopping 0 11 11
331 11 $log->infof( "Worker %d started", $pid );
332 5 };
333  
334 5 ▶ try {
Subroutine __ANON__: called CC=17 SCAR=43.2
335 # Only these first forks must succeed: without them nothing serves.
336 5 $spawn->() for 1 .. $self->workers;
337 5 my $delay = 0;
338 5 ▶ while ( %workers || !$stopping ) {
Branch: 1 branch
BranchTrueFalseTotal
if (%workers or not $stopping) 11 5 16
Condition66%2/3
%workers or not $stopping
l!l&&r!l&&!r
1105
MC/DC50%1/2
%workers or not $stopping
%workers not $stopping
Truth table66%2/3
A or not(B)
A= %workersB= not $stopping
ABresult
1X1
011
000
339 11 ▶ my $missing = $stopping ? 0 : $self->workers - keys %workers;
Branch: 1 branch
BranchTrueFalseTotal
$stopping ? : 6 5 11
340 11 ▶ if ( $missing > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($missing > 0) 0 11 11
341 0 ▶ sleep $delay if $delay; # a signal ends it early
Branch: 1 branch
BranchTrueFalseTotal
if $delay 0 0 0
342 0 ▶ next if $stopping;
Branch: 1 branch
BranchTrueFalseTotal
if $stopping 0 0 0
343 0 ▶ next if eval { $spawn->(); 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { &$spawn(); 1 } } 0 0 0
344 # A replacement that cannot be forked (EAGAIN, ENOMEM) is treated
345 # like a crashing worker: the others keep serving, and it is tried
346 # again after a pause (k64).
347 0 $delay = $self->_restart_delay($delay);
348 0 $log->errorf( "%s; trying again in %ds", _error_text($@), $delay );
349 }
350 # While a worker is missing, only look: the retry must not wait for
351 # the next death.
352 11 ▶ my $pid = waitpid( -1, $missing > 0 ? POSIX::WNOHANG() : 0 );
Branch: 1 branch
BranchTrueFalseTotal
$missing > 0 ? : 0 11 11
353 11 ▶ next if $pid == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $pid == 0 0 11 11
354 11 ▶ if ( $pid < 0 ) { # no children left
Branch: 1 branch
BranchTrueFalseTotal
if ($pid < 0) 0 11 11
355 0 ▶ last unless $missing > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $missing > 0 0 0 0
356 0 next;
357 }
358 11 ▶ my $started = delete $workers{$pid} // next;
Condition50%1/2
delete $workers{$pid} // (next)
l!l
110
MC/DC0%0/1
delete $workers{$pid} // (next)
delete $workers{$pid}
Truth table50%1/2
A
A= delete $workers{$pid}
Aresult
11
00
359 11 ▶ next if $stopping;
Branch: 1 branch
BranchTrueFalseTotal
if $stopping 11 0 11
360 0 my $status = $?;
361 # A worker that dies within 5s of its start is crashing: pause before
362 # the next one, so it cannot spin.
363 0 ▶ $delay = time - $started < 5 ? $self->_restart_delay($delay) : 0;
Branch: 1 branch
BranchTrueFalseTotal
time - $started < 5 ? : 0 0 0
364 0 ▶ $log->warnf( "Worker %d %s, starting a new one%s", $pid,
Branch: 1 branch
BranchTrueFalseTotal
$delay ? : 0 0 0
365 $self->_exit_text($status), $delay ? " in ${delay}s" : '' );
366 }
367 0 ▶ } catch {
Subroutine __ANON__: not called CC=2 SCAR=17.9
368 0 my $err = $_;
369 0 kill TERM => keys %workers;
370 0 waitpid( $_, 0 ) for keys %workers;
371 0 die $err;
372 5 };
373 5 return;
374 }
375  
376 # The pause before the next restart: 1, 2, 4 ... 30 seconds.
377 0 ▶sub _restart_delay {
Subroutine _restart_delay: not called CC=3 SCAR=24.8
378 0 my ($self, $delay) = @_;
379 0 ▶ $delay = $delay ? $delay * 2 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$delay ? : 0 0 0
380 0 ▶ return $delay > 30 ? 30 : $delay;
Branch: 1 branch
BranchTrueFalseTotal
$delay > 30 ? : 0 0 0
381 }
382  
383 6 ▶sub _prepare_workers {
Subroutine _prepare_workers: called CC=6 SCAR=18.3
384 6 my ($self) = @_;
385 6 ▶ $self->_listen unless $self->_server;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_server 6 0 6
386 6 my $loop = $self->loop;
387 # The sockets stay bound here for the workers, but this process accepts
388 # nothing on them.
389 6 $loop->remove($_) for grep { $_->loop } @{ $self->_servers };
390 6 ▶ if ( my $router = $self->router ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $router = $self->router) 6 0 6
391 6 ▶ $router->list_models if $router->can('list_models'); # auto-discovery
Branch: 1 branch
BranchTrueFalseTotal
if $router->can("list_models") 6 0 6
392 6 $self->_start_capability_probe;
393 6 ▶ $self->_capability_probe->get if $self->_capability_probe;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_capability_probe 6 0 6
394 }
395 6 $self->_drop_upstream_connections;
396 6 $self->_drop_resolver;
397 6 return;
398 }
399  
400 # Keep-alive upstream connections (the probe's) must not reach the workers:
401 # two processes on one socket read each other's responses. A
402 # Net::Async::HTTP closes its pooled connections when it leaves the loop and
403 # connects anew once it is back.
404 7 ▶sub _drop_upstream_connections {
Subroutine _drop_upstream_connections: called CC=3 SCAR=11.4
405 7 my ($self) = @_;
406 7 my $loop = $self->loop;
407 7 for my $http ( grep { $_->isa('Net::Async::HTTP') } $loop->notifiers ) {
408 1 ▶ if ( my $parent = $http->parent ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $parent = $http->parent) { } 0 1 1
409 0 $parent->remove_child($http);
410 0 $parent->add_child($http);
411 }
412 else {
413 1 $loop->remove($http);
414 1 $loop->add($http);
415 }
416 }
417 7 return;
418 }
419  
420 # The loop's resolver looks names up in helper processes, started by the
421 # first connect to a hostname -- the probe's. Workers that inherited them
422 # would share their pipes and read each other's answers: a request would go
423 # to another request's upstream, or hang (k63). The helpers exit here, and
424 # the loop gets a fresh resolver, for which every worker starts its own.
425 # Waiting for their exit also clears the loop's watch on their pids, which
426 # a worker's own helper could otherwise reuse.
427 6 ▶sub _drop_resolver {
Subroutine _drop_resolver: called CC=5 SCAR=16.2
428 6 my ($self) = @_;
429 6 my $loop = $self->loop;
430 6 ▶ my @resolvers = grep { $_->isa('IO::Async::Resolver') && !$_->parent } $loop->notifiers
Branch: 1 branch
BranchTrueFalseTotal
my(@resolvers) = grep({$_->isa("IO::Async::Resolver") and not $_->parent;} $loop->notifiers) or return 1 5 6
Condition66%2/3
$_->isa('IO::Async::Resolver') && !$_->parent
!ll&&!rl&&r
901
MC/DC50%1/2
$_->isa('IO::Async::Resolver') && !$_->parent
$_->isa('IO::Async::Resolver') !$_->parent
Truth table66%2/3
A && not(B)
A= $_->isa('IO::Async::Resolver')B= !$_->parent
ABresult
0X0
100
111
431 or return;
432 1 for my $resolver (@resolvers) {
433 1 my $stopped = $resolver->stop;
434 1 Future->wait_any( $stopped, $loop->delay_future( after => 10 ) )->get;
435 1 ▶ $log->warn("Resolver helpers did not exit within 10s") unless $stopped->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $stopped->is_ready 0 1 1
436 1 $loop->remove($resolver);
437 }
438 1 $loop->set_resolver( IO::Async::Resolver->new );
439 1 return;
440 }
441  
442 # Returns the worker's pid in the supervisor; the worker itself never
443 # returns. It drops the supervisor's signal handlers, rebuilds the loop's
444 # kernel state (epoll/kqueue fd, signal pipe) and accepts on the inherited
445 # sockets. POSIX::_exit: the supervisor's END blocks and destructors are not
446 # the worker's to run.
447 #
448 # SIGTERM and SIGINT stay blocked from before the fork until the worker has
449 # dropped the supervisor's handlers (k64): one that reached the worker in
450 # between would run the supervisor's stop -- killing the other workers --
451 # and the worker would serve on. Blocked, it waits and then ends the worker;
452 # in the supervisor it runs once the fork is done.
453 11 ▶sub _fork_worker {
Subroutine _fork_worker: called CC=10 SCAR=33.6
454 11 my ($self) = @_;
455 11 my $signals = POSIX::SigSet->new( POSIX::SIGTERM(), POSIX::SIGINT() );
456 11 my $mask = POSIX::SigSet->new;
457 11 ▶ POSIX::sigprocmask( POSIX::SIG_BLOCK(), $signals, $mask )
Branch: 1 branch
BranchTrueFalseTotal
POSIX::sigprocmask(0, $signals, $mask) or Carp::croak("Cannot block signals for the fork: $!") 11 0 11
458 or Carp::croak( "Cannot block signals for the fork: $!" );
459 11 my $pid = $self->_fork;
460 11 my $error = $!;
461 11 ▶ if ( defined $pid && !$pid ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pid and not $pid) 0 11 11
Condition33%1/3
defined $pid and not $pid
!ll&&!rl&&r
0110
MC/DC0%0/2
defined $pid and not $pid
defined $pid not $pid
Truth table33%1/3
A and not(B)
A= defined $pidB= not $pid
ABresult
0X0
100
111
462 0 $SIG{$_} = 'DEFAULT' for qw( TERM INT );
463 }
464 11 POSIX::sigprocmask( POSIX::SIG_SETMASK(), $mask );
465 11 ▶ Carp::croak( "Cannot fork a worker: $error" ) unless defined $pid;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pid 0 11 11
466 11 ▶ return $pid if $pid;
Branch: 1 branch
BranchTrueFalseTotal
if $pid 11 0 11
467 0 my $ok = eval {
468 0 my $loop = $self->loop;
469 0 $loop->post_fork;
470 0 $loop->add($_) for @{ $self->_servers };
471 0 $loop->run;
472 0 1;
473 };
474 0 ▶ $log->errorf( "Worker %d failed: %s", $$, $@ ) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
475 0 ▶ POSIX::_exit( $ok ? 0 : 1 );
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 0 0 0
476 }
477  
478 # The fork itself, apart so a test can make it fail.
479 11 ▶sub _fork { fork }
Subroutine _fork: called CC=1 SCAR=0.0
480  
481 0 ▶sub _exit_text {
Subroutine _exit_text: not called CC=2 SCAR=17.9
482 0 my ($self, $status) = @_;
483 0 ▶ return 'was killed by signal ' . ( $status & 127 ) if $status & 127;
Branch: 1 branch
BranchTrueFalseTotal
if $status & 127 0 0 0
484 0 return 'exited with status ' . ( $status >> 8 );
485 }
486  
487 1090 ▶sub _match_route {
Subroutine _match_route: called CC=4 SCAR=13.9
488 1090 my ($self, $method, $path) = @_;
489 1090 for my $r ( @{ $self->_routes } ) {
490 5787 ▶ next unless $r->{method} eq $method;
Branch: 1 branch
BranchTrueFalseTotal
unless $r->{"method"} eq $method 2318 3469 5787
491 3469 ▶ return $r if $r->{path} eq $path;
Branch: 1 branch
BranchTrueFalseTotal
if $r->{"path"} eq $path 1088 2381 3469
492 }
493 2 return undef;
494 }
495  
496 1088 ▶sub _check_auth {
Subroutine _check_auth: called CC=10 SCAR=23.0
497 1088 my ($self, $req, $action) = @_;
498 1088 ▶ 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 685 403 1088
Condition66%2/3
defined $self->auth_token and length $self->auth_token
!ll&&!rl&&r
6850403
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
499 # Discovery endpoints stay anonymous so clients can introspect.
500 403 ▶ return 1 if $action eq 'a2a_card';
Branch: 1 branch
BranchTrueFalseTotal
if $action eq "a2a_card" 15 388 403
501 # One element of the value is enough: a header sent twice arrives as one
502 # value joined with ', ' (k53).
503 388 for my $name ( 'Authorization', 'x-api-key' ) {
504 635 my $value = scalar $req->header($name);
505 635 ▶ next unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 261 374 635
506 374 my $bearer = lc $name eq 'authorization';
507 374 for my $element ( split /,/, $value ) {
508 390 $element =~ s/\A\s+|\s+\z//g;
509 390 ▶ next if $bearer && $element !~ s/\ABearer\s+//i;
Branch: 1 branch
BranchTrueFalseTotal
if $bearer and not $element =~ s/\ABearer\s+//i 36 354 390
Condition100%3/3
$bearer and not $element =~ s/\ABearer\s+//i
!ll&&!rl&&r
13222236
MC/DC100%2/2
$bearer and not $element =~ s/\ABearer\s+//i
$bearer not $element =~ s/\ABearer\s+//i
Truth table100%3/3
A and not(B)
A= $bearerB= not $element =~ s/\ABearer\s+//i
ABresult
0X0
100
111
510 354 ▶ return 1 if $element eq $self->auth_token;
Branch: 1 branch
BranchTrueFalseTotal
if $element eq $self->auth_token 233 121 354
511 }
512 }
513 155 return 0;
514 }
515  
516 # Headers Knarr reads its own key (auth_token) from.
517 50 my %PROXY_KEY_HEADER = ( 'authorization' => 1, 'x-api-key' => 1 );
518  
519 # A client header's value as it may leave Knarr (k44, k53). In Authorization
520 # and x-api-key, every comma-separated element that is Knarr's key -- bare
521 # or as 'Bearer <key>', in either header -- is removed: a header sent twice
522 # arrives as one value joined with ', ' under PSGI (one HTTP_* key), and
523 # a client may join them itself. Returns the value unchanged, byte for
524 # byte, when no element carries the key; the remaining elements joined with
525 # ', ' when some do; nothing when only the key was there, so the header is
526 # dropped.
527 # Every path that forwards client headers goes through here: the raw
528 # passthrough and the forward_headers of the protocol parsers.
529 1046 ▶sub _without_proxy_key {
Subroutine _without_proxy_key: called CC=10 SCAR=23.1
530 1046 my ($self, $name, $value) = @_;
531 1046 my $key = $self->auth_token;
532 return $value unless defined $key && length $key && defined $value
533 1046 ▶ && $PROXY_KEY_HEADER{ lc $name };
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key and length $key and defined $value and $PROXY_KEY_HEADER{lc $name} 774 272 1046
Condition77%7/9
defined $key and length $key and defined $value and $PROXY_KEY_HEADER{lc $name}
!ll&&!rl&&r
623151272
defined $key and length $key and defined $value
!ll&&!rl&&r
6230423
defined $key and length $key
!ll&&!rl&&r
6230423
MC/DC50%2/4
defined $key and length $key and defined $value and $PROXY_KEY_HEADER{lc $name}
defined $key length $key defined $value $PROXY_KEY_HEADER{lc $name}
Truth table60%3/5
A and B and C and D
A= defined $keyB= length $keyC= defined $valueD= $PROXY_KEY_HEADER{lc $name}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
534 272 my ( @kept, $dropped );
535 272 for my $element ( split /,/, $value ) {
536 323 ( my $token = $element ) =~ s/\A\s+|\s+\z//g;
537 323 ▶ next unless length $token;
Branch: 1 branch
BranchTrueFalseTotal
unless length $token 0 323 323
538 323 ( my $bare = $token ) =~ s/\ABearer\s+//i;
539 323 ▶ if ( $bare eq $key ) { $dropped = 1; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($bare eq $key) 187 136 323
540 136 push @kept, $token;
541 }
542 272 ▶ return $value unless $dropped;
Branch: 1 branch
BranchTrueFalseTotal
unless $dropped 93 179 272
543 179 ▶ return @kept ? join( ', ', @kept ) : ();
Branch: 1 branch
BranchTrueFalseTotal
@kept ? : 37 142 179
544 }
545  
546 # The protocol's parse, with Knarr's key taken out of the headers a
547 # passthrough handler in the chain forwards (forward_headers, k44). Shared
548 # by the native server and the PSGI adapter.
549 713 ▶sub _parse_chat_request {
Subroutine _parse_chat_request: called CC=5 SCAR=16.1
550 713 my ($self, $proto, $req, $body_ref) = @_;
551 713 my $sb_req = $proto->parse_chat_request( $req, $body_ref );
552 # One header line at a time, as the parser recorded them (k60): a line
553 # that was only the key is dropped, the others keep their order.
554 713 my $extra = $sb_req->extra;
555 713 ▶ if ( $extra && $extra->{forward_headers} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($extra and $extra->{"forward_headers"}) 598 115 713
Condition66%2/3
$extra and $extra->{"forward_headers"}
!ll&&!rl&&r
0115598
MC/DC50%1/2
$extra and $extra->{"forward_headers"}
$extra $extra->{"forward_headers"}
Truth table66%2/3
A and B
A= $extraB= $extra->{"forward_headers"}
ABresult
0X0
100
111
556 598 my @kept;
557 598 for my $pair ( $sb_req->forward_header_pairs ) {
558 409 my ($value) = $self->_without_proxy_key(@$pair);
559 409 ▶ push @kept, [ $pair->[0], $value ] if defined $value;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 307 102 409
560 }
561 598 $extra->{forward_headers} = \@kept;
562 }
563 713 return $sb_req;
564 }
565  
566 # The one 401 answer, shared by the native server and the PSGI adapter (k25).
567 155 ▶sub _unauthorized {
Subroutine _unauthorized: called CC=1 SCAR=0.0
568 155 my ($self) = @_;
569 155 return ( 401, 'application/json',
570 $self->_json->encode({ error => { message => 'unauthorized' } }) );
571 }
572  
573 588 ▶sub _dispatch {
Subroutine _dispatch: called CC=6 SCAR=18.3
574 588 my ($self, $req) = @_;
575 588 my $method = $req->method;
576 588 my $path = $req->path;
577 588 my $route = $self->_match_route( $method, $path );
578 588 ▶ unless ( $route ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($route) 1 587 588
579 1 return $self->_send_simple( $req, 404, 'application/json',
580 $self->_json->encode({ error => { message => "no route for $method $path" } }) );
581 }
582 587 my $action = $route->{action};
583 587 ▶ unless ( $self->_check_auth( $req, $action ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_check_auth($req, $action)) 79 508 587
584 79 return $self->_send_simple( $req, $self->_unauthorized );
585 }
586 508 my $proto = $route->{protocol};
587 508 my $simple = $self->_simple_action($action);
588 508 ▶ my $code = $simple ? undef : $self->can("_action_$action");
Branch: 1 branch
BranchTrueFalseTotal
$simple ? : 49 459 508
589 508 ▶ unless ( $simple || $code ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($simple or $code) 0 508 508
Condition66%2/3
$simple or $code
l!l&&r!l&&!r
494590
MC/DC0%0/2
$simple or $code
$simple $code
Truth table66%2/3
A or B
A= $simpleB= $code
ABresult
1X1
011
000
590 0 return $self->_send_simple( $req, 500, 'application/json',
591 $self->_json->encode({ error => { message => "unknown action $action" } }) );
592 }
593 508 ▶ try {
Subroutine __ANON__: called CC=3 SCAR=11.0
594 508 ▶ if ( $simple ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($simple) { } 49 459 508
595 49 my ($status, $headers, $body) = $self->$simple( $proto, $req->body );
596 49 ▶ $self->_send_simple( $req, $status, $headers->{'Content-Type'} // 'application/json', $body );
Condition50%1/2
$headers->{"Content-Type"} // "application/json"
l!l
490
MC/DC0%0/1
$headers->{"Content-Type"} // "application/json"
$headers->{"Content-Type"}
Truth table50%1/2
A
A= $headers->{"Content-Type"}
Aresult
11
00
597 }
598 else {
599 459 $self->$code( $proto, $req );
600 }
601 0 ▶ } catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
602 0 my $err = $_;
603 0 $log->errorf("Request error (%s): %s", $action, $err);
604 0 $self->_send_simple( $req, 500, 'application/json',
605 $self->_json->encode({ error => { message => "$err" } }) );
606 508 };
607 }
608  
609 387 ▶sub _action_chat {
Subroutine _action_chat: called CC=2 SCAR=6.9
610 387 my ($self, $proto, $req) = @_;
611 387 my $body = $req->body;
612 387 my $sb_req = $self->_parse_chat_request( $proto, $req, \$body );
613  
614 # Raw passthrough: pipe bytes 1:1 to upstream, skip handler chain
615 387 ▶ if ( $self->_is_raw_passthrough($sb_req) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_raw_passthrough($sb_req)) 106 281 387
616 106 return $self->_handle_raw_passthrough( $proto, $req, $sb_req );
617 }
618 281 return $self->_handle_chat( $proto, $req, $sb_req );
619 }
620  
621 # A parsed chat request answered through the handler chain -- also a raw
622 # passthrough that falls back to its engine (k66).
623 285 ▶sub _handle_chat {
Subroutine _handle_chat: called CC=2 SCAR=7.0
624 285 my ($self, $proto, $req, $sb_req) = @_;
625 285 my $session = $self->session( $sb_req->session_id );
626 285 my $handler = $self->handler;
627  
628 285 ▶ if ( $sb_req->stream ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sb_req->stream) 142 143 285
629 142 return $self->_handle_stream( $proto, $req, $sb_req, $session, $handler );
630 }
631  
632 143 my $f = $handler->handle_chat_f( $session, $sb_req );
633 132 ▶ $f->on_done( sub {
Subroutine __ANON__: called CC=1 SCAR=0.8
634 132 my ($response) = @_;
635 132 ▶ try {
Subroutine __ANON__: called CC=2 SCAR=7.2
636 132 my ($status, $headers, $body) = $proto->format_chat_response( $response, $sb_req );
637 132 ▶ $self->_send_simple( $req, $status, $headers->{'Content-Type'} // 'application/json', $body );
Condition50%1/2
$headers->{"Content-Type"} // "application/json"
l!l
1320
MC/DC0%0/1
$headers->{"Content-Type"} // "application/json"
$headers->{"Content-Type"}
Truth table50%1/2
A
A= $headers->{"Content-Type"}
Aresult
11
00
638 0 ▶ } catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
639 0 my $err = $_;
640 0 $log->errorf("Chat response error: %s", $err);
641 0 $self->_send_simple( $req, 500, 'application/json',
642 $self->_json->encode({ error => { message => "$err" } }) );
643 132 };
644 143 });
645 11 ▶ $f->on_fail( sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
646 11 my ($err, $category) = @_;
647 11 $log->errorf("Chat handler error: %s", $err);
648 11 ▶ if ( my @answer = $self->_handler_failure_answer( $proto, $err, $category ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@answer) = $self->_handler_failure_answer($proto, $err, $category)) 10 1 11
649 10 return $self->_send_simple( $req, @answer );
650 }
651 1 $self->_send_simple( $req, 500, 'application/json',
652 $self->_json->encode({ error => { message => "$err" } }) );
653 143 });
654 143 $f->retain;
655 }
656  
657 142 ▶sub _handle_stream {
Subroutine _handle_stream: called CC=3 SCAR=11.4
658 142 my ($self, $proto, $req, $sb_req, $session, $handler) = @_;
659  
660 # A handler that refuses the request outright (no route for the model,
661 # k41) has failed before any stream exists: answer it like a
662 # non-streaming request, before the stream's 200 goes out.
663 142 my $f = $handler->handle_stream_f( $session, $sb_req );
664 142 ▶ if ( $f->is_failed ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($f->is_failed) 4 138 142
665 4 ▶ if ( my @answer = $self->_handler_failure_answer( $proto, $f->failure ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@answer) = $self->_handler_failure_answer($proto, $f->failure)) 4 0 4
666 4 return $self->_send_simple( $req, @answer );
667 }
668 }
669  
670 138 my $header = HTTP::Response->new( 200 );
671 138 $header->protocol('HTTP/1.1');
672 138 $header->header( 'Content-Type' => $proto->stream_content_type );
673 138 $header->header( 'Cache-Control' => 'no-cache' );
674 138 $req->respond_chunk_header( $header );
675  
676 569 ▶ my $write = sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
677 569 my ($bytes) = @_;
678 569 ▶ return unless defined $bytes && length $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes and length $bytes 168 401 569
Condition66%2/3
defined $bytes and length $bytes
!ll&&!rl&&r
0168401
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
679 401 ▶ return if $req->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $req->is_closed 0 401 401
680 401 $req->write_chunk( $bytes );
681 138 };
682  
683 138 ▶ $f->on_done( sub {
Subroutine __ANON__: called CC=1 SCAR=0.1
684 138 my ($stream) = @_;
685 138 $write->( $proto->format_stream_open($sb_req) );
686 138 ▶ my $pump; $pump = sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
687 317 ▶ if ( $req->is_closed ) { undef $pump; return }
Branch: 1 branch
BranchTrueFalseTotal
if ($req->is_closed) 0 317 317
688 304 ▶ $stream->next_chunk_f->on_done( sub {
Subroutine __ANON__: called CC=6 SCAR=18.8
689 304 my ($delta) = @_;
690 304 ▶ if ( $req->is_closed ) { undef $pump; return }
Branch: 1 branch
BranchTrueFalseTotal
if ($req->is_closed) 0 304 304
691 304 ▶ if ( defined $delta ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $delta) { } 179 125 304
692 179 $write->( $proto->format_stream_chunk( $delta, $sb_req ) );
693 179 $pump->();
694 }
695 else {
696 # The backend's terminal reason, its complete tool calls and its
697 # token usage are known only now; the protocol maps the reason into
698 # its own vocabulary (k18) and frames the calls (k19) and the usage.
699 125 ▶ my $finish_reason = $stream->can('finish_reason') ? $stream->finish_reason : undef;
Branch: 1 branch
BranchTrueFalseTotal
$stream->can('finish_reason') ? : 125 0 125
700 125 ▶ my $tool_calls = $stream->can('tool_calls') ? $stream->tool_calls : [];
Branch: 1 branch
BranchTrueFalseTotal
$stream->can('tool_calls') ? : 125 0 125
701 125 ▶ my $usage = $stream->can('usage') ? $stream->usage : undef;
Branch: 1 branch
BranchTrueFalseTotal
$stream->can('usage') ? : 125 0 125
702 125 $write->( $proto->format_stream_close( $sb_req, $finish_reason, $tool_calls, $usage ) );
703 125 $write->( $proto->format_stream_done( $sb_req, $finish_reason, $tool_calls, $usage ) );
704 125 $req->write_chunk_eof;
705 125 undef $pump;
706 }
707 13 ▶ })->on_fail( sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
708 13 my ($err, $category) = @_;
709 13 $log->errorf("Stream chunk error: %s", $err);
710 13 undef $pump;
711 13 ▶ return if $self->_stream_failure_frame( $proto, $req, $err, $category );
Branch: 1 branch
BranchTrueFalseTotal
if $self->_stream_failure_frame($proto, $req, $err, $category) 12 1 13
712 1 $write->( $proto->format_stream_chunk( "[error: $err]", $sb_req ) );
713 1 $write->( $proto->format_stream_close($sb_req) );
714 1 $req->write_chunk_eof;
715 317 })->retain;
716 # Held until ready: a decorator's chained read (Tracing, RequestLog)
717 # is referenced by nothing else while the upstream is silent (k36).
718 138 };
719 138 $pump->();
720 138 });
721 0 ▶ $f->on_fail( sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
722 0 my ($err, $category) = @_;
723 0 $log->errorf("Stream handler error: %s", $err);
724 0 ▶ return if $self->_stream_failure_frame( $proto, $req, $err, $category );
Branch: 1 branch
BranchTrueFalseTotal
if $self->_stream_failure_frame($proto, $req, $err, $category) 0 0 0
725 0 $write->( $proto->format_stream_chunk( "[error: $err]", $sb_req ) );
726 0 $req->write_chunk_eof;
727 138 });
728 138 $f->retain;
729 }
730  
731 # The status a handler failure answers with, from its category (the second
732 # failure value). A Net::Async::HTTP timeout category (core's k278 engine
733 # timeouts, the UpstreamHTTP role's) is an upstream that did not answer in
734 # time: 504, as on the raw passthrough (k35, k36). 'model_not_found' is
735 # Handler::Router finding nothing to serve the model -- not configured, no
736 # passthrough for the protocol, no default engine: 404 (k41). Undef for any
737 # other failure, and for a core that sets no category.
738 54 ▶sub _handler_failure_status {
Subroutine _handler_failure_status: called CC=4 SCAR=13.9
739 54 my ($self, $category) = @_;
740 54 ▶ return 504 if Langertha::Knarr::Role::UpstreamHTTP->is_upstream_timeout($category);
Branch: 1 branch
BranchTrueFalseTotal
if "Langertha::Knarr::Role::UpstreamHTTP"->is_upstream_timeout($category) 36 18 54
741 18 ▶ return 404 if defined $category && $category eq 'model_not_found';
Branch: 1 branch
BranchTrueFalseTotal
if defined $category and $category eq "model_not_found" 16 2 18
Condition66%2/3
defined $category and $category eq "model_not_found"
!ll&&!rl&&r
2016
MC/DC50%1/2
defined $category and $category eq "model_not_found"
defined $category $category eq "model_not_found"
Truth table66%2/3
A and B
A= defined $categoryB= $category eq "model_not_found"
ABresult
0X0
100
111
742 2 return;
743 }
744  
745 # That status in the client protocol's error shape. Empty for a failure
746 # without one.
747 41 ▶sub _handler_failure_answer {
Subroutine _handler_failure_answer: called CC=3 SCAR=11.0
748 41 my ($self, $proto, $err, $category) = @_;
749 41 ▶ my $code = $self->_handler_failure_status($category) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $code = $self->_handler_failure_status($category) or return 40 1 41
750 40 my ($status, $headers, $body) = $proto->format_error_response( $code, _error_text($err) );
751 40 ▶ return ( $status, $headers->{'Content-Type'} // 'application/json', $body );
Condition50%1/2
$headers->{"Content-Type"} // "application/json"
l!l
400
MC/DC0%0/1
$headers->{"Content-Type"} // "application/json"
$headers->{"Content-Type"}
Truth table50%1/2
A
A= $headers->{"Content-Type"}
Aresult
11
00
752 }
753  
754 # The same for a stream whose headers are out: the protocol's error frame,
755 # then the end of the stream. False (nothing written) when the failure has
756 # no status or the protocol has no error frame, so the caller answers as
757 # before.
758 13 ▶sub _stream_failure_frame {
Subroutine _stream_failure_frame: called CC=4 SCAR=14.0
759 13 my ($self, $proto, $req, $err, $category) = @_;
760 13 ▶ my $code = $self->_handler_failure_status($category) or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $code = $self->_handler_failure_status($category) or return 0 12 1 13
761 12 my $frame = $proto->format_stream_error( $code, _error_text($err) );
762 12 ▶ return 0 unless length $frame;
Branch: 1 branch
BranchTrueFalseTotal
unless length $frame 0 12 12
763 12 ▶ return 1 if $req->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $req->is_closed 0 12 12
764 12 $req->write_chunk($frame);
765 12 $req->write_chunk_eof;
766 12 return 1;
767 }
768  
769 106 ▶sub _handle_raw_passthrough {
Subroutine _handle_raw_passthrough: called CC=3 SCAR=11.0
770 106 my ($self, $proto, $req, $sb_req) = @_;
771 106 my ($http_req, $trace, $trace_from) = $self->_raw_passthrough_request(
772 $sb_req, [ $req->headers ], $req->body, $req->path );
773 106 my $pt = $self->raw_passthrough;
774 106 ▶ my $model = $sb_req->model // 'unknown';
Condition50%1/2
$sb_req->model // "unknown"
l!l
1060
MC/DC0%0/1
$sb_req->model // "unknown"
$sb_req->model
Truth table50%1/2
A
A= $sb_req->model
Aresult
11
00
775  
776 106 ▶ if ($sb_req->stream) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sb_req->stream) { } 47 59 106
777 # The upstream may go silent before its headers (answered like a
778 # non-streaming failure: 504 or 502 in the protocol's shape) or in the
779 # middle of the stream (the headers are out: the protocol's error frame,
780 # then the end of the stream). stall_timeout covers both (k35).
781 47 my $headers_sent = 0;
782 47 my $fell_back = 0;
783 47 my $tail = '';
784 my $f = $pt->_upstream_request_f(
785 request => $http_req,
786 44 ▶ on_header => sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
787 44 my ($response) = @_;
788 # The status is known before any byte goes to the client: a refused
789 # discovered model is answered by its engine instead, and the
790 # upstream's refusal is read and dropped (k66).
791 44 ▶ if ( $self->_raw_passthrough_falls_back( $sb_req, $response ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_raw_passthrough_falls_back($sb_req, $response)) 2 42 44
792 2 $fell_back = 1;
793 2 $self->_raw_passthrough_fall_back( $proto, $req, $sb_req );
794 2 ▶ return sub { };
Subroutine __ANON__: called CC=1 SCAR=0.0
795 }
796 42 ▶ $trace = $self->_raw_passthrough_trace( $sb_req, $trace_from ) if $trace_from;
Branch: 1 branch
BranchTrueFalseTotal
if $trace_from 8 34 42
797 # The upstream's headers go back with it (k56).
798 42 my $header = HTTP::Response->new($response->code);
799 42 $header->protocol('HTTP/1.1');
800 42 $header->header('Content-Type' => scalar $response->header('Content-Type'));
801 42 $header->push_header(@$_) for @{ $self->_raw_passthrough_response_headers($response) };
802 42 ▶ $header->header('Cache-Control' => 'no-cache') unless defined $header->header('Cache-Control');
Branch: 1 branch
BranchTrueFalseTotal
unless defined $header->header("Cache-Control") 41 1 42
803 42 $req->respond_chunk_header($header);
804 42 $headers_sent = 1;
805 # The trace reads its usage off a copy of the bytes (k61).
806 42 my $usage = $self->_raw_passthrough_usage_reader( $trace, $response );
807  
808 371 ▶ return sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
809 371 my ($data) = @_;
810 371 ▶ if (!defined $data) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 38 333 371
811 38 ▶ $req->write_chunk_eof unless $req->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
unless $req->is_closed 38 0 38
812 38 ▶ $self->tracing->end_trace( $trace, output => '[stream]',
Branch: 2 branches
BranchTrueFalseTotal
if $trace 19 19 38
$usage ? : 18 1 19
813 $usage ? $usage->trace_args : () ) if $trace;
814 38 return;
815 }
816 333 ▶ return unless length $data;
Branch: 1 branch
BranchTrueFalseTotal
unless length $data 1 332 333
817 332 $tail = substr( $tail . $data, -2 );
818 332 ▶ $req->write_chunk($data) unless $req->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
unless $req->is_closed 332 0 332
819 332 ▶ $usage->add_chunk($data) if $usage;
Branch: 1 branch
BranchTrueFalseTotal
if $usage 171 161 332
820 42 };
821 },
822 47 );
823 7 ▶ $f->on_fail(sub {
Subroutine __ANON__: called CC=13 SCAR=27.6
824 7 my ($err, $category) = @_;
825 # The engine answers; the dropped refusal has nothing left to say.
826 7 ▶ return if $fell_back;
Branch: 1 branch
BranchTrueFalseTotal
if $fell_back 0 7 7
827 7 ▶ unless ($headers_sent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($headers_sent) 3 4 7
828 3 ▶ $trace = $self->_raw_passthrough_trace( $sb_req, $trace_from ) if $trace_from;
Branch: 1 branch
BranchTrueFalseTotal
if $trace_from 0 3 3
829 3 return $self->_send_simple( $req,
830 $self->_raw_passthrough_failed( $proto, $sb_req, $trace, $err, $category ) );
831 }
832 4 $log->errorf("Passthrough stream error [%s]: %s", $model, $err);
833 4 ▶ $self->tracing->end_trace($trace, error => "$err") if $trace;
Branch: 1 branch
BranchTrueFalseTotal
if $trace 0 4 4
834 4 ▶ return if $req->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $req->is_closed 0 4 4
835 4 my $frame = $proto->format_stream_error(
836 $self->_raw_passthrough_status($category), _error_text($err) );
837 4 ▶ if ( length $frame ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $frame) 4 0 4
838 # A frame cut off by the stall is ended first, so the error frame
839 # stands on its own: a blank line for SSE, a newline for NDJSON.
840 4 ▶ my $pad = $proto->stream_content_type =~ /ndjson/
Branch: 4 branches
BranchTrueFalseTotal
$proto->stream_content_type =~ /ndjson/ ? : 1 3 4
$tail eq '' || $tail =~ /\n\z/ ? : 1 0 1
$tail eq '' || $tail eq "\n\n" ? : 2 1 3
$tail =~ /\n\z/ ? : 0 1 1
Condition50%3/6
$tail eq "" or $tail =~ /\n\z/
l!l&&r!l&&!r
010
$tail eq "" or $tail eq "\n\n"
l!l&&r!l&&!r
021
MC/DC0%0/2
$tail eq "" or $tail =~ /\n\z/
$tail eq "" $tail =~ /\n\z/
MC/DC50%1/2
$tail eq "" or $tail eq "\n\n"
$tail eq "" $tail eq "\n\n"
Truth table33%1/3
A or B
A= $tail eq ""B= $tail =~ /\n\z/
ABresult
1X1
011
000
Truth table66%2/3
A or B
A= $tail eq ""B= $tail eq "\n\n"
ABresult
1X1
011
000
841 ? ( $tail eq '' || $tail =~ /\n\z/ ? '' : "\n" )
842 : ( $tail eq '' || $tail eq "\n\n" ? '' : $tail =~ /\n\z/ ? "\n" : "\n\n" );
843 4 $req->write_chunk( $pad . $frame );
844 }
845 4 $req->write_chunk_eof;
846 47 });
847 47 $f->retain;
848 } else {
849 59 my $f = $pt->_upstream_request_f(request => $http_req);
850 55 ▶ $f->on_done(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
851 55 my ($resp) = @_;
852 55 ▶ return $self->_raw_passthrough_fall_back( $proto, $req, $sb_req )
Branch: 1 branch
BranchTrueFalseTotal
if $self->_raw_passthrough_falls_back($sb_req, $resp) 2 53 55
853 if $self->_raw_passthrough_falls_back( $sb_req, $resp );
854 53 ▶ $trace = $self->_raw_passthrough_trace( $sb_req, $trace_from ) if $trace_from;
Branch: 1 branch
BranchTrueFalseTotal
if $trace_from 8 45 53
855 53 $self->_send_simple( $req,
856 $self->_raw_passthrough_answer( $sb_req, $trace, $resp ) );
857 59 });
858 4 ▶ $f->on_fail(sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
859 4 ▶ $trace = $self->_raw_passthrough_trace( $sb_req, $trace_from ) if $trace_from;
Branch: 1 branch
BranchTrueFalseTotal
if $trace_from 0 4 4
860 4 $self->_send_simple( $req,
861 $self->_raw_passthrough_failed( $proto, $sb_req, $trace, @_[0, 1] ) );
862 59 });
863 59 $f->retain;
864 }
865 }
866  
867 # Raw passthrough is decided and prepared here for both transports, the
868 # native server and Langertha::Knarr::PSGI (k26), so they cannot drift:
869 # which requests bypass the handler chain, which client headers reach the
870 # upstream, what the upstream request and its trace look like, and how an
871 # answer or a failure is returned. Only the byte pumping differs -- the
872 # native server streams chunks as they arrive, PSGI buffers.
873 713 ▶sub _is_raw_passthrough {
Subroutine _is_raw_passthrough: called CC=9 SCAR=22.0
874 713 my ($self, $sb_req) = @_;
875 713 my $pt = $self->raw_passthrough;
876 713 my $router = $self->router;
877 # Only for a protocol the passthrough has an upstream for: a request in
878 # any other protocol goes through the handler chain, to the default
879 # engine or to a 404 in the protocol's error shape (k41).
880 713 ▶ return 0 unless $pt && $router && $pt->serves_protocol( $sb_req->protocol );
Branch: 1 branch
BranchTrueFalseTotal
unless $pt and $router and $pt->serves_protocol($sb_req->protocol) 475 238 713
Condition83%5/6
$pt and $router and $pt->serves_protocol($sb_req->protocol)
!ll&&!rl&&r
44728238
$pt and $router
!ll&&!rl&&r
4470266
MC/DC66%2/3
$pt and $router and $pt->serves_protocol($sb_req->protocol)
$pt $router $pt->serves_protocol($sb_req->protocol)
Truth table75%3/4
A and B and C
A= $ptB= $routerC= $pt->serves_protocol($sb_req->protocol)
ABCresult
0XX0
10X0
1100
1111
881 238 ▶ return 1 if $router->is_passthrough_model( $sb_req->model );
Branch: 1 branch
BranchTrueFalseTotal
if $router->is_passthrough_model($sb_req->model) 144 94 238
882 # A model only auto-discovery knows, listed by this very upstream, goes
883 # there byte for byte too; discovery then only feeds the model lists
884 # (k47). One listed by another provider stays with its engine.
885 94 ▶ my $url = $router->can('discovered_url') ? $router->discovered_url( $sb_req->model ) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$router->can('discovered_url') ? : 92 2 94
886 94 ▶ return 0 unless defined $url && $pt->can('is_upstream_for')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and $pt->can("is_upstream_for") and $pt->is_upstream_for($sb_req->protocol, $url) 12 82 94
Condition83%5/6
defined $url and $pt->can("is_upstream_for") and $pt->is_upstream_for($sb_req->protocol, $url)
!ll&&!rl&&r
8482
defined $url and $pt->can("is_upstream_for")
!ll&&!rl&&r
8086
MC/DC66%2/3
defined $url and $pt->can("is_upstream_for") and $pt->is_upstream_for($sb_req->protocol, $url)
defined $url $pt->can("is_upstream_for") $pt->is_upstream_for($sb_req->protocol, $url)
Truth table75%3/4
A and B and C
A= defined $urlB= $pt->can("is_upstream_for")C= $pt->is_upstream_for($sb_req->protocol, $url)
ABCresult
0XX0
10X0
1100
1111
887 && $pt->is_upstream_for( $sb_req->protocol, $url );
888 # ...but only with the client's own provider key: without one the upstream
889 # would answer 401, while the engine that listed the model holds Knarr's
890 # key (k52).
891 82 return $self->_carries_provider_key($sb_req);
892 }
893  
894 # The headers a protocol's upstream takes its key from. A protocol not listed
895 # (Ollama) needs none.
896 50 my %PROVIDER_KEY_HEADERS = (
897 openai => [ 'authorization' ],
898 anthropic => [ 'x-api-key', 'authorization' ],
899 );
900  
901 # True when the request carries a provider key for its protocol's upstream,
902 # after Knarr's proxy key was taken out: the parser's forward_headers, as
903 # _parse_chat_request left them (k52).
904 82 ▶sub _carries_provider_key {
Subroutine _carries_provider_key: called CC=4 SCAR=14.1
905 82 my ($self, $sb_req) = @_;
906 82 ▶ my $names = $PROVIDER_KEY_HEADERS{ $sb_req->protocol // '' } or return 1;
Branch: 1 branch
BranchTrueFalseTotal
my $names = $PROVIDER_KEY_HEADERS{$sb_req->protocol // ""} or return 1 82 0 82
Condition50%1/2
$sb_req->protocol // ""
l!l
820
MC/DC0%0/1
$sb_req->protocol // ""
$sb_req->protocol
Truth table50%1/2
A
A= $sb_req->protocol
Aresult
11
00
907 82 ▶ return ( grep { length } map { $sb_req->forward_header($_) } @$names ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
grep({length $_;} map({$sb_req->forward_header($_);} @$names)) ? : 58 24 82
908 }
909  
910 # $headers: the client's request headers as [ name, value ] pairs; $path:
911 # the path the client asked for (Ollama /api/chat or /api/generate, k46).
912 202 ▶sub _raw_passthrough_request {
Subroutine _raw_passthrough_request: called CC=7 SCAR=19.5
913 202 my ($self, $sb_req, $headers, $body, $path) = @_;
914 202 ▶ my $model = $sb_req->model // 'unknown';
Condition50%1/2
$sb_req->model // "unknown"
l!l
2020
MC/DC0%0/1
$sb_req->model // "unknown"
$sb_req->model
Truth table50%1/2
A
A= $sb_req->model
Aresult
11
00
915 202 my $protocol = $sb_req->protocol;
916  
917 # Build upstream URL from passthrough config
918 202 my $url = $self->raw_passthrough->_upstream_url( $protocol, $path );
919 202 my $http_req = HTTP::Request->new(POST => $url);
920  
921 # Forward all client headers except hop-by-hop / connection-specific
922 # ones, with Knarr's own key taken out of each line (k44, k53). Every line
923 # is added, not set: a header sent twice reaches the upstream twice, in
924 # its order (k56).
925 202 my %skip = map { lc($_) => 1 } qw( host content-length connection transfer-encoding );
926 202 for my $pair (@$headers) {
927 1051 my ($name, $value) = @$pair;
928 1051 ▶ next if $skip{lc($name)};
Branch: 1 branch
BranchTrueFalseTotal
if $skip{lc $name} 414 637 1051
929 637 ($value) = $self->_without_proxy_key( $name, $value );
930 637 ▶ next unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 40 597 637
931 597 $http_req->push_header($name => $value);
932 }
933 202 $http_req->content($body);
934  
935 202 $log->infof("Passthrough %s [%s] -> %s", $model, $protocol, $url);
936  
937 # Lightweight tracing for passthrough requests. The trace of a request
938 # that may still fall back to its engine waits for the upstream's status,
939 # so a fallback is traced once, by the handler chain (k66); $trace_from
940 # is then the time the request goes out, for _raw_passthrough_trace.
941 202 my ( $trace, $trace_from );
942 202 ▶ if ( $self->_raw_passthrough_may_fall_back($sb_req) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_raw_passthrough_may_fall_back($sb_req)) { } 58 144 202
943 58 ▶ $trace_from = [ Time::HiRes::gettimeofday() ] if $self->tracing;
Branch: 1 branch
BranchTrueFalseTotal
if $self->tracing 40 18 58
944 }
945 else {
946 144 $trace = $self->_raw_passthrough_trace($sb_req);
947 }
948  
949 202 return ( $http_req, $trace, $trace_from );
950 }
951  
952 # The raw passthrough's trace, started now or, with $trace_from, dated back
953 # to it. Undef without tracing.
954 176 ▶sub _raw_passthrough_trace {
Subroutine _raw_passthrough_trace: called CC=4 SCAR=13.9
955 176 my ($self, $sb_req, $trace_from) = @_;
956 176 ▶ my $tracing = $self->tracing or return;
Branch: 1 branch
BranchTrueFalseTotal
my $tracing = $self->tracing or return 77 99 176
957 77 ▶ return $tracing->start_trace(
Branch: 1 branch
BranchTrueFalseTotal
$trace_from ? : 32 45 77
Condition50%1/2
$sb_req->model // "unknown"
l!l
770
MC/DC0%0/1
$sb_req->model // "unknown"
$sb_req->model
Truth table50%1/2
A
A= $sb_req->model
Aresult
11
00
958 model => $sb_req->model // 'unknown',
959 engine => 'passthrough',
960 format => $sb_req->protocol,
961 messages => $sb_req->messages,
962 $trace_from ? ( start_hires => $trace_from ) : (),
963 );
964 }
965  
966 # True for a raw passthrough that falls back to its engine should the
967 # upstream refuse the client's key (k66): one of a model only auto-discovery
968 # knows, which the router resolves -- every other raw passthrough is of a
969 # model it does not know, and has no engine to fall back to.
970 218 ▶sub _raw_passthrough_may_fall_back {
Subroutine _raw_passthrough_may_fall_back: called CC=3 SCAR=11.1
971 218 my ($self, $sb_req) = @_;
972 218 ▶ my $router = $self->router or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $router = $self->router or return 0 218 0 218
973 218 ▶ return $router->is_passthrough_model( $sb_req->model ) ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$router->is_passthrough_model($sb_req->model) ? : 152 66 218
974 }
975  
976 # True when the upstream's answer sends a raw passthrough to its engine
977 # instead (k66): a 401 -- the client's key refused, a placeholder an SDK
978 # sent -- for a request that may fall back. Notes the fallback on the
979 # request, for the handler chain's trace. Any other status, 403 and 429
980 # included, goes back to the client as before.
981 185 ▶sub _raw_passthrough_falls_back {
Subroutine _raw_passthrough_falls_back: called CC=4 SCAR=13.9
982 185 my ($self, $sb_req, $resp) = @_;
983 185 ▶ return 0 unless $resp->code == 401 && $self->_raw_passthrough_may_fall_back($sb_req);
Branch: 1 branch
BranchTrueFalseTotal
unless $resp->code == 401 and $self->_raw_passthrough_may_fall_back($sb_req) 177 8 185
Condition100%3/3
$resp->code == 401 and $self->_raw_passthrough_may_fall_back($sb_req)
!ll&&!rl&&r
16988
MC/DC100%2/2
$resp->code == 401 and $self->_raw_passthrough_may_fall_back($sb_req)
$resp->code == 401 $self->_raw_passthrough_may_fall_back($sb_req)
Truth table100%3/3
A and B
A= $resp->code == 401B= $self->_raw_passthrough_may_fall_back($sb_req)
ABresult
0X0
100
111
984 8 ▶ $log->infof("Passthrough %s refused the client's key (401), answering through its engine",
Condition50%1/2
$sb_req->model // "unknown"
l!l
80
MC/DC0%0/1
$sb_req->model // "unknown"
$sb_req->model
Truth table50%1/2
A
A= $sb_req->model
Aresult
11
00
985 $sb_req->model // 'unknown');
986 8 $sb_req->extra->{passthrough_fallback} = 401;
987 8 return 1;
988 }
989  
990 # The native server's fallback: the parsed request through the handler
991 # chain, where Handler::Router sends it to the engine that listed the
992 # model, with that engine's key. Nothing has gone to the client yet. It
993 # runs in the upstream's callback, outside _dispatch's catch, so it answers
994 # an error itself.
995 4 ▶sub _raw_passthrough_fall_back {
Subroutine _raw_passthrough_fall_back: called CC=1 SCAR=1.6
996 4 my ($self, $proto, $req, $sb_req) = @_;
997 4 ▶ try {
Subroutine __ANON__: called CC=1 SCAR=0.0
998 4 $self->_handle_chat( $proto, $req, $sb_req );
999 0 ▶ } catch {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1000 0 my $err = $_;
1001 0 ▶ $log->errorf("Passthrough fallback error [%s]: %s", $sb_req->model // 'unknown', $err);
Condition0%0/2
$sb_req->model // "unknown"
l!l
00
MC/DC0%0/1
$sb_req->model // "unknown"
$sb_req->model
Truth table0%0/2
A
A= $sb_req->model
Aresult
11
00
1002 0 $self->_send_simple( $req, 500, 'application/json',
1003 $self->_json->encode({ error => { message => "$err" } }) );
1004 4 };
1005 4 return;
1006 }
1007  
1008 # The upstream's answer as ( status, content type, body bytes, its other
1009 # headers ). A buffered stream (PSGI) is traced as a stream, like the
1010 # native one. The body goes back as Net::Async::HTTP handed it over, like a
1011 # stream: decoded when it knew the encoding, otherwise the upstream's bytes
1012 # with their Content-Encoding -- never decoded again here, where an
1013 # encoding HTTP::Message cannot decode (br without IO::Uncompress::Brotli,
1014 # anything unknown) came back as an empty body (k59).
1015 135 ▶sub _raw_passthrough_answer {
Subroutine _raw_passthrough_answer: called CC=7 SCAR=20.2
1016 135 my ($self, $sb_req, $trace, $resp) = @_;
1017 135 ▶ if ($trace) {
Branch: 1 branch
BranchTrueFalseTotal
if ($trace) 52 83 135
1018 52 my $usage = $self->_raw_passthrough_usage_reader( $trace, $resp );
1019 52 ▶ $usage->read_body( $resp->content ) if $usage;
Branch: 1 branch
BranchTrueFalseTotal
if $usage 52 0 52
1020 52 ▶ $self->tracing->end_trace( $trace,
Branch: 2 branches
BranchTrueFalseTotal
$sb_req->stream ? : 16 36 52
$usage ? : 52 0 52
1021 output => $sb_req->stream ? '[stream]' : '[passthrough]',
1022 $usage ? $usage->trace_args : () );
1023 }
1024 135 ▶ return ( $resp->code,
Condition50%2/4
scalar $resp->header("Content-Type") // "application/json"
l!l
1350
$resp->content // ""
l!l
1350
MC/DC0%0/1
scalar $resp->header("Content-Type") // "application/json"
scalar $resp->header("Content-Type")
MC/DC0%0/1
$resp->content // ""
$resp->content
Truth table50%1/2
A
A= scalar $resp->header("Content-Type")
Aresult
11
00
Truth table50%1/2
A
A= $resp->content
Aresult
11
00
1025 scalar $resp->header('Content-Type') // 'application/json',
1026 $resp->content // '',
1027 $self->_raw_passthrough_response_headers($resp) );
1028 }
1029  
1030 # Upstream response headers that stay behind: connection-level ones, the
1031 # framing Knarr sets for what it sends itself, Content-Type, which the
1032 # callers set, and the note Net::Async::HTTP leaves on a body it decoded.
1033 50 my %RESPONSE_HEADER_SKIP = map { $_ => 1 } qw(
1034 connection keep-alive proxy-connection te trailer upgrade
1035 transfer-encoding content-length content-type x-original-content-encoding );
1036  
1037 # The upstream's response headers that go back to the client, as [ name,
1038 # value ] pairs: every line, a repeated header (Set-Cookie) repeated in its
1039 # order (k56). Content-Encoding goes along only while the bytes still carry
1040 # it: Net::Async::HTTP decodes every encoding it knows (gzip, deflate)
1041 # before Knarr sees a byte, buffered or streamed, and passes any other as
1042 # it came (k59). The decision is its own: the whole header value, repeated
1043 # lines joined, is what it looks up -- in on_header it has not removed the
1044 # header yet, on a finished response it has.
1045 177 ▶sub _raw_passthrough_response_headers {
Subroutine _raw_passthrough_response_headers: called CC=2 SCAR=6.9
1046 177 my ($self, $resp) = @_;
1047 177 my $encoding = $resp->header('Content-Encoding');
1048 177 ▶ my $decoded = defined $encoding && Net::Async::HTTP->can_decode($encoding);
Condition100%3/3
defined $encoding && 'Net::Async::HTTP'->can_decode($encoding)
!ll&&!rl&&r
157182
MC/DC100%2/2
defined $encoding && 'Net::Async::HTTP'->can_decode($encoding)
defined $encoding 'Net::Async::HTTP'->can_decode($encoding)
Truth table100%3/3
A && B
A= defined $encodingB= 'Net::Async::HTTP'->can_decode($encoding)
ABresult
0X0
100
111
1049 177 my @pairs;
1050 439 ▶ $resp->headers->scan( sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1051 439 my ($name, $value) = @_;
1052 439 my $lc = lc $name;
1053 439 ▶ return if $RESPONSE_HEADER_SKIP{$lc};
Branch: 1 branch
BranchTrueFalseTotal
if $RESPONSE_HEADER_SKIP{$lc} 360 79 439
1054 79 ▶ return if $lc eq 'content-encoding' && $decoded;
Branch: 1 branch
BranchTrueFalseTotal
if $lc eq "content-encoding" and $decoded 2 77 79
Condition100%3/3
$lc eq "content-encoding" and $decoded
!ll&&!rl&&r
55222
MC/DC100%2/2
$lc eq "content-encoding" and $decoded
$lc eq "content-encoding" $decoded
Truth table100%3/3
A and B
A= $lc eq "content-encoding"B= $decoded
ABresult
0X0
100
111
1055 77 push @pairs, [ $name, $value ];
1056 177 });
1057 177 return \@pairs;
1058 }
1059  
1060 # What reads the token usage and model off a copy of the upstream's answer
1061 # for its trace (k61): nothing without a trace, and nothing for bytes that
1062 # still carry a Content-Encoding -- Net::Async::HTTP decodes the ones it
1063 # knows, the same decision as in _raw_passthrough_response_headers.
1064 94 ▶sub _raw_passthrough_usage_reader {
Subroutine _raw_passthrough_usage_reader: called CC=4 SCAR=13.9
1065 94 my ($self, $trace, $resp) = @_;
1066 94 ▶ return unless $trace;
Branch: 1 branch
BranchTrueFalseTotal
unless $trace 23 71 94
1067 71 my $encoding = $resp->header('Content-Encoding');
1068 71 ▶ return if defined $encoding && !Net::Async::HTTP->can_decode($encoding);
Branch: 1 branch
BranchTrueFalseTotal
if defined $encoding and not "Net::Async::HTTP"->can_decode($encoding) 1 70 71
Condition66%2/3
defined $encoding and not "Net::Async::HTTP"->can_decode($encoding)
!ll&&!rl&&r
7001
MC/DC50%1/2
defined $encoding and not "Net::Async::HTTP"->can_decode($encoding)
defined $encoding not "Net::Async::HTTP"->can_decode($encoding)
Truth table66%2/3
A and not(B)
A= defined $encodingB= not "Net::Async::HTTP"->can_decode($encoding)
ABresult
0X0
100
111
1069 70 return Langertha::Knarr::PassthroughUsage->new;
1070 }
1071  
1072 # An upstream that did not answer in time is a 504, any other failure to
1073 # reach it a 502, in the client protocol's error shape (k35).
1074 17 ▶sub _raw_passthrough_failed {
Subroutine _raw_passthrough_failed: called CC=4 SCAR=14.1
1075 17 my ($self, $proto, $sb_req, $trace, $err, $category) = @_;
1076 17 ▶ $log->errorf("Passthrough error [%s]: %s", $sb_req->model // 'unknown', $err);
Condition50%1/2
$sb_req->model // "unknown"
l!l
170
MC/DC0%0/1
$sb_req->model // "unknown"
$sb_req->model
Truth table50%1/2
A
A= $sb_req->model
Aresult
11
00
1077 17 ▶ $self->tracing->end_trace($trace, error => "$err") if $trace;
Branch: 1 branch
BranchTrueFalseTotal
if $trace 2 15 17
1078 17 my ($status, $headers, $body) = $proto->format_error_response(
1079 $self->_raw_passthrough_status($category), 'passthrough failed: ' . _error_text($err) );
1080 17 ▶ return ( $status, $headers->{'Content-Type'} // 'application/json', $body );
Condition50%1/2
$headers->{"Content-Type"} // "application/json"
l!l
170
MC/DC0%0/1
$headers->{"Content-Type"} // "application/json"
$headers->{"Content-Type"}
Truth table50%1/2
A
A= $headers->{"Content-Type"}
Aresult
11
00
1081 }
1082  
1083 21 ▶sub _raw_passthrough_status {
Subroutine _raw_passthrough_status: called CC=2 SCAR=6.9
1084 21 my ($self, $category) = @_;
1085 21 ▶ return Langertha::Knarr::Role::UpstreamHTTP->is_upstream_timeout($category) ? 504 : 502;
Branch: 1 branch
BranchTrueFalseTotal
'Langertha::Knarr::Role::UpstreamHTTP'->is_upstream_timeout($category) ? : 19 2 21
1086 }
1087  
1088 73 ▶sub _error_text {
Subroutine _error_text: called CC=1 SCAR=0.0
1089 73 my ($err) = @_;
1090 73 ( my $text = "$err" ) =~ s/\s+\z//;
1091 73 return $text;
1092 }
1093  
1094 10 ▶sub _action_acp_agents { goto &_action_models }
Subroutine _action_acp_agents: called CC=1 SCAR=0.0
1095 19 ▶sub _action_a2a_card {
Subroutine _action_a2a_card: called CC=2 SCAR=7.1
1096 19 my ($self, $proto, $req) = @_;
1097 19 my ($status, $headers, $body) = $proto->format_agent_card;
1098 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
1099 }
1100  
1101 # Actions answered with one buffered response from the request body alone.
1102 # The native server and the PSGI adapter both dispatch through this table,
1103 # so the two cannot drift: action => method( $proto, $body_bytes ) returning
1104 # ( status, \%headers, body ).
1105 50 my %SIMPLE_ACTIONS = (
1106 version => '_simple_version',
1107 show => '_simple_show',
1108 );
1109  
1110 890 ▶sub _simple_action {
Subroutine _simple_action: called CC=1 SCAR=0.0
1111 890 my ($self, $action) = @_;
1112 890 return $SIMPLE_ACTIONS{$action};
1113 }
1114  
1115 26 ▶sub _simple_version {
Subroutine _simple_version: called CC=1 SCAR=0.0
1116 26 my ($self, $proto) = @_;
1117 26 return $proto->format_version_response( $self->ollama_compat_version );
1118 }
1119  
1120 # POST /api/show (k29). VS Code Copilot calls it for every model and reads
1121 # tools/vision from capabilities; Continue reads it too. Only a model Knarr
1122 # lists (the /api/tags surface) is shown, anything else gets Ollama's 404.
1123 # capabilities never carry "thinking": Knarr drops think on the Ollama wire.
1124 61 ▶sub _simple_show {
Subroutine _simple_show: called CC=26 SCAR=33.0
1125 61 my ($self, $proto, $body) = @_;
1126 61 ▶ my $data = eval { $self->_json->decode( defined $body && length $body ? $body : '{}' ) };
Branch: 1 branch
BranchTrueFalseTotal
defined $body && length $body ? : 59 2 61
Condition66%2/3
defined $body and length $body
!ll&&!rl&&r
0259
MC/DC50%1/2
defined $body and length $body
defined $body length $body
Truth table66%2/3
A and B
A= defined $bodyB= length $body
ABresult
0X0
100
111
1127 61 ▶ $data = {} unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 61 61
1128 61 my $model = $data->{model};
1129 61 ▶ $model = $data->{name} unless defined $model && length $model; # Ollama's legacy field
Branch: 1 branch
BranchTrueFalseTotal
unless defined $model and length $model 6 55 61
Condition66%2/3
defined $model and length $model
!ll&&!rl&&r
6055
MC/DC50%1/2
defined $model and length $model
defined $model length $model
Truth table66%2/3
A and B
A= defined $modelB= length $model
ABresult
0X0
100
111
1130 61 ▶ return $proto->format_error_response( 400, 'model is required' )
Branch: 1 branch
BranchTrueFalseTotal
unless defined $model and not ref $model and length $model 4 57 61
Condition66%4/6
defined $model and not ref $model and length $model
!ll&&!rl&&r
4057
defined $model and not ref $model
!ll&&!rl&&r
4057
MC/DC33%1/3
defined $model and not ref $model and length $model
defined $model not ref $model length $model
Truth table50%2/4
A and not(B) and C
A= defined $modelB= not ref $modelC= length $model
ABCresult
0XX0
10X0
1100
1111
1131 unless defined $model && !ref $model && length $model;
1132  
1133 57 my $router = $self->router;
1134 57 ▶ my $listed = $router ? $router->list_models : $self->handler->list_models;
Branch: 1 branch
BranchTrueFalseTotal
$router ? : 35 22 57
1135 307 my ($known) = grep { $_ eq $model }
1136 57 ▶ map { ref $_ eq 'HASH' ? $_->{id} // '' : "$_" } @{ $listed || [] };
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 307 0 307
Condition50%2/4
$_->{"id"} // ""
l!l
3070
$listed || []
l!l
570
MC/DC0%0/1
$_->{"id"} // ""
$_->{"id"}
MC/DC0%0/1
$listed || []
$listed
Truth table50%1/2
A
A= $_->{"id"}
Aresult
11
00
Truth table50%1/2
A
A= $listed
Aresult
11
00
1137 57 ▶ return $proto->format_error_response( 404, "model '$model' not found" )
Branch: 1 branch
BranchTrueFalseTotal
unless defined $known 4 53 57
1138 unless defined $known;
1139  
1140 # The engine the router sends this model to, when it can build one; a
1141 # model it cannot build (key variable unset) or a custom handler without
1142 # a router leaves the capabilities at what the Ollama endpoint forwards.
1143 my $engine = $router
1144 53 ▶ ? eval { ( $router->resolve( $model, skip_default => 1 ) )[0] } : undef;
Branch: 1 branch
BranchTrueFalseTotal
$router ? : 31 22 53
1145 53 ▶ my $caps = blessed($engine) && $engine->can('supports') ? $engine : undef;
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($engine) && $engine->can('supports') ? : 29 24 53
Condition66%2/3
builtin::blessed($engine) and $engine->can("supports")
!ll&&!rl&&r
24029
MC/DC50%1/2
builtin::blessed($engine) and $engine->can("supports")
builtin::blessed($engine) $engine->can("supports")
Truth table66%2/3
A and B
A= builtin::blessed($engine)B= $engine->can("supports")
ABresult
0X0
100
111
1146  
1147 53 my @capabilities = ('completion');
1148 53 ▶ push @capabilities, 'tools'
Branch: 1 branch
BranchTrueFalseTotal
if not $caps or $caps->supports("tools_native") or $caps->supports("tools_hermes") 49 4 53
Condition100%6/6
not $caps or $caps->supports("tools_native") or $caps->supports("tools_hermes")
l!l&&r!l&&!r
4724
not $caps or $caps->supports("tools_native")
l!l&&r!l&&!r
24236
MC/DC100%3/3
not $caps or $caps->supports("tools_native") or $caps->supports("tools_hermes")
not $caps $caps->supports("tools_native") $caps->supports("tools_hermes")
Truth table100%4/4
not(A) or B or C
A= not $capsB= $caps->supports("tools_native")C= $caps->supports("tools_hermes")
ABCresult
1XX1
01X1
0011
0000
1149 if !$caps || $caps->supports('tools_native') || $caps->supports('tools_hermes');
1150 # "vision" from core's model-scoped image_input (core k266, ADR 0019),
1151 # evaluated for the upstream model: the router builds one engine per model,
1152 # so its chat_model is the model this name is sent to. A core without the
1153 # flag (0.503) cannot tell, so no claim; nor without a routed engine.
1154 push @capabilities, 'vision'
1155 53 ▶ if $caps && _image_input_known() && eval { $caps->supports('image_input') };
Branch: 1 branch
BranchTrueFalseTotal
if $caps and _image_input_known() and eval { do { $caps->supports("image_input") } } 10 43 53
Condition83%5/6
$caps and _image_input_known() and eval {
!ll&&!rl&&r
241910
$caps and _image_input_known()
!ll&&!rl&&r
24029
MC/DC66%2/3
$caps and _image_input_known() and eval { do { $caps->supports("image_input") } }
$caps _image_input_known() eval { do { $caps->supports("image_input") } }
Truth table75%3/4
A and B and C
A= $capsB= _image_input_known()C= eval { do { $caps->supports("image_input") } }
ABCresult
0XX0
10X0
1100
1111
1156 my $context_length = blessed($engine) && $engine->can('get_context_size')
1157 53 ▶ ? eval { $engine->get_context_size } : undef;
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($engine) && $engine->can('get_context_size') ? : 16 37 53
Condition100%3/3
builtin::blessed($engine) and $engine->can("get_context_size")
!ll&&!rl&&r
241316
MC/DC100%2/2
builtin::blessed($engine) and $engine->can("get_context_size")
builtin::blessed($engine) $engine->can("get_context_size")
Truth table100%3/3
A and B
A= builtin::blessed($engine)B= $engine->can("get_context_size")
ABresult
0X0
100
111
1158  
1159 53 ▶ return $proto->format_show_response( $model, {
Branch: 1 branch
BranchTrueFalseTotal
defined $context_length ? : 4 49 53
1160 capabilities => \@capabilities,
1161 ( defined $context_length ? ( context_length => $context_length ) : () ),
1162 } );
1163 }
1164  
1165 # True when the installed Langertha core knows the image_input capability
1166 # (Langertha::Role::ImageInput contributes it). Checked once per process.
1167 50 my $IMAGE_INPUT_KNOWN;
1168 29 ▶sub _image_input_known {
Subroutine _image_input_known: called CC=3 SCAR=11.3
1169 29 ▶ $IMAGE_INPUT_KNOWN //= eval { require Langertha::Role::ImageInput; 1 } ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Langertha::Role::ImageInput; 1 } } ? : 2 0 2
Condition66%2/3
$IMAGE_INPUT_KNOWN //= eval {
l!l&&r!l&&!r
2720
MC/DC0%0/2
$IMAGE_INPUT_KNOWN //= eval { do { require Langertha::Role::ImageInput; 1 } } ? 1 : 0
$IMAGE_INPUT_KNOWN eval { do { require Langertha::Role::ImageInput; 1 } } ? 1 : 0
Truth table66%2/3
A //= B
A= $IMAGE_INPUT_KNOWNB= eval { do { require Langertha::Role::ImageInput; 1 } } ? 1 : 0
ABresult
1X1
011
000
1170 29 return $IMAGE_INPUT_KNOWN;
1171 }
1172  
1173 22 ▶sub _action_manifest {
Subroutine _action_manifest: called CC=3 SCAR=11.0
1174 22 my ($self, $proto, $req) = @_;
1175 22 ▶ my $proto_header = lc( scalar( $req->header('X-Forwarded-Proto') ) // '' );
Condition100%2/2
scalar $req->header("X-Forwarded-Proto") // ""
l!l
220
MC/DC100%1/1
scalar $req->header("X-Forwarded-Proto") // ""
scalar $req->header("X-Forwarded-Proto")
Truth table100%2/2
A
A= scalar $req->header("X-Forwarded-Proto")
Aresult
11
00
1176 22 ▶ my ($status, $body) = $self->manifest_response(
Branch: 1 branch
BranchTrueFalseTotal
$proto_header =~ /\A(https?)\z/ ? : 1 21 22
1177 scheme => ( $proto_header =~ /\A(https?)\z/ ? $1 : 'http' ),
1178 host => scalar $req->header('Host'),
1179 );
1180 22 $self->_send_simple( $req, $status, 'application/json', $body );
1181 }
1182  
1183 39 ▶sub manifest_response {
Subroutine manifest_response: called CC=10 SCAR=24.4
Pod documented
1184 39 my ($self, %request) = @_;
1185 3 ▶ my $error = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1186 3 my ($status, $message) = @_;
1187 3 return ( $status, $self->_json->encode({ error => { message => $message } }) );
1188 39 };
1189 39 ▶ return $error->( 404, 'provider manifest not available: the installed Langertha'
Branch: 1 branch
BranchTrueFalseTotal
unless "Langertha::Knarr::Manifest"->available 2 37 39
1190 . ' has no Langertha::Manifest::Builder' )
1191 unless Langertha::Knarr::Manifest->available;
1192  
1193 37 my $base_url = $self->public_url;
1194 37 ▶ unless ( defined $base_url && length $base_url ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $base_url and length $base_url) 36 1 37
Condition66%2/3
defined $base_url and length $base_url
!ll&&!rl&&r
3601
MC/DC50%1/2
defined $base_url and length $base_url
defined $base_url length $base_url
Truth table66%2/3
A and B
A= defined $base_urlB= length $base_url
ABresult
0X0
100
111
1195 36 ▶ my $host = $request{host} // '';
Condition50%1/2
$request{"host"} // ""
l!l
360
MC/DC0%0/1
$request{"host"} // ""
$request{"host"}
Truth table50%1/2
A
A= $request{"host"}
Aresult
11
00
1196 # A hostname or bracketed IPv6 address, optional port; nothing else can
1197 # reach the published URLs.
1198 36 ▶ return $error->( 400, 'cannot derive the public URL: no valid Host header'
Branch: 1 branch
BranchTrueFalseTotal
unless $host =~ /\A(?:[A-Za-z0-9](?:[A-Za-z0-9.\-]*[A-Za-z0-9])?|\[[0-9A-Fa-f:.]+\])(?::[0-9]{1,5})?\z/ 1 35 36
1199 . ' (set public_url)' )
1200 unless $host =~ /\A(?:[A-Za-z0-9](?:[A-Za-z0-9.\-]*[A-Za-z0-9])?|\[[0-9A-Fa-f:.]+\])(?::[0-9]{1,5})?\z/;
1201 35 ▶ $base_url = ( $request{scheme} // 'http' ) . '://' . $host . ( $request{prefix} // '' );
Condition100%4/4
$request{"scheme"} // "http"
l!l
305
$request{"prefix"} // ""
l!l
1124
MC/DC100%1/1
$request{"scheme"} // "http"
$request{"scheme"}
MC/DC100%1/1
$request{"prefix"} // ""
$request{"prefix"}
Truth table100%2/2
A
A= $request{"scheme"}
Aresult
11
00
Truth table100%2/2
A
A= $request{"prefix"}
Aresult
11
00
1202 }
1203  
1204 36 my $manifest = eval { $self->_manifest->build($base_url) };
1205 36 ▶ unless ( $manifest ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($manifest) 0 36 36
1206 0 ▶ my $err = $@ || 'unknown error';
Condition0%0/2
$@ || 'unknown error'
l!l
00
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
1207 0 $err =~ s/ at \S+ line \d+\.?\n?\z//;
1208 0 $log->errorf("Manifest error: %s", $err);
1209 0 return $error->( 500, "provider manifest failed: $err" );
1210 }
1211 36 return ( 200, $manifest->to_json );
1212 }
1213  
1214 31 ▶sub _action_models {
Subroutine _action_models: called CC=2 SCAR=7.0
1215 31 my ($self, $proto, $req) = @_;
1216 31 my $models = $self->handler->list_models;
1217 31 my ($status, $headers, $body) = $proto->format_models_response( $models );
1218 31 ▶ $self->_send_simple( $req, $status, $headers->{'Content-Type'} // 'application/json', $body );
Condition50%1/2
$headers->{"Content-Type"} // "application/json"
l!l
310
MC/DC0%0/1
$headers->{"Content-Type"} // "application/json"
$headers->{"Content-Type"}
Truth table50%1/2
A
A= $headers->{"Content-Type"}
Aresult
11
00
1219 }
1220  
1221 # $headers: optional further [ name, value ] pairs, each line added (the
1222 # raw passthrough's upstream headers, k56).
1223 408 ▶sub _send_simple {
Subroutine _send_simple: called CC=3 SCAR=11.0
1224 408 my ($self, $req, $status, $ctype, $body, $headers) = @_;
1225 408 my $resp = HTTP::Response->new( $status );
1226 408 $resp->protocol('HTTP/1.1');
1227 408 ▶ $resp->push_header(@$_) for @{ $headers // [] };
Condition100%2/2
$headers // []
l!l
53355
MC/DC100%1/1
$headers // []
$headers
Truth table100%2/2
A
A= $headers
Aresult
11
00
1228 408 $resp->header( 'Content-Type' => $ctype );
1229 408 $resp->header( 'Content-Length' => length($body) );
1230 408 $resp->content($body);
1231 408 $req->respond($resp);
1232 }
1233  
1234 50 __PACKAGE__->meta->make_immutable;
1235 50 1;
1236  
1237 __END__
1238  
1239 =pod
1240  
1241 =encoding UTF-8
1242  
1243 =head1 NAME
1244  
1245 Langertha::Knarr - Universal LLM hub — proxy, server, and translator across OpenAI/Anthropic/Ollama/A2A/ACP/AG-UI
1246  
1247 =head1 VERSION
1248  
1249 version 1.102
1250  
1251 =head1 SYNOPSIS
1252  
1253 The fastest way to use Knarr is the Docker image:
1254  
1255 docker run -e ANTHROPIC_API_KEY -p 8080:8080 raudssus/langertha-knarr
1256 ANTHROPIC_BASE_URL=http://localhost:8080 claude
1257  
1258 The Perl API behind it:
1259  
1260 use IO::Async::Loop;
1261 use Langertha::Knarr;
1262 use Langertha::Knarr::Config;
1263 use Langertha::Knarr::Router;
1264 use Langertha::Knarr::Handler::Router;
1265  
1266 my $loop = IO::Async::Loop->new;
1267 my $config = Langertha::Knarr::Config->new(file => 'knarr.yaml');
1268 my $router = Langertha::Knarr::Router->new(config => $config);
1269  
1270 my $knarr = Langertha::Knarr->new(
1271 handler => Langertha::Knarr::Handler::Router->new(router => $router),
1272 router => $router,
1273 loop => $loop,
1274 listen => $config->listen,
1275 );
1276 $knarr->run; # blocks; OpenWebUI etc. can now connect
1277  
1278 C<knarr start> (see L<knarr>) builds exactly this from a config file, plus
1279 the raw passthrough, the tracing and request-log decorators, the proxy key
1280 and the other settings of L<Langertha::Knarr::Config>.
1281  
1282 =head1 DESCRIPTION
1283  
1284 Langertha::Knarr is a universal LLM hub that exposes any backend — a
1285 L<Langertha::Raider>, a raw L<Langertha::Engine>, a remote A2A or ACP
1286 agent, or any custom L<Langertha::Knarr::Handler> — over the standard
1287 LLM HTTP wire protocols spoken by OpenWebUI, the OpenAI / Anthropic /
1288 Ollama SDKs, and the agent ecosystems around A2A, ACP, and AG-UI.
1289  
1290 By default a single running Knarr answers all of these simultaneously on
1291 every listening port, driven by the same handler implementation:
1292  
1293 =over
1294  
1295 =item * OpenAI: C<POST /v1/chat/completions>, C<GET /v1/models>
1296  
1297 =item * Anthropic: C<POST /v1/messages>
1298  
1299 =item * Ollama: C<POST /api/chat>, C<POST /api/generate>, C<GET /api/tags>,
1300 C<GET /api/version>, C<POST /api/show>
1301  
1302 =item * A2A: C<GET /.well-known/agent.json> and JSON-RPC C<POST />
1303  
1304 =item * ACP: C<GET /agents>, C<POST /runs>
1305  
1306 =item * AG-UI: C<POST /awp>
1307  
1308 =item * Knarr's own C<GET /.well-known/langertha.json> (see L</MANIFEST>)
1309  
1310 =back
1311  
1312 Knarr is built on L<IO::Async> and L<Net::Async::HTTP::Server>
1313 with native L<Future::AsyncAwait> integration into Langertha engines,
1314 so streaming works end-to-end token-by-token without any thread or
1315 event-loop bridges.
1316  
1317 =head1 MANIFEST
1318  
1319 C<GET /.well-known/langertha.json> serves a Langertha provider manifest
1320 (schema v1, see L<Langertha::Manifest>) so a client such as
1321 C<raider --provider HOST> can configure itself. It is built by
1322 L<Langertha::Knarr::Manifest> from what this Knarr exposes: one endpoint
1323 per protocol with a manifest dialect (OpenAI C</v1> as C<openai-chat>,
1324 Anthropic as C<anthropic-compat>, Ollama as C<ollama>), every listed model
1325 (configured aliases and auto-discovered ids) on each of them, with the
1326 serving engine's model-scoped capabilities narrowed to what that protocol
1327 forwards, and an C<api_key> auth entry when L</auth_token> is set. The
1328 route is protected by L</auth_token> like C<GET /v1/models>. It never
1329 carries configuration: no upstream URL, key, key variable name, engine
1330 class or passthrough target.
1331  
1332 The manifest needs a Langertha that ships L<Langertha::Manifest::Builder>;
1333 with an older one the route answers C<404> with a JSON error.
1334  
1335 =head1 ARCHITECTURE
1336  
1337 Three pluggable layers:
1338  
1339 =over
1340  
1341 =item B<Protocols>
1342  
1343 Wire formats live in C<Langertha::Knarr::Protocol::*>. Each consumes
1344 L<Langertha::Knarr::Protocol> and is loaded by default. See
1345 L<Langertha::Knarr::Protocol::OpenAI>,
1346 L<Langertha::Knarr::Protocol::Anthropic>,
1347 L<Langertha::Knarr::Protocol::Ollama>,
1348 L<Langertha::Knarr::Protocol::A2A>,
1349 L<Langertha::Knarr::Protocol::ACP>,
1350 L<Langertha::Knarr::Protocol::AGUI>.
1351  
1352 =item B<Handlers>
1353  
1354 Backend logic — what answers the request. Knarr ships with
1355 L<Langertha::Knarr::Handler::Router> (the default, model→engine via
1356 L<Langertha::Knarr::Router>), L<Langertha::Knarr::Handler::Engine>
1357 (single engine), L<Langertha::Knarr::Handler::Raider> (per-session
1358 agent), L<Langertha::Knarr::Handler::Passthrough> (raw HTTP forward),
1359 L<Langertha::Knarr::Handler::A2AClient> /
1360 L<Langertha::Knarr::Handler::ACPClient> (consume remote agents), and
1361 L<Langertha::Knarr::Handler::Code> (coderef-backed for tests). Implement
1362 L<Langertha::Knarr::Handler> to write your own. Decorators
1363 (L<Langertha::Knarr::Handler::Tracing>,
1364 L<Langertha::Knarr::Handler::RequestLog>) wrap any inner handler and
1365 add behavior on top — they themselves consume the Handler role and
1366 compose freely.
1367  
1368 =item B<Transport>
1369  
1370 Default is L<Net::Async::HTTP::Server> with chunked SSE / NDJSON
1371 streaming on one or more listen sockets. For Plack deployments,
1372 L<Langertha::Knarr::PSGI> wraps the same Knarr instance into a PSGI
1373 app (buffered — see its docs for the streaming caveat).
1374  
1375 =back
1376  
1377 =head2 handler
1378  
1379 Required. An object consuming L<Langertha::Knarr::Handler>.
1380  
1381 =head2 listen
1382  
1383 ArrayRef of C<host:port> strings or C<< { host => ..., port => ... } >>
1384 hashes. Defaults to a single entry composed from L</host> and L</port>.
1385  
1386 =head2 host
1387  
1388 Default C<127.0.0.1>. Used when L</listen> is not given.
1389  
1390 =head2 port
1391  
1392 Default C<8088>. Used when L</listen> is not given.
1393  
1394 =head2 loop
1395  
1396 Optional L<IO::Async::Loop> instance. Defaults to a fresh one.
1397  
1398 =head2 workers
1399  
1400 Number of processes that serve requests. Default C<1>: L</run> serves from
1401 the calling process, nothing is forked. With more, L</run> binds the listen
1402 sockets, runs auto-discovery and the capability probe once (see L</run>),
1403 then forks that many workers that all accept on the same sockets, and stays
1404 behind as their supervisor, serving no request itself. Must be C<1> or more;
1405 anything else croaks at construction. C<knarr start> sets it from C<-w N>,
1406 else from L<Langertha::Knarr::Config/workers> (C<workers:> or
1407 C<KNARR_WORKERS>).
1408  
1409 Every worker has its own state: L<Langertha::Knarr::Session>s (so a
1410 L<Langertha::Knarr::Handler::Raider> conversation is only continued when
1411 its next request reaches the same worker -- nothing routes it there), the
1412 engine cache, and its own Langfuse batches, flushed by that worker. Request
1413 log lines from all workers go to the same C<logging.file>, one whole line
1414 per write. L<Langertha::Knarr::PSGI> never calls L</run>; there the PSGI
1415 server decides about processes.
1416  
1417 =head2 protocols
1418  
1419 ArrayRef of protocol class basenames to load. Defaults to all six
1420 shipped protocols.
1421  
1422 =head2 protocol_args
1423  
1424 Optional HashRef of constructor arguments per protocol, keyed by the name
1425 as it appears in L</protocols>. The A2A agent card name and description:
1426  
1427 protocol_args => { A2A => {
1428 agent_name => 'Support Agent',
1429 agent_description => 'Answers support questions',
1430 } },
1431  
1432 C<knarr start> passes L<Langertha::Knarr::Config/protocol_args>.
1433  
1434 =head2 auth_token
1435  
1436 Optional shared secret. When set, every incoming request must present
1437 it as C<Authorization: Bearer> or C<x-api-key>. Discovery routes
1438 (C</.well-known/agent.json>) stay anonymous.
1439  
1440 A header sent twice counts as one value of comma-separated elements (that
1441 is how a PSGI server and C<< HTTP::Headers->header >> merge it), and the key
1442 may be any one of them.
1443  
1444 The key never leaves Knarr: it is taken out of a request to a passthrough
1445 upstream (the L</raw_passthrough> and a
1446 L<Langertha::Knarr::Handler::Passthrough> in the handler chain alike).
1447 From C<Authorization> and C<x-api-key>, every element that is the key --
1448 bare or as C<Bearer> I<key>, in either header -- is removed, the others are
1449 kept, and a header left with nothing is dropped; a header without the key
1450 goes through unchanged. Every other header is forwarded, so a passthrough
1451 client sends its own provider key in the other header -- the proxy key in
1452 C<x-api-key> and the OpenAI key as C<Authorization: Bearer>, or the proxy
1453 key as C<Authorization: Bearer> and the Anthropic key in C<x-api-key>.
1454  
1455 =head2 ollama_compat_version
1456  
1457 The Ollama version reported at C<GET /api/version> as
1458 C<{"version":"..."}>. Default C<0.34.4>, the current Ollama release when
1459 it was chosen (2026-09-23). It is a compatibility claim, not Knarr's own
1460 version: Ollama clients read it as the server's Ollama version. Two
1461 clients set its limits:
1462  
1463 =over
1464  
1465 =item * VS Code Copilot (BYOK Ollama) refuses a server below C<0.6.4>.
1466  
1467 =item * Open WebUI parses every dotted part with C<int()>, so anything but
1468 digits and dots (C<0.34.4-knarr>, C<v0.34>) breaks its connection check.
1469  
1470 =back
1471  
1472 The value must therefore be three dot-separated numbers
1473 (C</^\d+\.\d+\.\d+$/>); anything else croaks at construction. No
1474 surveyed client gates C<think>, tools or C<format> on the version -- they
1475 read C</api/show> capabilities per model -- so raising it enables nothing
1476 Knarr lacks. Configured as C<ollama_compat_version> in the config file or
1477 C<KNARR_OLLAMA_COMPAT_VERSION>.
1478  
1479 =head2 public_url
1480  
1481 Optional public base URL (e.g. C<https://knarr.example>) used in the
1482 provider manifest. When unset, the base URL is taken from the request
1483 (C<Host>, and C<X-Forwarded-Proto> when it is C<http> or C<https>).
1484  
1485 =head2 raw_passthrough
1486  
1487 Optional L<Langertha::Knarr::Handler::Passthrough>. Together with a
1488 L</router>, a chat request for a model the router does not configure -- or
1489 knows only from auto-discovery on that same upstream
1490 (L<Langertha::Knarr::Router/discovered_url>,
1491 L<Langertha::Knarr::Handler::Passthrough/is_upstream_for>), when the
1492 request carries the client's own provider key -- is
1493 piped byte for byte to the upstream for the client's protocol (an Ollama
1494 C</api/generate> to the upstream's C</api/generate>, any other Ollama chat
1495 to C</api/chat>), bypassing the handler chain -- but only when that
1496 protocol has an upstream
1497 (L<Langertha::Knarr::Handler::Passthrough/serves_protocol>). A request in
1498 any other protocol (Ollama without an C<ollama> upstream, A2A, ACP, AG-UI)
1499 goes through the handler, where L<Langertha::Knarr::Handler::Router> hands
1500 it to the default engine, or answers C<404> in the protocol's error shape
1501 when there is none.
1502  
1503 Every client header line goes to the upstream as a line of its own, in
1504 its order -- a header sent twice arrives twice -- with the proxy key taken
1505 out of each line (see
1506 L</auth_token>) and without C<Host>, C<Content-Length>, C<Connection> and
1507 C<Transfer-Encoding>. The upstream's response headers come back the same
1508 way, repeats included (C<Set-Cookie> twice), except the connection-level
1509 ones and the framing Knarr sets itself (C<Transfer-Encoding>,
1510 C<Content-Length>). A body compressed with an encoding Knarr's HTTP client
1511 decodes (C<gzip>, C<deflate>) goes back decoded, without its
1512 C<Content-Encoding>; a body in any other encoding (C<br>, C<zstd>, several
1513 stacked), buffered or streamed, goes back as the upstream sent it, with
1514 it. A stream gets
1515 C<Cache-Control: no-cache> when the upstream sent none.
1516  
1517 The provider key is looked for once the proxy key is taken out (see
1518 L</auth_token>): C<Authorization> for OpenAI, C<x-api-key> or
1519 C<Authorization> for Anthropic; Ollama needs none. A discovered model
1520 requested without one goes through the handler instead, to the engine
1521 that listed it, with that engine's key -- the upstream would only answer
1522 C<401>. A model nobody configured or discovered passes through either way.
1523  
1524 A discovered model's request that does carry a key the upstream refuses
1525 with C<401> -- the placeholder key an SDK sends when it has none -- is
1526 answered the same way: through the handler, by the engine that listed the
1527 model, with that engine's key. The client never sees the C<401>, streaming
1528 or not: the upstream's status is known before any byte goes to the client.
1529 The upstream is asked once, its refusal is dropped, and the request is
1530 traced once, by L<Langertha::Knarr::Handler::Tracing>, with
1531 C<passthrough_fallback: 401> in the trace's metadata. Any other status
1532 (C<403>, C<429>, C<5xx>) goes back unchanged, and so does the C<401> for a
1533 model nobody configured or discovered, which has no engine to fall back
1534 to.
1535  
1536 =head2 router
1537  
1538 Optional L<Langertha::Knarr::Router>, usually the one the
1539 L<Langertha::Knarr::Handler::Router> handler wraps. Knarr itself uses it
1540 to decide which requests go to the L</raw_passthrough> (models it does not
1541 configure, and models it only discovered on that upstream when the client
1542 sends its own key), to answer
1543 C<POST /api/show> from the routed engine's
1544 capabilities (without a router it falls back to the handler's
1545 C<list_models> and claims no C<vision>), and to start the capability probe
1546 in L</start>.
1547  
1548 =head2 tracing
1549  
1550 Optional L<Langertha::Knarr::Tracing>. Only the L</raw_passthrough> uses
1551 it: a request that bypasses the handler chain gets a lightweight Langfuse
1552 trace from here. Its generation carries the token usage and the model the
1553 upstream reported, read off a copy of the answer by
1554 L<Langertha::Knarr::PassthroughUsage> -- the JSON body, or the frames of a
1555 stream that carry them (OpenAI's final usage chunk, which the client asks
1556 for with C<stream_options.include_usage>; Anthropic's C<message_start> and
1557 C<message_delta>; Ollama's C<done> frame). The bytes the client gets are
1558 never touched; nothing is read without an active trace, nor from bytes
1559 that still carry a C<Content-Encoding>. Requests through the handler chain are traced by the
1560 L<Langertha::Knarr::Handler::Tracing> decorator instead -- so is a raw
1561 passthrough that falls back to its engine after a C<401> (see
1562 L</raw_passthrough>); the trace of a request that may fall back is
1563 therefore opened only once the upstream's status is known, dated back to
1564 when the request went out. Raw passthrough requests are not written to the
1565 request log; a fallback is, by the handler chain.
1566  
1567 =head2 start
1568  
1569 $knarr->start;
1570  
1571 Binds all listen sockets and registers the dispatcher. Returns
1572 C<$self>. Does not enter the event loop. Each socket queues up to
1573 C<SOMAXCONN> pending connections (C<128> where L<Socket> does not know it;
1574 the kernel caps it at its own limit, C<net.core.somaxconn> on Linux).
1575  
1576 Once the sockets listen, it starts
1577 L<Langertha::Knarr::Router/probe_capabilities_f> on the L</loop> when a
1578 L</router> that has it is set (see
1579 L<Langertha::Knarr::Config/probe_capabilities>). The probe runs in the
1580 background; until it has finished, C<POST /api/show> and the manifest answer
1581 from Langertha's static capability tables. L<Langertha::Knarr::PSGI> does not
1582 call L</start>, so under PSGI the probe runs only when you call it.
1583  
1584 =head2 run
1585  
1586 $knarr->run; # blocks
1587  
1588 With one L</workers> (the default): calls L</start> if needed, then enters
1589 the L</loop> and blocks.
1590  
1591 With more, it prefork-serves and returns only once all workers are gone:
1592  
1593 =over
1594  
1595 =item 1. The listen sockets are bound here (L</start> may have done it),
1596 and this process stops accepting on them.
1597  
1598 =item 2. Auto-discovery and the capability probe run here, once, to the
1599 end, before any worker exists -- each worker inherits the discovered models
1600 and the learned capabilities instead of asking the upstreams again. Until
1601 the probe is done (each probe gives up after
1602 L<Langertha::Knarr::Config/probe_timeout>), connections wait in the
1603 sockets' backlog. Upstream connections the probe kept open are closed, and
1604 the helper processes of the loop's resolver end, so no two workers share
1605 one: each worker starts its own resolver helpers.
1606  
1607 =item 3. L</workers> processes are forked; each rebuilds the loop's kernel
1608 state (L<IO::Async::Loop/post_fork>) and accepts on the inherited sockets.
1609  
1610 =item 4. This process supervises them: a worker that exits is replaced --
1611 one that dies within five seconds of its start after a pause of 1, 2, 4
1612 ... up to 30 seconds, so a worker that cannot start does not spin. A
1613 replacement that cannot be forked (out of processes or memory) is tried
1614 again the same way while the other workers serve on; only a failed fork of
1615 the first workers makes L</run> die, after stopping those already started.
1616 C<SIGTERM> or C<SIGINT> is passed on to the workers as C<SIGTERM>; once
1617 they have exited, L</run> returns.
1618  
1619 =back
1620  
1621 =head2 session
1622  
1623 my $session = $knarr->session($id);
1624  
1625 Returns the L<Langertha::Knarr::Session> for the given id, creating
1626 one on demand. Used internally by the dispatcher.
1627  
1628 =head2 manifest_response
1629  
1630 my ($status, $json_body) = $knarr->manifest_response(
1631 scheme => 'https', host => 'knarr.example', prefix => '' );
1632  
1633 Builds the provider manifest (see L</MANIFEST>) and returns the HTTP
1634 status and JSON body. The base URL is L</public_url>, else
1635 C<scheme://host> plus C<prefix> from the request. C<404> when core has no
1636 manifest builder, C<400> when no base URL can be derived, C<500> when the
1637 manifest cannot be built. Used by the native server and
1638 L<Langertha::Knarr::PSGI>.
1639  
1640 =head1 SUPPORT
1641  
1642 =head2 Issues
1643  
1644 Please report bugs and feature requests on GitHub at
1645 L<https://github.com/Getty/langertha-knarr/issues>.
1646  
1647 =head2 IRC
1648  
1649 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
1650  
1651 =head1 CONTRIBUTING
1652  
1653 Contributions are welcome! Please fork the repository and submit a pull request.
1654  
1655 =head1 AUTHOR
1656  
1657 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
1658  
1659 =head1 COPYRIGHT AND LICENSE
1660  
1661 This software is copyright (c) 2026 by Torsten Raudssus.
1662  
1663 This is free software; you can redistribute it and/or modify it under
1664 the same terms as the Perl 5 programming language system itself.
1665  
1666 =cut
« blib/lib/Langertha/Knarr/Request.pm ↑ Summary blib/lib/Langertha/Knarr/Image.pm »