blib/lib/Langertha/Raider.pm

filter: Statementstmt 97.2% 1007 / 1035 Branchbran 80.8% 359 / 444 Conditioncond 65.4% 178 / 272 MC/DCmcdc 39.2% 62 / 158 Subroutinesub 99.2% 130 / 131 Podpod 92.3% 24 / 26 totaltotal 85.1% 1760 / 2066 CC 350 SCAR 27.4
CC
350
Cov
88%
_render_history_block
83.0
_raid_f
20.0
_execute_self_tool_f
15.7
CRAP 15.4
« blib/lib/Langertha/Raider/CLI/Sessions.pm ↑ Summary blib/lib/Langertha/Raider/ToolArgs.pm »
1 package Langertha::Raider;
2 # ABSTRACT: Autonomous agent with conversation history and MCP tools
3 98 our $VERSION = '0.503';
4 98 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 98 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 98 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 98 ▶use Time::HiRes qw( gettimeofday tv_interval );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 98 ▶use Carp qw( croak carp );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 98 ▶use Module::Runtime qw( use_module );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 98 ▶use Scalar::Util qw( blessed refaddr weaken );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 98 ▶use JSON::MaybeXS qw( JSON );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 98 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
13 98 ▶use MCP::Server;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 98 ▶use Net::Async::MCP;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 98 ▶use IO::Async::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 98 ▶use IO::Async::Loop;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 98 ▶use IO::Async::OS;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 98 ▶use Langertha::Usage;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 98 ▶use Langertha::Raider::ConnectCheck qw( connect_error );
Subroutine BEGIN: called CC=1 SCAR=0.0
20 98 ▶use Langertha::Raider::Result;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 98 ▶use Langertha::Raider::ToolArgs qw( tool_args_problems );
Subroutine BEGIN: called CC=1 SCAR=0.0
22 98 ▶use Langertha::RunContext;
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 98 with 'Langertha::Role::PluginHost', 'Langertha::Role::Runnable';
25  
26  
27 98 has engine => (
28 is => 'ro',
29 required => 1,
30 );
31  
32  
33 98 has mission => (
34 is => 'ro',
35 isa => 'Str',
36 predicate => 'has_mission',
37 writer => '_set_mission',
38 );
39  
40  
41 has history => (
42 is => 'rw',
43 isa => 'ArrayRef',
44 312 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
45 98 );
46  
47  
48 98 has max_iterations => (
49 is => 'ro',
50 isa => 'Int',
51 default => 10,
52 );
53  
54  
55 98 has max_context_tokens => (
56 is => 'ro',
57 isa => 'Int',
58 predicate => 'has_max_context_tokens',
59 );
60  
61  
62 98 has context_compress_threshold => (
63 is => 'ro',
64 isa => 'Num',
65 default => 0.75,
66 );
67  
68  
69 has compression_prompt => (
70 is => 'ro',
71 isa => 'Str',
72 lazy => 1,
73 6 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
74 6 'You are a conversation summarizer. Summarize the following conversation '
75 . 'between a user and an AI assistant. Preserve all key facts, decisions, '
76 . 'action items, file names, code references, and important context. '
77 . 'Be concise but complete. The summary will replace the conversation '
78 . 'history, so the assistant must be able to continue naturally.'
79 },
80 98 );
81  
82  
83 98 has compression_engine => (
84 is => 'ro',
85 predicate => 'has_compression_engine',
86 );
87  
88  
89 has session_history => (
90 is => 'ro',
91 isa => 'ArrayRef',
92 318 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
93 98 );
94  
95  
96 98 has _last_prompt_tokens => (
97 is => 'rw',
98 isa => 'Int',
99 predicate => 'has_last_prompt_tokens',
100 );
101  
102 has _injections => (
103 is => 'ro',
104 isa => 'ArrayRef',
105 318 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
106 98 );
107  
108 98 has on_iteration => (
109 is => 'rw',
110 isa => 'CodeRef',
111 predicate => 'has_on_iteration',
112 );
113  
114  
115 has metrics => (
116 is => 'rw',
117 isa => 'HashRef',
118 318 ▶ default => sub { {
Subroutine __ANON__: called CC=1 SCAR=0.0
119 318 raids => 0, iterations => 0, tool_calls => 0, time_ms => 0,
120 } },
121 98 );
122  
123  
124 98 has langfuse_trace_name => (
125 is => 'ro',
126 isa => 'Str',
127 default => 'raid',
128 );
129  
130  
131 98 has langfuse_user_id => (
132 is => 'ro',
133 isa => 'Str',
134 predicate => 'has_langfuse_user_id',
135 );
136  
137  
138 98 has langfuse_session_id => (
139 is => 'ro',
140 isa => 'Str',
141 predicate => 'has_langfuse_session_id',
142 );
143  
144  
145 98 has langfuse_tags => (
146 is => 'ro',
147 isa => 'ArrayRef[Str]',
148 predicate => 'has_langfuse_tags',
149 );
150  
151  
152 98 has langfuse_release => (
153 is => 'ro',
154 isa => 'Str',
155 predicate => 'has_langfuse_release',
156 );
157  
158  
159 98 has langfuse_version => (
160 is => 'ro',
161 isa => 'Str',
162 predicate => 'has_langfuse_version',
163 );
164  
165  
166 98 has langfuse_metadata => (
167 is => 'ro',
168 isa => 'HashRef',
169 predicate => 'has_langfuse_metadata',
170 );
171  
172  
173 98 has raider_mcp => (
174 is => 'ro',
175 predicate => 'has_raider_mcp',
176 );
177  
178  
179 98 has on_ask_user => (
180 is => 'rw',
181 isa => 'CodeRef',
182 predicate => 'has_on_ask_user',
183 );
184  
185  
186 98 has on_pause => (
187 is => 'rw',
188 isa => 'CodeRef',
189 predicate => 'has_on_pause',
190 );
191  
192  
193 98 has on_wait_for => (
194 is => 'rw',
195 isa => 'CodeRef',
196 predicate => 'has_on_wait_for',
197 );
198  
199  
200 98 has _continuation => (
201 is => 'rw',
202 predicate => 'has_continuation',
203 clearer => 'clear_continuation',
204 );
205  
206 # A requested cancel (ADR 0009): the flag, and a future completed on the
207 # loop that the waits of a raid race against.
208 98 has cancel_requested => (
209 is => 'ro',
210 isa => 'Bool',
211 init_arg => undef,
212 default => 0,
213 writer => '_set_cancel_requested',
214 );
215  
216 has _cancel_f => (
217 is => 'rw',
218 init_arg => undef,
219 lazy => 1,
220 155 ▶ default => sub { Future->new },
Subroutine __ANON__: called CC=1 SCAR=0.0
221 98 clearer => '_clear_cancel_f',
222 );
223  
224  
225 15 ▶sub cancel {
Subroutine cancel: called CC=3 SCAR=11.0
Pod documented
226 15 my ( $self ) = @_;
227 15 ▶ return if $self->cancel_requested;
Branch: 1 branch
BranchTrueFalseTotal
if $self->cancel_requested 0 15 15
228 15 $self->_set_cancel_requested(1);
229 # Only once a raid has waited on the loop is there a wait to wake up.
230 15 ▶ syswrite $self->_cancel_wake->{write}, 'c' if $self->_has_cancel_wake;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_has_cancel_wake 12 3 15
231 15 return;
232 }
233  
234 # A pipe on the raid's loop (ADR 0016: one loop): cancel writes to it, and
235 # the loop completes the cancel future. A signal alone does not wake the
236 # loop: IO::Async::Loop::Poll polls again after EINTR, with the same timeout.
237 98 has _cancel_wake => (
238 is => 'ro',
239 init_arg => undef,
240 lazy => 1,
241 builder => '_build_cancel_wake',
242 predicate => '_has_cancel_wake',
243 );
244  
245 127 ▶sub _build_cancel_wake {
Subroutine _build_cancel_wake: called CC=4 SCAR=14.1
246 127 my ( $self ) = @_;
247 127 ▶ my ( $read, $write ) = IO::Async::OS->pipepair or croak "Raider cancel pipe: $!";
Branch: 1 branch
BranchTrueFalseTotal
() = "IO::Async::OS"->pipepair or croak("Raider cancel pipe: $!") 127 0 127
248 127 $write->blocking(0);
249 127 weaken(my $weak = $self);
250 my $handle = IO::Async::Handle->new(
251 read_handle => $read,
252 8 ▶ on_read_ready => sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
253 8 sysread $read, my $buffer, 512;
254 8 ▶ my $raider = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $raider = $weak or return 8 0 8
255 8 my $f = $raider->_cancel_f;
256 8 ▶ $f->done if $raider->cancel_requested && !$f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $raider->cancel_requested and not $f->is_ready 5 3 8
Condition66%2/3
$raider->cancel_requested and not $f->is_ready
!ll&&!rl&&r
305
MC/DC50%1/2
$raider->cancel_requested and not $f->is_ready
$raider->cancel_requested not $f->is_ready
Truth table66%2/3
A and not(B)
A= $raider->cancel_requestedB= not $f->is_ready
ABresult
0X0
100
111
257 },
258 127 );
259 127 my $engine = $self->engine;
260 127 ▶ ( ( $engine->can('async_loop') && $engine->async_loop ) || IO::Async::Loop->new )->add($handle);
Condition66%4/6
$engine->can('async_loop') && $engine->async_loop || 'IO::Async::Loop'->new
l!l&&r!l&&!r
12250
$engine->can("async_loop") and $engine->async_loop
!ll&&!rl&&r
05122
MC/DC0%0/3
$engine->can('async_loop') && $engine->async_loop || 'IO::Async::Loop'->new
$engine->can("async_loop") $engine->async_loop 'IO::Async::Loop'->new
Truth table40%2/5
A and B || C
A= $engine->can("async_loop")B= $engine->async_loopC= 'IO::Async::Loop'->new
ABCresult
11X1
0X11
1011
0X00
1000
261 127 return { write => $write, handle => $handle };
262 }
263  
264 # The cancel pipe leaves the loop with the raider; at global destruction
265 # the process ends anyway.
266 234 ▶sub DEMOLISH {
Subroutine DEMOLISH: called CC=6 SCAR=18.5
Pod undocumented
267 234 my ( $self, $in_global_destruction ) = @_;
268 234 ▶ return if $in_global_destruction || !$self->_has_cancel_wake;
Branch: 1 branch
BranchTrueFalseTotal
if $in_global_destruction or not $self->_has_cancel_wake 165 69 234
Condition66%2/3
$in_global_destruction or not $self->_has_cancel_wake
l!l&&r!l&&!r
016569
MC/DC50%1/2
$in_global_destruction or not $self->_has_cancel_wake
$in_global_destruction not $self->_has_cancel_wake
Truth table66%2/3
A or not(B)
A= $in_global_destructionB= not $self->_has_cancel_wake
ABresult
1X1
011
000
269 69 my $wake = $self->_cancel_wake;
270 69 ▶ my $handle = $wake->{handle} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $handle = $$wake{"handle"} or return 69 0 69
271 69 ▶ $handle->loop->remove($handle) if $handle->loop;
Branch: 1 branch
BranchTrueFalseTotal
if $handle->loop 69 0 69
272 69 $handle->close;
273 69 ▶ close $wake->{write} if $wake->{write};
Branch: 1 branch
BranchTrueFalseTotal
if $$wake{"write"} 69 0 69
274 69 return;
275 }
276  
277 # The future $f, or nothing as soon as a cancel is requested: then $f is
278 # cancelled.
279 398 ▶sub _until_cancelled {
Subroutine _until_cancelled: called CC=3 SCAR=11.0
280 398 my ( $self, $f ) = @_;
281 398 $self->_cancel_wake; # on the loop before the raid waits
282 398 my $cancel_f = $self->_cancel_f;
283 398 ▶ $cancel_f->done if $self->cancel_requested && !$cancel_f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $self->cancel_requested and not $cancel_f->is_ready 4 394 398
Condition66%2/3
$self->cancel_requested and not $cancel_f->is_ready
!ll&&!rl&&r
39404
MC/DC50%1/2
$self->cancel_requested and not $cancel_f->is_ready
$self->cancel_requested not $cancel_f->is_ready
Truth table66%2/3
A and not(B)
A= $self->cancel_requestedB= not $cancel_f->is_ready
ABresult
0X0
100
111
284 398 return Future->wait_any($f, $cancel_f->without_cancel);
285 }
286  
287  
288 305 ▶sub clear_cancel {
Subroutine clear_cancel: called CC=1 SCAR=0.0
Pod documented
289 305 my ( $self ) = @_;
290 305 $self->_set_cancel_requested(0);
291 305 $self->_clear_cancel_f;
292 305 return;
293 }
294  
295 # Ends the cancel request when a raid (or respond) has ended.
296 163 ▶sub _end_raid {
Subroutine _end_raid: called CC=1 SCAR=0.0
297 163 my ( $self, $f ) = @_;
298 163 ▶ return $f->on_ready(sub { $self->clear_cancel });
Subroutine __ANON__: called CC=1 SCAR=0.0
299 }
300  
301 # The result of a raid stopped by a cancel, metrics finalized as for abort.
302 14 ▶sub _cancelled_result {
Subroutine _cancelled_result: called CC=1 SCAR=0.0
303 14 my ( $self, $state ) = @_;
304 14 my $m = $self->metrics;
305 14 $m->{iterations} += ${ $state->{raid_iterations} };
306 14 $m->{tool_calls} += ${ $state->{raid_tool_calls} };
307 14 $m->{time_ms} += tv_interval($state->{t0}) * 1000;
308 14 return Langertha::Raider::Result->cancelled('Cancelled');
309 }
310  
311 # Whether a cancel cut off the tool call $call_f: it was abandoned, or it
312 # ended with an error after the cancel was requested -- ended by the
313 # canceller, as a tool subprocess the CLI terminates. A call that succeeds
314 # keeps its result.
315 149 ▶sub _cut_off {
Subroutine _cut_off: called CC=5 SCAR=16.1
316 149 my ( $self, $call_f, $result ) = @_;
317 149 ▶ return 1 unless $call_f->is_done;
Branch: 1 branch
BranchTrueFalseTotal
unless $call_f->is_done 2 147 149
318 147 ▶ return $self->cancel_requested && ref $result eq 'HASH' && $result->{isError} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->cancel_requested && ref $result eq 'HASH' && $$result{'isError'} ? : 4 143 147
Condition83%5/6
$self->cancel_requested and ref $result eq "HASH" and $$result{"isError"}
!ll&&!rl&&r
14124
$self->cancel_requested and ref $result eq "HASH"
!ll&&!rl&&r
14106
MC/DC66%2/3
$self->cancel_requested and ref $result eq "HASH" and $$result{"isError"}
$self->cancel_requested ref $result eq "HASH" $$result{"isError"}
Truth table75%3/4
A and B and C
A= $self->cancel_requestedB= ref $result eq "HASH"C= $$result{"isError"}
ABCresult
0XX0
10X0
1100
1111
319 }
320  
321 # The result of a tool call cut off by a cancel.
322 7 ▶sub _cancelled_tool_result {
Subroutine _cancelled_tool_result: called CC=1 SCAR=0.0
323 7 my ( $self, $name ) = @_;
324 return {
325 7 content => [{ type => 'text', text => "Tool call '$name' was cancelled." }],
326 isError => JSON->true,
327 cancelled => 1,
328 };
329 }
330  
331 has tools => (
332 is => 'ro',
333 isa => 'ArrayRef[HashRef]',
334 297 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
335 98 );
336  
337  
338 has mcp_catalog => (
339 is => 'ro',
340 isa => 'HashRef',
341 317 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
342 98 );
343  
344  
345 has engine_catalog => (
346 is => 'ro',
347 isa => 'HashRef',
348 313 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
349 98 );
350  
351  
352 98 has _active_engine => (
353 is => 'rw',
354 predicate => '_has_active_engine',
355 clearer => '_clear_active_engine',
356 );
357  
358 98 has _active_engine_name => (
359 is => 'rw',
360 isa => 'Maybe[Str]',
361 default => undef,
362 );
363  
364 has _active_catalog_mcps => (
365 is => 'ro',
366 isa => 'HashRef',
367 318 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
368 98 );
369  
370 98 has _tools_dirty => (
371 is => 'rw',
372 isa => 'Bool',
373 default => 0,
374 );
375  
376 # The gate step of ADR 0005's one execution path ("check policy", k121): a
377 # CodeRef the code that builds the raider hands in. Every tool call about to
378 # run -- after plugin_before_tool_call and the inputSchema check -- is put to it
379 # as its canonical call:
380 # $gate->( $raider, { name => ..., source => ..., arguments => ... } )
381 # source is where the call runs: 'raider' (self-tools), 'inline', 'engine:N'
382 # (the engine's Nth MCP server), 'catalog:NAME'; undef for a tool no source
383 # offers. It answers { verdict => 'allow' }, { verdict => 'deny', reason => ... }
384 # or { verdict => 'ask', reason => ... }. Without a gate every call runs.
385 # Read-only and constructor-only on purpose: nothing a raid carries -- model
386 # output, a plugin, a manifest -- sets or changes it (ADR 0005: permissions
387 # never come from prompts). Internal (ADR 0017); no policy format yet.
388 98 has _tool_gate => (
389 is => 'ro',
390 isa => 'CodeRef',
391 predicate => '_has_tool_gate',
392 );
393  
394 98 has _inline_mcp => (
395 is => 'rw',
396 predicate => 'has_inline_mcp',
397 );
398  
399 98 has embedding_engine => (
400 is => 'ro',
401 predicate => 'has_embedding_engine',
402 );
403  
404  
405 has no_session_embeddings => (
406 is => 'ro',
407 262 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
408 98 );
409  
410  
411 has _session_embeddings => (
412 is => 'ro',
413 isa => 'ArrayRef',
414 318 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
415 98 );
416  
417 # The in-flight simple_embedding_f futures of _embed_session_slot, keyed by
418 # refaddr. Held here so none is lost to GC mid-request; each removes itself
419 # when ready, clear_session_history cancels the rest.
420 has _pending_embeddings => (
421 is => 'ro',
422 isa => 'HashRef',
423 318 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
424 98 );
425  
426 318 ▶sub BUILD {
Subroutine BUILD: called CC=3 SCAR=11.0
Pod undocumented
427 318 my ( $self ) = @_;
428  
429 # Auto-activate catalog MCPs with auto => 1
430 318 for my $name (keys %{$self->mcp_catalog}) {
431 2 my $entry = $self->mcp_catalog->{$name};
432 2 ▶ if ($entry->{auto}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$entry{"auto"}) 1 1 2
433 1 $self->_active_catalog_mcps->{$name} = $entry->{server};
434 }
435 }
436 }
437  
438 5 ▶sub clear_history {
Subroutine clear_history: called CC=1 SCAR=0.0
Pod documented
439 5 my ( $self ) = @_;
440 5 $self->history([]);
441 5 splice @{$self->_injections};
442 5 return $self;
443 }
444  
445  
446 5 ▶sub clear_session_history {
Subroutine clear_session_history: called CC=2 SCAR=6.9
Pod documented
447 5 my ( $self ) = @_;
448 5 splice @{$self->session_history};
449 5 splice @{$self->_session_embeddings};
450 # Their vectors would belong to entries that are gone: stop the requests.
451 5 my $pending = $self->_pending_embeddings;
452 5 my @inflight = values %$pending;
453 5 %$pending = ();
454 5 $_->cancel for grep { !$_->is_ready } @inflight;
455 5 return $self;
456 }
457  
458  
459 22 ▶sub add_history {
Subroutine add_history: called CC=1 SCAR=0.0
Pod documented
460 22 my ( $self, $role, $content ) = @_;
461 22 push @{$self->history}, { role => $role, content => $content };
462 22 return $self;
463 }
464  
465  
466 16 ▶sub add_session_history {
Subroutine add_session_history: called CC=1 SCAR=0.0
Pod documented
467 16 my ( $self, @entries ) = @_;
468 16 $self->_push_session_history(@entries);
469 16 return $self;
470 }
471  
472  
473 1 ▶sub inject {
Subroutine inject: called CC=1 SCAR=0.0
Pod documented
474 1 my ( $self, @messages ) = @_;
475 1 push @{$self->_injections}, @messages;
476 1 return $self;
477 }
478  
479  
480 1 ▶sub reset {
Subroutine reset: called CC=1 SCAR=0.0
Pod documented
481 1 my ( $self ) = @_;
482 1 $self->clear_history;
483 1 $self->_clear_active_engine;
484 1 $self->_active_engine_name(undef);
485 1 $self->metrics({
486 raids => 0, iterations => 0, tool_calls => 0, time_ms => 0,
487 });
488 1 return $self;
489 }
490  
491  
492 304 ▶sub active_engine {
Subroutine active_engine: called CC=2 SCAR=6.9
Pod documented
493 304 my ($self) = @_;
494 304 ▶ return $self->_has_active_engine ? $self->_active_engine : $self->engine;
Branch: 1 branch
BranchTrueFalseTotal
$self->_has_active_engine ? : 8 296 304
495 }
496  
497  
498 11 ▶sub active_engine_name {
Subroutine active_engine_name: called CC=1 SCAR=0.0
Pod documented
499 11 my ($self) = @_;
500 11 return $self->_active_engine_name;
501 }
502  
503  
504 10 ▶sub switch_engine {
Subroutine switch_engine: called CC=3 SCAR=11.0
Pod documented
505 10 my ($self, $name) = @_;
506 croak "Engine '$name' not found in engine_catalog"
507 10 ▶ unless exists $self->engine_catalog->{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->engine_catalog->{$name} 1 9 10
508 9 my $entry = $self->engine_catalog->{$name};
509 9 ▶ my $engine = $entry->{engine} // $self->engine;
Condition66%2/3
$$entry{"engine"} // $self->engine
l!l&&r!l&&!r
720
MC/DC0%0/2
$$entry{"engine"} // $self->engine
$$entry{"engine"} $self->engine
Truth table66%2/3
A // B
A= $$entry{"engine"}B= $self->engine
ABresult
1X1
011
000
510 9 $self->_active_engine($engine);
511 9 $self->_active_engine_name($name);
512 9 $self->_tools_dirty(1);
513 9 return $engine;
514 }
515  
516  
517 7 ▶sub reset_engine {
Subroutine reset_engine: called CC=1 SCAR=0.0
Pod documented
518 7 my ($self) = @_;
519 7 $self->_clear_active_engine;
520 7 $self->_active_engine_name(undef);
521 7 $self->_tools_dirty(1);
522 7 return $self->engine;
523 }
524  
525  
526 7 ▶sub engine_info {
Subroutine engine_info: called CC=3 SCAR=11.1
Pod documented
527 7 my ($self) = @_;
528 7 my $engine = $self->active_engine;
529 return {
530 7 ▶ name => $self->_active_engine_name // 'default',
Branch: 1 branch
BranchTrueFalseTotal
$engine->can('chat_model') ? : 7 0 7
Condition100%2/2
$self->_active_engine_name // "default"
l!l
43
MC/DC100%1/1
$self->_active_engine_name // "default"
$self->_active_engine_name
Truth table100%2/2
A
A= $self->_active_engine_name
Aresult
11
00
531 class => ref $engine,
532 model => $engine->can('chat_model') ? $engine->chat_model : undef,
533 };
534 }
535  
536  
537 2 ▶sub list_engines {
Subroutine list_engines: called CC=4 SCAR=14.0
Pod documented
538 2 my ($self) = @_;
539 2 my %list;
540 $list{default} = {
541 2 engine => $self->engine,
542 active => !$self->_has_active_engine,
543 };
544 2 for my $name (keys %{$self->engine_catalog}) {
545 6 my $entry = $self->engine_catalog->{$name};
546 $list{$name} = {
547 engine => $entry->{engine} // $self->engine,
548 description => $entry->{description},
549 6 ▶ active => (defined $self->_active_engine_name && $self->_active_engine_name eq $name),
Condition66%4/6
$$entry{"engine"} // $self->engine
l!l&&r!l&&!r
420
defined $self->_active_engine_name && $self->_active_engine_name eq $name
!ll&&!rl&&r
042
MC/DC0%0/2
$$entry{"engine"} // $self->engine
$$entry{"engine"} $self->engine
MC/DC50%1/2
defined $self->_active_engine_name && $self->_active_engine_name eq $name
defined $self->_active_engine_name $self->_active_engine_name eq $name
Truth table66%2/3
A // B
A= $$entry{"engine"}B= $self->engine
ABresult
1X1
011
000
Truth table66%2/3
A && B
A= defined $self->_active_engine_nameB= $self->_active_engine_name eq $name
ABresult
0X0
100
111
550 };
551 }
552 2 return \%list;
553 }
554  
555  
556 2 ▶sub add_engine {
Subroutine add_engine: called CC=1 SCAR=0.0
Pod documented
557 2 my ( $self, $name, %opts ) = @_;
558 2 $self->engine_catalog->{$name} = \%opts;
559 2 $self->_tools_dirty(1);
560 2 return;
561 }
562  
563  
564 3 ▶sub remove_engine {
Subroutine remove_engine: called CC=4 SCAR=13.9
Pod documented
565 3 my ( $self, $name ) = @_;
566 croak "Engine '$name' not found in engine_catalog"
567 3 ▶ unless exists $self->engine_catalog->{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->engine_catalog->{$name} 1 2 3
568 2 ▶ if (defined $self->_active_engine_name && $self->_active_engine_name eq $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->_active_engine_name and $self->_active_engine_name eq $name) 1 1 2
Condition66%2/3
defined $self->_active_engine_name and $self->_active_engine_name eq $name
!ll&&!rl&&r
101
MC/DC50%1/2
defined $self->_active_engine_name and $self->_active_engine_name eq $name
defined $self->_active_engine_name $self->_active_engine_name eq $name
Truth table66%2/3
A and B
A= defined $self->_active_engine_nameB= $self->_active_engine_name eq $name
ABresult
0X0
100
111
569 1 $self->reset_engine;
570 }
571 2 delete $self->engine_catalog->{$name};
572 2 $self->_tools_dirty(1);
573 2 return;
574 }
575  
576  
577 6 ▶async sub compress_history_f {
Subroutine compress_history_f: called CC=5 SCAR=16.1
Pod documented
578 6 my ( $self ) = @_;
579 6 my @history = @{$self->history};
580 6 ▶ return unless @history;
Branch: 1 branch
BranchTrueFalseTotal
unless @history 0 6 6
581  
582 6 ▶ my $engine = $self->has_compression_engine
Branch: 1 branch
BranchTrueFalseTotal
$self->has_compression_engine ? : 3 3 6
583 ? $self->compression_engine : $self->engine;
584  
585 6 my @messages = (
586 { role => 'system', content => $self->compression_prompt },
587 @history,
588 { role => 'user', content => 'Provide a concise summary.' },
589 );
590  
591 6 my $request = $engine->chat_request(\@messages);
592 6 my $response = await $engine->async_request_f($request);
593  
594 # Read the summary through the engine's public chat_response (core ADR 0028),
595 # the parser chat_f uses: an error carried in a 200 body croaks instead of
596 # yielding '' silently, and Gemini thought parts / <think> tags stay out of the
597 # text -- the same reasons the tool loop reads its replies via
598 # tool_loop_response (karr k85). This is a plain (non-tool) chat, so
599 # chat_response is the right hook, not tool_loop_response. A duck-typed engine
600 # that lacks chat_response (the in-process test fixtures) falls back to the
601 # legacy response_text_content, which never croaks.
602 6 my $summary;
603 6 ▶ if ( $engine->can('chat_response') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine->can('chat_response')) { } 2 4 6
604 2 ▶ $summary = $engine->chat_response($response)->content // '';
Condition50%1/2
$engine->chat_response($response)->content // ""
l!l
10
MC/DC0%0/1
$engine->chat_response($response)->content // ""
$engine->chat_response($response)->content
Truth table50%1/2
A
A= $engine->chat_response($response)->content
Aresult
11
00
605 } else {
606 4 my $data = $engine->parse_response($response);
607 4 $summary = $engine->response_text_content($data);
608 }
609  
610 # Replace working history with summary
611 5 $self->history([
612 { role => 'assistant', content => $summary },
613 ]);
614  
615 # Mark compression event in session_history — through the pusher, so the
616 # marker gets its embedding slot like every other message.
617 5 $self->_push_session_history({
618 role => 'system',
619 content => '[Context compressed — history summarized]',
620 });
621  
622 5 return $summary;
623 98 }
624  
625  
626 4 ▶sub compress_history {
Subroutine compress_history: called CC=1 SCAR=0.0
Pod documented
627 4 my ( $self ) = @_;
628 4 return $self->compress_history_f->get;
629 }
630  
631  
632 # --- Session history rendering (karr #96) ---
633 #
634 # session_history holds whatever the engine's format_tool_results() put on the
635 # wire, so an element's shape follows the engine's tool_wire_format: only the
636 # openai / ollama / hermes dialects give every element a {role} plus a
637 # plain-string {content}. Anthropic content is an ArrayRef of blocks, Gemini
638 # keeps its blocks under {parts}, and OpenAI Responses items have no {role} at
639 # all — they are discriminated by {type} (function_call, function_call_output,
640 # reasoning). Both readers of the history (the MCP tool registered by
641 # register_session_history_tool and the raider_session_history self-tool)
642 # render through the helpers below, so they cannot drift apart again.
643  
644 98 my $history_json = JSON->new->canonical(1)->allow_nonref(1);
645  
646 # Compact a tool-call argument payload for display: an already-serialized
647 # argument string (OpenAI, Responses) passes through, a structure (Anthropic
648 # input, Gemini args) gets canonical JSON.
649 39 ▶sub _render_history_args {
Subroutine _render_history_args: called CC=4 SCAR=14.0
650 39 my ( $args ) = @_;
651 39 ▶ return '' unless defined $args;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args 0 39 39
652 39 ▶ return $args unless ref $args;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args 23 16 39
653 16 my $encoded = eval { $history_json->encode($args) };
654 16 ▶ return defined $encoded ? $encoded : "$args";
Branch: 1 branch
BranchTrueFalseTotal
defined $encoded ? : 16 0 16
655 }
656  
657 34 ▶sub _render_history_tool_call {
Subroutine _render_history_tool_call: called CC=3 SCAR=13.1
658 34 my ( $name, $args ) = @_;
659 34 ▶ return sprintf 'tool_call %s(%s)',
Branch: 1 branch
BranchTrueFalseTotal
defined $name && length $name ? : 34 0 34
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
0034
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
660 ( defined $name && length $name ? $name : '?' ),
661 _render_history_args($args);
662 }
663  
664 # Flatten one wire block to text. The text rule is the one
665 # Langertha::ToolResult applies for the plain-text formats (to_gemini /
666 # to_hermes): a text part carries its text under ->{text}. Unlike a wire
667 # serializer this renderer must not swallow the non-text blocks — a tool call
668 # is named, never dropped, so an element that is only a tool call still shows
669 # up as something readable.
670 178 ▶sub _render_history_block {
Subroutine _render_history_block: called CC=53 SCAR=44.2
671 178 my ( $block ) = @_;
672 178 ▶ return '' unless defined $block;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $block 0 178 178
673 178 ▶ return "$block" unless ref $block eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $block eq "HASH" 0 178 178
674  
675 178 ▶ return $block->{text} if defined $block->{text} && !ref $block->{text};
Branch: 1 branch
BranchTrueFalseTotal
if defined $$block{"text"} and not ref $$block{"text"} 55 123 178
Condition66%2/3
defined $$block{"text"} and not ref $$block{"text"}
!ll&&!rl&&r
123055
MC/DC50%1/2
defined $$block{"text"} and not ref $$block{"text"}
defined $$block{"text"} not ref $$block{"text"}
Truth table66%2/3
A and not(B)
A= defined $$block{"text"}B= not ref $$block{"text"}
ABresult
0X0
100
111
676 123 ▶ return $block->{thinking} if defined $block->{thinking} && !ref $block->{thinking};
Branch: 1 branch
BranchTrueFalseTotal
if defined $$block{"thinking"} and not ref $$block{"thinking"} 0 123 123
Condition33%1/3
defined $$block{"thinking"} and not ref $$block{"thinking"}
!ll&&!rl&&r
12300
MC/DC0%0/2
defined $$block{"thinking"} and not ref $$block{"thinking"}
defined $$block{"thinking"} not ref $$block{"thinking"}
Truth table33%1/3
A and not(B)
A= defined $$block{"thinking"}B= not ref $$block{"thinking"}
ABresult
0X0
100
111
677  
678 # Gemini parts key their call/response by name instead of carrying a {type}.
679 123 ▶ if ( ref $block->{functionCall} eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $$block{"functionCall"} eq "HASH") 5 118 123
680 return _render_history_tool_call(
681 5 $block->{functionCall}{name}, $block->{functionCall}{args} );
682 }
683 118 ▶ if ( ref $block->{functionResponse} eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $$block{"functionResponse"} eq "HASH") 16 102 118
684 16 my $response = $block->{functionResponse}{response};
685 # A bare {result} is Langertha's string form; any other hash is the tool's
686 # MCP structuredContent (langertha k336) and renders whole, as JSON.
687 my $result = ref $response eq 'HASH'
688 && keys %$response == 1 && exists $response->{result}
689 16 ▶ ? $response->{result} : $response;
Branch: 1 branch
BranchTrueFalseTotal
ref $response eq 'HASH' && keys %$response == 1 && exists $$response{'result'} ? : 11 5 16
Condition66%4/6
ref $response eq "HASH" and keys %$response == 1 and exists $$response{"result"}
!ll&&!rl&&r
5011
ref $response eq "HASH" and keys %$response == 1
!ll&&!rl&&r
0511
MC/DC33%1/3
ref $response eq "HASH" and keys %$response == 1 and exists $$response{"result"}
ref $response eq "HASH" keys %$response == 1 exists $$response{"result"}
Truth table50%2/4
A and B and C
A= ref $response eq "HASH"B= keys %$response == 1C= exists $$response{"result"}
ABCresult
0XX0
10X0
1100
1111
690 # Gemini 3 carries a tool-result image beside the result string in
691 # functionResponse.parts[].inlineData (langertha k344).
692 32 ▶ return 'tool_result: ' . join "\n", grep { length }
Branch: 1 branch
BranchTrueFalseTotal
defined $result && !ref($result) ? : 11 5 16
Condition66%2/3
defined $result and not ref $result
!ll&&!rl&&r
0511
MC/DC50%1/2
defined $result and not ref $result
defined $result not ref $result
Truth table66%2/3
A and not(B)
A= defined $resultB= not ref $result
ABresult
0X0
100
111
693 ( defined $result && !ref $result ? $result : _render_history_args($result) ),
694 16 _render_history_payload_value( $block->{functionResponse}{parts} );
695 }
696 # An image is named, never dumped as base64.
697 return '[image]'
698 if ref $block->{inlineData} eq 'HASH'
699 102 ▶ && ( $block->{inlineData}{mimeType} // '' ) =~ m{^image/};
Branch: 1 branch
BranchTrueFalseTotal
if ref $$block{"inlineData"} eq "HASH" and ($$block{"inlineData"}{"mimeType"} // "") =~ m[^image/] 4 98 102
Condition80%4/5
ref $$block{"inlineData"} eq "HASH" and ($$block{"inlineData"}{"mimeType"} // "") =~ m[^image/]
!ll&&!rl&&r
9714
$$block{"inlineData"}{"mimeType"} // ""
l!l
50
MC/DC50%1/2
ref $$block{"inlineData"} eq "HASH" and ($$block{"inlineData"}{"mimeType"} // "") =~ m[^image/]
ref $$block{"inlineData"} eq "HASH" $$block{"inlineData"}{"mimeType"}
Truth table66%2/3
A and B
A= ref $$block{"inlineData"} eq "HASH"B= $$block{"inlineData"}{"mimeType"}
ABresult
0X0
100
111
700 # Any other inlineData (a tool-result PDF, langertha k361) is named by its
701 # MIME type, never dumped.
702 return '[document] ' . $block->{inlineData}{mimeType}
703 if ref $block->{inlineData} eq 'HASH'
704 98 ▶ && defined $block->{inlineData}{mimeType} && length $block->{inlineData}{mimeType};
Branch: 1 branch
BranchTrueFalseTotal
if ref $$block{"inlineData"} eq "HASH" and defined $$block{"inlineData"}{"mimeType"} and length $$block{"inlineData"}{"mimeType"} 1 97 98
Condition66%4/6
ref $$block{"inlineData"} eq "HASH" and defined $$block{"inlineData"}{"mimeType"} and length $$block{"inlineData"}{"mimeType"}
!ll&&!rl&&r
9701
ref $$block{"inlineData"} eq "HASH" and defined $$block{"inlineData"}{"mimeType"}
!ll&&!rl&&r
9701
MC/DC33%1/3
ref $$block{"inlineData"} eq "HASH" and defined $$block{"inlineData"}{"mimeType"} and length $$block{"inlineData"}{"mimeType"}
ref $$block{"inlineData"} eq "HASH" defined $$block{"inlineData"}{"mimeType"} length $$block{"inlineData"}{"mimeType"}
Truth table50%2/4
A and B and C
A= ref $$block{"inlineData"} eq "HASH"B= defined $$block{"inlineData"}{"mimeType"}C= length $$block{"inlineData"}{"mimeType"}
ABCresult
0XX0
10X0
1100
1111
705  
706 97 ▶ my $type = $block->{type} // '';
Condition50%1/2
$$block{"type"} // ""
l!l
970
MC/DC0%0/1
$$block{"type"} // ""
$$block{"type"}
Truth table50%1/2
A
A= $$block{"type"}
Aresult
11
00
707  
708 # Tool invocations: Anthropic tool_use, Responses function_call, and the
709 # OpenAI/Ollama {function=>{...}} entry from an assistant echo.
710 return _render_history_tool_call( $block->{name}, $block->{input} )
711 97 ▶ if $type eq 'tool_use';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "tool_use" 6 91 97
712 return _render_history_tool_call( $block->{name}, $block->{arguments} )
713 91 ▶ if $type eq 'function_call';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "function_call" 14 77 91
714 return _render_history_tool_call(
715 $block->{function}{name}, $block->{function}{arguments} )
716 77 ▶ if ref $block->{function} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $$block{"function"} eq "HASH" 9 68 77
717  
718 # Tool results: Anthropic nests the MCP content array, the Responses item
719 # carries the same payload JSON-encoded in {output} -- or, with an image,
720 # as an input_text / input_image part array (langertha k344).
721 68 ▶ if ( $type eq 'tool_result' || $type eq 'function_call_output' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "tool_result" or $type eq "function_call_output") 33 35 68
Condition100%3/3
$type eq "tool_result" or $type eq "function_call_output"
l!l&&r!l&&!r
221135
MC/DC100%2/2
$type eq "tool_result" or $type eq "function_call_output"
$type eq "tool_result" $type eq "function_call_output"
Truth table100%3/3
A or B
A= $type eq "tool_result"B= $type eq "function_call_output"
ABresult
1X1
011
000
722 return 'tool_result: '
723 . _render_history_payload_value(
724 33 ▶ defined $block->{output} ? $block->{output} : $block->{content} );
Branch: 1 branch
BranchTrueFalseTotal
defined $$block{'output'} ? : 11 22 33
725 }
726 # Responses input_image, Anthropic image (langertha k326).
727 35 ▶ return '[image]' if $type eq 'input_image' || $type eq 'image';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "input_image" or $type eq "image" 5 30 35
Condition100%3/3
$type eq "input_image" or $type eq "image"
l!l&&r!l&&!r
3230
MC/DC100%2/2
$type eq "input_image" or $type eq "image"
$type eq "input_image" $type eq "image"
Truth table100%3/3
A or B
A= $type eq "input_image"B= $type eq "image"
ABresult
1X1
011
000
728 # Responses input_file (a tool-result PDF, langertha k361): named by its
729 # filename, never the file_data / data: URL.
730 return defined $block->{filename} && !ref $block->{filename} && length $block->{filename}
731 30 ▶ ? '[document] ' . $block->{filename} : '[document]'
Branch: 2 branches
BranchTrueFalseTotal
if $type eq "input_file" 2 28 30
defined $$block{'filename'} && !ref($$block{'filename'}) && length $$block{'filename'} ? : 1 1 2
Condition66%4/6
defined $$block{"filename"} and not ref $$block{"filename"} and length $$block{"filename"}
!ll&&!rl&&r
101
defined $$block{"filename"} and not ref $$block{"filename"}
!ll&&!rl&&r
101
MC/DC33%1/3
defined $$block{"filename"} and not ref $$block{"filename"} and length $$block{"filename"}
defined $$block{"filename"} not ref $$block{"filename"} length $$block{"filename"}
Truth table50%2/4
A and not(B) and C
A= defined $$block{"filename"}B= not ref $$block{"filename"}C= length $$block{"filename"}
ABCresult
0XX0
10X0
1100
1111
732 if $type eq 'input_file';
733  
734 # Anthropic document (langertha k326): a text source gives its text, a
735 # content source (Citations custom content) its chunks, any other source
736 # (base64 PDF, url, file) is named, never dumped. The optional context the
737 # model reads beside it gets a line of its own.
738 28 ▶ if ( $type eq 'document' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "document") 24 4 28
739 24 ▶ my $source = ref $block->{source} eq 'HASH' ? $block->{source} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $$block{'source'} eq 'HASH' ? : 24 0 24
740 24 ▶ my $source_type = $source->{type} // '';
Condition50%1/2
$$source{"type"} // ""
l!l
240
MC/DC0%0/1
$$source{"type"} // ""
$$source{"type"}
Truth table50%1/2
A
A= $$source{"type"}
Aresult
11
00
741 24 ▶ my $has_title = defined $block->{title} && length $block->{title};
Condition66%2/3
defined $$block{'title'} && length $$block{'title'}
!ll&&!rl&&r
1707
MC/DC50%1/2
defined $$block{'title'} && length $$block{'title'}
defined $$block{'title'} length $$block{'title'}
Truth table66%2/3
A && B
A= defined $$block{'title'}B= length $$block{'title'}
ABresult
0X0
100
111
742 24 ▶ my $marker = $has_title ? '[document] ' . $block->{title} : '[document]';
Branch: 1 branch
BranchTrueFalseTotal
$has_title ? : 7 17 24
743 my $text = $source_type eq 'text' ? $source->{data} // ''
744 : $source_type eq 'content' ? _render_history_payload_value( $source->{content} )
745 24 ▶ : '';
Branch: 2 branches
BranchTrueFalseTotal
$source_type eq 'text' ? : 10 14 24
$source_type eq 'content' ? : 7 7 14
Condition50%1/2
$$source{"data"} // ""
l!l
100
MC/DC0%0/1
$$source{"data"} // ""
$$source{"data"}
Truth table50%1/2
A
A= $$source{"data"}
Aresult
11
00
746 my $context = defined $block->{context} && !ref $block->{context}
747 24 ▶ && length $block->{context} ? '[context] ' . $block->{context} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $$block{'context'} && !ref($$block{'context'}) && length $$block{'context'} ? : 11 13 24
Condition66%4/6
defined $$block{"context"} and not ref $$block{"context"} and length $$block{"context"}
!ll&&!rl&&r
13011
defined $$block{"context"} and not ref $$block{"context"}
!ll&&!rl&&r
13011
MC/DC33%1/3
defined $$block{"context"} and not ref $$block{"context"} and length $$block{"context"}
defined $$block{"context"} not ref $$block{"context"} length $$block{"context"}
Truth table50%2/4
A and not(B) and C
A= defined $$block{"context"}B= not ref $$block{"context"}C= length $$block{"context"}
ABCresult
0XX0
10X0
1100
1111
748 24 ▶ return join "\n", grep { length }
Branch: 1 branch
BranchTrueFalseTotal
$has_title || !length($text) ? : 14 10 24
Condition100%3/3
$has_title or not length $text
l!l&&r!l&&!r
7710
MC/DC100%2/2
$has_title or not length $text
$has_title not length $text
Truth table100%3/3
A or not(B)
A= $has_titleB= not length $text
ABresult
1X1
011
000
749 ( $has_title || !length $text ? $marker : () ), $context, $text;
750 }
751 # Anthropic search_result: title and source URL, then its text blocks.
752 4 ▶ if ( $type eq 'search_result' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "search_result") 4 0 4
753 8 return join "\n", grep { length }
754 12 ▶ join( ' ', grep { defined && length } '[search_result]', $block->{title},
Branch: 1 branch
BranchTrueFalseTotal
defined $$block{'source'} && !ref($$block{'source'}) ? : 4 0 4
Condition33%2/6
defined $_ && length $_
!ll&&!rl&&r
0012
defined $$block{"source"} and not ref $$block{"source"}
!ll&&!rl&&r
004
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
MC/DC0%0/2
defined $$block{"source"} and not ref $$block{"source"}
defined $$block{"source"} not ref $$block{"source"}
Truth table33%1/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
Truth table33%1/3
A and not(B)
A= defined $$block{"source"}B= not ref $$block{"source"}
ABresult
0X0
100
111
755 ( defined $block->{source} && !ref $block->{source}
756 ? '<' . $block->{source} . '>' : () ) ),
757 4 _render_history_payload_value( $block->{content} );
758 }
759  
760 # Unknown block: name it by its discriminator rather than dropping it.
761 0 my $rest = _render_history_payload_value( $block->{content} );
762 0 ▶ return length $rest
Branch: 3 branches
BranchTrueFalseTotal
length $rest ? : 0 0 0
length $type ? : 0 0 0
length $type ? : 0 0 0
763 ? ( length $type ? "<$type> $rest" : $rest )
764 : ( length $type ? "<$type>" : '<block>' );
765 }
766  
767 # Render a {content} / {parts} / {summary} / {tool_calls} payload: a plain
768 # string as-is, an ArrayRef of blocks flattened block by block.
769 250 ▶sub _render_history_payload_value {
Subroutine _render_history_payload_value: called CC=5 SCAR=17.5
770 250 my ( $value ) = @_;
771 250 ▶ return '' unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 11 239 250
772 239 ▶ return "$value" unless ref $value;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value 109 130 239
773 130 ▶ return join( "\n", grep { length } map { _render_history_block($_) } @$value )
Branch: 1 branch
BranchTrueFalseTotal
if ref $value eq "ARRAY" 130 0 130
774 if ref $value eq 'ARRAY';
775 0 ▶ return _render_history_block($value) if ref $value eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $value eq "HASH" 0 0 0
776 0 return "$value";
777 }
778  
779 # The readable body of one history element, without its role/type label. Also
780 # what the query/search filters match against, so a filter reaches the text of
781 # an Anthropic block or a Responses item too.
782 215 ▶sub _render_history_payload {
Subroutine _render_history_payload: called CC=8 SCAR=21.2
783 215 my ( $entry ) = @_;
784 215 ▶ return '' unless defined $entry;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry 0 215 215
785 215 ▶ return "$entry" unless ref $entry eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" 0 215 215
786  
787 215 my @body;
788 215 for my $key (qw( content parts summary tool_calls )) {
789 push @body, _render_history_payload_value( $entry->{$key} )
790 860 ▶ if defined $entry->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if defined $$entry{$key} 190 670 860
791 }
792 # Items that are a block in their own right (Responses function_call /
793 # function_call_output) carry no content payload at all.
794 215 ▶ unless (@body) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@body) 25 190 215
795 25 my $block = _render_history_block($entry);
796 # A bare "<type>" marker would only repeat the label the caller prints.
797 25 ▶ push @body, $block unless $block eq '<' . ( $entry->{type} // '' ) . '>';
Branch: 1 branch
BranchTrueFalseTotal
unless $block eq '<' . ($$entry{"type"} // "") . '>' 25 0 25
Condition50%1/2
$$entry{"type"} // ""
l!l
250
MC/DC0%0/1
$$entry{"type"} // ""
$$entry{"type"}
Truth table50%1/2
A
A= $$entry{"type"}
Aresult
11
00
798 }
799  
800 215 return join "\n", grep { length } @body;
801 }
802  
803 77 ▶sub _render_history_entry {
Subroutine _render_history_entry: called CC=6 SCAR=19.3
804 77 my ( $entry ) = @_;
805 77 ▶ return '' unless defined $entry;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry 0 77 77
806 77 ▶ return "$entry" unless ref $entry eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" 0 77 77
807  
808 77 ▶ my $label = $entry->{role} // $entry->{type} // 'message';
Condition60%3/5
($$entry{"role"} // $$entry{"type"}) // "message"
l!l
770
$$entry{"role"} // $$entry{"type"}
l!l&&r!l&&!r
61160
MC/DC0%0/2
($$entry{"role"} // $$entry{"type"}) // "message"
$$entry{"role"} $$entry{"type"}
Truth table66%2/3
A // B
A= $$entry{"role"}B= $$entry{"type"}
ABresult
1X1
011
000
809 77 my $body = _render_history_payload($entry);
810 77 ▶ return length $body ? "[$label] $body" : "[$label]";
Branch: 1 branch
BranchTrueFalseTotal
length $body ? : 77 0 77
811 }
812  
813 24 ▶sub _render_session_history {
Subroutine _render_session_history: called CC=1 SCAR=0.0
814 24 my ( @hist ) = @_;
815 24 return join "\n\n", map { _render_history_entry($_) } @hist;
816 }
817  
818 1 ▶sub register_session_history_tool {
Subroutine register_session_history_tool: called CC=1 SCAR=0.6
Pod documented
819 1 my ( $self, $server ) = @_;
820 $server->tool(
821 name => 'session_history',
822 description => 'Retrieve the full session history including tool calls.',
823 input_schema => {
824 type => 'object',
825 properties => {
826 query => { type => 'string', description => 'Filter messages containing this text' },
827 last_n => { type => 'integer', description => 'Return only the last N messages' },
828 },
829 },
830 1 ▶ code => sub {
Subroutine __ANON__: called CC=5 SCAR=19.7
831 1 my ( $tool, $args ) = @_;
832 1 my @hist = @{$self->session_history};
833 1 ▶ if (my $q = $args->{query}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $q = $$args{"query"}) 0 1 1
834 0 @hist = grep { _render_history_payload($_) =~ /\Q$q/i } @hist;
835 }
836 1 ▶ if (my $n = $args->{last_n}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $n = $$args{"last_n"}) 0 1 1
837 0 ▶ @hist = @hist[-$n..-1] if @hist > $n;
Branch: 1 branch
BranchTrueFalseTotal
if @hist > $n 0 0 0
838 }
839 1 my $text = _render_session_history(@hist);
840 1 ▶ $tool->text_result($text || 'No messages in session history.');
Condition50%1/2
$text || 'No messages in session history.'
l!l
10
MC/DC0%0/1
$text || 'No messages in session history.'
$text
Truth table50%1/2
A
A= $text
Aresult
11
00
841 },
842 1 );
843 }
844  
845  
846 1 ▶sub _langfuse_model_parameters {
Subroutine _langfuse_model_parameters: called CC=7 SCAR=23.8
847 1 my ( $self, $engine ) = @_;
848 1 ▶ my $e = $engine // $self->active_engine;
Condition33%1/3
$engine // $self->active_engine
l!l&&r!l&&!r
100
MC/DC0%0/2
$engine // $self->active_engine
$engine $self->active_engine
Truth table33%1/3
A // B
A= $engineB= $self->active_engine
ABresult
1X1
011
000
849 1 my %p;
850 1 ▶ $p{temperature} = $e->temperature if $e->can('has_temperature') && $e->has_temperature;
Branch: 1 branch
BranchTrueFalseTotal
if $e->can("has_temperature") and $e->has_temperature 1 0 1
Condition33%1/3
$e->can("has_temperature") and $e->has_temperature
!ll&&!rl&&r
001
MC/DC0%0/2
$e->can("has_temperature") and $e->has_temperature
$e->can("has_temperature") $e->has_temperature
Truth table33%1/3
A and B
A= $e->can("has_temperature")B= $e->has_temperature
ABresult
0X0
100
111
851 1 ▶ $p{max_tokens} = $e->get_response_size if $e->can('get_response_size') && $e->get_response_size;
Branch: 1 branch
BranchTrueFalseTotal
if $e->can("get_response_size") and $e->get_response_size 0 1 1
Condition33%1/3
$e->can("get_response_size") and $e->get_response_size
!ll&&!rl&&r
100
MC/DC0%0/2
$e->can("get_response_size") and $e->get_response_size
$e->can("get_response_size") $e->get_response_size
Truth table33%1/3
A and B
A= $e->can("get_response_size")B= $e->get_response_size
ABresult
0X0
100
111
852 1 ▶ return keys %p ? \%p : undef;
Branch: 1 branch
BranchTrueFalseTotal
keys %p ? : 1 0 1
853 }
854  
855 440 ▶sub _self_tool_enabled {
Subroutine _self_tool_enabled: called CC=5 SCAR=16.2
856 440 my ( $self, $tool_name ) = @_;
857 440 ▶ return 0 unless $self->has_raider_mcp;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_raider_mcp 8 432 440
858 432 my $cfg = $self->raider_mcp;
859 432 ▶ return 1 if !ref $cfg; # truthy scalar = all tools
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cfg 368 64 432
860 64 ▶ return $cfg->{$tool_name} ? 1 : 0 if ref $cfg eq 'HASH';
Branch: 2 branches
BranchTrueFalseTotal
if ref $cfg eq "HASH" 64 0 64
$$cfg{$tool_name} ? : 10 54 64
861 0 return 0;
862 }
863  
864 55 ▶sub _self_tool_definitions {
Subroutine _self_tool_definitions: called CC=10 SCAR=23.0
865 55 my ( $self ) = @_;
866 55 my @tools;
867  
868 55 ▶ if ($self->_self_tool_enabled('ask_user')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("ask_user")) 53 2 55
869 53 push @tools, {
870 name => 'raider_ask_user',
871 description => 'Ask the user a question and wait for their answer. Use this when you need clarification or a decision from the user.',
872 inputSchema => {
873 type => 'object',
874 properties => {
875 question => { type => 'string', description => 'The question to ask the user' },
876 options => { type => 'array', items => { type => 'string' }, description => 'Optional list of choices for the user' },
877 },
878 required => ['question'],
879 },
880 };
881 }
882  
883 55 ▶ if ($self->_self_tool_enabled('wait')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("wait")) 47 8 55
884 47 push @tools, {
885 name => 'raider_wait',
886 description => 'Wait for a specified number of seconds before continuing.',
887 inputSchema => {
888 type => 'object',
889 properties => {
890 seconds => { type => 'number', description => 'Number of seconds to wait' },
891 reason => { type => 'string', description => 'Why you are waiting' },
892 },
893 required => ['seconds'],
894 },
895 };
896 }
897  
898 55 ▶ if ($self->_self_tool_enabled('wait_for')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("wait_for")) 46 9 55
899 46 push @tools, {
900 name => 'raider_wait_for',
901 description => 'Wait for an external condition to be met. The condition is evaluated by the host application.',
902 inputSchema => {
903 type => 'object',
904 properties => {
905 condition => { type => 'string', description => 'Description of the condition to wait for' },
906 args => { type => 'object', description => 'Additional arguments for the condition check' },
907 timeout => { type => 'number', description => 'Timeout in seconds' },
908 },
909 required => ['condition'],
910 },
911 };
912 }
913  
914 55 ▶ if ($self->_self_tool_enabled('pause')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("pause")) 46 9 55
915 46 push @tools, {
916 name => 'raider_pause',
917 description => 'Pause execution and return control to the user. The user can resume later with respond_f.',
918 inputSchema => {
919 type => 'object',
920 properties => {
921 reason => { type => 'string', description => 'Why you are pausing' },
922 },
923 },
924 };
925 }
926  
927 55 ▶ if ($self->_self_tool_enabled('abort')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("abort")) 48 7 55
928 48 push @tools, {
929 name => 'raider_abort',
930 description => 'Abort the current raid. Use only when the task cannot be completed.',
931 inputSchema => {
932 type => 'object',
933 properties => {
934 reason => { type => 'string', description => 'Why you are aborting' },
935 },
936 },
937 };
938 }
939  
940 55 ▶ if ($self->_self_tool_enabled('session_history')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("session_history")) 46 9 55
941 46 push @tools, {
942 name => 'raider_session_history',
943 description => 'Search or retrieve the full session history including tool calls and results.',
944 inputSchema => {
945 type => 'object',
946 properties => {
947 query => { type => 'string', description => 'Filter messages containing this text' },
948 last_n => { type => 'integer', description => 'Return only the last N messages' },
949 search => { type => 'string', description => 'Semantic search query (requires embedding engine)' },
950 },
951 },
952 };
953 }
954  
955 55 ▶ if ($self->_self_tool_enabled('manage_mcps')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("manage_mcps")) 46 9 55
956 46 push @tools, {
957 name => 'raider_manage_mcps',
958 description => 'List, activate, or deactivate MCP tool servers from the catalog.',
959 inputSchema => {
960 type => 'object',
961 properties => {
962 action => { type => 'string', enum => ['list', 'activate', 'deactivate'], description => 'Action to perform' },
963 name => { type => 'string', description => 'Name of the MCP server (for activate/deactivate)' },
964 },
965 required => ['action'],
966 },
967 };
968 }
969  
970 55 ▶ if ($self->_self_tool_enabled('switch_engine') && keys %{$self->engine_catalog}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("switch_engine") and keys %{$self->engine_catalog;}) 3 52 55
Condition100%3/3
$self->_self_tool_enabled("switch_engine") and keys %{$self->engine_catalog;}
!ll&&!rl&&r
9433
MC/DC100%2/2
$self->_self_tool_enabled("switch_engine") and keys %{$self->engine_catalog;}
$self->_self_tool_enabled("switch_engine") keys %{$self->engine_catalog;}
Truth table100%3/3
A and B
A= $self->_self_tool_enabled("switch_engine")B= keys %{$self->engine_catalog;}
ABresult
0X0
100
111
971 3 my @names = ('default', sort keys %{$self->engine_catalog});
972 3 push @tools, {
973 name => 'raider_switch_engine',
974 description => 'Switch to a different AI engine from the catalog. Use "default" to reset to the original engine.',
975 inputSchema => {
976 type => 'object',
977 properties => {
978 name => {
979 type => 'string',
980 enum => \@names,
981 description => 'Name of the engine to switch to',
982 },
983 },
984 required => ['name'],
985 },
986 };
987 }
988  
989 55 return \@tools;
990 }
991  
992 44 ▶async sub _execute_self_tool_f {
Subroutine _execute_self_tool_f: called CC=15 SCAR=27.6
993 44 my ( $self, $name, $input ) = @_;
994 44 my $short = $name;
995 44 $short =~ s/^raider_//;
996  
997 44 ▶ if ($short eq 'ask_user') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "ask_user") 19 25 44
998 19 my $question = $input->{question};
999 19 my $options = $input->{options};
1000 19 ▶ if ($self->has_on_ask_user) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_on_ask_user) 2 17 19
1001 2 my $answer = $self->on_ask_user->($question, $options);
1002 2 return { type => 'result', content => [{ type => 'text', text => "$answer" }] };
1003 }
1004 17 return { type => 'question', question => $question, options => $options };
1005 }
1006  
1007 25 ▶ if ($short eq 'wait') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "wait") 10 15 25
1008 10 ▶ my $seconds = $input->{seconds} // 1;
Condition50%1/2
$$input{"seconds"} // 1
l!l
100
MC/DC0%0/1
$$input{"seconds"} // 1
$$input{"seconds"}
Truth table50%1/2
A
A= $$input{"seconds"}
Aresult
11
00
1009 10 return { type => 'wait', seconds => $seconds, reason => $input->{reason} };
1010 }
1011  
1012 15 ▶ if ($short eq 'wait_for') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "wait_for") 2 13 15
1013 2 ▶ croak "No on_wait_for callback configured" unless $self->has_on_wait_for;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_on_wait_for 1 1 2
1014 1 my $result = $self->on_wait_for->($input->{condition}, $input->{args});
1015 1 return { type => 'result', content => [{ type => 'text', text => "$result" }] };
1016 }
1017  
1018 13 ▶ if ($short eq 'pause') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "pause") 4 9 13
1019 4 ▶ my $reason = $input->{reason} // '';
Condition50%1/2
$$input{"reason"} // ""
l!l
40
MC/DC0%0/1
$$input{"reason"} // ""
$$input{"reason"}
Truth table50%1/2
A
A= $$input{"reason"}
Aresult
11
00
1020 4 ▶ if ($self->has_on_pause) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_on_pause) 1 3 4
1021 1 $self->on_pause->($reason);
1022 1 return { type => 'result', content => [{ type => 'text', text => "Resumed after pause." }] };
1023 }
1024 3 return { type => 'pause', reason => $reason };
1025 }
1026  
1027 9 ▶ if ($short eq 'abort') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "abort") 2 7 9
1028 2 ▶ return { type => 'abort', reason => $input->{reason} // 'Agent aborted' };
Condition50%1/2
$$input{"reason"} // "Agent aborted"
l!l
20
MC/DC0%0/1
$$input{"reason"} // "Agent aborted"
$$input{"reason"}
Truth table50%1/2
A
A= $$input{"reason"}
Aresult
11
00
1029 }
1030  
1031 7 ▶ if ($short eq 'session_history') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "session_history") 3 4 7
1032 3 return { type => 'result', content => [{ type => 'text', text => await $self->_query_session_history_f($input) }] };
1033 }
1034  
1035 4 ▶ if ($short eq 'manage_mcps') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "manage_mcps") 4 0 4
1036 4 return { type => 'result', content => [{ type => 'text', text => $self->_manage_mcps($input) }] };
1037 }
1038  
1039 0 ▶ if ($short eq 'switch_engine') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "switch_engine") 0 0 0
1040 0 return { type => 'result', content => [{ type => 'text', text => $self->_switch_engine_tool($input) }] };
1041 }
1042  
1043 0 die "Unknown self-tool: $name";
1044 98 }
1045  
1046 23 ▶async sub _query_session_history_f {
Subroutine _query_session_history_f: called CC=14 SCAR=26.5
1047 23 my ( $self, $args ) = @_;
1048 23 my $search = $args->{search};
1049  
1050 # Semantic search via embeddings. The vector of history element $i is
1051 # _session_embeddings->[$i], so a length mismatch means the two arrays drifted
1052 # apart (session_history is a public ArrayRef, code outside _push_session_history
1053 # can splice it) — searching a drifted index would answer with the wrong
1054 # message, so degrade to the text search instead of lying. A failed query
1055 # embedding degrades the same way.
1056 23 my $query_vec;
1057 23 ▶ my $engine = $search ? $self->_get_embedding_engine : undef;
Branch: 1 branch
BranchTrueFalseTotal
$search ? : 4 19 23
1058 23 ▶ if ($engine && @{$self->_session_embeddings} == @{$self->session_history}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine and @{$self->_session_embeddings;} == @{$self->session_history;}) 3 20 23
Condition100%3/3
$engine and @{$self->_session_embeddings;} == @{$self->session_history;}
!ll&&!rl&&r
1913
MC/DC100%2/2
$engine and @{$self->_session_embeddings;} == @{$self->session_history;}
$engine @{$self->_session_embeddings;} == @{$self->session_history;}
Truth table100%3/3
A and B
A= $engineB= @{$self->_session_embeddings;} == @{$self->session_history;}
ABresult
0X0
100
111
1059 3 ▶ ( $query_vec ) = await Future->call(sub { $engine->simple_embedding_f($search) })
Subroutine __ANON__: called CC=1 SCAR=0.0
1060 0 ▶ ->else(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1061 0 $log->warnf('[%s] session history search embedding failed, using text match: %s',
1062 __PACKAGE__, $_[0]);
1063 0 return Future->done;
1064 3 });
1065 }
1066  
1067 # Read after the await: the history may have changed meanwhile, and more
1068 # background embeddings may have landed.
1069 23 my @hist = @{$self->session_history};
1070 23 my $slots = $self->_session_embeddings;
1071  
1072 23 ▶ if ($search) {
Branch: 1 branch
BranchTrueFalseTotal
if ($search) 4 19 23
1073 # A slot whose embedding is still in flight (or failed) is undef and simply
1074 # not scored: the search ranks what is embedded now and never waits.
1075 4 ▶ if ($query_vec && @$slots == @hist) {
Branch: 1 branch
BranchTrueFalseTotal
if ($query_vec and @$slots == @hist) { } 3 1 4
Condition66%2/3
$query_vec and @$slots == @hist
!ll&&!rl&&r
103
MC/DC50%1/2
$query_vec and @$slots == @hist
$query_vec @$slots == @hist
Truth table66%2/3
A and B
A= $query_vecB= @$slots == @hist
ABresult
0X0
100
111
1076 3 my @scored;
1077 3 for my $i (0..$#hist) {
1078 9 my $emb = $slots->[$i];
1079 9 ▶ next unless $emb;
Branch: 1 branch
BranchTrueFalseTotal
unless $emb 2 7 9
1080 7 my $sim = _cosine_similarity($query_vec, $emb);
1081 7 push @scored, { idx => $i, score => $sim };
1082 }
1083 3 @scored = sort { $b->{score} <=> $a->{score} } @scored;
1084 3 ▶ @scored = @scored[0..9] if @scored > 10;
Branch: 1 branch
BranchTrueFalseTotal
if @scored > 10 0 3 3
1085 3 @hist = map { $hist[$_->{idx}] } @scored;
1086 } else {
1087 # Fallback to text grep
1088 1 @hist = grep { _render_history_payload($_) =~ /\Q$search/i } @hist;
1089 }
1090 }
1091  
1092 23 ▶ if (my $q = $args->{query}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $q = $$args{"query"}) 9 14 23
1093 9 @hist = grep { _render_history_payload($_) =~ /\Q$q/i } @hist;
1094 }
1095 23 ▶ if (my $n = $args->{last_n}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $n = $$args{"last_n"}) 1 22 23
1096 1 ▶ @hist = @hist[-$n..-1] if @hist > $n;
Branch: 1 branch
BranchTrueFalseTotal
if @hist > $n 1 0 1
1097 }
1098  
1099 23 my $text = _render_session_history(@hist);
1100 23 ▶ return $text || 'No messages in session history.';
Condition100%2/2
$text || 'No messages in session history.'
l!l
221
MC/DC100%1/1
$text || 'No messages in session history.'
$text
Truth table100%2/2
A
A= $text
Aresult
11
00
1101 98 }
1102  
1103 4 ▶sub _manage_mcps {
Subroutine _manage_mcps: called CC=11 SCAR=24.3
1104 4 my ( $self, $args ) = @_;
1105 4 my $action = $args->{action};
1106  
1107 4 ▶ if ($action eq 'list') {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq "list") 1 3 4
1108 1 my @lines;
1109 1 for my $name (sort keys %{$self->mcp_catalog}) {
1110 2 my $entry = $self->mcp_catalog->{$name};
1111 2 ▶ my $active = exists $self->_active_catalog_mcps->{$name} ? 'ACTIVE' : 'inactive';
Branch: 1 branch
BranchTrueFalseTotal
exists $self->_active_catalog_mcps->{$name} ? : 1 1 2
1112 2 ▶ my $desc = $entry->{description} // '';
Condition50%1/2
$$entry{"description"} // ""
l!l
20
MC/DC0%0/1
$$entry{"description"} // ""
$$entry{"description"}
Truth table50%1/2
A
A= $$entry{"description"}
Aresult
11
00
1113 2 push @lines, "- $name [$active] $desc";
1114 }
1115 1 ▶ return join("\n", @lines) || 'No MCP servers in catalog.';
Condition50%1/2
join("\n", @lines) || 'No MCP servers in catalog.'
l!l
10
MC/DC0%0/1
join("\n", @lines) || 'No MCP servers in catalog.'
join("\n", @lines)
Truth table50%1/2
A
A= join("\n", @lines)
Aresult
11
00
1116 }
1117  
1118 3 ▶ if ($action eq 'activate') {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq "activate") 2 1 3
1119 2 ▶ my $name = $args->{name} or return "Error: name required for activate";
Branch: 1 branch
BranchTrueFalseTotal
my $name = $$args{"name"} or return "Error: name required for activate" 2 0 2
1120 2 ▶ my $entry = $self->mcp_catalog->{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $entry = $self->mcp_catalog->{$name} or return "Error: '${name}' not found in catalog" 1 1 2
1121 or return "Error: '$name' not found in catalog";
1122 1 $self->_active_catalog_mcps->{$name} = $entry->{server};
1123 1 $self->_tools_dirty(1);
1124 1 return "Activated MCP server '$name'.";
1125 }
1126  
1127 1 ▶ if ($action eq 'deactivate') {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq "deactivate") 1 0 1
1128 1 ▶ my $name = $args->{name} or return "Error: name required for deactivate";
Branch: 1 branch
BranchTrueFalseTotal
my $name = $$args{"name"} or return "Error: name required for deactivate" 1 0 1
1129 1 delete $self->_active_catalog_mcps->{$name};
1130 1 $self->_tools_dirty(1);
1131 1 return "Deactivated MCP server '$name'.";
1132 }
1133  
1134 0 return "Error: unknown action '$action'";
1135 }
1136  
1137 4 ▶sub _switch_engine_tool {
Subroutine _switch_engine_tool: called CC=4 SCAR=13.9
1138 4 my ( $self, $args ) = @_;
1139 4 ▶ my $name = $args->{name} or return "Error: name required";
Branch: 1 branch
BranchTrueFalseTotal
my $name = $$args{"name"} or return "Error: name required" 3 1 4
1140  
1141 3 ▶ if ($name eq 'default') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "default") 1 2 3
1142 1 $self->reset_engine;
1143 1 my $info = $self->engine_info;
1144 1 return "Switched to default engine ($info->{class}, model: $info->{model}).";
1145 }
1146  
1147 2 ▶ my $entry = $self->engine_catalog->{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $entry = $self->engine_catalog->{$name} or return "Error: '${name}' not found in engine catalog" 1 1 2
1148 or return "Error: '$name' not found in engine catalog";
1149 1 $self->switch_engine($name);
1150 1 my $info = $self->engine_info;
1151 1 return "Switched to engine '$name' ($info->{class}, model: $info->{model}).";
1152 }
1153  
1154 394 ▶sub _get_embedding_engine {
Subroutine _get_embedding_engine: called CC=4 SCAR=13.9
1155 394 my ( $self ) = @_;
1156 394 ▶ return undef if $self->no_session_embeddings;
Branch: 1 branch
BranchTrueFalseTotal
if $self->no_session_embeddings 139 255 394
1157 255 ▶ return $self->embedding_engine if $self->has_embedding_engine;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_embedding_engine 25 230 255
1158 230 my $engine = $self->engine;
1159 230 ▶ return $engine if $engine->does('Langertha::Role::Embedding');
Branch: 1 branch
BranchTrueFalseTotal
if $engine->does("Langertha::Role::Embedding") 28 202 230
1160 202 return undef;
1161 }
1162  
1163 11 ▶sub _cosine_similarity {
Subroutine _cosine_similarity: called CC=4 SCAR=13.9
1164 11 my ( $a, $b ) = @_;
1165 11 my $dot = 0;
1166 11 my $na = 0;
1167 11 my $nb = 0;
1168 11 ▶ my $len = @$a < @$b ? @$a : @$b;
Branch: 1 branch
BranchTrueFalseTotal
@$a < @$b ? : 0 11 11
1169 11 for my $i (0..$len-1) {
1170 56 $dot += $a->[$i] * $b->[$i];
1171 56 $na += $a->[$i] * $a->[$i];
1172 56 $nb += $b->[$i] * $b->[$i];
1173 }
1174 11 my $denom = sqrt($na) * sqrt($nb);
1175 11 ▶ return $denom > 0 ? $dot / $denom : 0;
Branch: 1 branch
BranchTrueFalseTotal
$denom > 0 ? : 10 1 11
1176 }
1177  
1178 390 ▶sub _push_session_history {
Subroutine _push_session_history: called CC=4 SCAR=13.9
1179 390 my ( $self, @msgs ) = @_;
1180 390 push @{$self->session_history}, @msgs;
1181  
1182 # The embeddings are computed in the background (simple_embedding_f on the
1183 # raid's loop, k24): the raid never waits for them, so a slow embedding
1184 # endpoint, or one served by this same reactor, cannot stall it.
1185 #
1186 # _query_session_history_f looks the vector of history element $i up as
1187 # _session_embeddings->[$i], so this reserves EXACTLY one slot per message,
1188 # right now and synchronously — undef until its embedding lands, and for good
1189 # when a message has no embeddable text or its embedding fails. Skipping a
1190 # slot shifts every later vector onto the wrong message and the similarity
1191 # search silently answers with that one.
1192 390 my $slots = $self->_session_embeddings;
1193 390 my $first = @$slots;
1194 390 push @$slots, (undef) x scalar @msgs;
1195  
1196 390 ▶ my $engine = $self->_get_embedding_engine or return;
Branch: 1 branch
BranchTrueFalseTotal
my $engine = $self->_get_embedding_engine or return 49 341 390
1197 49 for my $n (0..$#msgs) {
1198 # The rendered payload, not the raw {content}: an element's shape follows
1199 # the engine's tool_wire_format, so {content} is an ArrayRef of blocks on
1200 # anthropic and absent entirely on gemini ({parts}) and on responses
1201 # envelope items. It is also the text the grep fallback in
1202 # _query_session_history_f matches, so both search modes see one history
1203 # element the same way.
1204 78 my $text = _render_history_payload($msgs[$n]);
1205 78 ▶ $self->_embed_session_slot($engine, $first + $n, $msgs[$n], $text) if length $text;
Branch: 1 branch
BranchTrueFalseTotal
if length $text 73 5 78
1206 }
1207  
1208 49 return;
1209 }
1210  
1211 # Fires the embedding of one history entry and fills slot $i when it lands.
1212 # By then the history may have been cleared, spliced or refilled, so the vector
1213 # is stored only while slot $i still belongs to the very same entry ($msg is
1214 # held by this closure, so its address cannot be reused meanwhile). A failure
1215 # is logged and leaves the slot undef; it never reaches the raid.
1216 73 ▶sub _embed_session_slot {
Subroutine _embed_session_slot: called CC=2 SCAR=7.3
1217 73 my ( $self, $engine, $i, $msg, $text ) = @_;
1218 73 weaken( my $weak = $self );
1219 73 ▶ my $f = Future->call(sub { $engine->simple_embedding_f($text) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1220 32 ▶ $f->on_done(sub {
Subroutine __ANON__: called CC=8 SCAR=25.4
1221 32 my ( $vec ) = @_;
1222 32 ▶ my $raider = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $raider = $weak or return 32 0 32
1223 32 ▶ return unless $i < @{$raider->_session_embeddings};
Branch: 1 branch
BranchTrueFalseTotal
unless $i < @{$raider->_session_embeddings;} 0 32 32
1224 32 my $entry = $raider->session_history->[$i];
1225 32 ▶ my $same = ref $msg
Branch: 1 branch
BranchTrueFalseTotal
ref $msg ? : 32 0 32
Condition22%2/9
ref $entry and builtin::refaddr($entry) == builtin::refaddr($msg)
!ll&&!rl&&r
0131
defined $entry and not ref $entry and $entry eq $msg
!ll&&!rl&&r
000
defined $entry and not ref $entry
!ll&&!rl&&r
000
MC/DC50%1/2
ref $entry and builtin::refaddr($entry) == builtin::refaddr($msg)
ref $entry builtin::refaddr($entry) == builtin::refaddr($msg)
MC/DC0%0/3
defined $entry and not ref $entry and $entry eq $msg
defined $entry not ref $entry $entry eq $msg
Truth table66%2/3
A and B
A= ref $entryB= builtin::refaddr($entry) == builtin::refaddr($msg)
ABresult
0X0
100
111
Truth table0%0/4
A and not(B) and C
A= defined $entryB= not ref $entryC= $entry eq $msg
ABCresult
0XX0
10X0
1100
1111
1226 ? ref $entry && refaddr($entry) == refaddr($msg)
1227 : defined $entry && !ref $entry && $entry eq $msg;
1228 32 ▶ $raider->_session_embeddings->[$i] = $vec if $same;
Branch: 1 branch
BranchTrueFalseTotal
if $same 31 1 32
1229 73 });
1230 28 ▶ $f->on_fail(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1231 28 $log->warnf('[%s] session history embedding failed: %s', __PACKAGE__, $_[0]);
1232 73 });
1233 73 ▶ return if $f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $f->is_ready 28 45 73
1234  
1235 45 my $key = refaddr $f;
1236 45 $self->_pending_embeddings->{$key} = $f;
1237 33 ▶ $f->on_ready(sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
1238 33 ▶ my $raider = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $raider = $weak or return 33 0 33
1239 33 delete $raider->_pending_embeddings->{$key};
1240 45 });
1241 45 return;
1242 }
1243  
1244 36 ▶sub raid {
Subroutine raid: called CC=1 SCAR=0.0
Pod documented
1245 36 my ( $self, @messages ) = @_;
1246 36 return $self->raid_f(@messages)->get;
1247 }
1248  
1249 4 ▶async sub run_f {
Subroutine run_f: called CC=8 SCAR=23.0
Pod documented
1250 4 my ( $self, $ctx ) = @_;
1251 4 ▶ $ctx = Langertha::RunContext->new(input => $ctx)
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($ctx) and $ctx->isa("Langertha::RunContext") 0 4 4
Condition33%1/3
builtin::blessed($ctx) and $ctx->isa("Langertha::RunContext")
!ll&&!rl&&r
004
MC/DC0%0/2
builtin::blessed($ctx) and $ctx->isa("Langertha::RunContext")
builtin::blessed($ctx) $ctx->isa("Langertha::RunContext")
Truth table33%1/3
A and B
A= builtin::blessed($ctx)B= $ctx->isa("Langertha::RunContext")
ABresult
0X0
100
111
1252 unless blessed($ctx) && $ctx->isa('Langertha::RunContext');
1253  
1254 4 my $input = $ctx->input;
1255 4 ▶ my @messages = ref($input) eq 'ARRAY' ? @{$input} : ($input);
Branch: 1 branch
BranchTrueFalseTotal
ref $input eq 'ARRAY' ? : 0 4 4
1256 4 @messages = grep { defined } @messages;
1257  
1258 4 my $result = await $self->raid_f(@messages);
1259  
1260 4 ▶ if ($result->is_final && $result->has_text) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->is_final and $result->has_text) 4 0 4
Condition33%1/3
$result->is_final and $result->has_text
!ll&&!rl&&r
004
MC/DC0%0/2
$result->is_final and $result->has_text
$result->is_final $result->has_text
Truth table33%1/3
A and B
A= $result->is_finalB= $result->has_text
ABresult
0X0
100
111
1261 4 $ctx->input($result->text);
1262 4 $ctx->state->{last_output} = $result->text;
1263 }
1264 4 $ctx->state->{last_result_type} = $result->type;
1265 4 ▶ $ctx->state->{last_result} = $result->as_hash if $result->can('as_hash');
Branch: 1 branch
BranchTrueFalseTotal
if $result->can("as_hash") 4 0 4
1266 4 ▶ $ctx->history($self->history) if $ctx->can('history');
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->can("history") 4 0 4
1267  
1268 4 return $result->with_context($ctx);
1269 98 }
1270  
1271  
1272  
1273 145 ▶async sub _gather_tools_f {
Subroutine _gather_tools_f: called CC=13 SCAR=25.7
1274 145 my ( $self ) = @_;
1275 145 my $engine = $self->active_engine;
1276 145 my ( @all_tools, %tool_server_map, %tool_source, %seen );
1277  
1278 # A name offered by more than one source is sent to the provider once --
1279 # providers reject a request that declares one function twice -- and the
1280 # first source (in gather order) wins, as core's
1281 # Langertha::Role::Tools->_tool_loop_tools does across mcp_servers (karr k332).
1282 # Raider assembles its own tool set from four kinds of source, so it needs its
1283 # own dedup. Returns true when the tool was accepted, false when it was a
1284 # duplicate of an earlier source and dropped with a carp. $source is the
1285 # short name of the source the tool gate sees (k121).
1286 621 ▶ my $accept = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1287 621 my ( $tool, $label, $source ) = @_;
1288 621 my $name = $tool->{name};
1289 621 ▶ if ( my $first = $seen{$name} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $first = $seen{$name}) 2 619 621
1290 2 carp "" . ( ref $self ) . ": tool '$name' is offered by $first and $label; using the first";
1291 2 return 0;
1292 }
1293 619 $seen{$name} = $label;
1294 619 $tool_source{$name} = $source;
1295 619 push @all_tools, $tool;
1296 619 return 1;
1297 145 };
1298  
1299 # Engine MCP servers
1300 145 ▶ if ($engine->can('mcp_servers')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine->can("mcp_servers")) 145 0 145
1301 145 my $no = 0;
1302 145 for my $mcp (@{$engine->mcp_servers}) {
1303 155 my $label = 'engine MCP server ' . ( ++$no ) . ' (' . ref($mcp) . ')';
1304 155 my $tools = await $mcp->list_tools;
1305 155 for my $tool (@$tools) {
1306 306 ▶ $tool_server_map{$tool->{name}} = $mcp if $accept->($tool, $label, 'engine:'.$no);
Branch: 1 branch
BranchTrueFalseTotal
if &$accept($tool, $label, 'engine:' . $no) 306 0 306
1307 }
1308 }
1309 }
1310  
1311 # Inline MCP
1312 145 ▶ if ($self->has_inline_mcp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_inline_mcp) 15 130 145
1313 15 my $tools = await $self->_inline_mcp->list_tools;
1314 15 for my $tool (@$tools) {
1315 15 ▶ $tool_server_map{$tool->{name}} = $self->_inline_mcp
Branch: 1 branch
BranchTrueFalseTotal
if &$accept($tool, "inline MCP", "inline") 15 0 15
1316 if $accept->($tool, 'inline MCP', 'inline');
1317 }
1318 }
1319  
1320 # Active catalog MCPs
1321 145 for my $name (sort keys %{$self->_active_catalog_mcps}) {
1322 4 my $mcp = $self->_active_catalog_mcps->{$name};
1323 4 my $tools = await $mcp->list_tools;
1324 4 for my $tool (@$tools) {
1325 6 ▶ $tool_server_map{$tool->{name}} = $mcp
Branch: 1 branch
BranchTrueFalseTotal
if &$accept($tool, "catalog MCP '${name}'", 'catalog:' . $name) 5 1 6
1326 if $accept->($tool, "catalog MCP '$name'", 'catalog:'.$name);
1327 }
1328 }
1329  
1330 # Self-tools (virtual — no MCP server mapping needed)
1331 145 ▶ if ($self->has_raider_mcp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_raider_mcp) 47 98 145
1332 47 $accept->($_, 'raider self-tools', 'raider') for @{$self->_self_tool_definitions};
1333 }
1334  
1335 145 return ( \@all_tools, \%tool_server_map, \%tool_source );
1336 98 }
1337  
1338 144 ▶async sub _initialize_inline_mcp_f {
Subroutine _initialize_inline_mcp_f: called CC=9 SCAR=22.3
1339 144 my ( $self ) = @_;
1340 144 ▶ return if $self->has_inline_mcp;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_inline_mcp 0 144 144
1341  
1342 # Collect inline tools + plugin tools
1343 144 my @all_inline;
1344 144 push @all_inline, @{$self->tools};
1345 144 for my $plugin (@{$self->plugin_instances}) {
1346 196 my $tools = $plugin->self_tools;
1347 196 ▶ push @all_inline, @$tools if $tools && @$tools;
Branch: 1 branch
BranchTrueFalseTotal
if $tools and @$tools 3 193 196
Condition66%2/3
$tools and @$tools
!ll&&!rl&&r
01933
MC/DC50%1/2
$tools and @$tools
$tools @$tools
Truth table66%2/3
A and B
A= $toolsB= @$tools
ABresult
0X0
100
111
1348 }
1349 144 ▶ return unless @all_inline;
Branch: 1 branch
BranchTrueFalseTotal
unless @all_inline 127 17 144
1350  
1351 17 my $server = MCP::Server->new(name => 'raider-inline', version => '1.0');
1352 17 for my $tdef (@all_inline) {
1353 $server->tool(
1354 name => $tdef->{name},
1355 description => $tdef->{description},
1356 input_schema => $tdef->{input_schema} // $tdef->{inputSchema},
1357 code => $tdef->{code},
1358 17 ▶ );
Condition33%1/3
$$tdef{"input_schema"} // $$tdef{"inputSchema"}
l!l&&r!l&&!r
1700
MC/DC0%0/2
$$tdef{"input_schema"} // $$tdef{"inputSchema"}
$$tdef{"input_schema"} $$tdef{"inputSchema"}
Truth table33%1/3
A // B
A= $$tdef{"input_schema"}B= $$tdef{"inputSchema"}
ABresult
1X1
011
000
1359 }
1360  
1361 17 my $mcp = Net::Async::MCP->new(server => $server);
1362 17 ▶ ($self->engine->async_loop // IO::Async::Loop->new)->add($mcp);
Condition66%2/3
$self->engine->async_loop // "IO::Async::Loop"->new
l!l&&r!l&&!r
1340
MC/DC0%0/2
$self->engine->async_loop // "IO::Async::Loop"->new
$self->engine->async_loop "IO::Async::Loop"->new
Truth table66%2/3
A // B
A= $self->engine->async_loopB= "IO::Async::Loop"->new
ABresult
1X1
011
000
1363 17 await $mcp->initialize;
1364 17 $self->_inline_mcp($mcp);
1365 98 }
1366  
1367 # One raid awaits the futures of every engine it may use, and one ->get drives
1368 # exactly one IO::Async loop: engines on two loops hang the raid (core karr
1369 # k228). An engine without a loop (sync fallback) counts as the process-wide
1370 # IO::Async::Loop->new, like everywhere else in raider.
1371 # Tradeoff: async_loop builds each engine's HTTP client now, so a sync-fallback warning may show at raid start.
1372 163 ▶sub _check_engine_loops {
Subroutine _check_engine_loops: called CC=3 SCAR=11.0
1373 163 my ( $self ) = @_;
1374 163 my @engines = $self->_raid_engines;
1375 172 ▶ my $loop_of = sub {
Subroutine __ANON__: called CC=3 SCAR=11.4
1376 172 my ( $engine ) = @_;
1377 172 ▶ return ( $engine->can('async_loop') && $engine->async_loop ) || IO::Async::Loop->new;
Condition66%4/6
$engine->can('async_loop') && $engine->async_loop || 'IO::Async::Loop'->new
l!l&&r!l&&!r
16390
$engine->can("async_loop") and $engine->async_loop
!ll&&!rl&&r
09163
MC/DC0%0/3
$engine->can('async_loop') && $engine->async_loop || 'IO::Async::Loop'->new
$engine->can("async_loop") $engine->async_loop 'IO::Async::Loop'->new
Truth table40%2/5
A and B || C
A= $engine->can("async_loop")B= $engine->async_loopC= 'IO::Async::Loop'->new
ABCresult
11X1
0X11
1011
0X00
1000
1378 163 };
1379 163 my $loop = $loop_of->($engines[0][1]);
1380 163 for my $entry (@engines[1..$#engines]) {
1381 9 ▶ next if refaddr($loop_of->($entry->[1])) == refaddr($loop);
Branch: 1 branch
BranchTrueFalseTotal
if builtin::refaddr(&$loop_of($$entry[1])) == builtin::refaddr($loop) 6 3 9
1382 3 croak "Raider $entry->[0] runs on a different event loop than engine; "
1383 . "a raid drives only one loop, so every engine of a raider must share it "
1384 . "(put their HTTP clients on the same IO::Async::Loop)";
1385 }
1386 160 return $loop;
1387 }
1388  
1389 # Every engine a raid may use, as [ name => engine ] pairs, engine first.
1390 323 ▶sub _raid_engines {
Subroutine _raid_engines: called CC=6 SCAR=17.9
1391 323 my ( $self ) = @_;
1392 323 my @engines = ( [ engine => $self->engine ] );
1393 323 ▶ push @engines, [ compression_engine => $self->compression_engine ]
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_compression_engine 5 318 323
1394 if $self->has_compression_engine;
1395 # Its futures complete only while the raid's loop runs.
1396 323 ▶ push @engines, [ embedding_engine => $self->embedding_engine ]
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_embedding_engine and not $self->no_session_embeddings 7 316 323
Condition100%3/3
$self->has_embedding_engine and not $self->no_session_embeddings
!ll&&!rl&&r
31427
MC/DC100%2/2
$self->has_embedding_engine and not $self->no_session_embeddings
$self->has_embedding_engine not $self->no_session_embeddings
Truth table100%3/3
A and not(B)
A= $self->has_embedding_engineB= not $self->no_session_embeddings
ABresult
0X0
100
111
1397 if $self->has_embedding_engine && !$self->no_session_embeddings;
1398 323 for my $name (sort keys %{$self->engine_catalog}) {
1399 3 ▶ my $engine = $self->engine_catalog->{$name}{engine} // next;
Condition50%1/2
$self->engine_catalog->{$name}{"engine"} // (next)
l!l
30
MC/DC0%0/1
$self->engine_catalog->{$name}{"engine"} // (next)
$self->engine_catalog->{$name}{"engine"}
Truth table50%1/2
A
A= $self->engine_catalog->{$name}{"engine"}
Aresult
11
00
1400 3 push @engines, [ "engine_catalog '$name'" => $engine ];
1401 }
1402 323 return @engines;
1403 }
1404  
1405 # Net::Async::HTTP loads what a connection needs only when it opens one, and
1406 # a load that dies there keeps the host's connection slot taken: every later
1407 # request to the host -- the chat request after the session-history
1408 # embedding -- waits forever (karr k107). Checked before the raid sends, a
1409 # missing module is an error that names it. Only engines with an event loop
1410 # and a url: the synchronous fallback connects through LWP.
1411 160 ▶sub _check_engine_connect {
Subroutine _check_engine_connect: called CC=7 SCAR=19.5
1412 160 my ( $self ) = @_;
1413 160 for my $entry ($self->_raid_engines) {
1414 166 my ( $name, $engine ) = @$entry;
1415 166 ▶ next unless $engine->can('async_loop') && $engine->async_loop
Branch: 1 branch
BranchTrueFalseTotal
unless $engine->can("async_loop") and $engine->async_loop and $engine->can("url") and defined $engine->url 141 25 166
Condition77%7/9
$engine->can("async_loop") and $engine->async_loop and $engine->can("url") and defined $engine->url
!ll&&!rl&&r
141025
$engine->can("async_loop") and $engine->async_loop and $engine->can("url")
!ll&&!rl&&r
913225
$engine->can("async_loop") and $engine->async_loop
!ll&&!rl&&r
09157
MC/DC50%2/4
$engine->can("async_loop") and $engine->async_loop and $engine->can("url") and defined $engine->url
$engine->can("async_loop") $engine->async_loop $engine->can("url") defined $engine->url
Truth table60%3/5
A and B and C and D
A= $engine->can("async_loop")B= $engine->async_loopC= $engine->can("url")D= defined $engine->url
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1416 && $engine->can('url') && defined $engine->url;
1417 25 ▶ my $error = connect_error($engine->url) // next;
Condition100%2/2
connect_error($engine->url) // (next)
l!l
223
MC/DC100%1/1
connect_error($engine->url) // (next)
connect_error($engine->url)
Truth table100%2/2
A
A= connect_error($engine->url)
Aresult
11
00
1418 2 croak "Raider $name: $error";
1419 }
1420 158 return;
1421 }
1422  
1423 146 ▶sub raid_f {
Subroutine raid_f: called CC=1 SCAR=0.0
Pod documented
1424 146 my ( $self, @messages ) = @_;
1425 146 return $self->_end_raid($self->_raid_f(@messages));
1426 }
1427  
1428 146 ▶async sub _raid_f {
Subroutine _raid_f: called CC=19 SCAR=30.0
1429 146 my ( $self, @messages ) = @_;
1430 146 $self->_check_engine_loops;
1431 143 $self->_check_engine_connect;
1432 141 my $engine = $self->active_engine;
1433 141 my $t0 = [gettimeofday];
1434 141 ▶ my $langfuse = $engine->can('langfuse_enabled') && $engine->langfuse_enabled;
Condition100%3/3
$engine->can('langfuse_enabled') && $engine->langfuse_enabled
!ll&&!rl&&r
114261
MC/DC100%2/2
$engine->can('langfuse_enabled') && $engine->langfuse_enabled
$engine->can('langfuse_enabled') $engine->langfuse_enabled
Truth table100%3/3
A && B
A= $engine->can('langfuse_enabled')B= $engine->langfuse_enabled
ABresult
0X0
100
111
1435 141 my $trace_id;
1436  
1437 141 ▶ if ($langfuse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($langfuse) 1 140 141
1438 my %trace_meta = (
1439 mission => $self->has_mission ? $self->mission : undef,
1440 1 ▶ history_length => scalar @{$self->history},
Branch: 1 branch
BranchTrueFalseTotal
$self->has_mission ? : 1 0 1
1441 );
1442 1 ▶ if ($self->has_langfuse_metadata) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_langfuse_metadata) 0 1 1
1443 0 %trace_meta = (%trace_meta, %{$self->langfuse_metadata});
1444 }
1445 1 ▶ $trace_id = $engine->langfuse_trace(
Branch: 5 branches
BranchTrueFalseTotal
$self->has_langfuse_user_id ? : 0 1 1
$self->has_langfuse_session_id ? : 0 1 1
$self->has_langfuse_tags ? : 0 1 1
$self->has_langfuse_release ? : 0 1 1
$self->has_langfuse_version ? : 0 1 1
1446 name => $self->langfuse_trace_name,
1447 input => \@messages,
1448 metadata => \%trace_meta,
1449 $self->has_langfuse_user_id ? ( user_id => $self->langfuse_user_id ) : (),
1450 $self->has_langfuse_session_id ? ( session_id => $self->langfuse_session_id ) : (),
1451 $self->has_langfuse_tags ? ( tags => $self->langfuse_tags ) : (),
1452 $self->has_langfuse_release ? ( release => $self->langfuse_release ) : (),
1453 $self->has_langfuse_version ? ( version => $self->langfuse_version ) : (),
1454 );
1455 }
1456  
1457 # Auto-compress if threshold exceeded
1458 141 ▶ if ($self->has_max_context_tokens && $self->has_last_prompt_tokens
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_max_context_tokens and $self->has_last_prompt_tokens and $self->_last_prompt_tokens > $self->max_context_tokens * $self->context_compress_threshold) 2 139 141
Condition100%6/6
$self->has_max_context_tokens and $self->has_last_prompt_tokens and $self->_last_prompt_tokens > $self->max_context_tokens * $self->context_compress_threshold
!ll&&!rl&&r
13812
$self->has_max_context_tokens and $self->has_last_prompt_tokens
!ll&&!rl&&r
68703
MC/DC100%3/3
$self->has_max_context_tokens and $self->has_last_prompt_tokens and $self->_last_prompt_tokens > $self->max_context_tokens * $self->context_compress_threshold
$self->has_max_context_tokens $self->has_last_prompt_tokens $self->_last_prompt_tokens > $self->max_context_tokens * $self->context_compress_threshold
Truth table100%4/4
A and B and C
A= $self->has_max_context_tokensB= $self->has_last_prompt_tokensC= $self->_last_prompt_tokens > $self->max_context_tokens * $self->context_compress_threshold
ABCresult
0XX0
10X0
1100
1111
1459 && $self->_last_prompt_tokens > $self->max_context_tokens * $self->context_compress_threshold) {
1460 2 await $self->compress_history_f();
1461 }
1462  
1463 # Plugin hook: transform input messages before raid
1464 141 for my $plugin (@{$self->plugin_instances}) {
1465 193 @messages = @{await $plugin->plugin_before_raid(\@messages)};
1466 }
1467  
1468 # Initialize inline MCP if tools defined
1469 141 await $self->_initialize_inline_mcp_f;
1470  
1471 # Gather tools from all sources
1472 141 my ( $all_tools, $tool_server_map, $tool_sources ) = await $self->_gather_tools_f;
1473  
1474 141 ▶ croak "No tools available (configure MCP servers, inline tools, or raider_mcp)"
Branch: 1 branch
BranchTrueFalseTotal
unless @$all_tools 0 141 141
1475 unless @$all_tools;
1476  
1477 141 my $formatted_tools = $engine->format_tools($all_tools);
1478 141 ▶ my $model_params = $langfuse ? $self->_langfuse_model_parameters($engine) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$langfuse ? : 1 140 141
1479  
1480 # Build new user messages
1481 my @user_msgs = map {
1482 141 ▶ ref $_ ? $_ : { role => 'user', content => $_ }
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 0 141 141
1483 } @messages;
1484  
1485 # Push user messages to session_history
1486 141 $self->_push_session_history(@user_msgs);
1487  
1488 # Build full conversation: mission + history + new messages
1489 141 my @conversation;
1490 141 ▶ push @conversation, { role => 'system', content => $self->mission }
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_mission 73 68 141
1491 if $self->has_mission;
1492 141 push @conversation, @{$self->history};
1493 141 push @conversation, @user_msgs;
1494  
1495 # Plugin hook: transform assembled conversation
1496 141 for my $plugin (@{$self->plugin_instances}) {
1497 193 @conversation = @{await $plugin->plugin_build_conversation(\@conversation)};
1498 }
1499  
1500 141 my $raid_iterations = 0;
1501 141 my $raid_tool_calls = 0;
1502 141 my @injected_history;
1503  
1504 # Package loop state for potential continuation
1505 141 my $state = {
1506 engine => $engine,
1507 t0 => $t0,
1508 langfuse => $langfuse,
1509 trace_id => $trace_id,
1510 tool_server_map => $tool_server_map,
1511 tool_sources => $tool_sources,
1512 tool_schemas => $self->_tool_schemas($all_tools),
1513 formatted_tools => $formatted_tools,
1514 model_params => $model_params,
1515 user_msgs => \@user_msgs,
1516 conversation => \@conversation,
1517 raid_iterations => \$raid_iterations,
1518 raid_tool_calls => \$raid_tool_calls,
1519 injected_history => \@injected_history,
1520 # The tool exchanges appended each iteration, tracked so in-loop compaction
1521 # can drop the oldest ones as whole units (karr k89).
1522 tool_segments => [],
1523 };
1524  
1525 141 return await $self->_run_raid_loop($state, 1);
1526 98 }
1527  
1528 # Reads one tool-loop turn's reply. An engine that carries the public
1529 # Langertha::Role::Tools->tool_loop_response hook (Langertha core from the
1530 # release that added it) together with a real chat_response reads the reply the
1531 # way core's own tool loops do: an error carried in a 200 body croaks instead of
1532 # ending the raid silently with '', Gemini thought parts and <think> tags stay
1533 # out of the final text, and a tool call whose arguments were cut off by the
1534 # token limit is dropped from the run and from the assistant echo (core
1535 # k321/k323/k324). A duck-typed engine that lacks either (the in-process test
1536 # fixtures, or any backend on a core older than the hook) falls back to the
1537 # legacy response_tool_calls / response_text_content readers, which never croak.
1538 # Returns ( \@tool_calls, $final_text, $echo_data ): the calls are
1539 # Langertha::ToolCall objects on the hook path and raw wire structures on the
1540 # fallback (both understood by _tool_call_name_input and by format_tool_results),
1541 # and $echo_data is the wire body to build the assistant echo from.
1542 230 ▶sub _read_tool_loop_reply {
Subroutine _read_tool_loop_reply: called CC=4 SCAR=13.9
1543 230 my ( $self, $engine, $data ) = @_;
1544 230 ▶ if ( $engine->can('tool_loop_response') && $engine->can('chat_response') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine->can("tool_loop_response") and $engine->can("chat_response")) 18 212 230
Condition100%3/3
$engine->can("tool_loop_response") and $engine->can("chat_response")
!ll&&!rl&&r
7214018
MC/DC100%2/2
$engine->can("tool_loop_response") and $engine->can("chat_response")
$engine->can("tool_loop_response") $engine->can("chat_response")
Truth table100%3/3
A and B
A= $engine->can("tool_loop_response")B= $engine->can("chat_response")
ABresult
0X0
100
111
1545 18 my $reply = $engine->tool_loop_response($data);
1546 17 my ( $calls, $echo_data ) = $engine->tool_loop_calls( $reply, $data );
1547 17 return ( $calls, $reply->content, $echo_data );
1548 }
1549 212 my $tool_calls = $engine->response_tool_calls($data);
1550 212 my $text = $engine->response_text_content($data);
1551 212 ▶ ( $text ) = $engine->filter_think_content($text) if $engine->think_tag_filter;
Branch: 1 branch
BranchTrueFalseTotal
if $engine->think_tag_filter 0 212 212
1552 212 return ( $tool_calls, $text, $data );
1553 }
1554  
1555 # The tool name and decoded arguments of one call, whether it is the
1556 # Langertha::ToolCall the tool_loop_response hook yields or the raw wire
1557 # structure an engine's response_tool_calls located (the fallback path).
1558 209 ▶sub _tool_call_name_input {
Subroutine _tool_call_name_input: called CC=2 SCAR=6.9
1559 209 my ( $self, $engine, $tc ) = @_;
1560 209 ▶ return ( $tc->name, $tc->arguments ) if blessed $tc;
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($tc) 9 200 209
1561 200 return $engine->extract_tool_call($tc);
1562 }
1563  
1564 # The error result a call whose arguments the model did not send as valid JSON
1565 # is answered with -- running the tool on the {} such a call decodes to is wrong
1566 # (karr k345). undef for a call whose arguments decoded, and for a raw wire
1567 # structure (the fallback path, where arguments_undecodable is not tracked). The
1568 # text matches core's Langertha::Role::Tools->_undecodable_arguments_result, so
1569 # the model sees the same error whichever loop ran it. A call whose arguments
1570 # were cut off by the token limit was already dropped upstream by
1571 # _read_tool_loop_reply (tool_loop_calls); this is the OTHER case -- a reply that
1572 # did not hit its token limit but still sent arguments that do not decode.
1573 199 ▶sub _undecodable_tool_result {
Subroutine _undecodable_tool_result: called CC=4 SCAR=13.9
1574 199 my ( $self, $tc ) = @_;
1575 199 ▶ return undef unless blessed $tc && $tc->arguments_undecodable;
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($tc) and $tc->arguments_undecodable 197 2 199
Condition100%3/3
builtin::blessed($tc) and $tc->arguments_undecodable
!ll&&!rl&&r
19072
MC/DC100%2/2
builtin::blessed($tc) and $tc->arguments_undecodable
builtin::blessed($tc) $tc->arguments_undecodable
Truth table100%3/3
A and B
A= builtin::blessed($tc)B= $tc->arguments_undecodable
ABresult
0X0
100
111
1576 return {
1577 2 ▶ content => [{ type => 'text',
Condition50%1/2
$tc->arguments_error // "not a JSON object"
l!l
20
MC/DC0%0/1
$tc->arguments_error // "not a JSON object"
$tc->arguments_error
Truth table50%1/2
A
A= $tc->arguments_error
Aresult
11
00
1578 text => "arguments are not valid JSON: " . ( $tc->arguments_error // 'not a JSON object' ) }],
1579 isError => JSON->true,
1580 };
1581 }
1582  
1583 # The inputSchema of every tool the raid offers, by name, from the tool set
1584 # _gather_tools_f assembled -- so for a name several sources offer, the schema
1585 # of the source that won and was shown to the model. MCP lists and the
1586 # self-tools carry inputSchema; input_schema is taken too.
1587 141 ▶sub _tool_schemas {
Subroutine _tool_schemas: called CC=3 SCAR=11.8
1588 141 my ( $self, $all_tools ) = @_;
1589 return { map {
1590 ( $_->{name} => $_->{inputSchema} // $_->{input_schema} )
1591 141 ▶ } grep { ref $_ eq 'HASH' && defined $_->{name} } @$all_tools };
Condition50%3/6
$$_{"inputSchema"} // $$_{"input_schema"}
l!l&&r!l&&!r
4370168
ref $_ eq 'HASH' && defined $$_{'name'}
!ll&&!rl&&r
00605
MC/DC50%1/2
$$_{"inputSchema"} // $$_{"input_schema"}
$$_{"inputSchema"} $$_{"input_schema"}
MC/DC0%0/2
ref $_ eq 'HASH' && defined $$_{'name'}
ref $_ eq 'HASH' defined $$_{'name'}
Truth table66%2/3
A // B
A= $$_{"inputSchema"}B= $$_{"input_schema"}
ABresult
1X1
011
000
Truth table33%1/3
A && B
A= ref $_ eq 'HASH'B= defined $$_{'name'}
ABresult
0X0
100
111
1592 }
1593  
1594 # The error result a call whose arguments clearly break its tool's inputSchema
1595 # is answered with (a required key missing, a top-level property of the wrong
1596 # type; Langertha::Raider::ToolArgs says what counts). undef when they pass,
1597 # and for a tool without a known schema. Same shape as the bad-JSON result.
1598 195 ▶sub _invalid_args_tool_result {
Subroutine _invalid_args_tool_result: called CC=4 SCAR=13.9
1599 195 my ( $self, $state, $name, $input ) = @_;
1600 195 ▶ my $schema = $state->{tool_schemas}{$name // ''} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $schema = $$state{"tool_schemas"}{$name // ""} or return undef 57 138 195
Condition50%1/2
$name // ""
l!l
1950
MC/DC0%0/1
$name // ""
$name
Truth table50%1/2
A
A= $name
Aresult
11
00
1601 57 ▶ my @problems = tool_args_problems($schema, $input) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my(@problems) = tool_args_problems($schema, $input) or return undef 7 50 57
1602 return {
1603 7 content => [{ type => 'text',
1604 text => "arguments do not match the input schema of tool '".$name."': ".join('; ', @problems) }],
1605 isError => JSON->true,
1606 };
1607 }
1608  
1609 # The tool gate's verdict on the canonical call $call (see _tool_gate):
1610 # { verdict => 'allow' } when no gate is set. A gate that answers anything
1611 # but allow, deny or ask croaks -- a broken gate must neither let the call
1612 # through nor have its intent guessed.
1613 188 ▶sub _gate_tool_call {
Subroutine _gate_tool_call: called CC=6 SCAR=18.7
1614 188 my ( $self, $call ) = @_;
1615 188 ▶ return { verdict => 'allow' } unless $self->_has_tool_gate;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_has_tool_gate 173 15 188
1616 15 my $verdict = $self->_tool_gate->($self, $call);
1617 croak __PACKAGE__."->_tool_gate gave no valid verdict for tool '".( $call->{name} // '' )."'"
1618 unless ref $verdict eq 'HASH' && defined $verdict->{verdict}
1619 15 ▶ && $verdict->{verdict} =~ /\A(?:allow|deny|ask)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $verdict eq "HASH" and defined $$verdict{"verdict"} and $$verdict{"verdict"} =~ /\A(?:allow|deny|ask)\z/ 1 14 15
Condition50%4/8
ref $verdict eq "HASH" and defined $$verdict{"verdict"} and $$verdict{"verdict"} =~ /\A(?:allow|deny|ask)\z/
!ll&&!rl&&r
0114
ref $verdict eq "HASH" and defined $$verdict{"verdict"}
!ll&&!rl&&r
0015
$$call{"name"} // ""
l!l
10
MC/DC33%1/3
ref $verdict eq "HASH" and defined $$verdict{"verdict"} and $$verdict{"verdict"} =~ /\A(?:allow|deny|ask)\z/
ref $verdict eq "HASH" defined $$verdict{"verdict"} $$verdict{"verdict"} =~ /\A(?:allow|deny|ask)\z/
MC/DC0%0/1
$$call{"name"} // ""
$$call{"name"}
Truth table50%2/4
A and B and C
A= ref $verdict eq "HASH"B= defined $$verdict{"verdict"}C= $$verdict{"verdict"} =~ /\A(?:allow|deny|ask)\z/
ABCresult
0XX0
10X0
1100
1111
Truth table50%1/2
A
A= $$call{"name"}
Aresult
11
00
1620 14 return $verdict;
1621 }
1622  
1623 # The error result for a call the gate did not allow. ask is refused like
1624 # deny for now: no surface can ask for an approval yet (k121, provisional
1625 # until the approval step lands).
1626 7 ▶sub _gate_refused_tool_result {
Subroutine _gate_refused_tool_result: called CC=5 SCAR=16.1
1627 7 my ( $self, $name, $verdict ) = @_;
1628 7 my $reason = $verdict->{reason};
1629 7 ▶ my $has_reason = defined $reason && length $reason;
Condition66%2/3
defined $reason && length $reason
!ll&&!rl&&r
205
MC/DC50%1/2
defined $reason && length $reason
defined $reason length $reason
Truth table66%2/3
A && B
A= defined $reasonB= length $reason
ABresult
0X0
100
111
1630 7 ▶ my $text = $verdict->{verdict} eq 'ask'
Branch: 3 branches
BranchTrueFalseTotal
$$verdict{'verdict'} eq 'ask' ? : 2 5 7
$has_reason ? : 1 1 2
$has_reason ? : 4 1 5
1631 ? "Tool call '".$name."' was not run: it needs approval"
1632 .( $has_reason ? ' ('.$reason.')' : '' ).', and this raid has no way to ask for it.'
1633 : $has_reason
1634 ? "Tool call '".$name."' was denied: ".$reason
1635 : "Tool call '".$name."' was denied by policy.";
1636 return {
1637 7 content => [{ type => 'text', text => $text }],
1638 isError => JSON->true,
1639 };
1640 }
1641  
1642 # Rough token estimate for one tracked tool exchange (a list of wire messages):
1643 # the JSON-encoded byte length over four, the usual ~4-chars-per-token rule. It
1644 # only has to rank exchanges by size and say roughly how much dropping one sheds,
1645 # never to be exact — the provider's real usage count drives the threshold, this
1646 # only decides how many of the oldest exchanges to drop to get back under it.
1647 4 ▶sub _estimate_message_tokens {
Subroutine _estimate_message_tokens: called CC=4 SCAR=14.1
1648 4 my ( $self, $segment ) = @_;
1649 4 my $chars = 0;
1650 4 for my $msg (@$segment) {
1651 8 my $encoded = eval { $history_json->encode($msg) };
1652 8 ▶ $chars += defined $encoded ? length $encoded : length "$msg";
Branch: 1 branch
BranchTrueFalseTotal
defined $encoded ? : 8 0 8
1653 }
1654 4 ▶ return int( $chars / 4 ) || 1;
Condition50%1/2
int $chars / 4 || 1
l!l
40
MC/DC0%0/1
int $chars / 4 || 1
int $chars / 4
Truth table50%1/2
A
A= int $chars / 4
Aresult
11
00
1655 }
1656  
1657 # In-loop context compaction (karr k89). Between raids _raid_f compresses the
1658 # working history via compress_history_f, but within one long raid the growth is
1659 # the assistant tool-call echoes and tool results appended to $conversation on
1660 # every iteration — messages _raid_f never sees and history never keeps. Left
1661 # alone a single mission with many tool calls blows past max_context_tokens on
1662 # smaller models. So when the last real prompt-token count (the provider's usage,
1663 # tracked in _last_prompt_tokens) has crossed the threshold, drop the OLDEST tool
1664 # exchanges from the in-flight conversation, oldest first, until the estimate is
1665 # back under the threshold — always keeping the most recent exchange, whose
1666 # results the model still has to act on. Each exchange is dropped as a whole unit
1667 # (the assistant echo carrying the tool_calls together with its tool results), so
1668 # no tool_use is ever left without its tool_result (a 400 on strict providers).
1669 # The header — mission/system prompt with its skill instructions, the pre-raid
1670 # history and the user turn — is never a tracked exchange, so activated skill
1671 # content always survives.
1672 240 ▶sub _compact_conversation {
Subroutine _compact_conversation: called CC=10 SCAR=23.1
1673 240 my ( $self, $state ) = @_;
1674 240 ▶ return unless $self->has_max_context_tokens && $self->has_last_prompt_tokens;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_max_context_tokens and $self->has_last_prompt_tokens 230 10 240
Condition100%3/3
$self->has_max_context_tokens and $self->has_last_prompt_tokens
!ll&&!rl&&r
11012010
MC/DC100%2/2
$self->has_max_context_tokens and $self->has_last_prompt_tokens
$self->has_max_context_tokens $self->has_last_prompt_tokens
Truth table100%3/3
A and B
A= $self->has_max_context_tokensB= $self->has_last_prompt_tokens
ABresult
0X0
100
111
1675 10 my $target = $self->max_context_tokens * $self->context_compress_threshold;
1676 10 ▶ return unless $self->_last_prompt_tokens > $target;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_last_prompt_tokens > $target 4 6 10
1677 6 my $segments = $state->{tool_segments};
1678 6 ▶ return unless $segments && @$segments > 1; # always keep the most recent exchange
Branch: 1 branch
BranchTrueFalseTotal
unless $segments and @$segments > 1 2 4 6
Condition66%2/3
$segments and @$segments > 1
!ll&&!rl&&r
024
MC/DC50%1/2
$segments and @$segments > 1
$segments @$segments > 1
Truth table66%2/3
A and B
A= $segmentsB= @$segments > 1
ABresult
0X0
100
111
1679  
1680 # Only exchanges still present in the live conversation may be dropped: a
1681 # plugin_before_llm_call hook may return a freshly built conversation arrayref
1682 # (see the write-back below), detaching the tracked messages — then there is
1683 # nothing safe to drop and compaction is a no-op.
1684 4 my %live = map { refaddr($_) => 1 } @{$state->{conversation}};
1685  
1686 4 my $over = $self->_last_prompt_tokens - $target;
1687 4 my $shed = 0;
1688 4 my @drop;
1689 4 ▶ while ( @$segments > 1 && $shed < $over ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$segments > 1 and $shed < $over) 4 4 8
Condition66%2/3
@$segments > 1 and $shed < $over
!ll&&!rl&&r
044
MC/DC50%1/2
@$segments > 1 and $shed < $over
@$segments > 1 $shed < $over
Truth table66%2/3
A and B
A= @$segments > 1B= $shed < $over
ABresult
0X0
100
111
1690 4 ▶ last unless grep { $live{ refaddr($_) } } @{ $segments->[0] };
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$live{builtin::refaddr($_)};} @{$$segments[0];} 0 4 4
1691 4 my $seg = shift @$segments;
1692 4 $shed += $self->_estimate_message_tokens($seg);
1693 4 push @drop, @$seg;
1694 }
1695 4 ▶ return unless @drop;
Branch: 1 branch
BranchTrueFalseTotal
unless @drop 0 4 4
1696  
1697 4 my %drop = map { refaddr($_) => 1 } @drop;
1698 4 @{$state->{conversation}} = grep { !$drop{ refaddr($_) } } @{$state->{conversation}};
1699 4 $log->debugf(
1700 'Raider in-loop compaction: dropped %d older tool message(s), ~%d est. tokens (%d over threshold %d)',
1701 scalar @drop, $shed, $self->_last_prompt_tokens, $target );
1702 4 return $shed;
1703 }
1704  
1705 # The raid loop: one iteration per model turn. Each prepares the conversation
1706 # (_prepare_iteration_f), sends it (_send_turn_f) and reads the reply
1707 # (_read_turn_f); a reply without tool calls ends the raid (_finish_raid_f),
1708 # otherwise the batch of tool calls runs (_execute_tool_calls_f) and the tool
1709 # exchange is appended for the next turn (_append_tool_turn). The cancel safe
1710 # points before each model call and each tool call sit here and in the batch
1711 # (ADR 0009). $state is the continuation respond_f resumes from; $iter is one
1712 # iteration's bookkeeping (number, Langfuse span and usage).
1713 157 ▶async sub _run_raid_loop {
Subroutine _run_raid_loop: called CC=6 SCAR=17.9
1714 157 my ( $self, $state, $start_iteration ) = @_;
1715  
1716 157 for my $iteration ($start_iteration..$self->max_iterations) {
1717 # Safe point: no model call once a cancel is requested.
1718 246 ▶ return $self->_cancelled_result($state) if $self->cancel_requested;
Branch: 1 branch
BranchTrueFalseTotal
if $self->cancel_requested 6 240 246
1719 240 ${$state->{raid_iterations}}++;
1720  
1721 240 await $self->_prepare_iteration_f($state, $iteration, $start_iteration);
1722 240 my $iter = $self->_start_iteration_trace($state, $iteration);
1723  
1724 240 my $response = await $self->_send_turn_f($state);
1725 234 ▶ return $self->_cancelled_result($state) if $self->cancel_requested;
Branch: 1 branch
BranchTrueFalseTotal
if $self->cancel_requested 2 232 234
1726 232 my $data = await $self->_read_turn_f($state, $iter, $response);
1727  
1728 # Read this turn's reply (see _read_tool_loop_reply): a 200 body that is an
1729 # error croaks instead of silently ending the raid with '', Gemini thought
1730 # parts stay out of the final text, and truncated calls are dropped.
1731 230 my ( $tool_calls, $final_text, $echo_data ) = $self->_read_tool_loop_reply($state->{engine}, $data);
1732  
1733 # No tool calls means done — use the reply's final text
1734 229 ▶ unless (@$tool_calls) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@$tool_calls) 113 116 229
1735 113 return await $self->_finish_raid_f($state, $iter, $final_text);
1736 }
1737  
1738 116 $self->_trace_tool_turn($state, $iter, $tool_calls);
1739 116 my @results;
1740 116 my $stop = await $self->_execute_tool_calls_f($state, $iter, $tool_calls, $echo_data, \@results);
1741 114 ▶ return $stop if defined $stop;
Branch: 1 branch
BranchTrueFalseTotal
if defined $stop 24 90 114
1742 90 $self->_close_iteration_trace($state, $iter, $tool_calls, \@results);
1743 90 $self->_append_tool_turn($state, $echo_data, \@results);
1744 }
1745  
1746 1 die "Raider tool loop exceeded ".$self->max_iterations." iterations";
1747 98 }
1748  
1749 # Brings the conversation up to date before an iteration's request: in-loop
1750 # compaction, the tool set rebuilt if it changed, injections (from the second
1751 # iteration of the raid on), then the plugin_before_llm_call hook.
1752 240 ▶async sub _prepare_iteration_f {
Subroutine _prepare_iteration_f: called CC=4 SCAR=13.9
1753 240 my ( $self, $state, $iteration, $start_iteration ) = @_;
1754  
1755 # Keep one long raid inside the context window: before building the next
1756 # request, drop the oldest tool exchanges if the last prompt crossed the
1757 # threshold (karr k89). Runs before injections and the plugin hook so both
1758 # see the compacted conversation.
1759 240 $self->_compact_conversation($state);
1760  
1761 240 await $self->_refresh_tools_f($state);
1762  
1763 # Drain injections for iterations 2+
1764 240 ▶ $self->_drain_injections($state, $iteration)
Branch: 1 branch
BranchTrueFalseTotal
if $iteration > $start_iteration or $start_iteration > 1 102 138 240
Condition100%3/3
$iteration > $start_iteration or $start_iteration > 1
l!l&&r!l&&!r
8616138
MC/DC100%2/2
$iteration > $start_iteration or $start_iteration > 1
$iteration > $start_iteration $start_iteration > 1
Truth table100%3/3
A or B
A= $iteration > $start_iterationB= $start_iteration > 1
ABresult
1X1
011
000
1765 if $iteration > $start_iteration || $start_iteration > 1;
1766  
1767 # Plugin hook: transform conversation before each LLM call
1768 240 my $conversation = $state->{conversation};
1769 240 for my $plugin (@{$self->plugin_instances}) {
1770 335 $conversation = await $plugin->plugin_before_llm_call($conversation, $iteration);
1771 }
1772 # A plugin may return a fresh arrayref. Keep the continuation state pointing
1773 # at whatever the loop now works with, because respond_f resumes from
1774 # $state->{conversation}: without this write-back a paused raid reverts to
1775 # the pre-plugin array and drops every message accumulated after divergence.
1776 240 $state->{conversation} = $conversation;
1777 240 return;
1778 98 }
1779  
1780 # Re-gathers the tool set for the active engine when the catalog or the engine
1781 # changed (_tools_dirty).
1782 240 ▶async sub _refresh_tools_f {
Subroutine _refresh_tools_f: called CC=3 SCAR=19.5
1783 240 my ( $self, $state ) = @_;
1784 240 ▶ return unless $self->_tools_dirty;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_tools_dirty 240 0 240
1785 0 my $engine = $self->active_engine;
1786 0 $state->{engine} = $engine;
1787 0 my ( $all_tools, $new_map, $new_sources ) = await $self->_gather_tools_f;
1788 0 $state->{formatted_tools} = $engine->format_tools($all_tools);
1789 0 $state->{tool_server_map} = $new_map;
1790 0 $state->{tool_sources} = $new_sources;
1791 0 $state->{tool_schemas} = $self->_tool_schemas($all_tools);
1792 $state->{model_params} = $self->_langfuse_model_parameters($engine)
1793 0 ▶ if $state->{langfuse};
Branch: 1 branch
BranchTrueFalseTotal
if $$state{"langfuse"} 0 0 0
1794 0 $self->_tools_dirty(0);
1795 0 return;
1796 98 }
1797  
1798 # Moves the queued inject() messages and those the on_iteration callback
1799 # returns into the conversation, the raid's injected history and
1800 # session_history.
1801 102 ▶sub _drain_injections {
Subroutine _drain_injections: called CC=7 SCAR=19.6
1802 102 my ( $self, $state, $iteration ) = @_;
1803 102 my @injected;
1804 102 ▶ if (@{$self->_injections}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->_injections;}) 1 101 102
1805 1 push @injected, splice @{$self->_injections};
1806 }
1807 102 ▶ if ($self->has_on_iteration) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_on_iteration) 1 101 102
1808 1 my $cb_msgs = $self->on_iteration->($self, $iteration);
1809 1 ▶ push @injected, @$cb_msgs if $cb_msgs && @$cb_msgs;
Branch: 1 branch
BranchTrueFalseTotal
if $cb_msgs and @$cb_msgs 1 0 1
Condition33%1/3
$cb_msgs and @$cb_msgs
!ll&&!rl&&r
001
MC/DC0%0/2
$cb_msgs and @$cb_msgs
$cb_msgs @$cb_msgs
Truth table33%1/3
A and B
A= $cb_msgsB= @$cb_msgs
ABresult
0X0
100
111
1810 }
1811 102 ▶ return unless @injected;
Branch: 1 branch
BranchTrueFalseTotal
unless @injected 101 1 102
1812 my @msgs = map {
1813 1 ▶ ref $_ ? $_ : { role => 'user', content => $_ }
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 0 2 2
1814 } @injected;
1815 1 push @{$state->{conversation}}, @msgs;
1816 1 push @{$state->{injected_history}}, @msgs;
1817 1 $self->_push_session_history(@msgs);
1818 1 return;
1819 }
1820  
1821 # Opens the iteration's Langfuse span. Returns the iteration's bookkeeping:
1822 # its number, and with Langfuse its start time and span id.
1823 240 ▶sub _start_iteration_trace {
Subroutine _start_iteration_trace: called CC=2 SCAR=6.9
1824 240 my ( $self, $state, $iteration ) = @_;
1825 240 my $iter = { iteration => $iteration };
1826 240 ▶ return $iter unless $state->{langfuse};
Branch: 1 branch
BranchTrueFalseTotal
unless $$state{"langfuse"} 238 2 240
1827 2 my $engine = $state->{engine};
1828 2 $iter->{t0} = $engine->langfuse_timestamp;
1829 $iter->{span_id} = $engine->langfuse_span(
1830 trace_id => $state->{trace_id},
1831 name => "iteration-$iteration",
1832 start_time => $iter->{t0},
1833 2 );
1834 2 return $iter;
1835 }
1836  
1837 # Sends the iteration's request. The future gives the HTTP response, or
1838 # nothing once a cancel abandons the request.
1839 240 ▶sub _send_turn_f {
Subroutine _send_turn_f: called CC=1 SCAR=0.0
1840 240 my ( $self, $state ) = @_;
1841 240 my $engine = $state->{engine};
1842 240 my $request = $engine->build_tool_chat_request($state->{conversation}, $state->{formatted_tools});
1843 240 return $self->_until_cancelled($engine->async_request_f($request));
1844 }
1845  
1846 # Parses the reply to the iteration's request (dying on a failed request),
1847 # runs the plugin_after_llm_response hook and records the prompt tokens for
1848 # auto-compression and, with Langfuse, the usage on $iter. Returns the body.
1849 232 ▶async sub _read_turn_f {
Subroutine _read_turn_f: called CC=7 SCAR=19.5
1850 232 my ( $self, $state, $iter, $response ) = @_;
1851 232 my $engine = $state->{engine};
1852  
1853 232 ▶ unless ($response->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 2 230 232
1854 2 die "".(ref $engine)." raid request failed: ".$response->status_line."\n".$response->content;
1855 }
1856  
1857 230 my $data = $engine->parse_response($response);
1858  
1859 # Plugin hook: inspect/transform LLM response
1860 230 for my $plugin (@{$self->plugin_instances}) {
1861 321 $data = await $plugin->plugin_after_llm_response($data, $iter->{iteration});
1862 }
1863  
1864 # Track prompt tokens for auto-compression. from_raw is undef when the
1865 # body reports no usage, but a Usage without a prompt count still has
1866 # input_tokens 0: treat 0 as not reported, so it never resets the count.
1867 230 my $usage = Langertha::Usage->from_raw($data);
1868 230 ▶ $self->_last_prompt_tokens($usage->input_tokens)
Branch: 1 branch
BranchTrueFalseTotal
if $usage and $usage->input_tokens > 0 21 209 230
Condition100%3/3
$usage and $usage->input_tokens > 0
!ll&&!rl&&r
208121
MC/DC100%2/2
$usage and $usage->input_tokens > 0
$usage $usage->input_tokens > 0
Truth table100%3/3
A and B
A= $usageB= $usage->input_tokens > 0
ABresult
0X0
100
111
1869 if $usage && $usage->input_tokens > 0;
1870  
1871 # Extract usage for Langfuse
1872 230 ▶ $iter->{usage} = $state->{langfuse} && $usage ? {
Branch: 1 branch
BranchTrueFalseTotal
$$state{'langfuse'} && $usage ? : 2 228 230
Condition66%2/3
$$state{"langfuse"} and $usage
!ll&&!rl&&r
22802
MC/DC50%1/2
$$state{"langfuse"} and $usage
$$state{"langfuse"} $usage
Truth table66%2/3
A and B
A= $$state{"langfuse"}B= $usage
ABresult
0X0
100
111
1873 input => $usage->input_tokens,
1874 output => $usage->output_tokens,
1875 total => $usage->total_tokens,
1876 } : undef;
1877  
1878 230 return $data;
1879 98 }
1880  
1881 # The Langfuse generation for the iteration's model call, nested under the
1882 # iteration span.
1883 2 ▶sub _trace_llm_call {
Subroutine _trace_llm_call: called CC=3 SCAR=11.3
1884 2 my ( $self, $state, $iter, $output, $end_time ) = @_;
1885 2 my $engine = $state->{engine};
1886 2 my $model_params = $state->{model_params};
1887 $engine->langfuse_generation(
1888 trace_id => $state->{trace_id},
1889 parent_observation_id => $iter->{span_id},
1890 name => 'llm-call',
1891 model => $engine->chat_model,
1892 input => $state->{conversation},
1893 output => $output,
1894 start_time => $iter->{t0},
1895 end_time => $end_time,
1896 2 ▶ $iter->{usage} ? ( usage => $iter->{usage} ) : (),
Branch: 2 branches
BranchTrueFalseTotal
$$iter{'usage'} ? : 2 0 2
$model_params ? : 2 0 2
1897 $model_params ? ( model_parameters => $model_params ) : (),
1898 );
1899 2 return;
1900 }
1901  
1902 # Ends the raid on a reply without tool calls: closes the Langfuse span and
1903 # trace, persists the user messages, injections and answer in history,
1904 # updates the metrics and returns the final Result through the
1905 # plugin_after_raid hook.
1906 113 ▶async sub _finish_raid_f {
Subroutine _finish_raid_f: called CC=4 SCAR=13.9
1907 113 my ( $self, $state, $iter, $text ) = @_;
1908  
1909 113 ▶ if ($state->{langfuse}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$state{"langfuse"}) 1 112 113
1910 1 my $engine = $state->{engine};
1911 1 my $iter_t1 = $engine->langfuse_timestamp;
1912  
1913 # Langfuse: generation nested under iteration span
1914 1 $self->_trace_llm_call($state, $iter, $text, $iter_t1);
1915  
1916 # Close iteration span
1917 $engine->langfuse_update_span(
1918 id => $iter->{span_id},
1919 1 end_time => $iter_t1,
1920 output => $text,
1921 );
1922  
1923 # Update trace with final output
1924 $engine->langfuse_update_trace(
1925 id => $state->{trace_id},
1926 1 output => $text,
1927 );
1928 }
1929  
1930 # Persist user messages, injections, and final assistant response in history
1931 113 my $injected_history = $state->{injected_history};
1932 113 push @{$self->history}, @{$state->{user_msgs}};
1933 113 ▶ push @{$self->history}, @$injected_history if @$injected_history;
Branch: 1 branch
BranchTrueFalseTotal
if @$injected_history 1 112 113
1934 113 push @{$self->history}, { role => 'assistant', content => $text };
1935  
1936 # Push final assistant response to session_history
1937 113 $self->_push_session_history({ role => 'assistant', content => $text });
1938  
1939 113 $self->metrics->{raids}++;
1940 113 $self->_record_raid_metrics($state);
1941  
1942 113 my $result = Langertha::Raider::Result->new(type => 'final', text => $text);
1943  
1944 # Plugin hook: transform final result before return
1945 113 for my $plugin (@{$self->plugin_instances}) {
1946 157 $result = await $plugin->plugin_after_raid($result);
1947 }
1948  
1949 113 return $result;
1950 98 }
1951  
1952 # Adds the raid's iterations, tool calls and elapsed time to the metrics.
1953 114 ▶sub _record_raid_metrics {
Subroutine _record_raid_metrics: called CC=1 SCAR=0.0
1954 114 my ( $self, $state ) = @_;
1955 114 my $elapsed = tv_interval($state->{t0}) * 1000;
1956 114 my $m = $self->metrics;
1957 114 $m->{iterations} += ${$state->{raid_iterations}};
1958 114 $m->{tool_calls} += ${$state->{raid_tool_calls}};
1959 114 $m->{time_ms} += $elapsed;
1960 114 return;
1961 }
1962  
1963 # Langfuse: generation for the model call that produced tool calls, its
1964 # output the called tool names.
1965 116 ▶sub _trace_tool_turn {
Subroutine _trace_tool_turn: called CC=2 SCAR=6.9
1966 116 my ( $self, $state, $iter, $tool_calls ) = @_;
1967 116 ▶ return unless $state->{langfuse};
Branch: 1 branch
BranchTrueFalseTotal
unless $$state{"langfuse"} 115 1 116
1968 1 my $engine = $state->{engine};
1969 1 my $post_llm_t = $engine->langfuse_timestamp;
1970 $self->_trace_llm_call($state, $iter, $engine->json->encode([map {
1971 1 ($self->_tool_call_name_input($engine, $_))[0]
1972 } @$tool_calls]), $post_llm_t);
1973 1 return;
1974 }
1975  
1976 # Runs a batch of tool calls in order and pushes one
1977 # { tool_call => ..., result => ... } per call onto $results. Returns the
1978 # Result that ends the raid when a cancel, an interactive self-tool or an
1979 # abort stops the batch; nothing when the whole batch ran. The iteration's
1980 # batch runs here, and so does the rest of a batch respond_f resumes (k120).
1981 133 ▶async sub _execute_tool_calls_f {
Subroutine _execute_tool_calls_f: called CC=4 SCAR=13.9
1982 133 my ( $self, $state, $iter, $tool_calls, $echo_data, $results ) = @_;
1983  
1984 133 for my $tc_idx (0 .. $#$tool_calls) {
1985 # Safe point: no further tool call once a cancel is requested.
1986 205 ▶ return $self->_cancelled_result($state) if $self->cancel_requested;
Branch: 1 branch
BranchTrueFalseTotal
if $self->cancel_requested 6 199 205
1987 # Only the calls AFTER a pausing self-tool are still pending. The ones
1988 # before it already ran and sit in $results; carrying them too (as a plain
1989 # "everything but $tc" filter did) re-runs their side effects and emits a
1990 # second tool_result for the same tool_use id on resume — a 400 on strict
1991 # providers like Anthropic.
1992 199 my $stop = await $self->_dispatch_tool_call_f($state, $iter, $echo_data,
1993 $tool_calls->[$tc_idx], [ @$tool_calls[$tc_idx+1 .. $#$tool_calls] ], $results);
1994 197 ▶ return $stop if defined $stop;
Branch: 1 branch
BranchTrueFalseTotal
if defined $stop 19 178 197
1995 }
1996  
1997 106 return;
1998 98 }
1999  
2000 # Dispatches one tool call: the single path every call of a raid takes, in
2001 # the first run of a batch and on resume alike (k120). Pushes its
2002 # { tool_call => ..., result => ... } onto $results, or returns the Result
2003 # that ends the raid (an interactive self-tool, which saves $remaining_tcs --
2004 # the calls queued after $tc -- for respond_f; an abort). Every call that
2005 # passed plugin_before_tool_call gets its result through
2006 # plugin_after_tool_call exactly once; a pausing self-tool gets it on
2007 # respond_f (k134).
2008 199 ▶async sub _dispatch_tool_call_f {
Subroutine _dispatch_tool_call_f: called CC=14 SCAR=26.4
2009 199 my ( $self, $state, $iter, $echo_data, $tc, $remaining_tcs, $results ) = @_;
2010 199 my $engine = $state->{engine};
2011 199 my ( $name, $input ) = $self->_tool_call_name_input($engine, $tc);
2012  
2013 # A call whose arguments the model did not send as valid JSON must not run
2014 # the tool on {} -- answer it with an error result the model can retry, as
2015 # core does (karr k345). Truncated calls were dropped upstream already.
2016 199 ▶ if ( my $bad = $self->_undecodable_tool_result($tc) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $bad = $self->_undecodable_tool_result($tc)) 2 197 199
2017 2 push @$results, { tool_call => $tc, result => $bad };
2018 2 ${$state->{raid_tool_calls}}++;
2019 2 return;
2020 }
2021  
2022 # Plugin hook: inspect/transform before tool execution
2023 197 my @plugin_tc = await $self->plugin_pipeline_tool_call_f($name, $input);
2024 197 ▶ unless (@plugin_tc) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@plugin_tc) 2 195 197
2025 # Plugin returned empty list — skip this tool call
2026 2 my $skip_result = {
2027 content => [{ type => 'text', text => "Tool call '$name' was skipped by plugin." }],
2028 };
2029 2 push @$results, { tool_call => $tc, result => $skip_result };
2030 2 ${$state->{raid_tool_calls}}++;
2031 2 return;
2032 }
2033 195 ( $name, $input ) = @plugin_tc;
2034  
2035 195 ▶ my $tool_t0 = $state->{langfuse} ? $engine->langfuse_timestamp : undef;
Branch: 1 branch
BranchTrueFalseTotal
$$state{'langfuse'} ? : 5 190 195
2036  
2037 # Arguments that clearly break the tool's inputSchema do not run the tool:
2038 # the model gets an error result it can correct (ADR 0005 "validate", k122).
2039 # Checked after plugin_before_tool_call, so it is the call that would run --
2040 # and the one the Events plugin recorded as tool.call -- that is held
2041 # against the schema, and the error result takes the same
2042 # plugin_after_tool_call path as any other result: one tool.result.
2043 195 ▶ if ( my $invalid = $self->_invalid_args_tool_result($state, $name, $input) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $invalid = $self->_invalid_args_tool_result($state, $name, $input)) 7 188 195
2044 7 my $result = await $self->_after_tool_call_f($state, $iter, $name, $input, $tool_t0, $invalid, 1);
2045 7 push @$results, { tool_call => $tc, result => $result };
2046 7 ${$state->{raid_tool_calls}}++;
2047 7 return;
2048 }
2049  
2050 # Virtual self-tools. A raider_-prefixed name routes here only when no tool
2051 # source announced it: an MCP source may offer a raider_-prefixed name and
2052 # win the first-wins dedup (karr k90), in which case it sits in
2053 # tool_server_map and was sent to the model as that MCP tool. Dispatch has
2054 # to follow the actual registration, not the prefix, or such a call dies as
2055 # "Unknown self-tool" instead of reaching its MCP source (karr k93).
2056 my $self_tool = $name =~ /^raider_/ && $self->has_raider_mcp
2057 188 ▶ && !$state->{tool_server_map}{$name};
Condition83%5/6
$name =~ /^raider_/ && $self->has_raider_mcp && !$$state{'tool_server_map'}{$name}
!ll&&!rl&&r
156230
$name =~ /^raider_/ and $self->has_raider_mcp
!ll&&!rl&&r
156032
MC/DC66%2/3
$name =~ /^raider_/ && $self->has_raider_mcp && !$$state{'tool_server_map'}{$name}
$name =~ /^raider_/ $self->has_raider_mcp !$$state{'tool_server_map'}{$name}
Truth table75%3/4
A and B && not(C)
A= $name =~ /^raider_/B= $self->has_raider_mcpC= !$$state{'tool_server_map'}{$name}
ABCresult
0XX0
10X0
1100
1111
2058  
2059 # The gate (ADR 0005 "check policy", k121): after the inputSchema check, on
2060 # the call exactly as it would run. A call it does not allow does not run;
2061 # its error result takes the plugin_after_tool_call path like any other, so
2062 # the call keeps one tool.call and one tool.result.
2063 my $verdict = $self->_gate_tool_call({
2064 name => $name,
2065 188 ▶ source => $self_tool ? 'raider' : $state->{tool_sources}{$name},
Branch: 1 branch
BranchTrueFalseTotal
$self_tool ? : 30 158 188
2066 arguments => $input,
2067 });
2068 187 ▶ unless ( $verdict->{verdict} eq 'allow' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($$verdict{"verdict"} eq "allow") 7 180 187
2069 7 my $result = await $self->_after_tool_call_f($state, $iter, $name, $input, $tool_t0,
2070 $self->_gate_refused_tool_result($name, $verdict), 1);
2071 7 push @$results, { tool_call => $tc, result => $result };
2072 7 ${$state->{raid_tool_calls}}++;
2073 7 return;
2074 }
2075  
2076 180 my $result;
2077  
2078 180 ▶ if ($self_tool) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self_tool) { } 29 151 180
2079 29 my $self_result = await $self->_execute_self_tool_f($name, $input);
2080  
2081 # Handle interactive self-tool results
2082 return $self->_pause_raid($state, $iter, $echo_data, $tc, $name, $input,
2083 $tool_t0, $remaining_tcs, $results, $self_result)
2084 29 ▶ if $self_result->{type} eq 'question' || $self_result->{type} eq 'pause';
Branch: 1 branch
BranchTrueFalseTotal
if $$self_result{"type"} eq "question" or $$self_result{"type"} eq "pause" 18 11 29
Condition100%3/3
$$self_result{"type"} eq "question" or $$self_result{"type"} eq "pause"
l!l&&r!l&&!r
16211
MC/DC100%2/2
$$self_result{"type"} eq "question" or $$self_result{"type"} eq "pause"
$$self_result{"type"} eq "question" $$self_result{"type"} eq "pause"
Truth table100%3/3
A or B
A= $$self_result{"type"} eq "question"B= $$self_result{"type"} eq "pause"
ABresult
1X1
011
000
2085  
2086 return $self->_abort_raid($state, $self_result)
2087 11 ▶ if $self_result->{type} eq 'abort';
Branch: 1 branch
BranchTrueFalseTotal
if $$self_result{"type"} eq "abort" 1 10 11
2088  
2089 10 ▶ if ($self_result->{type} eq 'wait') {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self_result{'type'} eq 'wait') { } 9 1 10
2090 $result = await $self->_wait_self_tool_f(
2091 9 $state, $iter, $name, $input, $tool_t0, $self_result->{seconds});
2092 }
2093 else {
2094 # type eq 'result' — normal self-tool result
2095 1 $result = await $self->_after_tool_call_f($state, $iter, $name, $input, $tool_t0, $self_result);
2096 }
2097 }
2098 else {
2099 151 $result = await $self->_call_mcp_tool_f($state, $iter, $name, $input, $tool_t0);
2100 }
2101  
2102 160 push @$results, { tool_call => $tc, result => $result };
2103 160 ${$state->{raid_tool_calls}}++;
2104 160 return;
2105 98 }
2106  
2107 # Saves the continuation respond_f resumes from when an interactive self-tool
2108 # stops the batch, and returns its question or pause Result. $name and $input
2109 # are the call as plugin_before_tool_call handed it on, for the
2110 # plugin_after_tool_call the answer runs through. $remaining_tcs are the
2111 # calls of the batch after $tc, $results those that already ran.
2112 18 ▶sub _pause_raid {
Subroutine _pause_raid: called CC=3 SCAR=11.0
2113 18 my ( $self, $state, $iter, $echo_data, $tc, $name, $input, $tool_t0,
2114 $remaining_tcs, $results, $self_result ) = @_;
2115 $self->_continuation({
2116 state => $state,
2117 iteration => $iter->{iteration},
2118 data => $echo_data,
2119 pending_tc => $tc,
2120 pending_name => $name,
2121 pending_input => $input,
2122 pending_t0 => $tool_t0,
2123 remaining_tcs => $remaining_tcs,
2124 results_so_far => $results,
2125 iter_span_id => $iter->{span_id},
2126 18 });
2127  
2128 18 ▶ if ($self_result->{type} eq 'question') {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self_result{"type"} eq "question") 16 2 18
2129 return Langertha::Raider::Result->new(
2130 type => 'question',
2131 content => $self_result->{question},
2132 16 ▶ $self_result->{options} ? (options => $self_result->{options}) : (),
Branch: 1 branch
BranchTrueFalseTotal
$$self_result{'options'} ? : 0 16 16
2133 );
2134 }
2135 return Langertha::Raider::Result->new(
2136 type => 'pause',
2137 content => $self_result->{reason},
2138 2 );
2139 }
2140  
2141 # Ends the raid on raider_abort, metrics finalized first.
2142 1 ▶sub _abort_raid {
Subroutine _abort_raid: called CC=1 SCAR=0.0
2143 1 my ( $self, $state, $self_result ) = @_;
2144 1 $self->_record_raid_metrics($state);
2145 return Langertha::Raider::Result->new(
2146 type => 'abort',
2147 content => $self_result->{reason},
2148 1 );
2149 }
2150  
2151 # Runs raider_wait: waits $seconds on the raid's loop unless a cancel cuts
2152 # the wait short. Returns the tool result -- a cancelled one after a cancel,
2153 # as for a cut-off MCP call -- through plugin_after_tool_call (k134).
2154 9 ▶async sub _wait_self_tool_f {
Subroutine _wait_self_tool_f: called CC=3 SCAR=11.0
2155 9 my ( $self, $state, $iter, $name, $input, $tool_t0, $seconds ) = @_;
2156 9 my $engine = $state->{engine};
2157 9 ▶ my $loop = $engine->async_loop // IO::Async::Loop->new;
Condition66%2/3
$engine->async_loop // "IO::Async::Loop"->new
l!l&&r!l&&!r
720
MC/DC0%0/2
$engine->async_loop // "IO::Async::Loop"->new
$engine->async_loop "IO::Async::Loop"->new
Truth table66%2/3
A // B
A= $engine->async_loopB= "IO::Async::Loop"->new
ABresult
1X1
011
000
2158 9 await $self->_until_cancelled($loop->delay_future(after => $seconds));
2159 9 ▶ my $result = $self->cancel_requested
Branch: 1 branch
BranchTrueFalseTotal
$self->cancel_requested ? : 1 8 9
2160 ? $self->_cancelled_tool_result($name)
2161 : { content => [{ type => 'text', text => "Waited $seconds seconds." }] };
2162 9 return await $self->_after_tool_call_f($state, $iter, $name, $input, $tool_t0, $result);
2163 98 }
2164  
2165 # Calls the tool $name on the MCP source that registered it. A name no server
2166 # offers is answered with an error result so the batch runs to the end and the
2167 # model can correct itself, instead of dying and losing the whole raid (core
2168 # k332). A failed call, or one a cancel cut off, is an error result too.
2169 151 ▶async sub _call_mcp_tool_f {
Subroutine _call_mcp_tool_f: called CC=4 SCAR=13.9
2170 151 my ( $self, $state, $iter, $name, $input, $tool_t0 ) = @_;
2171 151 my $mcp = $state->{tool_server_map}{$name};
2172 151 ▶ unless ($mcp) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($mcp) 1 150 151
2173 return {
2174 1 ▶ content => [{ type => 'text', text => "unknown tool ".($name // '') }],
Condition50%1/2
$name // ""
l!l
10
MC/DC0%0/1
$name // ""
$name
Truth table50%1/2
A
A= $name
Aresult
11
00
2175 isError => JSON->true,
2176 };
2177 }
2178  
2179 2 ▶ my $call_f = $mcp->call_tool($name, $input)->else(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2180 2 my ( $error ) = @_;
2181 2 Future->done({
2182 content => [{ type => 'text', text => "Error calling tool '$name': $error" }],
2183 isError => JSON->true,
2184 });
2185 150 });
2186 149 my $result = await $self->_until_cancelled($call_f);
2187 149 ▶ $result = $self->_cancelled_tool_result($name) if $self->_cut_off($call_f, $result);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_cut_off($call_f, $result) 6 143 149
2188  
2189 149 return await $self->_after_tool_call_f($state, $iter, $name, $input, $tool_t0, $result, 1);
2190 98 }
2191  
2192 # Runs the plugin_after_tool_call hook on a tool's result and traces the call
2193 # as a Langfuse span under the iteration span. With $flag_errors an error
2194 # result gets level ERROR (MCP calls; self-tool results carry no level).
2195 190 ▶async sub _after_tool_call_f {
Subroutine _after_tool_call_f: called CC=7 SCAR=19.5
2196 190 my ( $self, $state, $iter, $name, $input, $tool_t0, $result, $flag_errors ) = @_;
2197  
2198 # Plugin hook: transform tool result
2199 190 for my $plugin (@{$self->plugin_instances}) {
2200 290 $result = await $plugin->plugin_after_tool_call($name, $input, $result);
2201 }
2202  
2203 190 ▶ if ($state->{langfuse}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$state{"langfuse"}) 4 186 190
2204 4 ▶ my $tool_output = join('', map { $_->{text} // '' } @{$result->{content} // []});
Condition50%2/4
$$_{"text"} // ""
l!l
40
$$result{"content"} // []
l!l
40
MC/DC0%0/1
$$_{"text"} // ""
$$_{"text"}
MC/DC0%0/1
$$result{"content"} // []
$$result{"content"}
Truth table50%1/2
A
A= $$_{"text"}
Aresult
11
00
Truth table50%1/2
A
A= $$result{"content"}
Aresult
11
00
2205 $self->_trace_tool_call($state, $iter, $name, $input, $tool_t0, $tool_output,
2206 4 ▶ $flag_errors && $result->{isError} ? ( level => 'ERROR' ) : ());
Branch: 1 branch
BranchTrueFalseTotal
$flag_errors && $$result{'isError'} ? : 1 3 4
Condition100%3/3
$flag_errors and $$result{"isError"}
!ll&&!rl&&r
211
MC/DC100%2/2
$flag_errors and $$result{"isError"}
$flag_errors $$result{"isError"}
Truth table100%3/3
A and B
A= $flag_errorsB= $$result{"isError"}
ABresult
0X0
100
111
2207 }
2208  
2209 190 return $result;
2210 98 }
2211  
2212 # Langfuse: span for one tool call, nested under the iteration span.
2213 4 ▶sub _trace_tool_call {
Subroutine _trace_tool_call: called CC=1 SCAR=0.0
2214 4 my ( $self, $state, $iter, $name, $input, $tool_t0, $output, @extra ) = @_;
2215 4 my $engine = $state->{engine};
2216 $engine->langfuse_span(
2217 trace_id => $state->{trace_id},
2218 parent_observation_id => $iter->{span_id},
2219 4 name => "tool: $name",
2220 input => $input,
2221 output => $output,
2222 start_time => $tool_t0,
2223 end_time => $engine->langfuse_timestamp,
2224 @extra,
2225 );
2226 4 return;
2227 }
2228  
2229 # Langfuse: closes the iteration span once the batch of tool calls ran.
2230 90 ▶sub _close_iteration_trace {
Subroutine _close_iteration_trace: called CC=2 SCAR=6.9
2231 90 my ( $self, $state, $iter, $tool_calls, $results ) = @_;
2232 90 ▶ return unless $state->{langfuse};
Branch: 1 branch
BranchTrueFalseTotal
unless $$state{"langfuse"} 89 1 90
2233 1 my $engine = $state->{engine};
2234 $engine->langfuse_update_span(
2235 id => $iter->{span_id},
2236 end_time => $engine->langfuse_timestamp,
2237 metadata => {
2238 tool_calls => scalar @$tool_calls,
2239 tools_used => [map {
2240 1 ($self->_tool_call_name_input($engine, $_->{tool_call}))[0]
2241 } @$results],
2242 },
2243 );
2244 1 return;
2245 }
2246  
2247 # Appends the assistant echo and the tool results to the conversation and
2248 # session_history, and tracks them as one exchange for in-loop compaction
2249 # (k89). $echo_data is the wire body without any tool call whose arguments
2250 # were truncated, so the next turn never carries a call without a result.
2251 90 ▶sub _append_tool_turn {
Subroutine _append_tool_turn: called CC=1 SCAR=0.0
2252 90 my ( $self, $state, $echo_data, $results ) = @_;
2253 90 my @tool_msgs = $state->{engine}->format_tool_results($echo_data, $results);
2254 90 push @{$state->{conversation}}, @tool_msgs;
2255 90 push @{$state->{tool_segments}}, [ @tool_msgs ];
2256 90 $self->_push_session_history(@tool_msgs);
2257 90 return;
2258 }
2259  
2260 17 ▶sub respond_f {
Subroutine respond_f: called CC=1 SCAR=0.0
Pod documented
2261 17 my ( $self, $answer ) = @_;
2262 17 return $self->_end_raid($self->_respond_f($answer));
2263 }
2264  
2265 17 ▶async sub _respond_f {
Subroutine _respond_f: called CC=6 SCAR=18.1
2266 17 my ( $self, $answer ) = @_;
2267 17 ▶ croak "No pending interaction — call raid_f first"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_continuation 0 17 17
2268 unless $self->has_continuation;
2269 17 $self->_check_engine_loops;
2270 17 $self->_check_engine_connect;
2271  
2272 17 my $cont = $self->_continuation;
2273 17 $self->clear_continuation;
2274  
2275 17 my $state = $cont->{state};
2276 17 my $data = $cont->{data};
2277 17 my $pending_tc = $cont->{pending_tc};
2278 17 my @results = @{$cont->{results_so_far}};
2279 17 my $engine = $state->{engine};
2280  
2281 17 my $iter = { iteration => $cont->{iteration}, span_id => $cont->{iter_span_id} };
2282  
2283 # The answer is the tool result of the pending self-tool call. It runs
2284 # through plugin_after_tool_call like every other result, so the call's
2285 # tool.call event gets its tool.result (k134).
2286 my $answer_result = await $self->_after_tool_call_f($state, $iter,
2287 $cont->{pending_name}, $cont->{pending_input}, $cont->{pending_t0},
2288 17 { content => [{ type => 'text', text => "$answer" }] });
2289 17 push @results, { tool_call => $pending_tc, result => $answer_result };
2290 17 ${$state->{raid_tool_calls}}++;
2291  
2292 # Execute remaining tool calls from the same batch, through the same
2293 # per-call dispatch as the first run of the batch (k120): the
2294 # plugin_before_tool_call hook runs for each of them, and a second
2295 # interactive self-tool re-pauses carrying the calls still queued after it.
2296 # Every call handled here MUST leave a tool_result behind (or end the raid):
2297 # a trailing tool_use with no matching tool_result is a 400 on strict
2298 # providers.
2299 17 my $stop = await $self->_execute_tool_calls_f($state, $iter, $cont->{remaining_tcs}, $data, \@results);
2300 17 ▶ return $stop if defined $stop;
Branch: 1 branch
BranchTrueFalseTotal
if defined $stop 1 16 17
2301  
2302 # Close iteration span if Langfuse
2303 16 ▶ if ($state->{langfuse} && $cont->{iter_span_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$state{"langfuse"} and $$cont{"iter_span_id"}) 0 16 16
Condition33%1/3
$$state{"langfuse"} and $$cont{"iter_span_id"}
!ll&&!rl&&r
1600
MC/DC0%0/2
$$state{"langfuse"} and $$cont{"iter_span_id"}
$$state{"langfuse"} $$cont{"iter_span_id"}
Truth table33%1/3
A and B
A= $$state{"langfuse"}B= $$cont{"iter_span_id"}
ABresult
0X0
100
111
2304 $engine->langfuse_update_span(
2305 id => $cont->{iter_span_id},
2306 0 end_time => $engine->langfuse_timestamp,
2307 metadata => { tool_calls => scalar @results },
2308 );
2309 }
2310  
2311 # Format tool results and append to conversation
2312 16 my @tool_msgs = $engine->format_tool_results($data, \@results);
2313 16 push @{$state->{conversation}}, @tool_msgs;
2314 16 ▶ push @{$state->{tool_segments} //= []}, [ @tool_msgs ]; # track for in-loop compaction (k89)
Condition50%1/2
$$state{"tool_segments"} //= []
l!l
160
MC/DC0%0/1
$$state{"tool_segments"} //= []
$$state{"tool_segments"}
Truth table50%1/2
A
A= $$state{"tool_segments"}
Aresult
11
00
2315 16 $self->_push_session_history(@tool_msgs);
2316  
2317 # Continue the raid loop from the next iteration
2318 16 return await $self->_run_raid_loop($state, $cont->{iteration} + 1);
2319 98 }
2320  
2321 11 ▶sub respond {
Subroutine respond: called CC=1 SCAR=0.0
Pod documented
2322 11 my ( $self, $answer ) = @_;
2323 11 return $self->respond_f($answer)->get;
2324 }
2325  
2326  
2327  
2328 98 __PACKAGE__->meta->make_immutable;
2329  
2330 98 1;
2331  
2332 __END__
2333  
2334 =pod
2335  
2336 =encoding UTF-8
2337  
2338 =head1 NAME
2339  
2340 Langertha::Raider - Autonomous agent with conversation history and MCP tools
2341  
2342 =head1 VERSION
2343  
2344 version 0.503
2345  
2346 =head1 SYNOPSIS
2347  
2348 use IO::Async::Loop;
2349 use Future::AsyncAwait;
2350 use Net::Async::MCP;
2351 use MCP::Server;
2352 use Langertha::Engine::Anthropic;
2353 use Langertha::Raider;
2354  
2355 # Set up MCP server with tools
2356 my $server = MCP::Server->new(name => 'demo', version => '1.0');
2357 $server->tool(
2358 name => 'list_files',
2359 description => 'List files in a directory',
2360 input_schema => {
2361 type => 'object',
2362 properties => { path => { type => 'string' } },
2363 required => ['path'],
2364 },
2365 code => sub { $_[0]->text_result(join("\n", glob("$_[1]->{path}/*"))) },
2366 );
2367  
2368 my $loop = IO::Async::Loop->new;
2369 my $mcp = Net::Async::MCP->new(server => $server);
2370 $loop->add($mcp);
2371  
2372 async sub main {
2373 await $mcp->initialize;
2374  
2375 my $engine = Langertha::Engine::Anthropic->new(
2376 api_key => $ENV{ANTHROPIC_API_KEY},
2377 mcp_servers => [$mcp],
2378 );
2379  
2380 my $raider = Langertha::Raider->new(
2381 engine => $engine,
2382 mission => 'You are a code explorer. Investigate files thoroughly.',
2383 );
2384  
2385 # First raid — uses tools, builds history
2386 my $r1 = await $raider->raid_f('What files are in the current directory?');
2387 say $r1;
2388  
2389 # Second raid — has context from first conversation
2390 my $r2 = await $raider->raid_f('Tell me more about the first file you found.');
2391 say $r2;
2392  
2393 # Check metrics
2394 my $m = $raider->metrics;
2395 say "Raids: $m->{raids}, Tool calls: $m->{tool_calls}, Time: $m->{time_ms}ms";
2396  
2397 # Reset for a fresh conversation
2398 $raider->clear_history;
2399 }
2400  
2401 main()->get;
2402  
2403 =head1 DESCRIPTION
2404  
2405 Langertha::Raider is an autonomous agent that wraps a Langertha engine
2406 with MCP tools. It maintains conversation history across multiple
2407 interactions (raids), enabling multi-turn conversations where the LLM
2408 can reference prior context.
2409  
2410 B<Key features:>
2411  
2412 =over 4
2413  
2414 =item * Conversation history persisted across raids
2415  
2416 =item * Mission (system prompt) separate from engine's system_prompt
2417  
2418 =item * Automatic MCP tool calling loop
2419  
2420 =item * Tool arguments checked against the tool's C<inputSchema> before it
2421 runs: a missing C<required> key or a top-level property of the wrong type
2422 answers the call with an error result the model can correct, and the tool
2423 does not run
2424  
2425 =item * Cumulative metrics tracking
2426  
2427 =item * Hermes tool calling support (inherited from engine)
2428  
2429 =item * Mid-raid context injection via C<inject()> and C<on_iteration>
2430  
2431 =item * Automatic context management — between-raid LLM history summary plus in-raid mechanical compaction, mission and skills preserved
2432  
2433 =back
2434  
2435 B<History management:> Only user messages and final assistant text
2436 responses are persisted in history. Intermediate tool-call messages
2437 (assistant tool requests and tool results) are NOT persisted, preventing
2438 token bloat across long conversations. The full turn-by-turn record, tool
2439 calls and results included, is kept separately in L</session_history>.
2440  
2441 =head2 engine
2442  
2443 Required. A Langertha engine instance with MCP servers configured.
2444 The engine must compose L<Langertha::Role::Tools>.
2445  
2446 =head2 mission
2447  
2448 Optional system prompt for the Raider. This is separate from the
2449 engine's own C<system_prompt> — the Raider's mission takes precedence
2450 and is prepended to every conversation.
2451  
2452 =head2 history
2453  
2454 ArrayRef of message hashes representing the conversation history.
2455 Automatically managed by C<raid>/C<raid_f>. Can be inspected or
2456 manually set.
2457  
2458 =head2 max_iterations
2459  
2460 Maximum number of tool-calling round trips per raid. Defaults to C<10>.
2461  
2462 =head2 max_context_tokens
2463  
2464 Optional. Enables auto-compression when set. When prompt token usage
2465 exceeds C<context_compress_threshold * max_context_tokens>, the working
2466 history is summarized via LLM before the next raid, and B<within> a single
2467 long raid the oldest tool-call exchanges are dropped from the in-flight
2468 conversation as the tool loop runs, oldest first, so one long-running
2469 mission cannot outgrow the context window. The mission (system prompt,
2470 including any activated skill instructions) is never compacted — an agent
2471 must not lose its instructions mid-raid.
2472  
2473 =head2 context_compress_threshold
2474  
2475 Fraction of C<max_context_tokens> that triggers compression. Defaults
2476 to C<0.75> (75%).
2477  
2478 =head2 compression_prompt
2479  
2480 System prompt used for history summarization. Customizable. The default
2481 instructs the LLM to preserve key facts, decisions, and context.
2482  
2483 =head2 compression_engine
2484  
2485 Optional separate engine for compression (e.g. a cheaper model).
2486 Falls back to C<engine> when not set.
2487  
2488 =head2 session_history
2489  
2490 Full chronological archive of ALL messages including tool calls and
2491 results. Never auto-compressed. Persists across C<clear_history> and
2492 C<reset>. Cleared via C<clear_session_history>, which also empties the
2493 internal C<_session_embeddings> array to preserve their 1:1 invariant.
2494  
2495 =head2 on_iteration
2496  
2497 Optional CodeRef called before each LLM call (iterations 2+). Receives
2498 C<($raider, $iteration)> and returns an arrayref of messages to inject,
2499 or undef/empty to skip.
2500  
2501 my $raider = Langertha::Raider->new(
2502 engine => $engine,
2503 on_iteration => sub {
2504 my ($raider, $iteration) = @_;
2505 return ['Check the error log'] if $iteration == 3;
2506 return;
2507 },
2508 );
2509  
2510 =head2 metrics
2511  
2512 HashRef of cumulative metrics across all raids:
2513  
2514 {
2515 raids => 3, # Number of completed raids
2516 iterations => 7, # Total LLM round trips
2517 tool_calls => 12, # Total tool invocations
2518 time_ms => 4500.2, # Total wall-clock time in milliseconds
2519 }
2520  
2521 =head2 langfuse_trace_name
2522  
2523 Name for the Langfuse trace created per raid. Defaults to C<'raid'>.
2524  
2525 =head2 langfuse_user_id
2526  
2527 Optional user ID passed to the Langfuse trace.
2528  
2529 =head2 langfuse_session_id
2530  
2531 Optional session ID passed to the Langfuse trace. Use this to group
2532 multiple raids into a single Langfuse session.
2533  
2534 =head2 langfuse_tags
2535  
2536 Optional tags (ArrayRef[Str]) passed to the Langfuse trace.
2537  
2538 =head2 langfuse_release
2539  
2540 Optional release identifier passed to the Langfuse trace.
2541  
2542 =head2 langfuse_version
2543  
2544 Optional version string passed to the Langfuse trace.
2545  
2546 =head2 langfuse_metadata
2547  
2548 Optional metadata HashRef merged into the Langfuse trace metadata
2549 (alongside auto-generated fields like mission and history_length).
2550  
2551 =head2 raider_mcp
2552  
2553 Enables virtual self-tools that the LLM can call to interact with the
2554 Raider itself. Set to C<1> to enable all self-tools, or pass a HashRef
2555 to enable selectively:
2556  
2557 raider_mcp => 1 # all self-tools
2558 raider_mcp => { ask_user => 1, pause => 1 } # only these
2559  
2560 Available self-tools: C<ask_user>, C<wait>, C<wait_for>, C<pause>,
2561 C<abort>, C<session_history>, C<manage_mcps>, C<switch_engine>.
2562  
2563 =head2 on_ask_user
2564  
2565 Optional callback for the C<raider_ask_user> self-tool. Receives
2566 C<($question, $options)> and must return an answer string. When not set,
2567 the raid pauses and returns a C<question> Result that can be continued
2568 with L</respond_f>.
2569  
2570 =head2 on_pause
2571  
2572 Optional callback for the C<raider_pause> self-tool. Receives C<($reason)>.
2573 When not set, the raid pauses and returns a C<pause> Result.
2574  
2575 =head2 on_wait_for
2576  
2577 Callback for the C<raider_wait_for> self-tool. Receives
2578 C<($condition, $args)> and must return a result string. Required when the
2579 LLM uses C<raider_wait_for> — will die if not set.
2580  
2581 =head2 cancel
2582  
2583 $raider->cancel;
2584  
2585 Asks the raid in progress to stop (ADR 0009). It stops at its next safe
2586 point -- before the next model call, before the next tool call -- and a
2587 model response, tool call or C<raider_wait> it waits for right then is
2588 abandoned: that future is cancelled, which aborts an HTTP request in
2589 flight on L<Net::Async::HTTP>. A tool call cut off this way still gets its
2590 result, marked C<cancelled> (text C<Tool call 'NAME' was cancelled.>,
2591 C<isError>, C<< cancelled => 1 >>), through C<plugin_after_tool_call>.
2592 Tool subprocesses are not signalled; that is the caller's to do. A tool call
2593 that ends with an error once the cancel is requested -- its subprocess
2594 ended by the caller -- counts as cut off too; one that succeeds keeps its
2595 result.
2596  
2597 The raid then resolves with a C<cancelled> L<Langertha::Raider::Result>.
2598 Like a failed raid it adds nothing to L</history>; the tool calls made so
2599 far stay in L</session_history>.
2600  
2601 It only sets a flag and writes a byte to a pipe the event loop watches,
2602 so it is safe to call from a signal handler: the rest happens on the loop.
2603 A request made while no raid runs applies to the next one
2604 (L</clear_cancel> drops it); each raid ends with no request pending
2605 (L</cancel_requested>).
2606  
2607 =head2 cancel_requested
2608  
2609 True from L</cancel> until the raid it applies to has ended.
2610  
2611 =head2 clear_cancel
2612  
2613 $raider->clear_cancel;
2614  
2615 Drops a cancel request that no raid has used yet (L</cancel>). Every raid
2616 does this when it ends.
2617  
2618 =head2 tools
2619  
2620 Optional ArrayRef of inline tool definitions. Each entry is a HashRef with
2621 C<name>, C<description>, C<input_schema>, and C<code> keys — the same
2622 format as L<MCP::Server/tool>. An internal MCP server is created
2623 automatically.
2624  
2625 my $raider = Langertha::Raider->new(
2626 engine => $engine,
2627 tools => [{
2628 name => 'greet',
2629 description => 'Say hello',
2630 input_schema => { type => 'object', properties => { name => { type => 'string' } } },
2631 code => sub { $_[0]->text_result("Hello $_[1]->{name}!") },
2632 }],
2633 );
2634  
2635 =head2 mcp_catalog
2636  
2637 HashRef of named MCP servers available for dynamic activation. The LLM can
2638 use C<raider_manage_mcps> to list, activate, and deactivate catalog entries.
2639  
2640 mcp_catalog => {
2641 database => { server => $db_mcp, description => 'Database tools', auto => 1 },
2642 email => { server => $email_mcp, description => 'Email tools' },
2643 }
2644  
2645 Entries with C<< auto => 1 >> are activated at construction time.
2646  
2647 =head2 engine_catalog
2648  
2649 HashRef of named engines available for runtime switching via C<switch_engine>.
2650  
2651 engine_catalog => {
2652 fast => { engine => $groq, description => 'Fast inference' },
2653 smart => { engine => $anthropic, description => 'Complex reasoning' },
2654 code => { engine => $deepseek, description => 'Code generation' },
2655 }
2656  
2657 Entries without an C<engine> key refer to the default engine (the one passed
2658 as C<engine> at construction). This lets you give the default engine a named
2659 catalog entry with a description:
2660  
2661 engine_catalog => {
2662 sonnet => { description => 'Balanced model for everyday tasks' },
2663 fast => { engine => $groq, description => 'Fast inference' },
2664 smart => { engine => $opus, description => 'Complex reasoning' },
2665 }
2666  
2667 The LLM always sees a C<default> entry (reset to original) plus all catalog
2668 keys in the C<raider_switch_engine> tool enum.
2669  
2670 Use C<switch_engine>, C<reset_engine>, C<active_engine>, and C<engine_info>
2671 to control which engine is used during raids.
2672  
2673 =head2 embedding_engine
2674  
2675 Optional engine with L<Langertha::Role::Embedding> for semantic history search.
2676 When not set, auto-detects if the main C<engine> supports embeddings.
2677 Set L</no_session_embeddings> to disable auto-detection.
2678  
2679 Each C<session_history> entry is embedded in the background through
2680 C<simple_embedding_f>, so the raid never waits for it. Like every engine of
2681 the raider, the embedding engine must run on the same event loop as
2682 C<engine> (see L</raid_f>).
2683  
2684 =head2 no_session_embeddings
2685  
2686 When true, no session history entry is embedded, and the C<search> of
2687 C<raider_session_history> falls back to a plain text match. Use it when the
2688 engine supports embeddings but they are not wanted, e.g. to save the extra
2689 request per message. With it set, C<embedding_engine> is also left out of
2690 the event-loop check of L</raid_f>.
2691  
2692 =head2 clear_history
2693  
2694 $raider->clear_history;
2695  
2696 Clears conversation history and pending injections while preserving metrics.
2697  
2698 =head2 clear_session_history
2699  
2700 $raider->clear_session_history;
2701  
2702 Empties C<session_history> and the matching C<_session_embeddings> array
2703 in lock-step, so the 1:1 invariant both readers of C<session_history> rely
2704 on is preserved. Use this instead of splicing C<session_history> directly,
2705 which leaves C<_session_embeddings> stale. Embedding requests still in
2706 flight for the cleared entries are cancelled.
2707  
2708 =head2 add_history
2709  
2710 $raider->add_history('user', 'Hello');
2711 $raider->add_history('assistant', 'Hi there!');
2712  
2713 Appends a message to the conversation history. Useful for replaying
2714 persisted messages into a fresh Raider instance.
2715  
2716 =head2 add_session_history
2717  
2718 $raider->add_session_history(
2719 { role => 'user', content => 'Hello' },
2720 { role => 'tool', name => 'bash', content => 'README.md' },
2721 );
2722  
2723 Appends entries to C<session_history>, keeping the session embeddings in
2724 step. Useful for replaying a persisted session into a fresh Raider
2725 instance; C<history> is replayed separately with C<add_history>.
2726  
2727 =head2 inject
2728  
2729 $raider->inject('Also check the test files');
2730 $raider->inject({ role => 'user', content => 'Focus on .pm files' });
2731  
2732 Queues messages to be injected into the conversation at the next iteration.
2733 Strings are automatically wrapped as user messages. The Raider drains the
2734 queue before each LLM call (iterations 2+).
2735  
2736 =head2 reset
2737  
2738 $raider->reset;
2739  
2740 Clears conversation history, metrics, and resets to the default engine.
2741  
2742 =head2 active_engine
2743  
2744 my $engine = $raider->active_engine;
2745  
2746 Returns the currently active engine. If C<switch_engine> was called, returns
2747 the catalog engine; otherwise returns the default C<engine>.
2748  
2749 =head2 active_engine_name
2750  
2751 my $name = $raider->active_engine_name; # 'smart' or undef
2752  
2753 Returns the name of the currently active catalog engine, or C<undef> if using
2754 the default engine.
2755  
2756 =head2 switch_engine
2757  
2758 $raider->switch_engine('smart');
2759  
2760 Switches to a named engine from the C<engine_catalog>. Sets C<_tools_dirty>
2761 so the raid loop re-gathers and re-formats tools for the new engine.
2762 Croaks if the name is not in the catalog.
2763  
2764 =head2 reset_engine
2765  
2766 $raider->reset_engine;
2767  
2768 Switches back to the default engine (the one passed at construction).
2769  
2770 =head2 engine_info
2771  
2772 my $info = $raider->engine_info;
2773 # { name => 'smart', class => 'Langertha::Engine::Anthropic', model => 'claude-sonnet-4-6' }
2774  
2775 Returns a hashref with the active engine's name, class, and model.
2776  
2777 =head2 list_engines
2778  
2779 my $engines = $raider->list_engines;
2780  
2781 Returns a hashref of all available engines (default + catalog entries),
2782 each with C<engine>, C<description> (if from catalog), and C<active> flag.
2783  
2784 =head2 add_engine
2785  
2786 $raider->add_engine('vision', engine => $vision_engine, description => 'Vision model');
2787 $raider->add_engine('main', description => 'Default model for general tasks');
2788  
2789 Adds a new engine to the catalog at runtime. If C<engine> is omitted, the
2790 entry refers to the default engine. The LLM will see it in the
2791 C<raider_switch_engine> tool after the next tool re-gather.
2792  
2793 =head2 remove_engine
2794  
2795 $raider->remove_engine('vision');
2796  
2797 Removes an engine from the catalog. If the removed engine is currently active,
2798 automatically resets to the default engine. Croaks when the name is not in
2799 the catalog.
2800  
2801 =head2 compress_history_f
2802  
2803 my $summary = await $raider->compress_history_f;
2804  
2805 Async. Summarizes the current working history via LLM and replaces it
2806 with the summary. Uses C<compression_engine> if set, otherwise falls
2807 back to C<engine>. A marker is added to C<session_history>.
2808  
2809 The summary is read through the engine's public C<chat_response> (the parser
2810 L<Langertha::Role::Chat/chat_f> uses), so an error carried in a 200 body croaks
2811 instead of silently producing an empty summary, and Gemini thought parts stay
2812 out of the text. An engine that lacks C<chat_response> falls back to
2813 C<response_text_content>.
2814  
2815 =head2 compress_history
2816  
2817 my $summary = $raider->compress_history;
2818  
2819 Synchronous wrapper around C<compress_history_f>.
2820  
2821 =head2 register_session_history_tool
2822  
2823 $raider->register_session_history_tool($mcp_server);
2824  
2825 Registers a C<session_history> MCP tool on the given server, allowing
2826 the LLM to query its own full session history. Supports C<query>
2827 (text filter) and C<last_n> (return last N messages) parameters.
2828  
2829 =head2 run_f
2830  
2831 my $result = await $raider->run_f($ctx); # a Langertha::RunContext, or plain input
2832  
2833 The L<Langertha::Role::Runnable> entry point that lets a raider be a step
2834 of a L<Langertha::Raid>. Runs L</raid_f> on the context's C<input> (a
2835 string, or an ArrayRef of messages; plain input is wrapped in a new
2836 L<Langertha::RunContext>). A final answer becomes the context's C<input>
2837 and C<< state->{last_output} >> for the next step; C<last_result_type>,
2838 C<last_result> and C<history> are updated too. Returns the
2839 L<Langertha::Raider::Result> with the context attached.
2840  
2841 =head2 raid
2842  
2843 my $response = $raider->raid(@messages);
2844  
2845 Synchronous wrapper around C<raid_f>. Sends messages, runs the tool
2846 loop, and returns the L<Langertha::Raider::Result>, which stringifies to
2847 the final text. Updates history and metrics.
2848  
2849 =head2 raid_f
2850  
2851 my $result = await $raider->raid_f(@messages);
2852  
2853 Async tool-calling conversation. Accepts the same message arguments as
2854 C<simple_chat> (strings become user messages, hashrefs pass through).
2855 Returns a L<Future> resolving to a L<Langertha::Raider::Result>.
2856  
2857 The result stringifies to the final text (backward compatible), but also
2858 provides C<type>, C<is_final>, C<is_question>, C<is_pause>, C<is_abort>
2859 for programmatic handling of interactive self-tools, and C<is_cancelled>
2860 for a raid stopped by L</cancel>.
2861  
2862 All engines of a raider (C<engine>, C<compression_engine>, every
2863 C<engine_catalog> engine, and C<embedding_engine> unless
2864 C<no_session_embeddings> is set) must run on the same event loop, since one raid
2865 is driven by one loop. An engine without a loop (the synchronous fallback)
2866 counts as the process-wide C<< IO::Async::Loop->new >>. C<raid_f> and
2867 C<respond_f> fail right away, naming the engine, when one runs on another loop.
2868  
2869 They also fail right away, naming the engine and the module, when a module
2870 L<Net::Async::HTTP> needs to connect to an engine's C<url> does not load:
2871 L<IO::Async::Internals::Connector>, and for https L<IO::Async::SSL> (which
2872 needs L<IO::Socket::SSL>, L<Net::SSLeay> and the system libssl). Sent
2873 anyway, the first request would fail and every later one to that host would
2874 wait forever.
2875  
2876 =head2 respond_f
2877  
2878 my $result = await $raider->respond_f($answer);
2879  
2880 Continue a paused raid after a C<question> or C<pause> result. The answer
2881 is used as the tool result of the pausing self-tool call -- handed through
2882 C<plugin_after_tool_call> like any tool result -- and the raid loop resumes.
2883 Returns the next
2884 L<Langertha::Raider::Result>.
2885  
2886 =head2 respond
2887  
2888 my $result = $raider->respond($answer);
2889  
2890 Synchronous wrapper around C<respond_f>.
2891  
2892 =head2 plugins
2893  
2894 my $raider = Langertha::Raider->new(
2895 plugins => ['Langfuse', 'MyApp::CustomPlugin'],
2896 engine => $engine,
2897 );
2898  
2899 Arrayref of plugin names or L<Langertha::Plugin> instances. Short names
2900 are resolved first to C<Langertha::Plugin::$name>, then to
2901 C<LangerthaX::Plugin::$name>. Fully qualified names (with C<::>) are
2902 used as-is.
2903  
2904 A leading C<+> (C<+My::Plugin>) loads the class as named, without the
2905 prefix search, and a name may be followed by a HashRef of constructor
2906 arguments for that plugin.
2907  
2908 Plugin instances are created automatically with C<< host => $self >>.
2909 Extra constructor arguments can be passed via C<plugin_args>.
2910  
2911 Besides the tool-calling hooks every L<Langertha::Plugin> has, a raider
2912 calls C<plugin_before_raid> (the raid's messages), C<plugin_build_conversation>
2913 (the conversation sent to the model) and C<plugin_after_raid> (the final
2914 L<Langertha::Raider::Result>); the contract is in L<Langertha::Plugin>.
2915  
2916 =head1 SEE ALSO
2917  
2918 =over
2919  
2920 =item * L<Langertha::Role::Tools> - Lower-level single-turn tool calling
2921  
2922 =item * L<Langertha::Role::Langfuse> - Observability integration (used by Raider)
2923  
2924 =item * L<Langertha::Role::SystemPrompt> - Engine-level system prompt (Raider uses C<mission> instead)
2925  
2926 =item * L<Langertha::Plugin> - Base role and documentation for Raider plugins
2927  
2928 =back
2929  
2930 =head1 SUPPORT
2931  
2932 =head2 Issues
2933  
2934 Please report bugs and feature requests on GitHub at
2935 L<https://github.com/Getty/langertha-raider/issues>.
2936  
2937 =head2 IRC
2938  
2939 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
2940  
2941 =head1 CONTRIBUTING
2942  
2943 Contributions are welcome! Please fork the repository and submit a pull request.
2944  
2945 =head1 AUTHOR
2946  
2947 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
2948  
2949 =head1 COPYRIGHT AND LICENSE
2950  
2951 This software is copyright (c) 2026 by Torsten Raudssus.
2952  
2953 This is free software; you can redistribute it and/or modify it under
2954 the same terms as the Perl 5 programming language system itself.
2955  
2956 =cut
« blib/lib/Langertha/Raider/CLI/Sessions.pm ↑ Summary blib/lib/Langertha/Raider/ToolArgs.pm »