blib/lib/Langertha/Knarr.pm

filter: Statementstmt 96.8% 61 / 63 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 21 / 21 Podpod n/a totaltotal 97.6% 82 / 84 CC 1 SCAR 0.1
CC
1
Cov
97%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/Langertha/Knarr/Stack.pm ↑ Summary blib/lib/Langertha/Knarr/CLI/Cmd/Container.pm »
1 package Langertha::Knarr;
2 # ABSTRACT: Universal LLM hub - proxy, server, and translator across OpenAI/Anthropic/Ollama/A2A/ACP/AG-UI
3 our $VERSION = '1.103';
4 60 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 60 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 60 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 60 ▶use Future::Exception;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 60 ▶use IO::Async::Loop;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 60 ▶use IO::Async::Resolver;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 60 ▶use Net::Async::HTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 60 ▶use Net::Async::HTTP::Server;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 60 ▶use HTTP::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 60 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 60 ▶use Data::UUID;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 60 ▶use Module::Runtime qw( use_module );
Subroutine BEGIN: called CC=1 SCAR=0.0
16 60 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
17 60 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 60 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 60 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
20 60 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
21 60 ▶use Socket ();
Subroutine BEGIN: called CC=1 SCAR=0.0
22 60 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
23 60 ▶use Langertha::Knarr::Session;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 0 ▶use Langertha::Knarr::Authorizer::StaticKey;
Subroutine BEGIN: called CC=1 SCAR=2.6
25 use Langertha::Knarr::Manifest;
26 use Langertha::Knarr::PassthroughUsage;
27 use Langertha::Knarr::Role::UpstreamHTTP ();
28  
29  
30  
31 # Required, unless an admin brings it with its stack (k75). Replaced as a
32 # whole by _apply_stack.
33 has handler => (
34 is => 'ro',
35 writer => '_set_handler',
36 predicate => '_has_handler',
37 );
38  
39 has host => (
40 is => 'ro',
41 isa => 'Str',
42 default => '127.0.0.1',
43 );
44  
45 has port => (
46 is => 'ro',
47 isa => 'Int',
48 default => 8088,
49 );
50  
51 # Listen on one or more addresses. Each entry is either "host:port" or
52 # { host => ..., port => ... }. Defaults to a single entry composed from
53 # the host/port attributes above.
54 has listen => (
55 is => 'ro',
56 isa => 'ArrayRef',
57 lazy => 1,
58 builder => '_build_listen',
59 );
60  
61 sub _build_listen {
62 my ($self) = @_;
63 return [ { host => $self->host, port => $self->port + 0 } ];
64 }
65  
66 has loop => (
67 is => 'ro',
68 lazy => 1,
69 builder => '_build_loop',
70 );
71 sub _build_loop { IO::Async::Loop->new }
72  
73 # Serving processes (k51): 1 is this one, more are forked by run().
74 has workers => (
75 is => 'ro',
76 isa => 'Int',
77 default => 1,
78 trigger => sub {
79 Carp::croak( "workers '$_[1]' must be 1 or more" ) unless $_[1] >= 1;
80 },
81 );
82  
83 has protocols => (
84 is => 'ro',
85 isa => 'ArrayRef[Str]',
86 default => sub { [qw( OpenAI Anthropic Ollama A2A ACP AGUI )] },
87 );
88  
89 has protocol_args => (
90 is => 'ro',
91 isa => 'HashRef[HashRef]',
92 default => sub { {} },
93 );
94  
95 # Optional shared secret. When set, every incoming request must present it
96 # either as 'Authorization: Bearer <key>' or 'x-api-key: <key>'. The agent
97 # card and well-known discovery routes are exempt because they need to be
98 # anonymously fetchable.
99 has router => (
100 is => 'ro',
101 isa => 'Maybe[Object]',
102 default => sub { undef },
103 writer => '_set_router',
104 );
105  
106 has raw_passthrough => (
107 is => 'ro',
108 isa => 'Maybe[Object]',
109 default => sub { undef },
110 writer => '_set_raw_passthrough',
111 );
112  
113 has tracing => (
114 is => 'ro',
115 isa => 'Maybe[Object]',
116 default => sub { undef },
117 writer => '_set_tracing',
118 );
119  
120 has auth_token => (
121 is => 'ro',
122 isa => 'Maybe[Str]',
123 default => sub { undef },
124 writer => '_set_auth_token',
125 # The default authorizer is built over the key: a new key (admin push,
126 # k75) needs a new one.
127 trigger => sub { $_[0]->_clear_static_authorizer },
128 );
129  
130 # Who may use this Knarr and with which model (k82). A given authorizer
131 # stays for the Knarr's life; without one, a StaticKey over auth_token.
132 has _authorizer => (
133 is => 'ro',
134 isa => 'Maybe[Object]',
135 init_arg => 'authorizer',
136 default => sub { undef },
137 writer => '_set_authorizer',
138 );
139  
140 has _static_authorizer => (
141 is => 'ro',
142 lazy => 1,
143 builder => '_build_static_authorizer',
144 clearer => '_clear_static_authorizer',
145 );
146  
147 # The class of the default authorizer, named once (override point).
148 sub static_authorizer_class { 'Langertha::Knarr::Authorizer::StaticKey' }
149  
150 sub _build_static_authorizer {
151 my ($self) = @_;
152 return $self->static_authorizer_class->new( key => $self->auth_token );
153 }
154  
155 sub authorizer {
156 my ($self) = @_;
157 return $self->_authorizer // $self->_static_authorizer;
158 }
159  
160 # Admin routes and the setup they deliver (k75): a Langertha::Knarr::Admin.
161 has admin => (
162 is => 'ro',
163 isa => 'Maybe[Object]',
164 default => sub { undef },
165 );
166  
167 has public_url => (
168 is => 'ro',
169 isa => 'Maybe[Str]',
170 default => sub { undef },
171 );
172  
173 # What GET /api/version answers (k27): the Ollama version the Ollama
174 # endpoints are compatible with, not Knarr's own. Current Ollama release
175 # (k28); it must stay >= 0.6.4 (Copilot BYOK floor) and digits-and-dots only
176 # (Open WebUI int()s each part).
177 has ollama_compat_version => (
178 is => 'ro',
179 isa => 'Str',
180 default => '0.34.4',
181 trigger => sub { _check_ollama_compat_version( $_[1] ) },
182 );
183  
184 sub _check_ollama_compat_version {
185 my ($version) = @_;
186 Carp::croak( "ollama_compat_version '$version' must be three dot-separated"
187 . " numbers like 0.34.4 (Ollama clients parse each part as an integer)" )
188 unless $version =~ /\A\d+\.\d+\.\d+\z/;
189 return $version;
190 }
191  
192 has _manifest => (
193 is => 'ro',
194 lazy => 1,
195 default => sub { Langertha::Knarr::Manifest->new( knarr => $_[0] ) },
196 clearer => '_clear_manifest',
197 );
198  
199 has _protocol_objects => (
200 is => 'ro',
201 lazy => 1,
202 builder => '_build_protocol_objects',
203 );
204  
205 has _routes => (
206 is => 'ro',
207 lazy => 1,
208 builder => '_build_routes',
209 );
210  
211 has _sessions => (
212 is => 'ro',
213 default => sub { {} },
214 );
215  
216 has _uuid => (
217 is => 'ro',
218 default => sub { Data::UUID->new },
219 );
220  
221 has _json => (
222 is => 'ro',
223 default => sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1 ) },
224 );
225  
226 has _server => (
227 is => 'rw',
228 );
229  
230 # The startup capability probe (k37), held until it is ready.
231 has _capability_probe => (
232 is => 'rw',
233 );
234  
235 # The process that serves requests: set by start() with one worker and by
236 # each forked worker, never in the prefork supervisor (k82).
237 has _serving_pid => (
238 is => 'rw',
239 default => 0,
240 );
241  
242 has _servers => (
243 is => 'rw',
244 default => sub { [] },
245 );
246  
247 sub BUILD {
248 my ($self) = @_;
249 if ( my $admin = $self->admin ) {
250 # Every process holds its own delivered setup: a push would reach one
251 # worker of several (k75).
252 Carp::croak( "workers '".$self->workers."' cannot be combined with admin routes:"
253 . " each worker would hold its own setup" ) if $self->workers > 1;
254 # A tracing given to the constructor stays when the stack has none.
255 my $tracing = $self->tracing;
256 $self->_apply_stack( $admin->stack );
257 $self->_set_tracing($tracing) if $tracing && !$admin->stack->tracing;
258 }
259 Carp::croak( 'Attribute (handler) is required' ) unless $self->_has_handler;
260 }
261  
262 # The parts of a Langertha::Knarr::Stack that serve requests, swapped in at
263 # once (k75): no event loop turn between them, so a request sees either the
264 # old parts or the new ones. A request already running keeps the objects it
265 # holds -- a stream goes on with its engine. The manifest and the capability
266 # probe belong to the router and start over with the new one.
267 sub _apply_stack {
268 my ($self, $stack) = @_;
269 $self->_set_handler( $stack->handler );
270 $self->_set_router( $stack->router );
271 $self->_set_raw_passthrough( $stack->raw_passthrough );
272 $self->_set_auth_token( $stack->auth_token );
273 # A token_auth stack brings its authorizer (the same object across pushes,
274 # k82); otherwise the proxy key keeps being checked.
275 $self->_set_authorizer( $stack->authorizer ) if $stack->authorizer;
276 # A delivered langfuse section brings its own tracing (k75).
277 $self->_set_tracing( $stack->tracing );
278 # A serving process starts an authorizer it got from a push; the one it
279 # already had ignores the second start.
280 $self->_start_authorizer if $self->_serving_pid == $$;
281 $self->_clear_manifest;
282 if ( $self->_server ) {
283 if ( my $probe = $self->_capability_probe ) {
284 $probe->cancel unless $probe->is_ready;
285 }
286 $self->_capability_probe(undef);
287 $self->_start_capability_probe;
288 }
289 return;
290 }
291  
292 sub _build_protocol_objects {
293 my ($self) = @_;
294 my @objs;
295 for my $name ( @{ $self->protocols } ) {
296 my $class = $name =~ /::/ ? $name : "Langertha::Knarr::Protocol::$name";
297 use_module($class);
298 push @objs, $class->new( %{ $self->protocol_args->{$name} // {} } );
299 }
300 return \@objs;
301 }
302  
303 sub _build_routes {
304 my ($self) = @_;
305 my @routes;
306 for my $proto ( @{ $self->_protocol_objects } ) {
307 for my $r ( @{ $proto->protocol_routes } ) {
308 push @routes, { %$r, protocol => $proto };
309 }
310 }
311 # Knarr's own route, not a protocol's (k14).
312 push @routes, { method => 'GET', path => '/.well-known/langertha.json',
313 action => 'manifest', protocol => undef };
314 # The admin routes exist only with an admin (k75): without one they are a
315 # path like any unknown one.
316 if ( my $admin = $self->admin ) {
317 push @routes, map { { %$_, protocol => undef, admin => 1 } } $admin->routes;
318 }
319 return \@routes;
320 }
321  
322 sub session {
323 my ($self, $id) = @_;
324 $id //= $self->_uuid->create_str;
325 $self->_sessions->{$id} //= Langertha::Knarr::Session->new( id => $id );
326 $self->_sessions->{$id}->touch;
327 return $self->_sessions->{$id};
328 }
329  
330 sub _listen_addrs {
331 my ($self) = @_;
332 my @out;
333 for my $entry ( @{ $self->listen } ) {
334 if ( ref $entry eq 'HASH' ) {
335 push @out, { host => $entry->{host} // '127.0.0.1', port => $entry->{port} + 0 };
336 } else {
337 my ($h, $p) = split /:/, $entry, 2;
338 $h ||= '127.0.0.1';
339 push @out, { host => $h, port => ($p // 8088) + 0 };
340 }
341 }
342 return @out;
343 }
344  
345 sub start {
346 my ($self) = @_;
347 $self->_listen;
348 $self->_start_capability_probe;
349 # With workers, the supervisor only binds: each worker starts serving.
350 $self->_start_serving unless $self->workers > 1;
351 return $self;
352 }
353  
354 # This process serves from now on: its loop is set up, so the authorizer
355 # can open its connection (k82) -- once per process, never in the
356 # supervisor of prefork workers, whose connection every worker would share.
357 sub _start_serving {
358 my ($self) = @_;
359 $self->_serving_pid($$);
360 $self->_start_authorizer;
361 return;
362 }
363  
364 # Authorizer->start does not wait for its connection. A failure to start is
365 # logged: the authorizer still answers every request (503 while its store
366 # is not available).
367 sub _start_authorizer {
368 my ($self) = @_;
369 my $authorizer = $self->authorizer;
370 return unless $authorizer && $authorizer->can('start');
371 eval { $authorizer->start( $self->loop ); 1 }
372 or $log->errorf( 'Authorizer start failed: %s', _error_text($@) );
373 return;
374 }
375  
376 sub _listen {
377 my ($self) = @_;
378 my @servers;
379 for my $a ( $self->_listen_addrs ) {
380 my $server = Net::Async::HTTP::Server->new(
381 on_request => sub {
382 my ($srv, $req) = @_;
383 $self->_dispatch($req);
384 },
385 );
386 $self->loop->add($server);
387 $server->listen(
388 addr => {
389 family => 'inet',
390 socktype => 'stream',
391 port => $a->{port},
392 ip => $a->{host},
393 },
394 queuesize => $self->_listen_backlog,
395 )->get;
396 push @servers, $server;
397 }
398 $self->_servers(\@servers);
399 $self->_server( $servers[0] );
400 return;
401 }
402  
403 # Connections the kernel queues until a process accepts them (k51): the
404 # system maximum, not IO::Async's default of 3 -- with workers, connections
405 # wait here while the probe runs before the fork. The kernel caps it at
406 # net.core.somaxconn.
407 sub _listen_backlog {
408 my ($self) = @_;
409 my $max = eval { Socket::SOMAXCONN() };
410 return $max && $max > 0 ? $max : 128;
411 }
412  
413 # k37: once the server listens, ask each routed engine for its model's
414 # capabilities (Router->probe_capabilities_f). Deferred to the running loop
415 # so start() does not block on discovery; the Future is held here until it
416 # is ready. It never fails: probe errors are logged by the router.
417 sub _start_capability_probe {
418 my ($self) = @_;
419 my $router = $self->router;
420 return unless $router && $router->can('probe_capabilities_f');
421 return if $self->_capability_probe;
422 my $loop = $self->loop;
423 $self->_capability_probe( $loop->delay_future( after => 0 )->then(sub {
424 $router->probe_capabilities_f( loop => $loop );
425 })->else(sub {
426 $log->warnf( "Capability probe failed: %s", $_[0] );
427 Future->done(0);
428 }) );
429 return;
430 }
431  
432 sub run {
433 my ($self) = @_;
434 return $self->_run_workers if $self->workers > 1;
435 $self->start unless $self->_server;
436 $self->loop->run;
437 }
438  
439 # k51: prefork. This process binds, discovers and probes once, forks the
440 # workers -- which inherit all of it -- and supervises them until SIGTERM or
441 # SIGINT. It serves no request itself.
442 sub _run_workers {
443 my ($self) = @_;
444 $self->_prepare_workers;
445  
446 my %workers; # pid => start time
447 my $stopping = 0;
448 my $stop = sub {
449 my ($signal) = @_;
450 $log->infof( "SIG%s: stopping %d worker(s)", $signal, scalar keys %workers )
451 unless $stopping;
452 $stopping = 1;
453 kill TERM => keys %workers;
454 };
455 local $SIG{TERM} = $stop;
456 local $SIG{INT} = $stop;
457  
458 my $spawn = sub {
459 my $pid = $self->_fork_worker;
460 $workers{$pid} = time;
461 kill TERM => $pid if $stopping; # the signal came in during the fork
462 $log->infof( "Worker %d started", $pid );
463 };
464  
465 try {
466 # Only these first forks must succeed: without them nothing serves.
467 $spawn->() for 1 .. $self->workers;
468 my $delay = 0;
469 while ( %workers || !$stopping ) {
470 my $missing = $stopping ? 0 : $self->workers - keys %workers;
471 if ( $missing > 0 ) {
472 sleep $delay if $delay; # a signal ends it early
473 next if $stopping;
474 next if eval { $spawn->(); 1 };
475 # A replacement that cannot be forked (EAGAIN, ENOMEM) is treated
476 # like a crashing worker: the others keep serving, and it is tried
477 # again after a pause (k64).
478 $delay = $self->_restart_delay($delay);
479 $log->errorf( "%s; trying again in %ds", _error_text($@), $delay );
480 }
481 # While a worker is missing, only look: the retry must not wait for
482 # the next death.
483 my $pid = waitpid( -1, $missing > 0 ? POSIX::WNOHANG() : 0 );
484 next if $pid == 0;
485 if ( $pid < 0 ) { # no children left
486 last unless $missing > 0;
487 next;
488 }
489 my $started = delete $workers{$pid} // next;
490 next if $stopping;
491 my $status = $?;
492 # A worker that dies within 5s of its start is crashing: pause before
493 # the next one, so it cannot spin.
494 $delay = time - $started < 5 ? $self->_restart_delay($delay) : 0;
495 $log->warnf( "Worker %d %s, starting a new one%s", $pid,
496 $self->_exit_text($status), $delay ? " in ${delay}s" : '' );
497 }
498 } catch {
499 my $err = $_;
500 kill TERM => keys %workers;
501 waitpid( $_, 0 ) for keys %workers;
502 die $err;
503 };
504 return;
505 }
506  
507 # The pause before the next restart: 1, 2, 4 ... 30 seconds.
508 sub _restart_delay {
509 my ($self, $delay) = @_;
510 $delay = $delay ? $delay * 2 : 1;
511 return $delay > 30 ? 30 : $delay;
512 }
513  
514 sub _prepare_workers {
515 my ($self) = @_;
516 $self->_listen unless $self->_server;
517 my $loop = $self->loop;
518 # The sockets stay bound here for the workers, but this process accepts
519 # nothing on them.
520 $loop->remove($_) for grep { $_->loop } @{ $self->_servers };
521 if ( my $router = $self->router ) {
522 $router->list_models if $router->can('list_models'); # auto-discovery
523 $self->_start_capability_probe;
524 $self->_capability_probe->get if $self->_capability_probe;
525 }
526 $self->_drop_upstream_connections;
527 $self->_drop_resolver;
528 return;
529 }
530  
531 # Keep-alive upstream connections (the probe's) must not reach the workers:
532 # two processes on one socket read each other's responses. A
533 # Net::Async::HTTP closes its pooled connections when it leaves the loop and
534 # connects anew once it is back.
535 sub _drop_upstream_connections {
536 my ($self) = @_;
537 my $loop = $self->loop;
538 for my $http ( grep { $_->isa('Net::Async::HTTP') } $loop->notifiers ) {
539 if ( my $parent = $http->parent ) {
540 $parent->remove_child($http);
541 $parent->add_child($http);
542 }
543 else {
544 $loop->remove($http);
545 $loop->add($http);
546 }
547 }
548 return;
549 }
550  
551 # The loop's resolver looks names up in helper processes, started by the
552 # first connect to a hostname -- the probe's. Workers that inherited them
553 # would share their pipes and read each other's answers: a request would go
554 # to another request's upstream, or hang (k63). The helpers exit here, and
555 # the loop gets a fresh resolver, for which every worker starts its own.
556 # Waiting for their exit also clears the loop's watch on their pids, which
557 # a worker's own helper could otherwise reuse.
558 sub _drop_resolver {
559 my ($self) = @_;
560 my $loop = $self->loop;
561 my @resolvers = grep { $_->isa('IO::Async::Resolver') && !$_->parent } $loop->notifiers
562 or return;
563 for my $resolver (@resolvers) {
564 my $stopped = $resolver->stop;
565 Future->wait_any( $stopped, $loop->delay_future( after => 10 ) )->get;
566 $log->warn("Resolver helpers did not exit within 10s") unless $stopped->is_ready;
567 $loop->remove($resolver);
568 }
569 $loop->set_resolver( IO::Async::Resolver->new );
570 return;
571 }
572  
573 # Returns the worker's pid in the supervisor; the worker itself never
574 # returns. It drops the supervisor's signal handlers, rebuilds the loop's
575 # kernel state (epoll/kqueue fd, signal pipe) and accepts on the inherited
576 # sockets. POSIX::_exit: the supervisor's END blocks and destructors are not
577 # the worker's to run.
578 #
579 # SIGTERM and SIGINT stay blocked from before the fork until the worker has
580 # dropped the supervisor's handlers (k64): one that reached the worker in
581 # between would run the supervisor's stop -- killing the other workers --
582 # and the worker would serve on. Blocked, it waits and then ends the worker;
583 # in the supervisor it runs once the fork is done.
584 sub _fork_worker {
585 my ($self) = @_;
586 my $signals = POSIX::SigSet->new( POSIX::SIGTERM(), POSIX::SIGINT() );
587 my $mask = POSIX::SigSet->new;
588 POSIX::sigprocmask( POSIX::SIG_BLOCK(), $signals, $mask )
589 or Carp::croak( "Cannot block signals for the fork: $!" );
590 my $pid = $self->_fork;
591 my $error = $!;
592 if ( defined $pid && !$pid ) {
593 $SIG{$_} = 'DEFAULT' for qw( TERM INT );
594 }
595 POSIX::sigprocmask( POSIX::SIG_SETMASK(), $mask );
596 Carp::croak( "Cannot fork a worker: $error" ) unless defined $pid;
597 return $pid if $pid;
598 my $ok = eval {
599 my $loop = $self->loop;
600 $loop->post_fork;
601 $loop->add($_) for @{ $self->_servers };
602 $self->_start_serving;
603 $loop->run;
604 1;
605 };
606 $log->errorf( "Worker %d failed: %s", $$, $@ ) unless $ok;
607 POSIX::_exit( $ok ? 0 : 1 );
608 }
609  
610 # The fork itself, apart so a test can make it fail.
611 sub _fork { fork }
612  
613 sub _exit_text {
614 my ($self, $status) = @_;
615 return 'was killed by signal ' . ( $status & 127 ) if $status & 127;
616 return 'exited with status ' . ( $status >> 8 );
617 }
618  
619 sub _match_route {
620 my ($self, $method, $path) = @_;
621 for my $r ( @{ $self->_routes } ) {
622 next unless $r->{method} eq $method;
623 return $r if $r->{path} eq $path;
624 }
625 return undef;
626 }
627  
628 # The identify phase (k82), as a Future that is done with
629 # { identity => \%identity } or { status, message } and never fails. The
630 # admin key opens the admin routes and nothing else: it must never reach a
631 # handler or an upstream, whatever the authorizer (k75). An authorizer that
632 # fails anyway is a check that could not be made: 503, never a way in.
633 sub _identify_f {
634 my ($self, $req, $action) = @_;
635 return Future->done( $self->_unauthorized_result ) if $self->_presents_admin_key($req);
636 my $f = eval { $self->authorizer->identify_f( $req, $action ) }
637 // Future->fail( $@ || 'identify_f returned nothing' );
638 return $f->else( sub {
639 $log->errorf( 'Authorizer failed: %s', $_[0] );
640 Future->done( $self->_unavailable_result );
641 } );
642 }
643  
644 # The same, synchronously (Langertha::Knarr::PSGI).
645 sub _identify {
646 my ($self, $req, $action) = @_;
647 return $self->_unauthorized_result if $self->_presents_admin_key($req);
648 my $result = eval { $self->authorizer->identify( $req, $action ) };
649 return $result if $result;
650 $log->errorf( 'Authorizer failed: %s', $@ || 'identify returned nothing' );
651 return $self->_unavailable_result;
652 }
653  
654 sub _unauthorized_result { return { status => 401, message => 'unauthorized' } }
655 sub _unavailable_result { return { status => 503, message => 'token check unavailable' } }
656  
657 # The answer to a refused identify result, ( status, content type, body ) in
658 # the route's protocol's error shape (k78); empty for an identity.
659 sub _identify_refusal {
660 my ($self, $proto, $result, $body) = @_;
661 return unless defined $result->{status};
662 return $self->_error_answer( $proto, $result->{status},
663 $result->{message} // 'unauthorized', undef, $body );
664 }
665  
666 # The authorize phase (k82): empty when the identity may do $action with
667 # $model, else the refusal as ( status, content type, body ) in the
668 # protocol's error shape. Shared by the native server and the PSGI adapter.
669 sub _authorize_refusal {
670 my ($self, $proto, $identity, $action, $model, $sb_req, $body) = @_;
671 my ($status, $message) = $self->authorizer->authorize( $identity // {}, $action, $model );
672 return unless defined $status;
673 $log->debugf( 'Authorization refused (%s): %s', $action, $status );
674 return $self->_error_answer( $proto, $status, $message // 'forbidden', $sb_req, $body );
675 }
676  
677 # Equal keys, compared in constant time (k76); see
678 # Langertha::Knarr::Authorizer::StaticKey.
679 sub _same_key {
680 my ($given, $want) = @_;
681 return __PACKAGE__->static_authorizer_class->_same_key( $given, $want );
682 }
683  
684 # True when any element of Authorization or x-api-key is the admin key.
685 sub _presents_admin_key {
686 my ($self, $req) = @_;
687 my $admin = $self->admin or return 0;
688 for my $name ( 'Authorization', 'x-api-key' ) {
689 my $value = scalar $req->header($name);
690 next unless defined $value;
691 for my $element ( split /,/, $value ) {
692 $element =~ s/\A\s+|\s+\z//g;
693 $element =~ s/\ABearer\s+//i;
694 return 1 if $admin->is_key($element);
695 }
696 }
697 return 0;
698 }
699  
700 # The answer to every route but the admin routes while an admin has no
701 # setup to serve from (remote_config without a start setup, before the first push, k75): 503 in the
702 # protocol's error shape. Empty when Knarr can serve.
703 sub _not_configured_answer {
704 my ($self, $proto, $body) = @_;
705 my $admin = $self->admin or return;
706 return if $admin->configured;
707 return $self->_error_answer( $proto, 503, 'not configured: Knarr has no setup yet', undef, $body );
708 }
709  
710 # An error Knarr answers itself, as ( status, content type, body ) in the
711 # client protocol's error shape (format_error_response): Anthropic's typed
712 # error object, Ollama's plain string. A route of Knarr's own, without a
713 # protocol, gets the OpenAI wire's {"error":{"message":...}}. Every such
714 # answer goes through here -- 401, 404, 500, 502-504 alike (k78) -- on the
715 # native server and the PSGI adapter. $sb_req, when the request was parsed,
716 # lets a protocol address the error to it (A2A's JSON-RPC id); $body, the
717 # request's raw body, does so for an error that came before the parse (401,
718 # 503) or because of it -- only for a protocol that reads it
719 # (Protocol::error_uses_body, k80).
720 sub _error_answer {
721 my ($self, $proto, $code, $message, $sb_req, $raw_body) = @_;
722 return ( $code, 'application/json',
723 $self->_json->encode({ error => { message => "$message" } }) ) unless $proto;
724 my ($status, $headers, $body) = $proto->format_error_response( $code, $message, $sb_req, $raw_body );
725 return ( $status, $headers->{'Content-Type'} // 'application/json', $body );
726 }
727  
728 # An admin request, answered by the admin for both transports (k75).
729 sub _dispatch_admin {
730 my ($self, $req, $action) = @_;
731 my $body = $req->body;
732 my $peer = eval { $req->stream->read_handle->peerhost };
733 return $self->_send_simple( $req, $self->admin->handle(
734 knarr => $self,
735 action => $action,
736 request => $req,
737 content_length => length( $body // '' ),
738 body => sub { $body },
739 peer => $peer,
740 ) );
741 }
742  
743 # Headers Knarr reads its own key (auth_token) from.
744 my %PROXY_KEY_HEADER = ( 'authorization' => 1, 'x-api-key' => 1 );
745  
746 # A client header's value as it may leave Knarr (k44, k53). In Authorization
747 # and x-api-key, every comma-separated element that is Knarr's key -- bare
748 # or as 'Bearer <key>', in either header -- is removed: a header sent twice
749 # arrives as one value joined with ', ' under PSGI (one HTTP_* key), and
750 # a client may join them itself. Returns the value unchanged, byte for
751 # byte, when no element carries the key; the remaining elements joined with
752 # ', ' when some do; nothing when only the key was there, so the header is
753 # dropped.
754 # Every path that forwards client headers goes through here: the raw
755 # passthrough and the forward_headers of the protocol parsers. Under an
756 # authorizer that does not forward the client's key (token auth, k82) both
757 # headers carry nothing but Knarr's credential and are dropped whole.
758 sub _without_proxy_key {
759 my ($self, $name, $value) = @_;
760 return if $PROXY_KEY_HEADER{ lc $name } && !$self->authorizer->forwards_client_key;
761 my $key = $self->auth_token;
762 return $value unless defined $key && length $key && defined $value
763 && $PROXY_KEY_HEADER{ lc $name };
764 my ( @kept, $dropped );
765 for my $element ( split /,/, $value ) {
766 ( my $token = $element ) =~ s/\A\s+|\s+\z//g;
767 next unless length $token;
768 ( my $bare = $token ) =~ s/\ABearer\s+//i;
769 if ( $bare eq $key ) { $dropped = 1; next }
770 push @kept, $token;
771 }
772 return $value unless $dropped;
773 return @kept ? join( ', ', @kept ) : ();
774 }
775  
776 # The protocol's parse, with Knarr's key taken out of the headers a
777 # passthrough handler in the chain forwards (forward_headers, k44), and the
778 # identity of the identify phase on the request (grant, k82). Shared by the
779 # native server and the PSGI adapter.
780 sub _parse_chat_request {
781 my ($self, $proto, $req, $body_ref, $identity) = @_;
782 # A body that is no JSON object is the client's mistake: 400 in the
783 # protocol's shape, a fixed text (k81). Checked before the parse, which
784 # alone would die with the decoder's message and become a 500.
785 if ( defined( my $reason = $proto->request_body_error($body_ref) ) ) {
786 die Future::Exception->new( $reason, 'bad_request' );
787 }
788 my $sb_req = $proto->parse_chat_request( $req, $body_ref );
789 # One header line at a time, as the parser recorded them (k60): a line
790 # that was only the key is dropped, the others keep their order.
791 my $extra = $sb_req->extra;
792 if ( $extra && $extra->{forward_headers} ) {
793 my @kept;
794 for my $pair ( $sb_req->forward_header_pairs ) {
795 my ($value) = $self->_without_proxy_key(@$pair);
796 push @kept, [ $pair->[0], $value ] if defined $value;
797 }
798 $extra->{forward_headers} = \@kept;
799 }
800 # A request that names no model gets the identity's (a token is for one).
801 $sb_req->apply_grant($identity) if $identity;
802 return $sb_req;
803 }
804  
805 sub _dispatch {
806 my ($self, $req) = @_;
807 my $method = $req->method;
808 my $path = $req->path;
809 my $route = $self->_match_route( $method, $path );
810 unless ( $route ) {
811 return $self->_send_simple( $req, 404, 'application/json',
812 $self->_json->encode({ error => { message => "no route for $method $path" } }) );
813 }
814 my $action = $route->{action};
815 return $self->_dispatch_admin( $req, $action ) if $route->{admin};
816 # Who asks, before the body is read (k82). A check that has to ask a
817 # store answers later; the loop serves on meanwhile.
818 my $identified = $self->_identify_f( $req, $action );
819 return $self->_dispatch_identified( $req, $route, $identified->get )
820 if $identified->is_ready;
821 $identified->on_done( sub {
822 my ($result) = @_;
823 return if $req->is_closed;
824 $self->_dispatch_identified( $req, $route, $result );
825 } )->retain;
826 return;
827 }
828  
829 sub _dispatch_identified {
830 my ($self, $req, $route, $result) = @_;
831 my $action = $route->{action};
832 my $proto = $route->{protocol};
833 if ( my @refused = $self->_identify_refusal( $proto, $result, $req->body ) ) {
834 return $self->_send_simple( $req, @refused );
835 }
836 my $identity = $result->{identity} // {};
837 if ( my @answer = $self->_not_configured_answer( $proto, $req->body ) ) {
838 return $self->_send_simple( $req, @answer );
839 }
840 my $simple = $self->_simple_action($action);
841 my $code = $simple ? undef : $self->can("_action_$action");
842 unless ( $simple || $code ) {
843 return $self->_send_simple( $req,
844 $self->_error_answer( $proto, 500, "unknown action $action", undef, $req->body ) );
845 }
846 try {
847 if ( $simple ) {
848 my ($status, $headers, $body) = $self->$simple( $proto, $req->body, $identity );
849 $self->_send_simple( $req, $status, $headers->{'Content-Type'} // 'application/json', $body );
850 }
851 else {
852 $self->$code( $proto, $req, $identity );
853 }
854 } catch {
855 my $err = $_;
856 my ( $message, $category ) = blessed($err) && $err->isa('Future::Exception')
857 ? ( $err->message, $err->category ) : ( $err );
858 $log->errorf("Request error (%s): %s", $action, $message);
859 $self->_send_simple( $req,
860 $self->_handler_failure_answer( $proto, $message, $category, undef, $req->body ) );
861 };
862 }
863  
864 sub _action_chat {
865 my ($self, $proto, $req, $identity) = @_;
866 my $body = $req->body;
867 my $sb_req = $self->_parse_chat_request( $proto, $req, \$body, $identity );
868 # The model is known now (k82): a 403 before any handler work, so a
869 # refused stream never sends its 200.
870 if ( my @refused = $self->_authorize_refusal( $proto, $identity, 'chat', $sb_req->model, $sb_req, $body ) ) {
871 return $self->_send_simple( $req, @refused );
872 }
873  
874 # Raw passthrough: pipe bytes 1:1 to upstream, skip handler chain
875 if ( $self->_is_raw_passthrough($sb_req) ) {
876 return $self->_handle_raw_passthrough( $proto, $req, $sb_req );
877 }
878 return $self->_handle_chat( $proto, $req, $sb_req );
879 }
880  
881 # A parsed chat request answered through the handler chain -- also a raw
882 # passthrough that falls back to its engine (k66).
883 sub _handle_chat {
884 my ($self, $proto, $req, $sb_req) = @_;
885 my $session = $self->session( $sb_req->session_id );
886 my $handler = $self->handler;
887  
888 if ( $sb_req->stream ) {
889 return $self->_handle_stream( $proto, $req, $sb_req, $session, $handler );
890 }
891  
892 my $f = $handler->handle_chat_f( $session, $sb_req );
893 $f->on_done( sub {
894 my ($response) = @_;
895 try {
896 my ($status, $headers, $body) = $proto->format_chat_response( $response, $sb_req );
897 $self->_send_simple( $req, $status, $headers->{'Content-Type'} // 'application/json', $body );
898 } catch {
899 my $err = $_;
900 $log->errorf("Chat response error: %s", $err);
901 $self->_send_simple( $req, $self->_error_answer( $proto, 500, _error_text($err), $sb_req ) );
902 };
903 });
904 $f->on_fail( sub {
905 my ($err, $category) = @_;
906 $log->errorf("Chat handler error: %s", $err);
907 $self->_send_simple( $req, $self->_handler_failure_answer( $proto, $err, $category, $sb_req ) );
908 });
909 $f->retain;
910 }
911  
912 sub _handle_stream {
913 my ($self, $proto, $req, $sb_req, $session, $handler) = @_;
914  
915 # The stream's 200 goes out with its first event -- its first chunk, or
916 # its end -- not before. Until then the status is still free: a handler
917 # that fails (nothing serves the model, k41; an upstream timeout, k36; any
918 # backend failure, k78) is answered like a non-streaming request, in the
919 # protocol's error shape. Only a failure after that ends the started
920 # stream.
921 my $started = 0;
922  
923 my $write = sub {
924 my ($bytes) = @_;
925 return unless defined $bytes && length $bytes;
926 return if $req->is_closed;
927 $req->write_chunk( $bytes );
928 };
929  
930 my $start = sub {
931 return if $started++;
932 my $header = HTTP::Response->new( 200 );
933 $header->protocol('HTTP/1.1');
934 $header->header( 'Content-Type' => $proto->stream_content_type );
935 $header->header( 'Cache-Control' => 'no-cache' );
936 $req->respond_chunk_header( $header );
937 $write->( $proto->format_stream_open($sb_req) );
938 };
939  
940 my $refuse = sub {
941 my ($err, $category) = @_;
942 return if $req->is_closed;
943 $self->_send_simple( $req, $self->_handler_failure_answer( $proto, $err, $category, $sb_req ) );
944 };
945  
946 my $f = $handler->handle_stream_f( $session, $sb_req );
947 $f->on_done( sub {
948 my ($stream) = @_;
949 my $pump; $pump = sub {
950 if ( $req->is_closed ) { undef $pump; return }
951 $stream->next_chunk_f->on_done( sub {
952 my ($delta) = @_;
953 if ( $req->is_closed ) { undef $pump; return }
954 $start->();
955 if ( defined $delta ) {
956 $write->( $proto->format_stream_chunk( $delta, $sb_req ) );
957 $pump->();
958 }
959 else {
960 # The backend's terminal reason, its complete tool calls and its
961 # token usage are known only now; the protocol maps the reason into
962 # its own vocabulary (k18) and frames the calls (k19) and the usage.
963 my $finish_reason = $stream->can('finish_reason') ? $stream->finish_reason : undef;
964 my $tool_calls = $stream->can('tool_calls') ? $stream->tool_calls : [];
965 my $usage = $stream->can('usage') ? $stream->usage : undef;
966 $write->( $proto->format_stream_close( $sb_req, $finish_reason, $tool_calls, $usage ) );
967 $write->( $proto->format_stream_done( $sb_req, $finish_reason, $tool_calls, $usage ) );
968 $req->write_chunk_eof;
969 undef $pump;
970 }
971 })->on_fail( sub {
972 my ($err, $category) = @_;
973 $log->errorf("Stream chunk error: %s", $err);
974 undef $pump;
975 return $refuse->( $err, $category ) unless $started;
976 return if $self->_stream_failure_frame( $proto, $req, $err, $category, $sb_req );
977 $write->( $proto->format_stream_chunk( '[error: '._error_text($err).']', $sb_req ) );
978 $write->( $proto->format_stream_close($sb_req) );
979 $req->write_chunk_eof;
980 })->retain;
981 # Held until ready: a decorator's chained read (Tracing, RequestLog)
982 # is referenced by nothing else while the upstream is silent (k36).
983 };
984 $pump->();
985 });
986 $f->on_fail( sub {
987 my ($err, $category) = @_;
988 $log->errorf("Stream handler error: %s", $err);
989 $refuse->( $err, $category );
990 });
991 $f->retain;
992 }
993  
994 # The status a handler failure answers with, from its category (the second
995 # failure value). A Net::Async::HTTP timeout category (core's k278 engine
996 # timeouts, the UpstreamHTTP role's) is an upstream that did not answer in
997 # time: 504, as on the raw passthrough (k35, k36). 'model_not_found' is
998 # Handler::Router finding nothing to serve the model -- not configured, no
999 # passthrough for the protocol, no default engine: 404 (k41). Undef for any
1000 # other failure, and for a core that sets no category.
1001 sub _handler_failure_status {
1002 my ($self, $category) = @_;
1003 return 504 if Langertha::Knarr::Role::UpstreamHTTP->is_upstream_timeout($category);
1004 return 404 if defined $category && $category eq 'model_not_found';
1005 return 400 if defined $category && $category eq 'bad_request';
1006 # A handler that refuses the request's grant (Handler::TokenRoutes: no
1007 # route for its provider), or lacks what it needs to serve it (its key
1008 # variable unset), k82.
1009 return 403 if defined $category && $category eq 'forbidden';
1010 return 503 if defined $category && $category eq 'unavailable';
1011 return;
1012 }
1013  
1014 # A handler failure as ( status, content type, body ) in the client
1015 # protocol's error shape: the status of its category, else 500 -- a backend
1016 # that failed is answered in the client's own shape too (k78).
1017 sub _handler_failure_answer {
1018 my ($self, $proto, $err, $category, $sb_req, $body) = @_;
1019 return $self->_error_answer( $proto,
1020 $self->_handler_failure_status($category) // 500, _error_text($err), $sb_req, $body );
1021 }
1022  
1023 # The same for a stream whose headers are out: the protocol's error frame
1024 # (status of the category, else 500), then the end of the stream; the frame
1025 # is the stream's end, no success marker follows it (k79). False (nothing
1026 # written) only when the protocol has no error frame, so the caller answers
1027 # as before.
1028 sub _stream_failure_frame {
1029 my ($self, $proto, $req, $err, $category, $sb_req) = @_;
1030 my $code = $self->_handler_failure_status($category) // 500;
1031 my $frame = $proto->format_stream_error( $code, _error_text($err), $sb_req );
1032 return 0 unless length $frame;
1033 return 1 if $req->is_closed;
1034 $req->write_chunk($frame);
1035 $req->write_chunk_eof;
1036 return 1;
1037 }
1038  
1039 sub _handle_raw_passthrough {
1040 my ($self, $proto, $req, $sb_req) = @_;
1041 my ($http_req, $trace, $trace_from) = $self->_raw_passthrough_request(
1042 $sb_req, [ $req->headers ], $req->body, $req->path );
1043 my $pt = $self->raw_passthrough;
1044 my $model = $sb_req->model // 'unknown';
1045  
1046 if ($sb_req->stream) {
1047 # The upstream may go silent before its headers (answered like a
1048 # non-streaming failure: 504 or 502 in the protocol's shape) or in the
1049 # middle of the stream (the headers are out: the protocol's error frame,
1050 # then the end of the stream). stall_timeout covers both (k35).
1051 my $headers_sent = 0;
1052 my $fell_back = 0;
1053 my $tail = '';
1054 my $f = $pt->_upstream_request_f(
1055 request => $http_req,
1056 on_header => sub {
1057 my ($response) = @_;
1058 # The status is known before any byte goes to the client: a refused
1059 # discovered model is answered by its engine instead, and the
1060 # upstream's refusal is read and dropped (k66).
1061 if ( $self->_raw_passthrough_falls_back( $sb_req, $response ) ) {
1062 $fell_back = 1;
1063 $self->_raw_passthrough_fall_back( $proto, $req, $sb_req );
1064 return sub { };
1065 }
1066 $trace = $self->_raw_passthrough_trace( $sb_req, $trace_from ) if $trace_from;
1067 # The upstream's headers go back with it (k56).
1068 my $header = HTTP::Response->new($response->code);
1069 $header->protocol('HTTP/1.1');
1070 $header->header('Content-Type' => scalar $response->header('Content-Type'));
1071 $header->push_header(@$_) for @{ $self->_raw_passthrough_response_headers($response) };
1072 $header->header('Cache-Control' => 'no-cache') unless defined $header->header('Cache-Control');
1073 $req->respond_chunk_header($header);
1074 $headers_sent = 1;
1075 # The trace reads its usage off a copy of the bytes (k61).
1076 my $usage = $self->_raw_passthrough_usage_reader( $trace, $response );
1077  
1078 return sub {
1079 my ($data) = @_;
1080 if (!defined $data) {
1081 $req->write_chunk_eof unless $req->is_closed;
1082 $self->tracing->end_trace( $trace, output => '[stream]',
1083 $usage ? $usage->trace_args : () ) if $trace;
1084 return;
1085 }
1086 return unless length $data;
1087 $tail = substr( $tail . $data, -2 );
1088 $req->write_chunk($data) unless $req->is_closed;
1089 $usage->add_chunk($data) if $usage;
1090 };
1091 },
1092 );
1093 $f->on_fail(sub {
1094 my ($err, $category) = @_;
1095 # The engine answers; the dropped refusal has nothing left to say.
1096 return if $fell_back;
1097 unless ($headers_sent) {
1098 $trace = $self->_raw_passthrough_trace( $sb_req, $trace_from ) if $trace_from;
1099 return $self->_send_simple( $req,
1100 $self->_raw_passthrough_failed( $proto, $sb_req, $trace, $err, $category ) );
1101 }
1102 $log->errorf("Passthrough stream error [%s]: %s", $model, $err);
1103 $self->tracing->end_trace($trace, error => "$err") if $trace;
1104 return if $req->is_closed;
1105 my $frame = $proto->format_stream_error(
1106 $self->_raw_passthrough_status($category), _error_text($err) );
1107 if ( length $frame ) {
1108 # A frame cut off by the stall is ended first, so the error frame
1109 # stands on its own: a blank line for SSE, a newline for NDJSON.
1110 my $pad = $proto->stream_content_type =~ /ndjson/
1111 ? ( $tail eq '' || $tail =~ /\n\z/ ? '' : "\n" )
1112 : ( $tail eq '' || $tail eq "\n\n" ? '' : $tail =~ /\n\z/ ? "\n" : "\n\n" );
1113 $req->write_chunk( $pad . $frame );
1114 }
1115 $req->write_chunk_eof;
1116 });
1117 $f->retain;
1118 } else {
1119 my $f = $pt->_upstream_request_f(request => $http_req);
1120 $f->on_done(sub {
1121 my ($resp) = @_;
1122 return $self->_raw_passthrough_fall_back( $proto, $req, $sb_req )
1123 if $self->_raw_passthrough_falls_back( $sb_req, $resp );
1124 $trace = $self->_raw_passthrough_trace( $sb_req, $trace_from ) if $trace_from;
1125 $self->_send_simple( $req,
1126 $self->_raw_passthrough_answer( $sb_req, $trace, $resp ) );
1127 });
1128 $f->on_fail(sub {
1129 $trace = $self->_raw_passthrough_trace( $sb_req, $trace_from ) if $trace_from;
1130 $self->_send_simple( $req,
1131 $self->_raw_passthrough_failed( $proto, $sb_req, $trace, @_[0, 1] ) );
1132 });
1133 $f->retain;
1134 }
1135 }
1136  
1137 # Raw passthrough is decided and prepared here for both transports, the
1138 # native server and Langertha::Knarr::PSGI (k26), so they cannot drift:
1139 # which requests bypass the handler chain, which client headers reach the
1140 # upstream, what the upstream request and its trace look like, and how an
1141 # answer or a failure is returned. Only the byte pumping differs -- the
1142 # native server streams chunks as they arrive, PSGI buffers.
1143 sub _is_raw_passthrough {
1144 my ($self, $sb_req) = @_;
1145 my $pt = $self->raw_passthrough;
1146 my $router = $self->router;
1147 # Only for a protocol the passthrough has an upstream for: a request in
1148 # any other protocol goes through the handler chain, to the default
1149 # engine or to a 404 in the protocol's error shape (k41).
1150 return 0 unless $pt && $router && $pt->serves_protocol( $sb_req->protocol );
1151 # The client's key never goes upstream under an authorizer that keeps it
1152 # (token auth, k82).
1153 return 0 unless $self->authorizer->forwards_client_key;
1154 return 1 if $router->is_passthrough_model( $sb_req->model );
1155 # A model only auto-discovery knows, listed by this very upstream, goes
1156 # there byte for byte too; discovery then only feeds the model lists
1157 # (k47). One listed by another provider stays with its engine.
1158 my $url = $router->can('discovered_url') ? $router->discovered_url( $sb_req->model ) : undef;
1159 return 0 unless defined $url && $pt->can('is_upstream_for')
1160 && $pt->is_upstream_for( $sb_req->protocol, $url );
1161 # ...but only with the client's own provider key: without one the upstream
1162 # would answer 401, while the engine that listed the model holds Knarr's
1163 # key (k52).
1164 return $self->_carries_provider_key($sb_req);
1165 }
1166  
1167 # The headers a protocol's upstream takes its key from. A protocol not listed
1168 # (Ollama) needs none.
1169 my %PROVIDER_KEY_HEADERS = (
1170 openai => [ 'authorization' ],
1171 anthropic => [ 'x-api-key', 'authorization' ],
1172 );
1173  
1174 # True when the request carries a provider key for its protocol's upstream,
1175 # after Knarr's proxy key was taken out: the parser's forward_headers, as
1176 # _parse_chat_request left them (k52).
1177 sub _carries_provider_key {
1178 my ($self, $sb_req) = @_;
1179 my $names = $PROVIDER_KEY_HEADERS{ $sb_req->protocol // '' } or return 1;
1180 return ( grep { length } map { $sb_req->forward_header($_) } @$names ) ? 1 : 0;
1181 }
1182  
1183 # $headers: the client's request headers as [ name, value ] pairs; $path:
1184 # the path the client asked for (Ollama /api/chat or /api/generate, k46).
1185 sub _raw_passthrough_request {
1186 my ($self, $sb_req, $headers, $body, $path) = @_;
1187 my $model = $sb_req->model // 'unknown';
1188 my $protocol = $sb_req->protocol;
1189  
1190 # Build upstream URL from passthrough config
1191 my $url = $self->raw_passthrough->_upstream_url( $protocol, $path );
1192 my $http_req = HTTP::Request->new(POST => $url);
1193  
1194 # Forward all client headers except hop-by-hop / connection-specific
1195 # ones, with Knarr's own key taken out of each line (k44, k53). Every line
1196 # is added, not set: a header sent twice reaches the upstream twice, in
1197 # its order (k56).
1198 my %skip = map { lc($_) => 1 } qw( host content-length connection transfer-encoding );
1199 for my $pair (@$headers) {
1200 my ($name, $value) = @$pair;
1201 next if $skip{lc($name)};
1202 ($value) = $self->_without_proxy_key( $name, $value );
1203 next unless defined $value;
1204 $http_req->push_header($name => $value);
1205 }
1206 $http_req->content($body);
1207  
1208 $log->infof("Passthrough %s [%s] -> %s", $model, $protocol, $url);
1209  
1210 # Lightweight tracing for passthrough requests. The trace of a request
1211 # that may still fall back to its engine waits for the upstream's status,
1212 # so a fallback is traced once, by the handler chain (k66); $trace_from
1213 # is then the time the request goes out, for _raw_passthrough_trace.
1214 my ( $trace, $trace_from );
1215 if ( $self->_raw_passthrough_may_fall_back($sb_req) ) {
1216 $trace_from = [ Time::HiRes::gettimeofday() ] if $self->tracing;
1217 }
1218 else {
1219 $trace = $self->_raw_passthrough_trace($sb_req);
1220 }
1221  
1222 return ( $http_req, $trace, $trace_from );
1223 }
1224  
1225 # The raw passthrough's trace, started now or, with $trace_from, dated back
1226 # to it. Undef without tracing.
1227 sub _raw_passthrough_trace {
1228 my ($self, $sb_req, $trace_from) = @_;
1229 my $tracing = $self->tracing or return;
1230 return $tracing->start_trace(
1231 model => $sb_req->model // 'unknown',
1232 engine => 'passthrough',
1233 format => $sb_req->protocol,
1234 messages => $sb_req->messages,
1235 $trace_from ? ( start_hires => $trace_from ) : (),
1236 );
1237 }
1238  
1239 # True for a raw passthrough that falls back to its engine should the
1240 # upstream refuse the client's key (k66): one of a model only auto-discovery
1241 # knows, which the router resolves -- every other raw passthrough is of a
1242 # model it does not know, and has no engine to fall back to.
1243 sub _raw_passthrough_may_fall_back {
1244 my ($self, $sb_req) = @_;
1245 my $router = $self->router or return 0;
1246 return $router->is_passthrough_model( $sb_req->model ) ? 0 : 1;
1247 }
1248  
1249 # True when the upstream's answer sends a raw passthrough to its engine
1250 # instead (k66): a 401 -- the client's key refused, a placeholder an SDK
1251 # sent -- for a request that may fall back. Notes the fallback on the
1252 # request, for the handler chain's trace. Any other status, 403 and 429
1253 # included, goes back to the client as before.
1254 sub _raw_passthrough_falls_back {
1255 my ($self, $sb_req, $resp) = @_;
1256 return 0 unless $resp->code == 401 && $self->_raw_passthrough_may_fall_back($sb_req);
1257 $log->infof("Passthrough %s refused the client's key (401), answering through its engine",
1258 $sb_req->model // 'unknown');
1259 $sb_req->extra->{passthrough_fallback} = 401;
1260 return 1;
1261 }
1262  
1263 # The native server's fallback: the parsed request through the handler
1264 # chain, where Handler::Router sends it to the engine that listed the
1265 # model, with that engine's key. Nothing has gone to the client yet. It
1266 # runs in the upstream's callback, outside _dispatch's catch, so it answers
1267 # an error itself.
1268 sub _raw_passthrough_fall_back {
1269 my ($self, $proto, $req, $sb_req) = @_;
1270 try {
1271 $self->_handle_chat( $proto, $req, $sb_req );
1272 } catch {
1273 my $err = $_;
1274 $log->errorf("Passthrough fallback error [%s]: %s", $sb_req->model // 'unknown', $err);
1275 $self->_send_simple( $req, $self->_error_answer( $proto, 500, _error_text($err), $sb_req ) );
1276 };
1277 return;
1278 }
1279  
1280 # The upstream's answer as ( status, content type, body bytes, its other
1281 # headers ). A buffered stream (PSGI) is traced as a stream, like the
1282 # native one. The body goes back as Net::Async::HTTP handed it over, like a
1283 # stream: decoded when it knew the encoding, otherwise the upstream's bytes
1284 # with their Content-Encoding -- never decoded again here, where an
1285 # encoding HTTP::Message cannot decode (br without IO::Uncompress::Brotli,
1286 # anything unknown) came back as an empty body (k59).
1287 sub _raw_passthrough_answer {
1288 my ($self, $sb_req, $trace, $resp) = @_;
1289 if ($trace) {
1290 my $usage = $self->_raw_passthrough_usage_reader( $trace, $resp );
1291 $usage->read_body( $resp->content ) if $usage;
1292 $self->tracing->end_trace( $trace,
1293 output => $sb_req->stream ? '[stream]' : '[passthrough]',
1294 $usage ? $usage->trace_args : () );
1295 }
1296 return ( $resp->code,
1297 scalar $resp->header('Content-Type') // 'application/json',
1298 $resp->content // '',
1299 $self->_raw_passthrough_response_headers($resp) );
1300 }
1301  
1302 # Upstream response headers that stay behind: connection-level ones, the
1303 # framing Knarr sets for what it sends itself, Content-Type, which the
1304 # callers set, and the note Net::Async::HTTP leaves on a body it decoded.
1305 my %RESPONSE_HEADER_SKIP = map { $_ => 1 } qw(
1306 connection keep-alive proxy-connection te trailer upgrade
1307 transfer-encoding content-length content-type x-original-content-encoding );
1308  
1309 # The upstream's response headers that go back to the client, as [ name,
1310 # value ] pairs: every line, a repeated header (Set-Cookie) repeated in its
1311 # order (k56). Content-Encoding goes along only while the bytes still carry
1312 # it: Net::Async::HTTP decodes every encoding it knows (gzip, deflate)
1313 # before Knarr sees a byte, buffered or streamed, and passes any other as
1314 # it came (k59). The decision is its own: the whole header value, repeated
1315 # lines joined, is what it looks up -- in on_header it has not removed the
1316 # header yet, on a finished response it has.
1317 sub _raw_passthrough_response_headers {
1318 my ($self, $resp) = @_;
1319 my $encoding = $resp->header('Content-Encoding');
1320 my $decoded = defined $encoding && Net::Async::HTTP->can_decode($encoding);
1321 my @pairs;
1322 $resp->headers->scan( sub {
1323 my ($name, $value) = @_;
1324 my $lc = lc $name;
1325 return if $RESPONSE_HEADER_SKIP{$lc};
1326 return if $lc eq 'content-encoding' && $decoded;
1327 push @pairs, [ $name, $value ];
1328 });
1329 return \@pairs;
1330 }
1331  
1332 # What reads the token usage and model off a copy of the upstream's answer
1333 # for its trace (k61): nothing without a trace, and nothing for bytes that
1334 # still carry a Content-Encoding -- Net::Async::HTTP decodes the ones it
1335 # knows, the same decision as in _raw_passthrough_response_headers.
1336 sub _raw_passthrough_usage_reader {
1337 my ($self, $trace, $resp) = @_;
1338 return unless $trace;
1339 my $encoding = $resp->header('Content-Encoding');
1340 return if defined $encoding && !Net::Async::HTTP->can_decode($encoding);
1341 return Langertha::Knarr::PassthroughUsage->new;
1342 }
1343  
1344 # An upstream that did not answer in time is a 504, any other failure to
1345 # reach it a 502, in the client protocol's error shape (k35).
1346 sub _raw_passthrough_failed {
1347 my ($self, $proto, $sb_req, $trace, $err, $category) = @_;
1348 $log->errorf("Passthrough error [%s]: %s", $sb_req->model // 'unknown', $err);
1349 $self->tracing->end_trace($trace, error => "$err") if $trace;
1350 return $self->_error_answer( $proto,
1351 $self->_raw_passthrough_status($category), 'passthrough failed: ' . _error_text($err) );
1352 }
1353  
1354 sub _raw_passthrough_status {
1355 my ($self, $category) = @_;
1356 return Langertha::Knarr::Role::UpstreamHTTP->is_upstream_timeout($category) ? 504 : 502;
1357 }
1358  
1359 # What a client may be told of a failure (k79): the message without where
1360 # Perl died -- " at /path/Module.pm line 12." and "<$fh> line 3", the stack
1361 # frames of a confess, the @INC list of a missing module, any remaining
1362 # source path. The full text goes to the log and the request log, not here.
1363 # A message that is nothing but a location becomes "internal error".
1364 sub _error_text {
1365 my ($err) = @_;
1366 my $text = "$err";
1367 $text = join "\n", grep { !/^\s+\S.*\bcalled at\b/ && !/^\t/ } split /\n/, $text;
1368 $text =~ s/\s*\(\@INC[^)]*\)//g;
1369 $text =~ s/,?\s*\bat (?:\S+|\((?:re_)?eval \d+\)) line \d+(?:, <[^>]*> (?:line|chunk) \d+)?\.?//g;
1370 $text =~ s{(?<![\w.])/(?:[\w.\-]+/)*[\w.\-]+\.(?:pm|pl|t|xs)\b}{<file>}g;
1371 $text =~ s/\s+\z//;
1372 $text =~ s/\A\s+//;
1373 return length $text ? $text : 'internal error';
1374 }
1375  
1376 sub _action_acp_agents { goto &_action_models }
1377 sub _action_a2a_card {
1378 my ($self, $proto, $req) = @_;
1379 my ($status, $headers, $body) = $proto->format_agent_card;
1380 $self->_send_simple( $req, $status, $headers->{'Content-Type'} // 'application/json', $body );
1381 }
1382  
1383 # Actions answered with one buffered response from the request body alone.
1384 # The native server and the PSGI adapter both dispatch through this table,
1385 # so the two cannot drift: action => method( $proto, $body_bytes ) returning
1386 # ( status, \%headers, body ).
1387 my %SIMPLE_ACTIONS = (
1388 version => '_simple_version',
1389 show => '_simple_show',
1390 );
1391  
1392 sub _simple_action {
1393 my ($self, $action) = @_;
1394 return $SIMPLE_ACTIONS{$action};
1395 }
1396  
1397 sub _simple_version {
1398 my ($self, $proto) = @_;
1399 return $proto->format_version_response( $self->ollama_compat_version );
1400 }
1401  
1402 # POST /api/show (k29). VS Code Copilot calls it for every model and reads
1403 # tools/vision from capabilities; Continue reads it too. Only a model Knarr
1404 # lists (the /api/tags surface) is shown, anything else gets Ollama's 404.
1405 # capabilities never carry "thinking": Knarr drops think on the Ollama wire.
1406 sub _simple_show {
1407 my ($self, $proto, $body, $identity) = @_;
1408 my $data = eval { $self->_json->decode( defined $body && length $body ? $body : '{}' ) };
1409 $data = {} unless ref $data eq 'HASH';
1410 my $model = $data->{model};
1411 $model = $data->{name} unless defined $model && length $model; # Ollama's legacy field
1412 return $proto->format_error_response( 400, 'model is required' )
1413 unless defined $model && !ref $model && length $model;
1414 # May this identity see the model at all (k82)?
1415 my ($refused, $message) = $self->authorizer->authorize( $identity // {}, 'show', $model );
1416 return $proto->format_error_response( $refused, $message // 'forbidden' ) if defined $refused;
1417  
1418 my $router = $self->router;
1419 my $listed = $self->authorizer->visible_models( $identity // {},
1420 $router ? $router->list_models : $self->handler->list_models );
1421 my ($known) = grep { $_ eq $model }
1422 map { ref $_ eq 'HASH' ? $_->{id} // '' : "$_" } @{ $listed || [] };
1423 return $proto->format_error_response( 404, "model '$model' not found" )
1424 unless defined $known;
1425  
1426 # The engine the router sends this model to, when it can build one; a
1427 # model it cannot build (key variable unset) or a custom handler without
1428 # a router leaves the capabilities at what the Ollama endpoint forwards.
1429 my $engine = $router
1430 ? eval { ( $router->resolve( $model, skip_default => 1 ) )[0] } : undef;
1431 my $caps = blessed($engine) && $engine->can('supports') ? $engine : undef;
1432  
1433 my @capabilities = ('completion');
1434 push @capabilities, 'tools'
1435 if !$caps || $caps->supports('tools_native') || $caps->supports('tools_hermes');
1436 # "vision" from core's model-scoped image_input (core k266, ADR 0019),
1437 # evaluated for the upstream model: the router builds one engine per model,
1438 # so its chat_model is the model this name is sent to. A core without the
1439 # flag (0.503) cannot tell, so no claim; nor without a routed engine.
1440 push @capabilities, 'vision'
1441 if $caps && _image_input_known() && eval { $caps->supports('image_input') };
1442 my $context_length = blessed($engine) && $engine->can('get_context_size')
1443 ? eval { $engine->get_context_size } : undef;
1444  
1445 return $proto->format_show_response( $model, {
1446 capabilities => \@capabilities,
1447 ( defined $context_length ? ( context_length => $context_length ) : () ),
1448 } );
1449 }
1450  
1451 # True when the installed Langertha core knows the image_input capability
1452 # (Langertha::Role::ImageInput contributes it). Checked once per process.
1453 my $IMAGE_INPUT_KNOWN;
1454 sub _image_input_known {
1455 $IMAGE_INPUT_KNOWN //= eval { require Langertha::Role::ImageInput; 1 } ? 1 : 0;
1456 return $IMAGE_INPUT_KNOWN;
1457 }
1458  
1459 sub _action_manifest {
1460 my ($self, $proto, $req, $identity) = @_;
1461 if ( my @refused = $self->_authorize_refusal( $proto, $identity, 'manifest', undef ) ) {
1462 return $self->_send_simple( $req, @refused );
1463 }
1464 my $proto_header = lc( scalar( $req->header('X-Forwarded-Proto') ) // '' );
1465 my ($status, $body) = $self->manifest_response(
1466 scheme => ( $proto_header =~ /\A(https?)\z/ ? $1 : 'http' ),
1467 host => scalar $req->header('Host'),
1468 );
1469 $self->_send_simple( $req, $status, 'application/json', $body );
1470 }
1471  
1472 sub manifest_response {
1473 my ($self, %request) = @_;
1474 my $error = sub {
1475 my ($status, $message) = @_;
1476 return ( $status, $self->_json->encode({ error => { message => $message } }) );
1477 };
1478 return $error->( 404, 'provider manifest not available: the installed Langertha'
1479 . ' has no Langertha::Manifest::Builder' )
1480 unless Langertha::Knarr::Manifest->available;
1481  
1482 my $base_url = $self->public_url;
1483 unless ( defined $base_url && length $base_url ) {
1484 my $host = $request{host} // '';
1485 # A hostname or bracketed IPv6 address, optional port; nothing else can
1486 # reach the published URLs.
1487 return $error->( 400, 'cannot derive the public URL: no valid Host header'
1488 . ' (set public_url)' )
1489 unless $host =~ /\A(?:[A-Za-z0-9](?:[A-Za-z0-9.\-]*[A-Za-z0-9])?|\[[0-9A-Fa-f:.]+\])(?::[0-9]{1,5})?\z/;
1490 $base_url = ( $request{scheme} // 'http' ) . '://' . $host . ( $request{prefix} // '' );
1491 }
1492  
1493 my $manifest = eval { $self->_manifest->build($base_url) };
1494 unless ( $manifest ) {
1495 my $err = $@ || 'unknown error';
1496 $err =~ s/ at \S+ line \d+\.?\n?\z//;
1497 $log->errorf("Manifest error: %s", $err);
1498 return $error->( 500, "provider manifest failed: $err" );
1499 }
1500 return ( 200, $manifest->to_json );
1501 }
1502  
1503 sub _action_models {
1504 my ($self, $proto, $req, $identity) = @_;
1505 my $models = $self->_visible_models($identity);
1506 my ($status, $headers, $body) = $proto->format_models_response( $models );
1507 $self->_send_simple( $req, $status, $headers->{'Content-Type'} // 'application/json', $body );
1508 }
1509  
1510 # What a model list shows this identity (k82): the handler's models,
1511 # narrowed by the authorizer. Shared by the native server and the PSGI
1512 # adapter.
1513 sub _visible_models {
1514 my ($self, $identity) = @_;
1515 return $self->authorizer->visible_models( $identity // {}, $self->handler->list_models );
1516 }
1517  
1518 # $headers: optional further [ name, value ] pairs, each line added (the
1519 # raw passthrough's upstream headers, k56).
1520 sub _send_simple {
1521 my ($self, $req, $status, $ctype, $body, $headers) = @_;
1522 my $resp = HTTP::Response->new( $status );
1523 $resp->protocol('HTTP/1.1');
1524 $resp->push_header(@$_) for @{ $headers // [] };
1525 $resp->header( 'Content-Type' => $ctype );
1526 $resp->header( 'Content-Length' => length($body) );
1527 $resp->content($body);
1528 $req->respond($resp);
1529 }
1530  
1531 __PACKAGE__->meta->make_immutable;
1532 1;
1533  
1534 __END__
« blib/lib/Langertha/Knarr/Stack.pm ↑ Summary blib/lib/Langertha/Knarr/CLI/Cmd/Container.pm »